LifeMate — Personal, Family & Learning Companion
feat(auth): add opt-in SMS adapter and isolate test delivery credentials
Codex committed
Oct 8, 2026 at 16:30 UTC
c85f863ece6c1c8d4ec096c710772c8352d72159
8 files changed
+206
-8
backend/package.json
+1
-1
@@ -5,7 +5,7 @@
5
"type": "module",
6
"scripts": {
7
"start": "node src/entrypoint.js",
8
- "test": "node --test tests/*.test.js",
8
+ "test": "node scripts/test.js",
9
"migrate": "node scripts/migrate.js",
10
"check": "node scripts/check-syntax.js"
11
},
backend/scripts/test.js
new
+17
@@ -0,0 +1,17 @@
1
+import { readdirSync } from 'node:fs';
2
+import { spawnSync } from 'node:child_process';
3
+
4
+// Tests never inherit an operator's live delivery or AI configuration.
5
+// Database/JWT fixture inputs remain available; individual fixtures can inject local providers.
6
+const env = { ...process.env, NODE_ENV: 'test', SMS_PROVIDER: 'disabled' };
7
+for (const key of ['SMS_PROVIDER_URL', 'SMS_PROVIDER_TOKEN', 'EMAIL_FROM', 'RESEND_API_KEY',
8
+ 'SMTP_HOST', 'SMTP_PORT', 'SMTP_USER', 'SMTP_PASSWORD', 'AI_API_KEY', 'AI_BASE_URL', 'AI_MODEL', 'OPENAI_API_KEY']) env[key] = '';
9
+env.SMTP_SECURE = 'false';
10
+const files = readdirSync(new URL('../tests/', import.meta.url))
11
+ .filter((file) => !file.startsWith('.') && file.endsWith('.test.js')).sort()
12
+ .map((file) => `tests/${file}`);
13
+const result = spawnSync(process.execPath, ['--test', ...process.argv.slice(2), ...files], {
14
+ cwd: new URL('../', import.meta.url), env, stdio: 'inherit',
15
+});
16
+if (result.error) throw new Error('test_runner_start_failed');
17
+process.exit(result.status ?? 1);
backend/src/auth_delivery.js
+50
-3
@@ -8,9 +8,56 @@ export class SmsProvider {
8
async sendOtp(_message) { return { delivered: false, reason: 'provider_unconfigured' }; }
9
}
10
11
-export function createSmsProvider() {
12
- // No SMS carrier is selected or enabled. A real adapter needs explicit setup.
13
- return new SmsProvider();
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 } = {}) {
backend/tests/auth_delivery.test.js
+1
@@ -59,6 +59,7 @@ before(async () => {
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: '',
backend/tests/online_acceptance.test.js
+1
-1
@@ -32,7 +32,7 @@ async function startApi() {
32
env: { ...process.env, NODE_ENV: 'test', DATABASE_URL: databaseUrl, JWT_SECRET: secret, PORT: String(port),
33
RATE_LIMIT_GENERAL_MAX: '2000', RATE_LIMIT_AUTH_MAX: '2000', ENABLE_SENSITIVE_FEATURES: 'false',
34
EMAIL_FROM: '', SMTP_HOST: '', SMTP_PORT: '', RESEND_API_KEY: '',
35
- SMS_PROVIDER: '', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '' },
35
+ SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '' },
36
stdio: ['ignore', 'pipe', 'pipe'],
37
});
38
apiProcess.stdout.on('data', (chunk) => { output += chunk.toString(); });
backend/tests/request_safety.test.js
+4
-2
@@ -32,6 +32,8 @@ before(async () => {
32
...process.env,
33
PORT: String(port),
34
NODE_ENV: 'production',
35
+ SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '',
36
+ EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '',
37
ENABLE_SENSITIVE_FEATURES: 'true', // Explicit synthetic cycle/error fixtures only.
38
CORS_ORIGINS: allowedOrigin,
39
RATE_LIMIT_AUTH_MAX: '2000',
@@ -120,7 +122,7 @@ async function errorEvent(requestId, { errorProcess = child, readErrors = () =>
122
test('importing the shared app in production does not leave a second listener open', async () => {
123
const imported = spawn(process.execPath, ['--input-type=module', '-e', 'const { pool } = await import("./src/server.js"); await pool.end();'], {
124
cwd: new URL('..', import.meta.url),
123
- env: { ...process.env, NODE_ENV: 'production', PORT: '0' },
125
+ env: { ...process.env, NODE_ENV: 'production', SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', PORT: '0' },
126
stdio: 'ignore',
127
});
128
let timedOut = false;
@@ -275,7 +277,7 @@ test('errors after a partial HTTP response terminate the stream without leaking
277
let fixtureErrors = '';
278
const streamServer = spawn(process.execPath, ['tests/fixtures/partial_error_server.js'], {
279
cwd: new URL('..', import.meta.url),
278
- env: { ...process.env, NODE_ENV: 'production', STREAM_ERROR_MARKER: marker },
280
+ env: { ...process.env, NODE_ENV: 'production', SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', STREAM_ERROR_MARKER: marker },
281
stdio: ['ignore', 'pipe', 'pipe'],
282
});
283
streamServer.stdout.on('data', (chunk) => { fixtureOutput += chunk.toString(); });
backend/tests/school_crud.test.js
+2
-1
@@ -22,7 +22,8 @@ async function start() {
22
base = `http://127.0.0.1:${port}`;
23
let startup = '';
24
child = spawn(process.execPath, ['src/entrypoint.js'], {
25
- env: { ...process.env, NODE_ENV: 'production', PORT: String(port), EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '',
25
+ env: { ...process.env, NODE_ENV: 'production', PORT: String(port),
26
+ SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '',
27
CORS_ORIGINS: '', TRUSTED_PROXY_CIDRS: '', ENABLE_SENSITIVE_FEATURES: 'false',
28
RATE_LIMIT_AUTH_MAX: '2000', RATE_LIMIT_GENERAL_MAX: '4000', RATE_LIMIT_AI_MAX: '2000' },
29
stdio: ['ignore', 'pipe', 'pipe'],
backend/tests/sms_provider.test.js
new
+130
@@ -0,0 +1,130 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { createEmailProvider, createSmsProvider, safelyDeliver } from '../src/auth_delivery.js';
4
+
5
+const secret = 'SYNTHETIC_SMS_SECRET_MARKER_20261008';
6
+const endpoint = 'https://sms-gateway.example.test/otp';
7
+const env = { SMS_PROVIDER: 'webhook', SMS_PROVIDER_URL: endpoint, SMS_PROVIDER_TOKEN: secret };
8
+const message = { phone: '+155500000001', code: '765432', expiresIn: 300, idempotencyKey: '11111111-1111-4111-8111-111111111111' };
9
+const sensitive = `${secret} ${message.phone} ${message.code}`;
10
+const safeError = (error, code) => {
11
+ assert.equal(error.message, code);
12
+ assert.equal(String(error.stack).includes(secret), false);
13
+ assert.equal(String(error.stack).includes(message.phone), false);
14
+ assert.equal(String(error.stack).includes(message.code), false);
15
+ assert.equal(error.cause, undefined);
16
+ return true;
17
+};
18
+
19
+test('SMS remains disabled without an explicit webhook selection and makes no outbound request', async () => {
20
+ let calls = 0;
21
+ for (const selection of [undefined, '', 'none', 'disabled']) {
22
+ const provider = createSmsProvider({ env: { ...env, SMS_PROVIDER: selection }, fetchImpl: async () => { calls++; } });
23
+ assert.equal(provider.configured, false);
24
+ assert.equal(provider.status, 'UNVERIFIED');
25
+ assert.equal((await provider.sendOtp(message)).delivered, false);
26
+ }
27
+ assert.equal(calls, 0);
28
+});
29
+
30
+test('explicit HTTPS webhook uses bearer authentication, minimal OTP data and an opaque idempotency key', async () => {
31
+ const calls = [];
32
+ const provider = createSmsProvider({ env, fetchImpl: async (url, options) => { calls.push({ url, options }); return new Response('', { status: 202 }); } });
33
+ assert.equal(provider.configured, true);
34
+ assert.equal(provider.status, 'CONFIGURED_UNVERIFIED');
35
+ assert.equal(JSON.stringify(provider).includes(secret) || JSON.stringify(provider).includes(endpoint), false);
36
+ assert.equal((await provider.sendOtp({ ...message, privateNotes: 'MUST-NOT-SEND' })).delivered, true);
37
+ assert.equal(calls.length, 1);
38
+ const { url, options } = calls[0];
39
+ assert.equal(url === endpoint, true);
40
+ assert.equal(options.method, 'POST');
41
+ assert.equal(options.redirect, 'error');
42
+ assert.equal(options.headers.Authorization === `Bearer ${secret}`, true);
43
+ assert.equal(options.headers['Idempotency-Key'] === message.idempotencyKey, true);
44
+ assert.equal(options.headers['Content-Type'], 'application/json');
45
+ assert.ok(options.signal instanceof AbortSignal);
46
+ const payload = JSON.parse(options.body);
47
+ assert.deepEqual(Object.keys(payload).sort(), ['code', 'expiresIn', 'phone']);
48
+ assert.equal(payload.phone === message.phone && payload.code === message.code && payload.expiresIn === 300, true);
49
+});
50
+
51
+test('unsupported or unsafe explicit SMS configuration fails clearly without echoing configuration secrets', () => {
52
+ let calls = 0;
53
+ const bad = [
54
+ { SMS_PROVIDER: 'unknown' }, { SMS_PROVIDER_URL: '' }, { SMS_PROVIDER_URL: 'http://sms-gateway.example.test/otp' },
55
+ { SMS_PROVIDER_URL: `https://user:${secret}@sms-gateway.example.test/otp` },
56
+ { SMS_PROVIDER_URL: `https://sms-gateway.example.test/otp#${secret}` },
57
+ { SMS_PROVIDER_URL: sensitive }, { SMS_PROVIDER_TOKEN: '' }, { SMS_PROVIDER_TOKEN: 'short' },
58
+ { SMS_PROVIDER_TOKEN: secret + '\n' },
59
+ ];
60
+ for (const config of bad) assert.throws(() => createSmsProvider({ env: { ...env, ...config }, fetchImpl: async () => { calls++; } }), (error) => {
61
+ assert.match(error.message, /^sms_provider_(unsupported|url_invalid|token_invalid)$/);
62
+ assert.equal(String(error.stack).includes(secret), false);
63
+ return true;
64
+ });
65
+ assert.equal(calls, 0);
66
+});
67
+
68
+test('webhook rejection exposes only a sanitized error and retries only transient response statuses', async () => {
69
+ for (const status of [302, 400, 401, 429, 503]) {
70
+ let bodyRead = false;
71
+ const provider = createSmsProvider({ env, fetchImpl: async () => ({ ok: false, status, async text() { bodyRead = true; return sensitive; }, async json() { bodyRead = true; return { error: sensitive }; } }) });
72
+ await assert.rejects(provider.sendOtp(message), (error) => {
73
+ safeError(error, 'sms_provider_rejected');
74
+ assert.equal(error.retryable, status === 429 || status >= 500);
75
+ return true;
76
+ });
77
+ assert.equal(bodyRead, false);
78
+ }
79
+});
80
+
81
+test('webhook network exceptions cannot expose provider URL, OTP or authentication material', async () => {
82
+ const provider = createSmsProvider({ env, fetchImpl: async () => { throw new Error(sensitive); } });
83
+ await assert.rejects(provider.sendOtp(message), (error) => {
84
+ safeError(error, 'sms_provider_unavailable');
85
+ assert.equal(error.retryable, false);
86
+ return true;
87
+ });
88
+});
89
+
90
+test('webhook timeout actually aborts its transport and returns a sanitized uncertain-delivery error', async () => {
91
+ let aborted = false;
92
+ const provider = createSmsProvider({ env, timeoutMs: 20, fetchImpl: async (_url, { signal }) => new Promise((_resolve, reject) => {
93
+ const keepAlive = setTimeout(() => reject(new Error('Synthetic transport ignored abort')), 1000);
94
+ signal.addEventListener('abort', () => { aborted = true; clearTimeout(keepAlive); reject(new Error(sensitive)); }, { once: true });
95
+ }) });
96
+ await assert.rejects(provider.sendOtp(message), (error) => {
97
+ safeError(error, 'sms_provider_timeout');
98
+ assert.equal(error.retryable, false);
99
+ return true;
100
+ });
101
+ assert.equal(aborted, true);
102
+});
103
+
104
+test('webhook retries preserve one auth-delivery idempotency key and production logs contain metadata only', async () => {
105
+ const keys = [], logs = [];
106
+ const provider = createSmsProvider({ env, fetchImpl: async (_url, options) => {
107
+ keys.push(options.headers['Idempotency-Key']);
108
+ return new Response(sensitive, { status: keys.length < 3 ? 503 : 202 });
109
+ } });
110
+ const originalLog = console.log;
111
+ let result;
112
+ try {
113
+ console.log = (line) => { logs.push(String(line)); };
114
+ result = await safelyDeliver({ configured: provider.configured, send: (payload) => provider.sendOtp(payload) }, message, { attemptId: message.idempotencyKey, env: { NODE_ENV: 'production' } });
115
+ } finally { console.log = originalLog; }
116
+ assert.equal(result.delivered, true);
117
+ assert.equal(keys.length, 3);
118
+ assert.equal(keys.every((key) => key === message.idempotencyKey), true);
119
+ assert.equal(logs.length, 1);
120
+ const event = JSON.parse(logs[0]);
121
+ assert.deepEqual(Object.keys(event).sort(), ['attemptId', 'status', 'type']);
122
+ assert.equal(event.status, 'accepted');
123
+ assert.equal(event.type, 'auth_delivery');
124
+ assert.equal(logs[0].includes(secret) || logs[0].includes(message.phone) || logs[0].includes(message.code), false);
125
+});
126
+
127
+test('test runner disables inherited external delivery configuration for default providers', () => {
128
+ assert.equal(createSmsProvider().configured, false);
129
+ assert.equal(createEmailProvider().configured, false);
130
+});