LifeMate — Personal, Family & Learning Companion

test/personal-notification-settings
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 99 lines 5.39 KB
Raw
1 // Only loopback PostgreSQL and synthetic identities; no delivery provider is called.
2 import test, { after } from 'node:test';
3 import assert from 'node:assert/strict';
4 import crypto from 'node:crypto';
5 import express from 'express';
6 import pg from 'pg';
7 import { createAuthRouter } from '../src/auth_router.js';
8
9 const url = new URL(process.env.DATABASE_URL);
10 assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname));
11 assert.match(url.pathname, /^\/(?:lifeguide_roles_source_[a-f0-9]{16}|lifemate_ci|lifeguide_\w*test\w*)$/);
12 const marker = 'auth-expiry-' + crypto.randomUUID();
13 const pool = new pg.Pool({ connectionString: url.href, application_name: marker });
14 const secret = 'synthetic-auth-expiry-fixture-not-a-live-key-2026';
15 const users = [];
16 const app = express();
17 app.use(express.json());
18 app.use('/auth', createAuthRouter({ pool, jwtSecret: secret, env: { NODE_ENV: 'test' },
19 auth: (_req, _res, next) => next(),
20 emailProvider: { configured: false },
21 smsProvider: { configured: true, status: 'TEST_ONLY', async sendOtp() { assert.fail('No SMS should be sent'); } },
22 }));
23 const server = app.listen(0, '127.0.0.1');
24 await new Promise(resolve => server.once('listening', resolve));
25 const base = 'http://127.0.0.1:' + server.address().port + '/auth';
26 after(async () => {
27 await new Promise(resolve => server.close(resolve));
28 await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
29 await pool.end();
30 });
31
32 async function owner() {
33 const id = crypto.randomUUID(); users.push(id);
34 await pool.query("insert into app_user(id,identity_subject,email_normalized,phone_verified_at) values($1,$2,$3,now())",
35 [id, 'synthetic-expiry:' + id, 'expiry-' + id + '@example.test']);
36 return id;
37 }
38 async function request(path, body) {
39 return fetch(base + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(10000) });
40 }
41 async function observedWait() {
42 for (let n = 0; n < 250; n++) {
43 const r = await pool.query("select 1 from pg_stat_activity where application_name=$1 and wait_event_type='Lock'", [marker]);
44 if (r.rowCount) return;
45 await new Promise(resolve => setTimeout(resolve, 10));
46 }
47 assert.fail('Expected an actual PostgreSQL row-lock wait');
48 }
49 async function blockedRequest(userId, operation, expire) {
50 const blocker = await pool.connect();
51 try {
52 await blocker.query('begin');
53 await blocker.query('select 1 from app_user where id=$1 for update', [userId]);
54 const response = operation();
55 await observedWait();
56 // Expire after the request transaction began, without a timing-sensitive sleep.
57 await expire();
58 await blocker.query('commit');
59 return await response;
60 } finally { await blocker.query('rollback'); blocker.release(); }
61 }
62
63 for (const kind of ['email_verification', 'password_reset']) {
64 test(kind + ' expires during an observed account-row wait and cannot be consumed', async () => {
65 const userId = await owner(), token = crypto.randomBytes(32).toString('base64url');
66 await pool.query("insert into auth_token(user_id,kind,token_digest,expires_at) values($1,$2,$3,now()+interval '1 hour')",
67 [userId, kind, crypto.createHash('sha256').update(token).digest('hex')]);
68 const response = await blockedRequest(userId,
69 () => request(kind === 'email_verification' ? '/verify-email' : '/reset-password', { token, newPassword: 'SyntheticReplacement123!' }),
70 () => pool.query("update auth_token set expires_at=clock_timestamp() where user_id=$1", [userId]));
71 assert.equal(response.status, 400);
72 assert.equal((await response.json()).error, 'invalid_or_expired_token');
73 assert.equal((await pool.query('select used_at from auth_token where user_id=$1', [userId])).rows[0].used_at, null);
74 });
75 }
76
77 test('refresh expiry after an observed account-row wait cannot mint a replacement session', async () => {
78 const userId = await owner(), raw = crypto.randomBytes(32).toString('base64url');
79 await pool.query("insert into auth_session(user_id,refresh_digest,expires_at) values($1,$2,now()+interval '1 hour')",
80 [userId, crypto.createHash('sha256').update(raw).digest('hex')]);
81 const response = await blockedRequest(userId, () => request('/refresh', { refreshToken: raw }),
82 () => pool.query("update auth_session set expires_at=clock_timestamp() where user_id=$1", [userId]));
83 assert.equal(response.status, 401);
84 const rows = await pool.query('select revoked_at from auth_session where user_id=$1', [userId]);
85 assert.equal(rows.rowCount, 1);
86 assert.equal(rows.rows[0].revoked_at, null);
87 });
88
89 test('OTP expiry after an observed account-row wait neither authenticates nor consumes the challenge', async () => {
90 const userId = await owner(), id = crypto.randomUUID(), code = '123456';
91 const digest = crypto.createHmac('sha256', secret).update(`otp:${id}:${code}`).digest('hex');
92 await pool.query("insert into auth_phone_challenge(id,user_id,purpose,code_digest,expires_at) values($1,$2,'login',$3,now()+interval '5 minutes')", [id, userId, digest]);
93 const response = await blockedRequest(userId, () => request('/phone/verify-otp', { challengeId: id, code }),
94 () => pool.query("update auth_phone_challenge set expires_at=clock_timestamp() where id=$1", [id]));
95 assert.equal(response.status, 401);
96 const row = (await pool.query('select attempts,used_at from auth_phone_challenge where id=$1', [id])).rows[0];
97 assert.equal(row.used_at, null);
98 assert.equal(row.attempts, 0);
99 });