LifeMate — Personal, Family & Learning Companion
fix/lifeguide-qa-pages-env-deployment
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
| 1 | import crypto from 'node:crypto'; |
| 2 | import nodemailer from 'nodemailer'; |
| 3 | import { createKavenegarSmsProvider } from './kavenegar_sms.js'; |
| 4 | |
| 5 | // Provider ports have no authority to create/verify users or issue sessions. |
| 6 | export class SmsProvider { |
| 7 | configured = false; |
| 8 | status = 'UNVERIFIED'; |
| 9 | async sendOtp(_message) { return { delivered: false, reason: 'provider_unconfigured' }; } |
| 10 | } |
| 11 | |
| 12 | class WebhookSmsProvider extends SmsProvider { |
| 13 | configured = true; |
| 14 | status = 'CONFIGURED_UNVERIFIED'; |
| 15 | #url; #token; #fetch; #timeout; |
| 16 | constructor({ url, token, fetchImpl, timeoutMs }) { |
| 17 | super(); |
| 18 | this.#url = url; this.#token = token; this.#fetch = fetchImpl; this.#timeout = timeoutMs; |
| 19 | } |
| 20 | async sendOtp({ phone, code, expiresIn, idempotencyKey }) { |
| 21 | if (typeof phone !== 'string' || typeof code !== 'string' || |
| 22 | !/^\+[1-9]\d{7,14}$/.test(phone) || !/^\d{6}$/.test(code) || |
| 23 | !Number.isInteger(expiresIn) || expiresIn < 1 || expiresIn > 300 || |
| 24 | 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'); |
| 25 | const signal = AbortSignal.timeout(this.#timeout); |
| 26 | let response; |
| 27 | try { |
| 28 | response = await this.#fetch(this.#url, { |
| 29 | method: 'POST', redirect: 'error', signal, |
| 30 | headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey }, |
| 31 | body: JSON.stringify({ phone, code, expiresIn }), |
| 32 | }); |
| 33 | } catch { |
| 34 | const error = new Error(signal.aborted ? 'sms_provider_timeout' : 'sms_provider_unavailable'); |
| 35 | // Transport failure has uncertain acceptance; a later explicit retry is safer. |
| 36 | error.retryable = false; |
| 37 | throw error; |
| 38 | } |
| 39 | // Do not read or serialize a webhook response body, which may contain secrets. |
| 40 | try { await response?.body?.cancel(); } catch { /* Discard only. */ } |
| 41 | if (!response?.ok) { |
| 42 | const error = new Error('sms_provider_rejected'); |
| 43 | error.retryable = response?.status === 429 || (response?.status >= 500 && response?.status <= 599); |
| 44 | throw error; |
| 45 | } |
| 46 | // A 2xx confirms webhook acceptance, never handset delivery. |
| 47 | return { delivered: true }; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | export function createSmsProvider({ env = process.env, fetchImpl = fetch, timeoutMs = 10000 } = {}) { |
| 52 | const selection = String(env.SMS_PROVIDER ?? '').trim().toLowerCase(); |
| 53 | if (['', 'none', 'disabled'].includes(selection)) return new SmsProvider(); |
| 54 | if (selection === 'kavenegar') return createKavenegarSmsProvider({ env, fetchImpl, timeoutMs }); |
| 55 | if (selection !== 'webhook') throw new Error('sms_provider_unsupported'); |
| 56 | let url; |
| 57 | try { url = new URL(env.SMS_PROVIDER_URL); } catch { throw new Error('sms_provider_url_invalid'); } |
| 58 | if (url.protocol !== 'https:' || !url.hostname || url.username || url.password || url.hash) throw new Error('sms_provider_url_invalid'); |
| 59 | const token = env.SMS_PROVIDER_TOKEN; |
| 60 | if (typeof token !== 'string' || token.length < 32 || token.length > 4096 || !/^[A-Za-z0-9._~+/-]+=*$/.test(token)) throw new Error('sms_provider_token_invalid'); |
| 61 | const boundedTimeout = Number.isInteger(timeoutMs) && timeoutMs > 0 && timeoutMs <= 10000 ? timeoutMs : 10000; |
| 62 | return new WebhookSmsProvider({ url: url.href, token, fetchImpl, timeoutMs: boundedTimeout }); |
| 63 | } |
| 64 | |
| 65 | export function createEmailProvider({ env = process.env, fetchImpl = fetch, transportFactory = nodemailer.createTransport } = {}) { |
| 66 | const configured = env.NODE_ENV !== 'test' && Boolean(env.EMAIL_FROM && (env.RESEND_API_KEY || (env.SMTP_HOST && Number(env.SMTP_PORT) > 0))); |
| 67 | return { |
| 68 | configured, |
| 69 | status: configured ? 'CONFIGURED_UNVERIFIED' : 'UNVERIFIED', |
| 70 | async send({ to, subject, text, idempotencyKey }) { |
| 71 | if (!configured) return { delivered: false, reason: 'provider_unconfigured' }; |
| 72 | if (env.RESEND_API_KEY) { |
| 73 | const response = await fetchImpl('https://api.resend.com/emails', { |
| 74 | method: 'POST', signal: AbortSignal.timeout(10000), |
| 75 | headers: { Authorization: `Bearer ${env.RESEND_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey }, |
| 76 | body: JSON.stringify({ from: env.EMAIL_FROM, to: [to], subject, text }), |
| 77 | }); |
| 78 | if (!response.ok) { |
| 79 | const error = new Error('email_provider_rejected'); |
| 80 | error.retryable = response.status === 429 || response.status >= 500; |
| 81 | throw error; |
| 82 | } |
| 83 | return { delivered: true }; |
| 84 | } |
| 85 | const transport = transportFactory({ |
| 86 | host: env.SMTP_HOST, port: Number(env.SMTP_PORT), secure: env.SMTP_SECURE === 'true', |
| 87 | connectionTimeout: 10000, greetingTimeout: 10000, socketTimeout: 10000, |
| 88 | logger: false, debug: false, |
| 89 | auth: env.SMTP_USER ? { user: env.SMTP_USER, pass: env.SMTP_PASSWORD } : undefined, |
| 90 | }); |
| 91 | try { |
| 92 | await transport.sendMail({ from: env.EMAIL_FROM, to, subject, text, messageId: `<${idempotencyKey}@lifeguide.invalid>` }); |
| 93 | return { delivered: true }; |
| 94 | } finally { transport.close?.(); } |
| 95 | }, |
| 96 | }; |
| 97 | } |
| 98 | |
| 99 | export async function safelyDeliver(provider, message, { pool, attemptId, env = process.env } = {}) { |
| 100 | let status = 'unconfigured'; |
| 101 | const idempotencyKey = attemptId ?? crypto.randomUUID(); |
| 102 | if (provider.configured) { |
| 103 | for (let attempt = 0; attempt < 3; attempt++) { |
| 104 | try { |
| 105 | const result = await provider.send({ ...message, idempotencyKey }); |
| 106 | status = result?.delivered === true ? 'accepted' : 'failed'; |
| 107 | break; |
| 108 | } catch (error) { |
| 109 | status = 'failed'; |
| 110 | if (error?.retryable !== true || attempt === 2) break; |
| 111 | await new Promise((resolve) => setTimeout(resolve, 250 * (2 ** attempt))); |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | if (pool && attemptId) { |
| 116 | try { await pool.query('update auth_delivery_attempt set status=$2,updated_at=now() where id=$1', [attemptId, status]); } |
| 117 | catch { /* Account/token is already committed; delivery bookkeeping cannot undo it. */ } |
| 118 | } |
| 119 | if (env.NODE_ENV !== 'test') { |
| 120 | // Never serialize provider errors, recipients, tokens, message text or OTPs. |
| 121 | console.log(JSON.stringify({ type: 'auth_delivery', status, attemptId: idempotencyKey })); |
| 122 | } |
| 123 | return { delivered: status === 'accepted', status }; |
| 124 | } |