LifeMate — Personal, Family & Learning Companion
feat/learning-content-operations
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 test, { after, before } from 'node:test'; |
| 2 | import assert from 'node:assert/strict'; |
| 3 | import crypto from 'node:crypto'; |
| 4 | import { spawn } from 'node:child_process'; |
| 5 | import { once } from 'node:events'; |
| 6 | import net from 'node:net'; |
| 7 | import pg from 'pg'; |
| 8 | import express from 'express'; |
| 9 | import argon2 from 'argon2'; |
| 10 | import jwt from 'jsonwebtoken'; |
| 11 | import { createAuthRouter } from '../src/auth_router.js'; |
| 12 | import { createSessionAuth } from '../src/session_auth.js'; |
| 13 | import { SmsProvider, createEmailProvider, safelyDeliver } from '../src/auth_delivery.js'; |
| 14 | import { operationalErrorHandler } from '../src/operations.js'; |
| 15 | |
| 16 | assert.ok(process.env.DATABASE_URL, 'Auth delivery tests require a migrated synthetic PostgreSQL database'); |
| 17 | assert.ok(process.env.JWT_SECRET?.length >= 32, 'Auth delivery tests require a synthetic JWT secret'); |
| 18 | const suffix = crypto.randomUUID(); |
| 19 | const applicationName = `auth-fixture-${suffix}`; |
| 20 | const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, application_name: applicationName }); |
| 21 | const email = `delivery-${suffix}@example.test`; |
| 22 | let child; |
| 23 | let base; |
| 24 | let output = ''; |
| 25 | let errors = ''; |
| 26 | let smtp; |
| 27 | let providerServer; |
| 28 | let providerBase; |
| 29 | const mail = []; |
| 30 | const smsMessages = []; |
| 31 | const recipients = new Set([email]); |
| 32 | const userIds = new Set(); |
| 33 | const familyIds = new Set(); |
| 34 | const challengeIds = new Set(); |
| 35 | const jwtSecret = process.env.JWT_SECRET; |
| 36 | const recipientDigest = (recipient) => crypto.createHmac('sha256', jwtSecret).update(`delivery:${recipient}`).digest('hex'); |
| 37 | const tokenDigest = (token) => crypto.createHash('sha256').update(token).digest('hex'); |
| 38 | const password = 'SyntheticPass123!'; |
| 39 | const replacement = 'ReplacementSynthetic123!'; |
| 40 | |
| 41 | // Only the external delivery ports are fixtures: HTTP, identity, hashes and DB are real. |
| 42 | class CapturingSmsProvider extends SmsProvider { |
| 43 | configured = true; |
| 44 | status = 'TEST_ONLY'; |
| 45 | async sendOtp(message) { smsMessages.push(message); return { delivered: true }; } |
| 46 | } |
| 47 | |
| 48 | before(async () => { |
| 49 | // A rejecting local SMTP fixture: no message or credential is transmitted. |
| 50 | smtp = net.createServer((socket) => socket.end('421 synthetic service unavailable\r\n')); |
| 51 | smtp.listen(0, '127.0.0.1'); |
| 52 | await once(smtp, 'listening'); |
| 53 | const reservation = net.createServer(); |
| 54 | reservation.listen(0, '127.0.0.1'); |
| 55 | await once(reservation, 'listening'); |
| 56 | const port = reservation.address().port; |
| 57 | await new Promise((resolve) => reservation.close(resolve)); |
| 58 | base = `http://127.0.0.1:${port}`; |
| 59 | child = spawn(process.execPath, ['src/entrypoint.js'], { |
| 60 | env: { |
| 61 | ...process.env, NODE_ENV: 'production', PORT: String(port), |
| 62 | SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', |
| 63 | EMAIL_FROM: 'LifeGuide Test <fixture@example.test>', |
| 64 | SMTP_HOST: '127.0.0.1', SMTP_PORT: String(smtp.address().port), |
| 65 | SMTP_SECURE: 'false', SMTP_USER: '', SMTP_PASSWORD: '', RESEND_API_KEY: '', |
| 66 | PUBLIC_APP_URL: 'https://app.example.test', CORS_ORIGINS: '', |
| 67 | RATE_LIMIT_AUTH_MAX: '2000', RATE_LIMIT_GENERAL_MAX: '2000', |
| 68 | }, |
| 69 | stdio: ['ignore', 'pipe', 'pipe'], |
| 70 | }); |
| 71 | child.stdout.on('data', (chunk) => { output += chunk.toString(); }); |
| 72 | child.stderr.on('data', (chunk) => { errors += chunk.toString(); }); |
| 73 | await new Promise((resolve, reject) => { |
| 74 | const timer = setTimeout(() => reject(new Error('Auth fixture startup timed out')), 10000); |
| 75 | const onData = () => { |
| 76 | if (!output.includes('"type":"startup"')) return; |
| 77 | clearTimeout(timer); |
| 78 | child.stdout.off('data', onData); |
| 79 | resolve(); |
| 80 | }; |
| 81 | child.stdout.on('data', onData); |
| 82 | child.once('error', (error) => { clearTimeout(timer); reject(error); }); |
| 83 | }); |
| 84 | const fixtureApp = express(); |
| 85 | fixtureApp.use(express.json({ limit: '64kb' })); |
| 86 | fixtureApp.use('/v1/auth', createAuthRouter({ |
| 87 | pool, jwtSecret, auth: createSessionAuth({ pool, jwtSecret }), |
| 88 | env: { NODE_ENV: 'production', PUBLIC_APP_URL: 'https://app.example.test' }, |
| 89 | emailProvider: { configured: true, status: 'TEST_ONLY', async send(message) { mail.push(message); return { delivered: true }; } }, |
| 90 | smsProvider: new CapturingSmsProvider(), |
| 91 | })); |
| 92 | fixtureApp.use(operationalErrorHandler); |
| 93 | providerServer = fixtureApp.listen(0, '127.0.0.1'); |
| 94 | await once(providerServer, 'listening'); |
| 95 | providerBase = `http://127.0.0.1:${providerServer.address().port}`; |
| 96 | }); |
| 97 | |
| 98 | after(async () => { |
| 99 | if (child && child.exitCode === null && child.signalCode === null) { |
| 100 | const closed = once(child, 'close'); |
| 101 | child.kill('SIGTERM'); |
| 102 | await closed; |
| 103 | } |
| 104 | if (smtp) await new Promise((resolve) => smtp.close(resolve)); |
| 105 | if (providerServer) await new Promise((resolve) => providerServer.close(resolve)); |
| 106 | await pool.query('delete from access_audit where actor_user_id=any($1::uuid[]) or family_id=any($2::uuid[])', [[...userIds], [...familyIds]]); |
| 107 | await pool.query('delete from family_workspace where id=any($1::uuid[])', [[...familyIds]]); |
| 108 | await pool.query('delete from auth_phone_challenge where id=any($1::uuid[])', [[...challengeIds]]); |
| 109 | await pool.query('delete from auth_delivery_attempt where recipient_digest=any($1::text[])', [[...recipients].map(recipientDigest)]); |
| 110 | await pool.query('delete from app_user where id=any($1::uuid[]) or email_normalized=$2', [[...userIds], email]); |
| 111 | await pool.end(); |
| 112 | }); |
| 113 | |
| 114 | async function request(path, body, { method = 'POST', token, origin = base } = {}) { |
| 115 | const response = await fetch(origin + path, { |
| 116 | method, |
| 117 | headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, |
| 118 | body: body === undefined ? undefined : JSON.stringify(body), |
| 119 | }); |
| 120 | const text = await response.text(); |
| 121 | return { status: response.status, body: text ? JSON.parse(text) : null, headers: response.headers }; |
| 122 | } |
| 123 | |
| 124 | const providerRequest = (path, body, options = {}) => request(path, body, { ...options, origin: providerBase }); |
| 125 | async function until(check) { |
| 126 | for (let i = 0; i < 100; i++) { |
| 127 | const value = await check(); |
| 128 | if (value) return value; |
| 129 | await new Promise((resolve) => setTimeout(resolve, 20)); |
| 130 | } |
| 131 | assert.fail('Synthetic delivery fixture did not complete'); |
| 132 | } |
| 133 | async function identify(contact) { |
| 134 | const row = await pool.query('select id from app_user where email_normalized=$1 or phone_normalized=$1', [contact]); |
| 135 | assert.equal(row.rowCount, 1); |
| 136 | userIds.add(row.rows[0].id); |
| 137 | return row.rows[0].id; |
| 138 | } |
| 139 | async function resetCooldown(contact, purpose) { |
| 140 | await pool.query("update auth_delivery_attempt set requested_at=now()-interval '2 hours' where recipient_digest=$1 and purpose=$2", [recipientDigest(contact), purpose]); |
| 141 | } |
| 142 | function freshEmail() { const value = `auth-${crypto.randomUUID()}@example.test`; recipients.add(value); return value; } |
| 143 | function freshPhone() { const value = `+1555${crypto.randomInt(100000000, 999999999)}`; recipients.add(value); return value; } |
| 144 | async function emailAccount() { |
| 145 | const contact = freshEmail(); |
| 146 | assert.equal((await providerRequest('/v1/auth/register', { email: contact, displayName: 'Synthetic Email', password })).status, 202); |
| 147 | const id = await identify(contact); |
| 148 | const message = await until(() => mail.find((item) => item.to === contact)); |
| 149 | const token = new URL(message.text.match(/https:\/\/\S+/)[0]).searchParams.get('token'); |
| 150 | return { contact, id, token }; |
| 151 | } |
| 152 | async function otp(contact, purpose = 'verify') { |
| 153 | await resetCooldown(contact, 'phone_otp'); |
| 154 | const previous = smsMessages.length; |
| 155 | const response = await providerRequest('/v1/auth/phone/request-otp', { phone: contact, purpose }); |
| 156 | assert.equal(response.status, 202); |
| 157 | challengeIds.add(response.body.challengeId); |
| 158 | assert.equal(response.body.expiresIn, 300); |
| 159 | assert.equal(Object.hasOwn(response.body, 'code'), false); |
| 160 | const message = await until(() => smsMessages.slice(previous).find((item) => item.phone === contact)); |
| 161 | return { challengeId: response.body.challengeId, code: message.code }; |
| 162 | } |
| 163 | async function phoneAccount() { |
| 164 | const contact = freshPhone(); |
| 165 | const registered = await providerRequest('/v1/auth/register', { phone: contact, displayName: 'Synthetic Phone', password }); |
| 166 | assert.equal(registered.status, 202); |
| 167 | assert.deepEqual(registered.body, { accepted: true }); |
| 168 | return { contact, id: await identify(contact) }; |
| 169 | } |
| 170 | async function familyFixture() { |
| 171 | const parent = await emailAccount(); |
| 172 | assert.equal((await providerRequest('/v1/auth/verify-email', { token: parent.token, newPassword: password })).status, 204); |
| 173 | const login = await request('/v1/auth/login', { email: parent.contact, password }); |
| 174 | assert.equal(login.status, 200); |
| 175 | const child = await phoneAccount(); |
| 176 | const proof = await otp(child.contact); |
| 177 | const verified = await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password }); |
| 178 | assert.equal(verified.status, 200); |
| 179 | const family = await request('/v1/families', { name: 'Synthetic Management Family', role: 'parent_guardian' }, { token: login.body.accessToken }); |
| 180 | assert.equal(family.status, 201); |
| 181 | familyIds.add(family.body.id); |
| 182 | return { parent: { ...parent, accessToken: login.body.accessToken }, child: { ...child, accessToken: verified.body.accessToken }, familyId: family.body.id }; |
| 183 | } |
| 184 | async function phoneInvitation(fixture, role = 'teen_minor') { |
| 185 | const invitation = await request(`/v1/families/${fixture.familyId}/invitations`, { phone: fixture.child.contact, role }, { token: fixture.parent.accessToken }); |
| 186 | assert.equal(invitation.status, 201); |
| 187 | return invitation.body; |
| 188 | } |
| 189 | |
| 190 | test('registration remains recoverable and generic when email delivery fails after commit', async () => { |
| 191 | const body = { email, displayName: 'Synthetic User', password: 'SyntheticPass123!' }; |
| 192 | const created = await request('/v1/auth/register', body); |
| 193 | assert.equal(created.status, 202); |
| 194 | assert.deepEqual(created.body, { accepted: true }); |
| 195 | const row = await pool.query('select u.id,c.password_hash from app_user u join auth_credential c on c.user_id=u.id where u.email_normalized=$1', [email]); |
| 196 | assert.equal(row.rowCount, 1); |
| 197 | assert.equal(row.rows[0].password_hash.startsWith('$argon2id$'), true); |
| 198 | userIds.add(row.rows[0].id); |
| 199 | await until(async () => (await pool.query("select 1 from auth_delivery_attempt where user_id=$1 and purpose='email_verification' and status='failed'", [row.rows[0].id])).rowCount); |
| 200 | const duplicate = await request('/v1/auth/register', { ...body, displayName: 'Must Not Replace', password: 'OtherSyntheticPass123!' }); |
| 201 | assert.equal(duplicate.status, 202); |
| 202 | assert.deepEqual(duplicate.body, created.body); |
| 203 | assert.equal((await pool.query('select display_name from profile where user_id=$1', [row.rows[0].id])).rows[0].display_name, 'Synthetic User'); |
| 204 | assert.equal((await pool.query('select password_hash=$2 as unchanged from auth_credential where user_id=$1', [row.rows[0].id, row.rows[0].password_hash])).rows[0].unchanged, true); |
| 205 | }); |
| 206 | |
| 207 | test('forgot-password delivery failure keeps the generic response and stored recovery token', async () => { |
| 208 | const known = await request('/v1/auth/forgot-password', { email }); |
| 209 | const unknown = await request('/v1/auth/forgot-password', { email: `missing-${suffix}@example.test` }); |
| 210 | recipients.add(`missing-${suffix}@example.test`); |
| 211 | assert.equal(known.status, 200); |
| 212 | assert.equal(unknown.status, 200); |
| 213 | assert.deepEqual(known.body, { accepted: true }); |
| 214 | assert.deepEqual(unknown.body, known.body); |
| 215 | assert.equal((await pool.query("select count(*)::int as n from auth_token t join app_user u on u.id=t.user_id where u.email_normalized=$1 and t.kind='password_reset'", [email])).rows[0].n, 1); |
| 216 | assert.equal(errors.includes(email), false); |
| 217 | assert.equal(errors.includes('SyntheticPass123!'), false); |
| 218 | }); |
| 219 | |
| 220 | test('unconfigured SMS returns the same recoverable failure before account creation or lookup', async () => { |
| 221 | const contact = freshPhone(); |
| 222 | const caps = await request('/v1/auth/capabilities', undefined, { method: 'GET' }); |
| 223 | assert.equal(caps.status, 200); |
| 224 | assert.equal(caps.body.smsAvailable, false); |
| 225 | assert.equal(caps.body.smsStatus, 'UNVERIFIED'); |
| 226 | const rejected = await request('/v1/auth/register', { phone: contact, displayName: 'Synthetic Phone', password }); |
| 227 | assert.equal(rejected.status, 503); |
| 228 | assert.deepEqual(rejected.body, { error: 'sms_unavailable' }); |
| 229 | assert.equal((await pool.query('select 1 from app_user where phone_normalized=$1', [contact])).rowCount, 0); |
| 230 | const created = await phoneAccount(); |
| 231 | const known = await request('/v1/auth/phone/request-otp', { phone: created.contact }); |
| 232 | const unknown = await request('/v1/auth/phone/request-otp', { phone: contact }); |
| 233 | assert.equal(known.status, 503); |
| 234 | assert.equal(unknown.status, known.status); |
| 235 | assert.deepEqual(unknown.body, known.body); |
| 236 | assert.equal((await pool.query('select 1 from auth_phone_challenge where user_id=$1', [created.id])).rowCount, 0); |
| 237 | }); |
| 238 | |
| 239 | test('resend verification is generic, rate limited for known and unknown contacts, and recoverable after provider failure', async () => { |
| 240 | const unknown = freshEmail(); |
| 241 | await resetCooldown(email, 'email_verification'); |
| 242 | const known = await request('/v1/auth/resend-verification', { email }); |
| 243 | const absent = await request('/v1/auth/resend-verification', { email: unknown }); |
| 244 | assert.equal(known.status, 202); |
| 245 | assert.equal(absent.status, 202); |
| 246 | assert.deepEqual(known.body, absent.body); |
| 247 | for (const contact of [email, unknown]) { |
| 248 | const blocked = await request('/v1/auth/resend-verification', { email: contact }); |
| 249 | assert.equal(blocked.status, 429); |
| 250 | assert.equal(Number(blocked.headers.get('Retry-After')) > 0, true); |
| 251 | await pool.query("update auth_delivery_attempt set requested_at=now()-interval '61 seconds' where recipient_digest=$1 and purpose='email_verification' and requested_at>now()-interval '1 hour'", [recipientDigest(contact)]); |
| 252 | assert.equal((await request('/v1/auth/resend-verification', { email: contact })).status, 202); |
| 253 | await pool.query("update auth_delivery_attempt set requested_at=now()-interval '61 seconds' where recipient_digest=$1 and purpose='email_verification' and requested_at>now()-interval '1 hour'", [recipientDigest(contact)]); |
| 254 | assert.equal((await request('/v1/auth/resend-verification', { email: contact })).status, 202); |
| 255 | const hourlyLimit = await request('/v1/auth/resend-verification', { email: contact }); |
| 256 | assert.equal(hourlyLimit.status, 429); |
| 257 | assert.equal(Number(hourlyLimit.headers.get('Retry-After')) > 60, true); |
| 258 | } |
| 259 | const stored = await pool.query("select count(*)::int as n from auth_token t join app_user u on u.id=t.user_id where u.email_normalized=$1 and t.kind='email_verification'", [email]); |
| 260 | assert.equal(stored.rows[0].n >= 4, true); |
| 261 | }); |
| 262 | |
| 263 | test('email verification and reset tokens are hashed, expire and can be consumed only once', async () => { |
| 264 | const account = await emailAccount(); |
| 265 | const stored = (await pool.query('select token_digest from auth_token where user_id=$1', [account.id])).rows[0].token_digest; |
| 266 | assert.equal(stored === tokenDigest(account.token), true); |
| 267 | assert.equal(stored === account.token, false); |
| 268 | await pool.query("update auth_token set created_at=now()-interval '2 days',expires_at=now()-interval '1 day' where user_id=$1", [account.id]); |
| 269 | assert.equal((await providerRequest('/v1/auth/verify-email', { token: account.token, newPassword: password })).status, 400); |
| 270 | await resetCooldown(account.contact, 'email_verification'); |
| 271 | const previous = mail.length; |
| 272 | assert.equal((await providerRequest('/v1/auth/resend-verification', { email: account.contact })).status, 202); |
| 273 | const verification = await until(() => mail.slice(previous).find((item) => item.to === account.contact)); |
| 274 | const token = new URL(verification.text.match(/https:\/\/\S+/)[0]).searchParams.get('token'); |
| 275 | assert.equal((await providerRequest('/v1/auth/verify-email', { token, newPassword: password })).status, 204); |
| 276 | assert.equal((await providerRequest('/v1/auth/verify-email', { token, newPassword: password })).status, 400); |
| 277 | const login = await providerRequest('/v1/auth/login', { identifier: account.contact, password }); |
| 278 | assert.equal(login.status, 200); |
| 279 | const before = mail.length; |
| 280 | assert.equal((await providerRequest('/v1/auth/forgot-password', { email: account.contact })).status, 200); |
| 281 | const resetMessage = await until(() => mail.slice(before).find((item) => item.to === account.contact)); |
| 282 | const expiredReset = new URL(resetMessage.text.match(/https:\/\/\S+/)[0]).searchParams.get('token'); |
| 283 | await pool.query("update auth_token set created_at=now()-interval '1 hour',expires_at=now()-interval '30 minutes' where token_digest=$1", [tokenDigest(expiredReset)]); |
| 284 | assert.equal((await providerRequest('/v1/auth/reset-password', { token: expiredReset, newPassword: replacement })).status, 400); |
| 285 | await resetCooldown(account.contact, 'password_reset'); |
| 286 | const resendStart = mail.length; |
| 287 | assert.equal((await providerRequest('/v1/auth/forgot-password', { email: account.contact })).status, 200); |
| 288 | const resentReset = await until(() => mail.slice(resendStart).find((item) => item.to === account.contact)); |
| 289 | const reset = new URL(resentReset.text.match(/https:\/\/\S+/)[0]).searchParams.get('token'); |
| 290 | assert.equal((await providerRequest('/v1/auth/reset-password', { token: reset, newPassword: replacement })).status, 204); |
| 291 | assert.equal((await providerRequest('/v1/auth/reset-password', { token: reset, newPassword: password })).status, 400); |
| 292 | assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: login.body.refreshToken })).status, 401); |
| 293 | assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password })).status, 401); |
| 294 | assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password: replacement })).status, 200); |
| 295 | }); |
| 296 | |
| 297 | test('phone-only ownership proof replaces pending credentials; OTP is hashed and single-use', async () => { |
| 298 | const account = await phoneAccount(); |
| 299 | assert.equal((await providerRequest('/v1/auth/login', { phone: account.contact, password })).status, 403); |
| 300 | const proof = await otp(account.contact); |
| 301 | const stored = (await pool.query('select code_digest,expires_at-created_at as ttl from auth_phone_challenge where id=$1', [proof.challengeId])).rows[0]; |
| 302 | assert.equal(stored.code_digest.length, 64); |
| 303 | assert.equal(stored.code_digest === crypto.createHmac('sha256', jwtSecret).update(`otp:${proof.challengeId}:${proof.code}`).digest('hex'), true); |
| 304 | assert.equal(stored.code_digest === proof.code, false); |
| 305 | assert.equal(stored.ttl.minutes, 5); |
| 306 | assert.equal((await providerRequest('/v1/auth/phone/verify-otp', proof)).status, 400); |
| 307 | assert.equal((await pool.query('select phone_verified_at from app_user where id=$1', [account.id])).rows[0].phone_verified_at, null); |
| 308 | const verified = await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: replacement }); |
| 309 | assert.equal(verified.status, 200); |
| 310 | assert.ok(verified.body.refreshToken); |
| 311 | assert.equal((await pool.query('select email_normalized,phone_verified_at from app_user where id=$1', [account.id])).rows[0].email_normalized, null); |
| 312 | assert.equal((await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password })).status, 401); |
| 313 | assert.equal((await providerRequest('/v1/auth/login', { identifier: account.contact, password })).status, 401); |
| 314 | assert.equal((await providerRequest('/v1/auth/login', { identifier: account.contact, password: replacement })).status, 200); |
| 315 | }); |
| 316 | |
| 317 | test('phone OTP expiry, bounded guessing, unknown accounts and recovery enforce server policy', async () => { |
| 318 | const account = await phoneAccount(); |
| 319 | const initial = await otp(account.contact); |
| 320 | assert.equal((await providerRequest('/v1/auth/phone/verify-otp', { ...initial, newPassword: replacement })).status, 200); |
| 321 | const authenticated = await providerRequest('/v1/auth/login', { phone: account.contact, password: replacement }); |
| 322 | const expired = await otp(account.contact, 'login'); |
| 323 | await pool.query("update auth_phone_challenge set created_at=now()-interval '10 minutes',expires_at=now()-interval '5 minutes' where id=$1", [expired.challengeId]); |
| 324 | assert.equal((await providerRequest('/v1/auth/phone/verify-otp', expired)).status, 401); |
| 325 | const bounded = await otp(account.contact, 'login'); |
| 326 | const wrong = bounded.code === '000000' ? '000001' : '000000'; |
| 327 | for (let i = 0; i < 5; i++) assert.equal((await providerRequest('/v1/auth/phone/verify-otp', { ...bounded, code: wrong })).status, 401); |
| 328 | assert.equal((await providerRequest('/v1/auth/phone/verify-otp', bounded)).status, 401); |
| 329 | assert.equal((await pool.query('select attempts from auth_phone_challenge where id=$1', [bounded.challengeId])).rows[0].attempts, 5); |
| 330 | const missing = freshPhone(); |
| 331 | const before = smsMessages.length; |
| 332 | const absent = await providerRequest('/v1/auth/phone/request-otp', { phone: missing, purpose: 'recovery' }); |
| 333 | assert.equal(absent.status, 202); |
| 334 | challengeIds.add(absent.body.challengeId); |
| 335 | assert.equal(smsMessages.length, before); |
| 336 | assert.equal((await providerRequest('/v1/auth/phone/verify-otp', { challengeId: absent.body.challengeId, code: '000000', newPassword: password })).status, 401); |
| 337 | const recovery = await otp(account.contact, 'recovery'); |
| 338 | const recovered = await providerRequest('/v1/auth/phone/verify-otp', { ...recovery, newPassword: password }); |
| 339 | assert.equal(recovered.status, 200); |
| 340 | assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: authenticated.body.refreshToken })).status, 401); |
| 341 | assert.equal((await providerRequest('/v1/auth/login', { phone: account.contact, password: replacement })).status, 401); |
| 342 | assert.equal((await providerRequest('/v1/auth/login', { phone: account.contact, password })).status, 200); |
| 343 | const disabledProof = await otp(account.contact, 'login'); |
| 344 | await pool.query('update app_user set disabled_at=now() where id=$1', [account.id]); |
| 345 | assert.equal((await providerRequest('/v1/auth/phone/verify-otp', disabledProof)).status, 401); |
| 346 | assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: recovered.body.refreshToken })).status, 401); |
| 347 | }); |
| 348 | |
| 349 | test('two phone challenges and competing refresh requests serialize without token reuse or deadlock', async () => { |
| 350 | const account = await phoneAccount(); |
| 351 | const first = await otp(account.contact); |
| 352 | const second = await otp(account.contact); |
| 353 | const verified = await Promise.all([first, second].map((proof) => providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password }))); |
| 354 | assert.deepEqual(verified.map((response) => response.status).sort(), [200, 401]); |
| 355 | const tokens = verified.find((response) => response.status === 200).body; |
| 356 | const refreshed = await Promise.all([1, 2].map(() => providerRequest('/v1/auth/refresh', { refreshToken: tokens.refreshToken }))); |
| 357 | assert.deepEqual(refreshed.map((response) => response.status).sort(), [200, 401]); |
| 358 | const active = refreshed.find((response) => response.status === 200).body; |
| 359 | assert.equal((await pool.query('select count(*)::int as n from auth_session where user_id=$1 and revoked_at is null', [account.id])).rows[0].n, 1); |
| 360 | assert.equal((await request('/v1/profile', undefined, { method: 'GET', token: tokens.accessToken })).status, 401); |
| 361 | assert.equal((await request('/v1/profile', undefined, { method: 'GET', token: active.accessToken })).status, 200); |
| 362 | assert.equal((await providerRequest('/v1/auth/logout', { refreshToken: active.refreshToken })).status, 204); |
| 363 | assert.equal((await providerRequest('/v1/auth/logout', { refreshToken: 'invalid-synthetic-proof' })).status, 204); |
| 364 | assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: active.refreshToken })).status, 401); |
| 365 | }); |
| 366 | |
| 367 | test('refresh expiry and logout with expired access proof preserve opaque refresh revocation', async () => { |
| 368 | const account = await phoneAccount(); |
| 369 | const proof = await otp(account.contact); |
| 370 | const verified = await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password }); |
| 371 | assert.equal(verified.status, 200); |
| 372 | const identity = jwt.verify(verified.body.accessToken, jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' }); |
| 373 | assert.equal(identity.exp - identity.iat, 900); |
| 374 | await pool.query("update auth_session set created_at=now()-interval '31 days',expires_at=now()-interval '1 day' where id=$1", [identity.sid]); |
| 375 | assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: verified.body.refreshToken })).status, 401); |
| 376 | const login = await providerRequest('/v1/auth/login', { phone: account.contact, password }); |
| 377 | assert.equal(login.status, 200); |
| 378 | const active = jwt.verify(login.body.accessToken, jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' }); |
| 379 | const expiredAccess = jwt.sign({ sub: active.sub, sid: active.sid, aud: 'lifemate-api' }, jwtSecret, { issuer: 'lifemate', expiresIn: -1 }); |
| 380 | assert.equal((await request('/v1/profile', undefined, { method: 'GET', token: expiredAccess })).status, 401); |
| 381 | assert.equal((await request('/v1/auth/logout', { refreshToken: login.body.refreshToken }, { token: expiredAccess })).status, 204); |
| 382 | assert.equal((await pool.query('select revoked_at from auth_session where id=$1', [active.sid])).rows[0].revoked_at instanceof Date, true); |
| 383 | assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: login.body.refreshToken })).status, 401); |
| 384 | }); |
| 385 | |
| 386 | test('phone-only family invites require the matching verified contact and keep the inviter-selected role', async () => { |
| 387 | const parent = await emailAccount(); |
| 388 | assert.equal((await providerRequest('/v1/auth/verify-email', { token: parent.token, newPassword: password })).status, 204); |
| 389 | const parentLogin = await request('/v1/auth/login', { email: parent.contact, password }); |
| 390 | assert.equal(parentLogin.status, 200); |
| 391 | const phone = await phoneAccount(); |
| 392 | const proof = await otp(phone.contact); |
| 393 | const verified = await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password }); |
| 394 | assert.equal(verified.status, 200); |
| 395 | const family = await request('/v1/families', { name: 'Synthetic Phone Family', role: 'parent_guardian' }, { token: parentLogin.body.accessToken }); |
| 396 | assert.equal(family.status, 201); |
| 397 | familyIds.add(family.body.id); |
| 398 | const invitation = await request(`/v1/families/${family.body.id}/invitations`, { phone: phone.contact, role: 'teen_minor' }, { token: parentLogin.body.accessToken }); |
| 399 | assert.equal(invitation.status, 201); |
| 400 | assert.ok(invitation.body.invitationToken); |
| 401 | assert.equal(invitation.body.invitationLink.startsWith('https://app.example.test/'), true); |
| 402 | const stored = (await pool.query('select invited_email_normalized,invited_phone_normalized,token_digest from family_invitation where id=$1', [invitation.body.id])).rows[0]; |
| 403 | assert.equal(stored.invited_email_normalized, null); |
| 404 | assert.equal(stored.invited_phone_normalized, phone.contact); |
| 405 | assert.equal(stored.token_digest === tokenDigest(invitation.body.invitationToken), true); |
| 406 | assert.equal((await request('/v1/invitations/accept', { token: invitation.body.invitationToken }, { token: parentLogin.body.accessToken })).status, 403); |
| 407 | // Existing session remains active when the fixture removes the verification timestamp. |
| 408 | await pool.query('update app_user set phone_verified_at=null where id=$1', [phone.id]); |
| 409 | assert.equal((await request('/v1/invitations/accept', { token: invitation.body.invitationToken }, { token: verified.body.accessToken })).status, 403); |
| 410 | await pool.query('update app_user set phone_verified_at=now() where id=$1', [phone.id]); |
| 411 | assert.equal((await request('/v1/invitations/accept', { token: invitation.body.invitationToken, role: 'parent_guardian' }, { token: verified.body.accessToken })).status, 204); |
| 412 | const member = (await pool.query('select role,is_admin from family_membership where family_id=$1 and user_id=$2', [family.body.id, phone.id])).rows[0]; |
| 413 | assert.equal(member.role, 'teen_minor'); |
| 414 | assert.equal(member.is_admin, false); |
| 415 | assert.equal((await request(`/v1/families/${family.body.id}/invitations`, { phone: freshPhone(), role: 'parent_guardian' }, { token: verified.body.accessToken })).status, 403); |
| 416 | const emailInvite = await request(`/v1/families/${family.body.id}/invitations`, { email: freshEmail(), role: 'adult_member' }, { token: parentLogin.body.accessToken }); |
| 417 | assert.equal(emailInvite.status, 201); |
| 418 | assert.ok(emailInvite.body.invitationToken); |
| 419 | await until(() => output.split('\n').some((line) => { |
| 420 | try { const event = JSON.parse(line); return event.type === 'auth_delivery' && event.attemptId === emailInvite.body.id && event.status === 'failed'; } |
| 421 | catch { return false; } |
| 422 | })); |
| 423 | assert.equal((await pool.query('select 1 from family_invitation where id=$1 and status=\'pending\'', [emailInvite.body.id])).rowCount, 1); |
| 424 | assert.equal(errors.includes(invitation.body.invitationToken), false); |
| 425 | assert.equal(output.includes(invitation.body.invitationToken), false); |
| 426 | assert.equal(errors.includes(emailInvite.body.invitationToken), false); |
| 427 | assert.equal(output.includes(emailInvite.body.invitationToken), false); |
| 428 | }); |
| 429 | |
| 430 | test('provider retry uses one idempotency key and never exposes a rejected provider payload', async () => { |
| 431 | const attempts = []; |
| 432 | const provider = createEmailProvider({ |
| 433 | env: { NODE_ENV: 'production', EMAIL_FROM: 'fixture@example.test', RESEND_API_KEY: 'synthetic-local-not-a-real-key' }, |
| 434 | async fetchImpl(_url, options) { |
| 435 | attempts.push(options.headers['Idempotency-Key']); |
| 436 | return { ok: attempts.length === 3, status: 503 }; |
| 437 | }, |
| 438 | }); |
| 439 | const result = await safelyDeliver(provider, { to: 'synthetic@example.test', subject: 'Synthetic', text: 'Synthetic fixture' }, { env: { NODE_ENV: 'test' } }); |
| 440 | assert.equal(result.delivered, true); |
| 441 | assert.equal(attempts.length, 3); |
| 442 | assert.equal(new Set(attempts).size, 1); |
| 443 | }); |
| 444 | |
| 445 | test('email ownership verification cannot enable a pre-registered attacker password', async () => { |
| 446 | const account = await emailAccount(); |
| 447 | const duplicate = await providerRequest('/v1/auth/register', { email: account.contact, displayName: 'Real Owner', password: replacement }); |
| 448 | assert.equal(duplicate.status, 202); |
| 449 | assert.deepEqual(duplicate.body, { accepted: true }); |
| 450 | const oldHash = (await pool.query('select password_hash from auth_credential where user_id=$1', [account.id])).rows[0].password_hash; |
| 451 | assert.equal(await argon2.verify(oldHash, password), true); |
| 452 | assert.equal((await providerRequest('/v1/auth/verify-email', { token: account.token })).status, 400); |
| 453 | assert.equal((await pool.query('select email_verified_at from app_user where id=$1', [account.id])).rows[0].email_verified_at, null); |
| 454 | assert.equal((await providerRequest('/v1/auth/verify-email', { token: account.token, newPassword: replacement })).status, 204); |
| 455 | assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password })).status, 401); |
| 456 | assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password: replacement })).status, 200); |
| 457 | }); |
| 458 | |
| 459 | test('login cannot issue a session using a stale password after concurrent recovery commits', async () => { |
| 460 | const account = await emailAccount(); |
| 461 | assert.equal((await providerRequest('/v1/auth/verify-email', { token: account.token, newPassword: password })).status, 204); |
| 462 | const before = mail.length; |
| 463 | assert.equal((await providerRequest('/v1/auth/forgot-password', { email: account.contact })).status, 200); |
| 464 | const resetMessage = await until(() => mail.slice(before).find((item) => item.to === account.contact)); |
| 465 | const reset = new URL(resetMessage.text.match(/https:\/\/\S+/)[0]).searchParams.get('token'); |
| 466 | const barrier = await pool.connect(); |
| 467 | let recovery; |
| 468 | let staleLogin; |
| 469 | try { |
| 470 | await barrier.query('begin'); |
| 471 | await barrier.query('select id from app_user where id=$1 for update', [account.id]); |
| 472 | const blocked = async (count) => (await pool.query( |
| 473 | "select count(*)::int as n from pg_stat_activity where application_name=$1 and wait_event_type='Lock' and query='select 1 from app_user where id=$1 and disabled_at is null for update'", [applicationName], |
| 474 | )).rows[0].n >= count; |
| 475 | // Queue real recovery first, then let real login verify the old hash before it blocks. |
| 476 | recovery = providerRequest('/v1/auth/reset-password', { token: reset, newPassword: replacement }); |
| 477 | await until(() => blocked(1)); |
| 478 | staleLogin = providerRequest('/v1/auth/login', { email: account.contact, password }); |
| 479 | await until(() => blocked(2)); |
| 480 | await barrier.query('commit'); |
| 481 | assert.equal((await recovery).status, 204); |
| 482 | assert.equal((await staleLogin).status, 401); |
| 483 | } finally { |
| 484 | await barrier.query('rollback').catch(() => {}); |
| 485 | barrier.release(); |
| 486 | await Promise.allSettled([recovery, staleLogin].filter(Boolean)); |
| 487 | } |
| 488 | assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password: replacement })).status, 200); |
| 489 | }); |
| 490 | |
| 491 | test('disabled SMS gates verification uniformly before reading or consuming a pending proof', async () => { |
| 492 | const account = await phoneAccount(); |
| 493 | const proof = await otp(account.contact); |
| 494 | const known = await request('/v1/auth/phone/verify-otp', { ...proof, newPassword: password }); |
| 495 | const malformed = await request('/v1/auth/phone/verify-otp', { challengeId: 'synthetic-invalid', code: 'bad' }); |
| 496 | assert.equal(known.status, 503); |
| 497 | assert.equal(malformed.status, 503); |
| 498 | assert.deepEqual(known.body, malformed.body); |
| 499 | const stored = (await pool.query('select attempts,used_at from auth_phone_challenge where id=$1', [proof.challengeId])).rows[0]; |
| 500 | assert.equal(stored.attempts, 0); |
| 501 | assert.equal(stored.used_at, null); |
| 502 | }); |
| 503 | |
| 504 | test('phone OTP cooldown applies equally to known and unknown contacts across purposes', async () => { |
| 505 | const account = await phoneAccount(); |
| 506 | const unknown = freshPhone(); |
| 507 | for (const contact of [account.contact, unknown]) { |
| 508 | const first = await providerRequest('/v1/auth/phone/request-otp', { phone: contact, purpose: 'verify' }); |
| 509 | assert.equal(first.status, 202); |
| 510 | challengeIds.add(first.body.challengeId); |
| 511 | const blocked = await providerRequest('/v1/auth/phone/request-otp', { phone: contact, purpose: 'recovery' }); |
| 512 | assert.equal(blocked.status, 429); |
| 513 | assert.equal(Number(blocked.headers.get('Retry-After')) > 0, true); |
| 514 | } |
| 515 | }); |
| 516 | |
| 517 | test('Persian and Iranian phone representations normalize consistently without binding a second unverified channel', async () => { |
| 518 | const local = `0900${crypto.randomInt(1000000, 9999999)}`; |
| 519 | const normalized = '+98' + local.slice(1); |
| 520 | recipients.add(normalized); |
| 521 | const persian = local.replace(/\d/g, (digit) => String.fromCharCode(0x6f0 + Number(digit))); |
| 522 | assert.equal((await providerRequest('/v1/auth/register', { phone: persian, password, displayName: 'Synthetic Persian Phone' })).status, 202); |
| 523 | const id = await identify(normalized); |
| 524 | const duplicate = await providerRequest('/v1/auth/register', { phone: `00${normalized.slice(1)}`, password: replacement, displayName: 'Must Not Replace' }); |
| 525 | assert.equal(duplicate.status, 202); |
| 526 | assert.equal((await pool.query('select count(*)::int as n from app_user where phone_normalized=$1', [normalized])).rows[0].n, 1); |
| 527 | assert.equal((await providerRequest('/v1/auth/register', { email: freshEmail(), phone: normalized, password, displayName: 'Cannot Bind Second Contact' })).status, 400); |
| 528 | assert.equal((await pool.query('select email_normalized from app_user where id=$1', [id])).rows[0].email_normalized, null); |
| 529 | }); |
| 530 | |
| 531 | test('archived families and revoked inviters cannot authorize outstanding invitations', async () => { |
| 532 | for (const revoke of ['archive', 'admin', 'membership']) { |
| 533 | const fixture = await familyFixture(); |
| 534 | const invitation = await phoneInvitation(fixture); |
| 535 | if (revoke === 'archive') await pool.query('update family_workspace set archived_at=now() where id=$1', [fixture.familyId]); |
| 536 | if (revoke === 'admin') await pool.query('update family_membership set is_admin=false where family_id=$1 and user_id=$2', [fixture.familyId, fixture.parent.id]); |
| 537 | if (revoke === 'membership') await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [fixture.familyId, fixture.parent.id]); |
| 538 | const accepted = await request('/v1/invitations/accept', { token: invitation.invitationToken }, { token: fixture.child.accessToken }); |
| 539 | assert.equal(accepted.status, 400); |
| 540 | assert.equal((await pool.query('select 1 from family_membership where family_id=$1 and user_id=$2', [fixture.familyId, fixture.child.id])).rowCount, 0); |
| 541 | if (revoke === 'archive') { |
| 542 | assert.equal((await request(`/v1/families/${fixture.familyId}/members`, undefined, { method: 'GET', token: fixture.parent.accessToken })).status, 403); |
| 543 | assert.equal((await request(`/v1/families/${fixture.familyId}/invitations`, { phone: freshPhone(), role: 'teen_minor' }, { token: fixture.parent.accessToken })).status, 403); |
| 544 | } |
| 545 | } |
| 546 | }); |
| 547 | |
| 548 | test('a former admin rejoining as a child cannot resurrect admin powers or override an active role', async () => { |
| 549 | const fixture = await familyFixture(); |
| 550 | await pool.query("insert into family_membership(family_id,user_id,role,is_admin,ended_at) values($1,$2,'adult_member',true,now())", [fixture.familyId, fixture.child.id]); |
| 551 | const invitation = await phoneInvitation(fixture); |
| 552 | assert.equal((await request('/v1/invitations/accept', { token: invitation.invitationToken }, { token: fixture.child.accessToken })).status, 204); |
| 553 | const row = (await pool.query('select role,is_admin from family_membership where family_id=$1 and user_id=$2', [fixture.familyId, fixture.child.id])).rows[0]; |
| 554 | assert.equal(row.role, 'teen_minor'); |
| 555 | assert.equal(row.is_admin, false); |
| 556 | assert.equal((await request(`/v1/families/${fixture.familyId}/invitations`, { phone: freshPhone(), role: 'parent_guardian' }, { token: fixture.child.accessToken })).status, 403); |
| 557 | // An older pending alternative grant must not change an already-active membership. |
| 558 | const alternateToken = crypto.randomBytes(32).toString('base64url'); |
| 559 | await pool.query("insert into family_invitation(family_id,invited_phone_normalized,intended_role,token_digest,invited_by,expires_at) values($1,$2,'parent_guardian',$3,$4,now()+interval '7 days')", [fixture.familyId, fixture.child.contact, tokenDigest(alternateToken), fixture.parent.id]); |
| 560 | assert.equal((await request('/v1/invitations/accept', { token: alternateToken }, { token: fixture.child.accessToken })).status, 409); |
| 561 | assert.equal((await pool.query('select role from family_membership where family_id=$1 and user_id=$2', [fixture.familyId, fixture.child.id])).rows[0].role, 'teen_minor'); |
| 562 | }); |
| 563 | |
| 564 | test('family management persists edits and securely revokes guardians, membership and archived access', async () => { |
| 565 | const fixture = await familyFixture(); |
| 566 | const invitation = await phoneInvitation(fixture); |
| 567 | assert.equal((await request('/v1/invitations/accept', { token: invitation.invitationToken }, { token: fixture.child.accessToken })).status, 204); |
| 568 | const path = `/v1/families/${fixture.familyId}`; |
| 569 | assert.equal((await request(path, { name: 'Unauthorized Rename' }, { method: 'PATCH', token: fixture.child.accessToken })).status, 403); |
| 570 | assert.equal((await request(path, { name: 'Renamed Synthetic Family' }, { method: 'PATCH', token: fixture.parent.accessToken })).status, 200); |
| 571 | const found = await request(path, undefined, { method: 'GET', token: fixture.child.accessToken }); |
| 572 | assert.equal(found.status, 200); |
| 573 | assert.equal(found.body.name, 'Renamed Synthetic Family'); |
| 574 | const relation = { guardianUserId: fixture.parent.id, minorUserId: fixture.child.id }; |
| 575 | assert.equal((await request(`${path}/guardians`, relation, { token: fixture.parent.accessToken })).status, 204); |
| 576 | assert.equal((await request(`${path}/guardians`, relation, { method: 'DELETE', token: fixture.child.accessToken })).status, 403); |
| 577 | assert.equal((await request(`${path}/guardians`, relation, { method: 'DELETE', token: fixture.parent.accessToken })).status, 204); |
| 578 | assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3', [fixture.familyId, fixture.parent.id, fixture.child.id])).rows[0].active, false); |
| 579 | assert.equal((await request(`${path}/guardians`, relation, { token: fixture.parent.accessToken })).status, 204); |
| 580 | assert.equal((await request(`${path}/members/${fixture.parent.id}`, undefined, { method: 'DELETE', token: fixture.parent.accessToken })).status, 409); |
| 581 | assert.equal((await request(`${path}/members/${fixture.child.id}`, undefined, { method: 'DELETE', token: fixture.parent.accessToken })).status, 204); |
| 582 | assert.equal((await request(path, undefined, { method: 'GET', token: fixture.child.accessToken })).status, 403); |
| 583 | assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3', [fixture.familyId, fixture.parent.id, fixture.child.id])).rows[0].active, false); |
| 584 | const outstanding = await phoneInvitation(fixture); |
| 585 | assert.equal((await request(path, undefined, { method: 'DELETE', token: fixture.parent.accessToken })).status, 204); |
| 586 | assert.equal((await request(path, undefined, { method: 'GET', token: fixture.parent.accessToken })).status, 403); |
| 587 | assert.equal((await request('/v1/invitations/accept', { token: outstanding.invitationToken }, { token: fixture.child.accessToken })).status, 400); |
| 588 | const archived = (await pool.query('select archived_at from family_workspace where id=$1', [fixture.familyId])).rows[0]; |
| 589 | assert.ok(archived.archived_at); |
| 590 | }); |