LifeMate — Personal, Family & Learning Companion

feat/flutter-mobile-navigation
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
mjs 156 lines 7.01 KB
Raw
1 #!/usr/bin/env node
2 // Real loopback HTTPS only. Temporary CA/private keys are removed after the suite.
3 import assert from 'node:assert/strict';
4 import { spawn, execFile } from 'node:child_process';
5 import { promisify } from 'node:util';
6 import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
7 import https from 'node:https';
8 import { tmpdir } from 'node:os';
9 import { join } from 'node:path';
10 import { fileURLToPath } from 'node:url';
11 import { after, before, test } from 'node:test';
12
13 const runFile = promisify(execFile);
14 const smoke = fileURLToPath(new URL('./reachability-smoke.mjs', import.meta.url));
15 let directory;
16 let caFile;
17 const certificates = {};
18
19 before(async () => {
20 directory = await mkdtemp(join(tmpdir(), 'lifeguide-smoke-tls-'));
21 try {
22 caFile = join(directory, 'ca.pem');
23 const caKey = join(directory, 'ca-key.pem');
24 await runFile('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1',
25 '-keyout', caKey, '-out', caFile, '-subj', '/CN=LifeGuide local regression CA',
26 '-addext', 'basicConstraints=critical,CA:TRUE']);
27 for (const [name, san] of [['matching', 'IP:127.0.0.1'], ['mismatch', 'DNS:wrong.invalid']]) {
28 const keyFile = join(directory, `${name}-key.pem`);
29 const requestFile = join(directory, `${name}.csr`);
30 const certFile = join(directory, `${name}.pem`);
31 const extensionsFile = join(directory, `${name}.ext`);
32 await writeFile(extensionsFile, `subjectAltName=${san}\nextendedKeyUsage=serverAuth\n`);
33 await runFile('openssl', ['req', '-new', '-newkey', 'rsa:2048', '-nodes',
34 '-keyout', keyFile, '-out', requestFile, '-subj', '/CN=LifeGuide loopback fixture']);
35 await runFile('openssl', ['x509', '-req', '-in', requestFile, '-CA', caFile,
36 '-CAkey', caKey, '-CAcreateserial', '-days', '1', '-out', certFile,
37 '-extfile', extensionsFile]);
38 certificates[name] = { key: await readFile(keyFile), cert: await readFile(certFile) };
39 }
40 } catch (error) {
41 await rm(directory, { recursive: true, force: true });
42 throw error;
43 }
44 });
45
46 after(async () => {
47 if (directory) await rm(directory, { recursive: true, force: true });
48 });
49
50 async function exercise({ certificate = 'matching', trustCa = false, disableTls = false, allowWrite = false } = {}) {
51 const requests = [];
52 const sockets = new Set();
53 const server = https.createServer(certificates[certificate], (req, res) => {
54 requests.push({ method: req.method, path: req.url, authorization: Boolean(req.headers.authorization) });
55 res.setHeader('Content-Type', 'application/json');
56 if (req.url === '/health') res.end(JSON.stringify({ status: 'ok' }));
57 else if (req.url === '/') {
58 res.setHeader('Content-Type', 'text/html');
59 res.end('<!doctype html><title>LifeGuide local fixture</title>');
60 } else if (req.url === '/manifest.json') res.end(JSON.stringify({ display: 'standalone' }));
61 else if (req.url === '/config.json') {
62 res.setHeader('Cache-Control', 'no-store');
63 res.end(JSON.stringify({ apiBaseUrl: '/api' }));
64 } else {
65 res.statusCode = 401;
66 res.end(JSON.stringify({ error: 'authentication_required' }));
67 }
68 });
69 server.on('connection', socket => {
70 sockets.add(socket);
71 socket.on('close', () => sockets.delete(socket));
72 });
73 await new Promise((resolve, reject) => {
74 server.once('error', reject);
75 server.listen(0, '127.0.0.1', resolve);
76 });
77 try {
78 const env = { PATH: process.env.PATH };
79 if (trustCa) env.ROOT_CA_FILE = caFile;
80 // Adversarial inherited setting: never used for the trusted acceptance case.
81 if (disableTls) env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
82 if (allowWrite) {
83 env.SMOKE_ALLOW_SYNTHETIC_WRITE = 'yes';
84 env.SMOKE_EMAIL = 'loopback-fixture@lifeguide.test';
85 env.SMOKE_PASSWORD = 'local-synthetic-fixture-password';
86 }
87 const child = spawn(process.execPath, [smoke, `https://127.0.0.1:${server.address().port}`], {
88 env, stdio: ['ignore', 'pipe', 'pipe'],
89 });
90 let stdout = '';
91 let stderr = '';
92 child.stdout.on('data', chunk => { stdout += chunk; });
93 child.stderr.on('data', chunk => { stderr += chunk; });
94 const timer = setTimeout(() => child.kill('SIGKILL'), 20000);
95 let code;
96 try {
97 code = await new Promise((resolve, reject) => {
98 child.once('error', reject);
99 child.once('close', resolve);
100 });
101 } finally {
102 clearTimeout(timer);
103 }
104 assert.notEqual(code, null, 'Loopback smoke timed out');
105 return { code, report: JSON.parse(stdout), stderr, requests };
106 } finally {
107 for (const socket of sockets) socket.destroy();
108 await new Promise(resolve => server.close(resolve));
109 }
110 }
111
112 function assertTlsFailure(outcome) {
113 assert.equal(outcome.code, 1, 'Unverified TLS must fail the smoke process');
114 assert.equal(outcome.report.results.some(result => result.name === 'TLS' && result.status === 'PASS'), false,
115 'Unverified TLS must never be reported as PASS');
116 assert.equal(outcome.report.results[0]?.status, 'FAIL');
117 assert.equal(outcome.requests.some(request => request.authorization || request.method !== 'GET'
118 || request.path.startsWith('/api/v1/auth/')), false, 'TLS failure must precede auth and writes');
119 }
120
121 test('trusted local CA and matching hostname pass read-only smoke without TLS-disable', async () => {
122 const outcome = await exercise({ trustCa: true });
123 assert.equal(outcome.code, 0);
124 assert.equal(outcome.report.results.find(result => result.name === 'TLS')?.status, 'PASS');
125 assert.equal(outcome.report.results.some(result => result.status === 'FAIL'), false);
126 assert.equal(outcome.report.results.find(result => result.name === 'API round-trip')?.status, 'UNVERIFIED');
127 assert.deepEqual(outcome.requests.map(request => request.path),
128 ['/health', '/', '/manifest.json', '/config.json', '/api/v1/plan-items']);
129 assert.equal(outcome.requests.some(request => request.authorization || request.method !== 'GET'), false);
130 assert.equal(outcome.stderr, '');
131 });
132
133 test('untrusted CA fails before opted-in synthetic auth or writes', async () => {
134 const outcome = await exercise({ allowWrite: true });
135 assertTlsFailure(outcome);
136 assert.equal(outcome.requests.length, 0);
137 });
138
139 test('inherited NODE_TLS_REJECT_UNAUTHORIZED=0 cannot produce a false TLS PASS', async t => {
140 const outcome = await exercise({ disableTls: true });
141 t.diagnostic(`Local untrusted fixture: exit=${outcome.code}, TLS=${outcome.report.results.find(result => result.name === 'TLS')?.status ?? 'not recorded'}`);
142 assertTlsFailure(outcome);
143 assert.equal(outcome.requests.length, 0);
144 });
145
146 test('inherited TLS-disable cannot reach opted-in synthetic auth or writes', async () => {
147 const outcome = await exercise({ disableTls: true, allowWrite: true });
148 assertTlsFailure(outcome);
149 assert.equal(outcome.requests.length, 0);
150 });
151
152 test('trusted CA with hostname mismatch fails before opted-in synthetic auth or writes', async () => {
153 const outcome = await exercise({ certificate: 'mismatch', trustCa: true, allowWrite: true });
154 assertTlsFailure(outcome);
155 assert.equal(outcome.requests.length, 0);
156 });