LifeMate — Personal, Family & Learning Companion

fix/study-duration-display
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
js 122 lines 5.96 KB
Raw
1 import crypto from 'node:crypto';
2 import nodemailer from 'nodemailer';
3
4 // Provider ports have no authority to create/verify users or issue sessions.
5 export class SmsProvider {
6 configured = false;
7 status = 'UNVERIFIED';
8 async sendOtp(_message) { return { delivered: false, reason: 'provider_unconfigured' }; }
9 }
10
11 class WebhookSmsProvider extends SmsProvider {
12 configured = true;
13 status = 'CONFIGURED_UNVERIFIED';
14 #url; #token; #fetch; #timeout;
15 constructor({ url, token, fetchImpl, timeoutMs }) {
16 super();
17 this.#url = url; this.#token = token; this.#fetch = fetchImpl; this.#timeout = timeoutMs;
18 }
19 async sendOtp({ phone, code, expiresIn, idempotencyKey }) {
20 if (typeof phone !== 'string' || typeof code !== 'string' ||
21 !/^\+[1-9]\d{7,14}$/.test(phone) || !/^\d{6}$/.test(code) ||
22 !Number.isInteger(expiresIn) || expiresIn < 1 || expiresIn > 300 ||
23 typeof idempotencyKey !== 'string' || !/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(idempotencyKey)) throw new Error('sms_provider_input_invalid');
24 const signal = AbortSignal.timeout(this.#timeout);
25 let response;
26 try {
27 response = await this.#fetch(this.#url, {
28 method: 'POST', redirect: 'error', signal,
29 headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey },
30 body: JSON.stringify({ phone, code, expiresIn }),
31 });
32 } catch {
33 const error = new Error(signal.aborted ? 'sms_provider_timeout' : 'sms_provider_unavailable');
34 // Transport failure has uncertain acceptance; a later explicit retry is safer.
35 error.retryable = false;
36 throw error;
37 }
38 // Do not read or serialize a webhook response body, which may contain secrets.
39 try { await response?.body?.cancel(); } catch { /* Discard only. */ }
40 if (!response?.ok) {
41 const error = new Error('sms_provider_rejected');
42 error.retryable = response?.status === 429 || (response?.status >= 500 && response?.status <= 599);
43 throw error;
44 }
45 // A 2xx confirms webhook acceptance, never handset delivery.
46 return { delivered: true };
47 }
48 }
49
50 export function createSmsProvider({ env = process.env, fetchImpl = fetch, timeoutMs = 10000 } = {}) {
51 const selection = String(env.SMS_PROVIDER ?? '').trim().toLowerCase();
52 if (['', 'none', 'disabled'].includes(selection)) return new SmsProvider();
53 if (selection !== 'webhook') throw new Error('sms_provider_unsupported');
54 let url;
55 try { url = new URL(env.SMS_PROVIDER_URL); } catch { throw new Error('sms_provider_url_invalid'); }
56 if (url.protocol !== 'https:' || !url.hostname || url.username || url.password || url.hash) throw new Error('sms_provider_url_invalid');
57 const token = env.SMS_PROVIDER_TOKEN;
58 if (typeof token !== 'string' || token.length < 32 || token.length > 4096 || !/^[A-Za-z0-9._~+/-]+=*$/.test(token)) throw new Error('sms_provider_token_invalid');
59 const boundedTimeout = Number.isInteger(timeoutMs) && timeoutMs > 0 && timeoutMs <= 10000 ? timeoutMs : 10000;
60 return new WebhookSmsProvider({ url: url.href, token, fetchImpl, timeoutMs: boundedTimeout });
61 }
62
63 export function createEmailProvider({ env = process.env, fetchImpl = fetch, transportFactory = nodemailer.createTransport } = {}) {
64 const configured = env.NODE_ENV !== 'test' && Boolean(env.EMAIL_FROM && (env.RESEND_API_KEY || (env.SMTP_HOST && Number(env.SMTP_PORT) > 0)));
65 return {
66 configured,
67 status: configured ? 'CONFIGURED_UNVERIFIED' : 'UNVERIFIED',
68 async send({ to, subject, text, idempotencyKey }) {
69 if (!configured) return { delivered: false, reason: 'provider_unconfigured' };
70 if (env.RESEND_API_KEY) {
71 const response = await fetchImpl('https://api.resend.com/emails', {
72 method: 'POST', signal: AbortSignal.timeout(10000),
73 headers: { Authorization: `Bearer ${env.RESEND_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey },
74 body: JSON.stringify({ from: env.EMAIL_FROM, to: [to], subject, text }),
75 });
76 if (!response.ok) {
77 const error = new Error('email_provider_rejected');
78 error.retryable = response.status === 429 || response.status >= 500;
79 throw error;
80 }
81 return { delivered: true };
82 }
83 const transport = transportFactory({
84 host: env.SMTP_HOST, port: Number(env.SMTP_PORT), secure: env.SMTP_SECURE === 'true',
85 connectionTimeout: 10000, greetingTimeout: 10000, socketTimeout: 10000,
86 logger: false, debug: false,
87 auth: env.SMTP_USER ? { user: env.SMTP_USER, pass: env.SMTP_PASSWORD } : undefined,
88 });
89 try {
90 await transport.sendMail({ from: env.EMAIL_FROM, to, subject, text, messageId: `<${idempotencyKey}@lifeguide.invalid>` });
91 return { delivered: true };
92 } finally { transport.close?.(); }
93 },
94 };
95 }
96
97 export async function safelyDeliver(provider, message, { pool, attemptId, env = process.env } = {}) {
98 let status = 'unconfigured';
99 const idempotencyKey = attemptId ?? crypto.randomUUID();
100 if (provider.configured) {
101 for (let attempt = 0; attempt < 3; attempt++) {
102 try {
103 const result = await provider.send({ ...message, idempotencyKey });
104 status = result?.delivered === true ? 'accepted' : 'failed';
105 break;
106 } catch (error) {
107 status = 'failed';
108 if (error?.retryable !== true || attempt === 2) break;
109 await new Promise((resolve) => setTimeout(resolve, 250 * (2 ** attempt)));
110 }
111 }
112 }
113 if (pool && attemptId) {
114 try { await pool.query('update auth_delivery_attempt set status=$2,updated_at=now() where id=$1', [attemptId, status]); }
115 catch { /* Account/token is already committed; delivery bookkeeping cannot undo it. */ }
116 }
117 if (env.NODE_ENV !== 'test') {
118 // Never serialize provider errors, recipients, tokens, message text or OTPs.
119 console.log(JSON.stringify({ type: 'auth_delivery', status, attemptId: idempotencyKey }));
120 }
121 return { delivered: status === 'accepted', status };
122 }