@davoodmehraban89 / LifeMate / commits / ef12054
Fork 0

LifeMate — Personal, Family & Learning Companion

fix(auth): persist shared IP quotas and enforce guarded startup

Quinn White committed Oct 15, 2026 at 22:18 UTC ef1205417b6523e199ace4ac3d3667a8aaf9cab5
14 files changed +473 -23
CHANGELOG.md
+8
@@ -1,5 +1,13 @@
1 # LifeGuide Changelog
2
3 +## Unreleased — Phase 1 auth hardening
4 +
5 +- Share auth/session IP quotas in PostgreSQL across processes and restart, storing domain-separated HMAC metadata rather than raw addresses; retain separate contact cooldowns.
6 +- Recheck one-time token, refresh and OTP expiry after database lock waits with fresh wall time.
7 +- Require explicit live-SMS and Kavenegar template approval flags; defaults remain disabled.
8 +- Reject direct production server startup that bypasses shared security middleware. Preserve the existing 20 migration files and add local migration0023; no live schema or deployment changed.
9 +- Verification and remaining Phase1 policy gates: [auth audit](docs/audits/2026-10-15-phase1-auth-hardening.md). Backend package version remains0.7.1; this is not a release.
10 +
11 ## 0.7.1 — 2026-10-12 — shared-network session recovery
12
13 - Fix a real three-account PWA acceptance blocker: public auth capabilities no longer consume sensitive login/delivery attempts, and refresh/logout have a separate bounded session bucket.
PROJECT_STATE.md
+7 -1
@@ -1,6 +1,12 @@
1 # LifeGuide / لایف‌گاید — وضعیت واقعی پروژه
2
3 -## Supabase LifeGuide-QA full private schema — 2026-10-15 (LATEST VERIFIED)
3 +## فاز۱ — اصلاح هویت در PR وابسته؛ بدون انتشار
4 +
5 +مالک پس از گزارش فاز۰ شروع فاز۱ را تأیید کرد. شاخه `fix/auth-abuse-expiry-safety` از PR14 در `5da6c4290e422162c13c3fe5260345770dde7ffa` منشعب است؛ به main یا سرویس زنده منتقل نشده است. محدودیت IP مشترک PostgreSQL، بررسی تازه انقضا پس از قفل و gate تأیید ارسال SMS پیاده شد. **VERIFIED محلی:** `npm test -- --test-concurrency=1` →271pass/0fail/0skip؛ migration و import تکراری، چهار SQL matrix و syntax موفق. [گزارش و محدودیت‌ها](docs/audits/2026-10-15-phase1-auth-hardening.md).
6 +
7 +Migration0023 فقط محلی آزموده شد؛۲۰ فایل اصلی و۳bundle تاریخی تغییر نکرده‌اند و Supabase زنده همان baseline20 است. manifest جدید generator شامل21فایل، گواه اعمال روی QA نیست. AI/guardian/cycle policy، سرور آنلاین، دستگاه/Safari، SMS واقعی و امضای release هنوز تأیید/تکمیل نشده‌اند؛ **فاز۱ کامل نیست**. پاکسازی مخزن و اسناد گزینه‌های سیاستی در PRهای مستقل آماده می‌شوند. هیچ merge،deploy،DNS،داده یا schema زنده تغییر نکرده و این PR اجازه آن‌ها نیست.
8 +
9 +## Supabase LifeGuide-QA full private schema — 2026-10-15 (HISTORICAL CHECKPOINT)
10
11 **20/20 original PostgreSQL migrations copied to the isolated QA database, SQL family/privacy assertions PASS, client-access remains DENY ALL.** This is a **database integration milestone**, not a publicly operational LifeGuide Android/PWA.
12
backend/migrations/0023_auth_ip_rate_limit.sql new
+17
@@ -0,0 +1,17 @@
1 +begin;
2 +
3 +-- Abuse-prevention metadata only: no IP, contact, account, or request body.
4 +-- The digest is a domain-separated HMAC using the server signing secret.
5 +create table auth_ip_rate_limit (
6 + quota_profile text not null check(quota_profile in ('auth','session')),
7 + client_digest text not null check(client_digest ~ '^[a-f0-9]{64}$'),
8 + window_start timestamptz not null,
9 + window_end timestamptz not null,
10 + request_count bigint not null check(request_count > 0),
11 + primary key(quota_profile,client_digest,window_start),
12 + check(window_end > window_start)
13 +);
14 +create index auth_ip_rate_limit_expiry on auth_ip_rate_limit(window_end);
15 +revoke all on auth_ip_rate_limit from public;
16 +
17 +commit;
backend/scripts/build-supabase-qa-sql.js
+15 -4
@@ -1,4 +1,5 @@
1 -// Build a one-time, QA-only copy of the existing 20 LifeGuide PostgreSQL migrations.
1 +// Build a one-time, QA-only copy of the 20 baseline migrations plus auth metadata.
2 +// Existing provider-applied 0001..0020 bundles remain historical and unchanged.
3 // This script outputs SQL, does NOT connect to a DB and cannot deploy by itself.
4 // Crucially, original migration files / Compose role-provisioning stay unchanged.
5 import { readdir, readFile } from 'node:fs/promises';
@@ -32,6 +33,14 @@ function normalizeMigration(filename, source) {
33 if (n !== (filename.startsWith('0019_') ? 5 : 0)) throw new Error(`unexpected_function_search_path:${filename}`);
34 sql = sql.replace(oldFunctionPath, `set search_path=${targetSchema},pg_catalog`);
35
36 + // The additive auth migration removes PUBLIC access to its one metadata
37 + // table. The QA wrapper below already revokes ALL tables for every client
38 + // role. Allow only this exact restriction; arbitrary GRANT/REVOKE still fails.
39 + if (filename === '0023_auth_ip_rate_limit.sql') {
40 + sql = sql.replace(/^revoke all on auth_ip_rate_limit from public;$/m,
41 + '-- Auth metadata is included in the QA wrapper table-wide lockdown.');
42 + }
43 +
44 // Fail closed if a future source migration changes its privilege/schema rules.
45 if (/\b(?:public|auth|storage|realtime)\s*\./i.test(sql) ||
46 /\b(?:create|alter|drop)\s+(?:role|database|schema|extension)\b/i.test(sql) ||
@@ -44,9 +53,11 @@ function normalizeMigration(filename, source) {
53
54 export async function buildSupabaseQaSql({ migrationsDir = sourceRoot } = {}) {
55 const entries = (await readdir(migrationsDir)).filter(name => /^\d{4}_[a-z0-9_]+\.sql$/.test(name)).sort();
47 - if (entries.length !== 20 || entries[0].slice(0,4) !== '0001' || entries.at(-1).slice(0,4) !== '0020' ||
48 - entries.some((name, i) => name.slice(0,4) !== String(i+1).padStart(4, '0'))) {
49 - throw new Error('expected_exactly_20_original_migrations_in_order');
56 + const expected = [...Array.from({length:20}, (_,i) => String(i+1).padStart(4,'0')), '0023'];
57 + if (entries.length !== expected.length ||
58 + entries.some((name, i) => name.slice(0,4) !== expected[i]) ||
59 + entries.at(-1) !== '0023_auth_ip_rate_limit.sql') {
60 + throw new Error('expected_baseline_and_auth_migrations_in_order');
61 }
62
63 const parts = [`begin;
backend/scripts/db-role-policy.js
+1 -1
@@ -6,7 +6,7 @@ import fs from 'node:fs/promises';
6 export const applicationTables = [
7 'academic_term', 'academic_year', 'access_audit', 'activity_state_event',
8 'ai_guide_message', 'ai_guide_session', 'ai_plan_proposal', 'app_user',
9 - 'auth_credential', 'auth_delivery_attempt', 'auth_phone_challenge', 'auth_session',
9 + 'auth_credential', 'auth_delivery_attempt', 'auth_ip_rate_limit', 'auth_phone_challenge', 'auth_session',
10 'auth_token', 'class_session', 'curriculum_subject', 'education_profile',
11 'family_invitation', 'family_membership', 'family_workspace', 'guardian_relationship',
12 'iran_calendar_event', 'learning_checkin', 'learning_goal', 'life_context',
backend/src/auth_rate_limit.js new
+83
@@ -0,0 +1,83 @@
1 +import crypto from 'node:crypto';
2 +import { isIP } from 'node:net';
3 +import { rateLimitProfile } from './operations.js';
4 +
5 +const digestDomain = 'lifeguide:auth-ip:v1\0';
6 +
7 +function canonicalIp(value) {
8 + const address = String(value ?? '');
9 + if (isIP(address) === 4) return address;
10 + if (isIP(address) !== 6) throw new Error('Invalid client address');
11 + const canonical = new URL(`http://[${address}]`).hostname.slice(1, -1);
12 + // Socket addresses can represent the same IPv4 client as mapped IPv6.
13 + const mapped = /^::ffff:([a-f0-9]{1,4}):([a-f0-9]{1,4})$/.exec(canonical);
14 + if (!mapped) return canonical;
15 + const upper = Number.parseInt(mapped[1], 16), lower = Number.parseInt(mapped[2], 16);
16 + return `${upper >> 8}.${upper & 255}.${lower >> 8}.${lower & 255}`;
17 +}
18 +
19 +/** Shared fixed-window budgets for auth and session routes. Forwarded headers
20 + * are deliberately never read here: Express req.ip reflects the separately
21 + * validated, operator-pinned trusted-proxy configuration.
22 + */
23 +export function createAuthIpRateLimit({ pool, jwtSecret, env = process.env }) {
24 + if (typeof jwtSecret !== 'string' || jwtSecret.length < 32) throw new Error('Invalid auth limiter signing secret');
25 + return async function authIpRateLimit(req, res, next) {
26 + if (env.NODE_ENV === 'test' || req.method === 'OPTIONS') return next();
27 + const profile = rateLimitProfile(req, env);
28 + if (!['auth', 'session'].includes(profile.name)) return next();
29 + let client;
30 + try {
31 + const digest = crypto.createHmac('sha256', jwtSecret).update(digestDomain)
32 + .update(canonicalIp(req.ip || req.socket?.remoteAddress)).digest('hex');
33 + client = await pool.connect();
34 + await client.query("begin; set local lock_timeout='2s'; set local statement_timeout='3s'");
35 + // Lock the stable digest/profile, not a precomputed window. A waiting
36 + // request samples the PostgreSQL clock only after acquiring this lock.
37 + await client.query("select pg_advisory_xact_lock(hashtextextended('lifeguide:auth-ip:' || $1 || ':' || $2,0))", [profile.name, digest]);
38 + const result = await client.query(`
39 + with clock as (select statement_timestamp() as instant),
40 + quota_window as (select to_timestamp(floor(extract(epoch from instant)/$3::integer)*$3::integer) as start from clock)
41 + insert into auth_ip_rate_limit(quota_profile,client_digest,window_start,window_end,request_count)
42 + select $1,$2,start,start+make_interval(secs=>$3::integer),1 from quota_window
43 + on conflict(quota_profile,client_digest,window_start) do update
44 + set request_count=auth_ip_rate_limit.request_count+1
45 + returning request_count,
46 + greatest(1,ceil(extract(epoch from window_end-statement_timestamp())))::integer as retry_after`,
47 + [profile.name, digest, profile.windowSeconds]);
48 + await client.query('commit');
49 + const row = result.rows[0];
50 + const count = Number(row.request_count);
51 + // The in-memory middleware must not charge these routes a second time.
52 + req.authRateLimitCharged = true;
53 + res.setHeader('RateLimit-Limit', String(profile.limit));
54 + res.setHeader('RateLimit-Remaining', String(Math.max(0, profile.limit - count)));
55 + if (count > profile.limit) {
56 + res.setHeader('Retry-After', String(row.retry_after));
57 + return res.status(429).json({ error: 'rate_limited' });
58 + }
59 + return next();
60 + } catch {
61 + if (client) await client.query('rollback').catch(() => {});
62 + // Database/key/address failures never fall back to a per-process quota.
63 + // Do not expose or log connection strings, raw IPs, or PostgreSQL errors.
64 + res.setHeader('Retry-After', '5');
65 + return res.status(503).json({ error: 'temporarily_unavailable' });
66 + } finally { client?.release(); }
67 + };
68 +}
69 +
70 +/** Explicit local/operator housekeeping hook; no timer, worker or external
71 + * scheduler is started. Each call deletes at most 500 expired metadata rows.
72 + * Current windows are retained, so housekeeping cannot reopen an active quota.
73 + */
74 +export async function pruneExpiredAuthRateLimits(pool, batchSize = 500) {
75 + if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > 500) throw new Error('Invalid auth limiter cleanup batch');
76 + const result = await pool.query(`with expired as (
77 + select quota_profile,client_digest,window_start from auth_ip_rate_limit
78 + where window_end<=statement_timestamp() order by window_end
79 + limit $1 for update skip locked
80 + ) delete from auth_ip_rate_limit b using expired e
81 + where b.quota_profile=e.quota_profile and b.client_digest=e.client_digest and b.window_start=e.window_start`, [batchSize]);
82 + return result.rowCount;
83 +}
backend/src/entrypoint.js
+2
@@ -8,6 +8,7 @@ import {
8 requestContext,
9 requestTelemetry,
10 } from './operations.js';
11 +import { createAuthIpRateLimit } from './auth_rate_limit.js';
12
13 const { app, pool } = await import('./server.js');
14
@@ -16,6 +17,7 @@ outer.disable('x-powered-by');
17 configureTrustedProxy(outer);
18 outer.use(requestContext);
19 outer.use(requestTelemetry);
20 +outer.use(createAuthIpRateLimit({ pool, jwtSecret: process.env.JWT_SECRET }));
21 outer.use(rateLimit);
22
23 outer.get('/live', (_req, res) => {
backend/src/operations.js
+11 -10
@@ -61,7 +61,7 @@ export function configureTrustedProxy(app, value = process.env.TRUSTED_PROXY_CID
61 app.set('trust proxy', entries.length ? entries : false);
62 }
63
64 -function profileFor(req) {
64 +export function rateLimitProfile(req, env = process.env) {
65 const path = req.path;
66 const discovery = req.method === 'GET' && path === '/v1/auth/capabilities';
67 // Express accepts case variants and trailing slashes. Only these literal
@@ -70,27 +70,27 @@ function profileFor(req) {
70 if (req.method === 'POST' && (path === '/v1/auth/refresh' || path === '/v1/auth/logout')) {
71 return {
72 name: 'session',
73 - limit: positiveInt(process.env.RATE_LIMIT_SESSION_MAX, 60),
74 - windowSeconds: positiveInt(process.env.RATE_LIMIT_SESSION_WINDOW_SECONDS, 10 * 60),
73 + limit: positiveInt(env.RATE_LIMIT_SESSION_MAX, 60),
74 + windowSeconds: positiveInt(env.RATE_LIMIT_SESSION_WINDOW_SECONDS, 10 * 60),
75 };
76 }
77 return {
78 name: 'auth',
79 - limit: positiveInt(process.env.RATE_LIMIT_AUTH_MAX, 10),
80 - windowSeconds: positiveInt(process.env.RATE_LIMIT_AUTH_WINDOW_SECONDS, 10 * 60),
79 + limit: positiveInt(env.RATE_LIMIT_AUTH_MAX, 10),
80 + windowSeconds: positiveInt(env.RATE_LIMIT_AUTH_WINDOW_SECONDS, 10 * 60),
81 };
82 }
83 if (/^\/v1\/ai\//.test(path) || /\/family-guidance$/.test(path)) {
84 return {
85 name: 'ai',
86 - limit: positiveInt(process.env.RATE_LIMIT_AI_MAX, 30),
87 - windowSeconds: positiveInt(process.env.RATE_LIMIT_AI_WINDOW_SECONDS, 10 * 60),
86 + limit: positiveInt(env.RATE_LIMIT_AI_MAX, 30),
87 + windowSeconds: positiveInt(env.RATE_LIMIT_AI_WINDOW_SECONDS, 10 * 60),
88 };
89 }
90 return {
91 name: 'general',
92 - limit: positiveInt(process.env.RATE_LIMIT_GENERAL_MAX, 120),
93 - windowSeconds: positiveInt(process.env.RATE_LIMIT_GENERAL_WINDOW_SECONDS, 60),
92 + limit: positiveInt(env.RATE_LIMIT_GENERAL_MAX, 120),
93 + windowSeconds: positiveInt(env.RATE_LIMIT_GENERAL_WINDOW_SECONDS, 60),
94 };
95 }
96
@@ -98,7 +98,8 @@ export function rateLimit(req, res, next) {
98 if (process.env.NODE_ENV === 'test' || req.method === 'OPTIONS' || req.path === '/live' || req.path === '/ready' || req.path === '/health') {
99 return next();
100 }
101 - const profile = profileFor(req);
101 + const profile = rateLimitProfile(req);
102 + if (req.authRateLimitCharged && ['auth', 'session'].includes(profile.name)) return next();
103 const now = nowSeconds();
104 const windowStart = Math.floor(now / profile.windowSeconds) * profile.windowSeconds;
105 const key = `${profile.name}:${clientKey(req)}:${windowStart}`;
backend/src/server.js
+3 -2
@@ -489,10 +489,11 @@ app.use('/v1', createStudySessionsRouter({ pool, auth }));
489
490 app.use(operationalErrorHandler);
491
492 -const port = Number(process.env.PORT ?? 8080);
492 const invokedDirectly = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
493 if (!testMode && invokedDirectly) {
495 - app.listen(port, () => console.log(`LifeGuide API listening on ${port}`));
494 + // Production must include the shared request/security/IP-quota middleware.
495 + // Tests may import app; a second production listener would bypass those guards.
496 + throw new Error('production_entrypoint_required: use npm start (src/entrypoint.js)');
497 }
498
499 export { app, pool };
backend/tests/auth_ip_rate_limit.test.js new
+244
@@ -0,0 +1,244 @@
1 +import test, { after } 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 { pruneExpiredAuthRateLimits } from '../src/auth_rate_limit.js';
9 +
10 +const fixtureUrl = process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL;
11 +assert.ok(fixtureUrl, 'Auth IP tests require migrated synthetic PostgreSQL');
12 +const database = new URL(fixtureUrl);
13 +assert.ok(['localhost', '127.0.0.1', '[::1]', '::1'].includes(database.hostname), 'Only loopback PostgreSQL allowed');
14 +assert.ok(['/lifeguide_library_test', '/lifeguide_contentops_test', '/lifemate_ci'].includes(database.pathname) ||
15 + /^\/lifeguide_roles_source_[a-f0-9]{16}$/.test(database.pathname), 'Only synthetic test databases allowed');
16 +const pool = new pg.Pool({ connectionString: fixtureUrl });
17 +const processes = new Set();
18 +const secret = `synthetic-auth-ip-key-${crypto.randomUUID()}`;
19 +const fixtureIps = new Set(['127.0.0.1']);
20 +
21 +async function start({ trusted = '127.0.0.1/32', connectionString = fixtureUrl, quota = 3, sessionQuota = 5, windowSeconds = 600 } = {}) {
22 + const reservation = net.createServer().listen(0, '127.0.0.1');
23 + await once(reservation, 'listening');
24 + const port = reservation.address().port;
25 + await new Promise(resolve => reservation.close(resolve));
26 + const env = { ...process.env, DATABASE_URL: connectionString, NODE_ENV: 'production', PORT: String(port),
27 + JWT_SECRET: secret, LOG_REQUESTS: 'false', TRUSTED_PROXY_CIDRS: trusted, CORS_ORIGINS: '',
28 + RATE_LIMIT_AUTH_MAX: String(quota), RATE_LIMIT_AUTH_WINDOW_SECONDS: String(windowSeconds),
29 + RATE_LIMIT_SESSION_MAX: String(sessionQuota), RATE_LIMIT_SESSION_WINDOW_SECONDS: String(windowSeconds),
30 + RATE_LIMIT_GENERAL_MAX: '2000', SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '',
31 + KAVENEGAR_API_KEY: '', EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '',
32 + AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '', OPENAI_API_KEY: '', ENABLE_SENSITIVE_FEATURES: 'false' };
33 + delete env.TEST_FIXTURE_DATABASE_URL;
34 + delete env.AUTH_RATE_LIMIT_KEY;
35 + const child = spawn(process.execPath, ['src/entrypoint.js'], { cwd: new URL('../', import.meta.url),
36 + env, stdio: ['ignore', 'pipe', 'pipe'] });
37 + processes.add(child);
38 + child.stderr.on('data', () => {});
39 + await new Promise((resolve, reject) => {
40 + let output = '';
41 + const timer = setTimeout(() => reject(new Error('Auth IP fixture startup timed out')), 10000);
42 + child.stdout.on('data', chunk => {
43 + output += chunk;
44 + if (output.includes('"type":"startup"')) { clearTimeout(timer); resolve(); }
45 + });
46 + child.once('error', () => { clearTimeout(timer); reject(new Error('Auth IP fixture process failed')); });
47 + child.once('exit', () => {
48 + if (!output.includes('"type":"startup"')) { clearTimeout(timer); reject(new Error('Auth IP fixture exited before startup')); }
49 + });
50 + });
51 + return { child, url: `http://127.0.0.1:${port}` };
52 +}
53 +
54 +async function stop(service) {
55 + const child = service.child;
56 + if (child.exitCode === null && child.signalCode === null) {
57 + const closed = once(child, 'close'); child.kill('SIGTERM'); await closed;
58 + }
59 + processes.delete(child);
60 +}
61 +
62 +async function request(service, path = '/v1/auth/login', { ip = '192.0.2.11', method = 'POST', headers = {} } = {}) {
63 + fixtureIps.add(ip);
64 + const response = await fetch(service.url + path, { method,
65 + headers: { 'content-type': 'application/json', 'x-forwarded-for': ip, ...headers },
66 + ...(['GET', 'HEAD', 'OPTIONS'].includes(method) ? {} : { body: '{}' }) });
67 + const raw = await response.text();
68 + return { status: response.status, headers: response.headers,
69 + body: raw && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(raw) : null };
70 +}
71 +
72 +after(async () => {
73 + await Promise.all([...processes].map(child => stop({ child })));
74 + try {
75 + // These are test-owned HMACs only; never delete another test/API's bucket.
76 + const digests = [...fixtureIps].map(ip => crypto.createHmac('sha256', secret)
77 + .update('lifeguide:auth-ip:v1\0').update(ip).digest('hex'));
78 + await pool.query('delete from auth_ip_rate_limit where client_digest=any($1::text[])', [digests]);
79 + } catch (error) { if (error.code !== '42P01') throw error; }
80 + finally { await pool.end(); }
81 +});
82 +
83 +test('auth quota is shared atomically between API instances and survives process restart', async () => {
84 + const first = await start(), second = await start();
85 + // Syntactically valid forwarding data is accepted only from the explicitly
86 + // trusted loopback gateway. No real account/contact is involved.
87 + const results = await Promise.all(Array.from({ length: 8 }, (_, index) => request(index % 2 ? first : second)));
88 + assert.deepEqual(results.map(result => result.status).sort(), [401, 401, 401, 429, 429, 429, 429, 429],
89 + 'Two processes must share one atomic quota, not each allow three requests');
90 + for (const result of results) assert.equal(result.headers.get('RateLimit-Limit'), '3');
91 + const limited = results.find(result => result.status === 429);
92 + assert.equal(limited.body.error, 'rate_limited');
93 + const retry = Number(limited.headers.get('Retry-After'));
94 + const clock = (await pool.query('select extract(epoch from statement_timestamp())::bigint n')).rows[0].n;
95 + const expected = 600 - (Number(clock) % 600);
96 + assert.ok(Number.isInteger(retry) && retry > 0 && retry <= 600 && Math.abs(retry - expected) <= 2);
97 + await stop(first); await stop(second);
98 + const restarted = await start();
99 + assert.equal((await request(restarted)).status, 429, 'Restart must not reset auth abuse protection');
100 + await stop(restarted);
101 +});
102 +
103 +test('strict and session budgets are separate, capability discovery and OPTIONS do not charge either', async () => {
104 + const service = await start({ quota: 2, sessionQuota: 2 });
105 + const options = { ip: '192.0.2.12' };
106 + for (let index = 0; index < 4; index++) {
107 + assert.equal((await request(service, '/v1/auth/capabilities', { ...options, method: 'GET' })).status, 200);
108 + assert.equal((await request(service, '/v1/auth/login', { ...options, method: 'OPTIONS' })).status, 204);
109 + }
110 + assert.equal((await request(service, '/v1/auth/login', options)).status, 401);
111 + assert.equal((await request(service, '/v1/auth/login', options)).status, 401);
112 + assert.equal((await request(service, '/v1/auth/login', options)).status, 429);
113 + assert.equal((await request(service, '/v1/auth/logout', options)).status, 204);
114 + assert.equal((await request(service, '/v1/auth/logout', options)).status, 204);
115 + assert.equal((await request(service, '/v1/auth/refresh', options)).status, 429);
116 + for (const [method, path] of [
117 + ['HEAD', '/v1/auth/capabilities'], ['POST', '/v1/auth/capabilities'],
118 + ['GET', '/v1/auth/capabilities/'], ['GET', '/v1/auth/Capabilities'],
119 + ['GET', '/V1/AUTH/capabilities'], ['POST', '/v1/auth/refresh/'], ['POST', '/v1/auth/refreshing'],
120 + ]) assert.equal((await request(service, path, { ...options, method })).status, 429, `${method} ${path} stays strict`);
121 + await stop(service);
122 +});
123 +
124 +test('untrusted forwarding headers cannot rotate a quota, and an explicitly pinned gateway separates clients', async () => {
125 + const standalone = await start({ trusted: '', quota: 2 });
126 + assert.equal((await request(standalone, '/v1/auth/login', { ip: '198.51.100.1' })).status, 401);
127 + assert.equal((await request(standalone, '/v1/auth/login', { ip: '198.51.100.2' })).status, 401);
128 + assert.equal((await request(standalone, '/v1/auth/login', { ip: '198.51.100.3', headers: {
129 + forwarded: 'for=203.0.113.123', 'x-real-ip': '203.0.113.123',
130 + } })).status, 429);
131 + await stop(standalone);
132 + const gateway = await start({ quota: 2 });
133 + assert.equal((await request(gateway, '/v1/auth/login', { ip: '192.0.2.13' })).status, 401);
134 + assert.equal((await request(gateway, '/v1/auth/login', { ip: '192.0.2.13' })).status, 401);
135 + assert.equal((await request(gateway, '/v1/auth/login', { ip: '203.0.113.123, 192.0.2.13' })).status, 429);
136 + assert.equal((await request(gateway, '/v1/auth/login', { ip: '192.0.2.14' })).status, 401);
137 + await stop(gateway);
138 +});
139 +
140 +test('database failure closes auth with generic 503 while public discovery remains available', async () => {
141 + const schema = `synthetic_auth_unavailable_${crypto.randomBytes(6).toString('hex')}`;
142 + await pool.query(`create schema ${schema}`);
143 + try {
144 + const isolated = new URL(fixtureUrl);
145 + isolated.searchParams.set('options', `-c search_path=${schema}`);
146 + const service = await start({ connectionString: isolated.href });
147 + const result = await request(service, '/v1/auth/login', { ip: '192.0.2.15' });
148 + assert.equal(result.status, 503);
149 + assert.deepEqual(result.body, { error: 'temporarily_unavailable' });
150 + assert.equal(result.headers.get('Retry-After'), '5');
151 + assert.equal((await request(service, '/v1/auth/capabilities', { method: 'GET' })).status, 200);
152 + assert.equal((await request(service, '/live', { method: 'GET' })).status, 200);
153 + await stop(service);
154 + } finally { await pool.query(`drop schema ${schema}`); }
155 +});
156 +
157 +test('persisted buckets contain only HMAC metadata and the server-clock window expires', async () => {
158 + const service = await start({ quota: 1, windowSeconds: 5 });
159 + const options = { ip: '192.0.2.16' };
160 + // Align against the actual PostgreSQL clock, not an injected fake clock.
161 + // Keep both immediate calls away from a natural fixed-window rollover.
162 + for (;;) {
163 + const now = Number((await pool.query('select extract(epoch from clock_timestamp()) n')).rows[0].n);
164 + if (now % 5 < 1) break;
165 + await new Promise(resolve => setTimeout(resolve, 100));
166 + }
167 + assert.equal((await request(service, '/v1/auth/window-probe', options)).status, 401);
168 + assert.equal((await request(service, '/v1/auth/window-probe', options)).status, 429);
169 + const columns = (await pool.query(`select column_name from information_schema.columns
170 + where table_schema=current_schema() and table_name='auth_ip_rate_limit' order by ordinal_position`)).rows.map(row => row.column_name);
171 + assert.deepEqual(columns, ['quota_profile', 'client_digest', 'window_start', 'window_end', 'request_count']);
172 + const rows = (await pool.query("select * from auth_ip_rate_limit where window_end-window_start=interval '5 seconds'")).rows;
173 + assert.ok(rows.length > 0);
174 + for (const row of rows) {
175 + assert.match(row.client_digest, /^[a-f0-9]{64}$/);
176 + assert.equal(JSON.stringify(row).includes(options.ip), false);
177 + }
178 + await new Promise(resolve => setTimeout(resolve, 5100));
179 + assert.equal((await request(service, '/v1/auth/window-probe', options)).status, 401, 'New server-clock window receives a new quota');
180 + await stop(service);
181 +});
182 +
183 +test('a request waiting for the shared lock samples its quota window after the wait', async () => {
184 + const ip = '192.0.2.17', options = { ip };
185 + // One second guarantees this controlled wait stays below the production
186 + // two-second lock timeout, even when the request starts near a boundary.
187 + const service = await start({ quota: 1, windowSeconds: 1 });
188 + const digest = crypto.createHmac('sha256', secret).update('lifeguide:auth-ip:v1\0').update(ip).digest('hex');
189 + assert.equal((await request(service, '/v1/auth/window-probe', options)).status, 401);
190 + const client = await pool.connect();
191 + let pending;
192 + try {
193 + await client.query('begin');
194 + const pid = Number((await client.query('select pg_backend_pid() pid')).rows[0].pid);
195 + await client.query("select pg_advisory_xact_lock(hashtextextended('lifeguide:auth-ip:auth:' || $1,0))", [digest]);
196 + pending = request(service, '/v1/auth/window-probe', options);
197 + let blocked = false;
198 + for (let index = 0; index < 100; index++) {
199 + blocked = (await pool.query('select exists(select 1 from pg_stat_activity where $1=any(pg_blocking_pids(pid))) blocked', [pid])).rows[0].blocked;
200 + if (blocked) break;
201 + await new Promise(resolve => setTimeout(resolve, 10));
202 + }
203 + assert.ok(blocked, 'Independent PostgreSQL confirms the API is waiting on the shared quota lock');
204 + const waitMs = Number((await pool.query(`select greatest(0,extract(epoch from max(window_end)-clock_timestamp())*1000)::integer ms
205 + from auth_ip_rate_limit where quota_profile='auth' and client_digest=$1`, [digest])).rows[0].ms);
206 + await new Promise(resolve => setTimeout(resolve, waitMs + 100));
207 + await client.query('commit');
208 + assert.equal((await pending).status, 401, 'Expired pre-wait window must not reject a new-window request');
209 + const windows = (await pool.query('select request_count from auth_ip_rate_limit where client_digest=$1 order by window_start', [digest])).rows;
210 + assert.equal(windows.length, 2);
211 + assert.ok(windows.every(row => Number(row.request_count) === 1));
212 + } finally {
213 + await client.query('rollback').catch(() => {});
214 + client.release();
215 + if (pending) await pending;
216 + await stop(service);
217 + }
218 +});
219 +
220 +test('explicit housekeeping is bounded and retains active quotas', async () => {
221 + const schema = `synthetic_auth_cleanup_${crypto.randomBytes(6).toString('hex')}`;
222 + await pool.query(`create schema ${schema}`);
223 + await pool.query(`create table ${schema}.auth_ip_rate_limit (like auth_ip_rate_limit including all)`);
224 + const isolated = new URL(fixtureUrl);
225 + isolated.searchParams.set('options', `-c search_path=${schema}`);
226 + const cleanupPool = new pg.Pool({ connectionString: isolated.href });
227 + try {
228 + await cleanupPool.query(`insert into auth_ip_rate_limit values
229 + ('auth',$1,now()-interval '2 hours',now()-interval '1 hour',1),
230 + ('session',$1,now()-interval '2 hours',now()-interval '1 hour',1),
231 + ('auth',$1,now(),now()+interval '1 hour',1)`, ['a'.repeat(64)]);
232 + assert.equal(await pruneExpiredAuthRateLimits(cleanupPool, 1), 1);
233 + assert.equal(Number((await cleanupPool.query('select count(*) n from auth_ip_rate_limit')).rows[0].n), 2);
234 + assert.equal(await pruneExpiredAuthRateLimits(cleanupPool, 1), 1);
235 + assert.equal(await pruneExpiredAuthRateLimits(cleanupPool, 1), 0);
236 + const remaining = (await cleanupPool.query('select window_end>statement_timestamp() active from auth_ip_rate_limit')).rows;
237 + assert.deepEqual(remaining, [{ active: true }]);
238 + await assert.rejects(pruneExpiredAuthRateLimits(cleanupPool, 501), /Invalid auth limiter cleanup batch/);
239 + await assert.rejects(pruneExpiredAuthRateLimits(cleanupPool, 0), /Invalid auth limiter cleanup batch/);
240 + } finally {
241 + await cleanupPool.end();
242 + await pool.query(`drop schema ${schema} cascade`);
243 + }
244 +});
backend/tests/auth_nat_rate_limit.test.js
+9 -1
@@ -18,9 +18,14 @@ const pool = new pg.Pool({ connectionString: fixtureUrl });
18 const users = [];
19 const password = `SyntheticNat-${crypto.randomUUID()}!`;
20 const secret = 'synthetic-nat-rate-limit-signing-secret-32-characters';
21 +const fixtureIpDigest = crypto.createHmac('sha256', secret)
22 + .update('lifeguide:auth-ip:v1\0').update('127.0.0.1').digest('hex');
23 let child, base;
24
25 before(async () => {
26 + // This fixture deliberately uses a stable key to assert shipping defaults.
27 + // Remove only its own prior-run quota, never another API/test's buckets.
28 + await pool.query("delete from auth_ip_rate_limit where client_digest=$1 and quota_profile in ('auth','session')", [fixtureIpDigest]);
29 const hash = await argon2.hash(password, { type: argon2.argon2id });
30 for (let index = 0; index < 3; index++) {
31 const id = crypto.randomUUID(), email = `nat-${id}@example.test`;
@@ -65,7 +70,10 @@ after(async () => {
70 if (child && child.exitCode === null && child.signalCode === null) {
71 const closed = once(child, 'close'); child.kill('SIGTERM'); await closed;
72 }
68 - try { await pool.query('delete from app_user where id=any($1::uuid[])', [users.map(user => user.id)]); }
73 + try {
74 + await pool.query('delete from app_user where id=any($1::uuid[])', [users.map(user => user.id)]);
75 + await pool.query("delete from auth_ip_rate_limit where client_digest=$1 and quota_profile in ('auth','session')", [fixtureIpDigest]);
76 + }
77 finally { await pool.end(); }
78 });
79 async function request(method, path, body, headers = {}) {
backend/tests/production_entrypoint.test.js new
+16
@@ -0,0 +1,16 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { spawnSync } from 'node:child_process';
4 +
5 +test('direct production server start fails closed instead of bypassing shared auth IP and request guards', () => {
6 + const result = spawnSync(process.execPath, ['src/server.js'], {
7 + cwd: new URL('../', import.meta.url),
8 + env: { ...process.env, NODE_ENV: 'production', PORT: '0', SMS_PROVIDER: 'disabled', EMAIL_FROM: '',
9 + JWT_SECRET: 'synthetic-entrypoint-guard-fixture-not-live-2026',
10 + SMTP_HOST: '', RESEND_API_KEY: '', AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '' },
11 + timeout: 2000, encoding: 'utf8',
12 + });
13 + assert.equal(result.status, 1, 'Use npm start; server.js must not open an unguarded production listener');
14 + assert.match(result.stderr, /production_entrypoint_required/);
15 + assert.doesNotMatch(result.stdout, /listening|startup/);
16 +});
backend/tests/supabase_qa_bundle.test.js
+7 -4
@@ -6,10 +6,12 @@ import { join } from 'node:path';
6 import { pathToFileURL } from 'node:url';
7 import { buildSupabaseQaSql } from '../scripts/build-supabase-qa-sql.js';
8
9 -test('QA bundle retains 20 original checksums, creates private schema objects and corrects school guard paths', async () => {
9 +test('QA bundle retains 20 original checksums plus additive auth metadata and keeps private lockdown', async () => {
10 const { sql, manifest } = await buildSupabaseQaSql();
11 - assert.equal(manifest.length, 20);
12 - assert.ok(manifest.every((x,i) => x.filename.startsWith(String(i+1).padStart(4,'0')+'_')));
11 + assert.equal(manifest.length, 21);
12 + assert.ok(manifest.slice(0,20).every((x,i) => x.filename.startsWith(String(i+1).padStart(4,'0')+'_')));
13 + assert.equal(manifest[20].filename, '0023_auth_ip_rate_limit.sql');
14 + assert.match(sql, /create table auth_ip_rate_limit/);
15 assert.ok(manifest.every(x => /^[a-f0-9]{64}$/.test(x.sha256)));
16 assert.match(sql, /set local search_path=lifeguide_qa,extensions,pg_catalog/);
17 assert.equal((sql.match(/set search_path=lifeguide_qa,pg_catalog/gi) ?? []).length, 5);
@@ -29,7 +31,7 @@ test('QA bundle generation fails closed if source migration count is incomplete'
31 const dir = await mkdtemp(join(tmpdir(),'lifeguide-qa-missing-'));
32 try {
33 await writeFile(join(dir,'0001_identity_family.sql'),'select 1;');
32 - await assert.rejects(buildSupabaseQaSql({ migrationsDir:pathToFileURL(dir+'/') }),/expected_exactly_20_original_migrations_in_order/);
34 + await assert.rejects(buildSupabaseQaSql({ migrationsDir:pathToFileURL(dir+'/') }),/expected_baseline_and_auth_migrations_in_order/);
35 } finally { await rm(dir,{recursive:true,force:true}); }
36 });
37
@@ -43,6 +45,7 @@ test('QA bundle generation rejects drift adding production schema privileges', a
45 'select 1;';
46 await writeFile(join(dir,`${id}_test.sql`),sql);
47 }
48 + await writeFile(join(dir,'0023_auth_ip_rate_limit.sql'), 'select 1;');
49 await writeFile(join(dir,'0004_test.sql'),'create table public.account(id int);');
50 await assert.rejects(buildSupabaseQaSql({ migrationsDir:pathToFileURL(dir+'/') }),/source_migration_outside_private_qa:0004_test.sql/);
51 } finally { await rm(dir,{recursive:true,force:true}); }
docs/audits/2026-10-15-phase1-auth-hardening.md new
+50
@@ -0,0 +1,50 @@
1 +# LifeGuide — بسته اصلاح هویت در فاز۱
2 +
3 +این بسته بر شاخه `fix/auth-abuse-expiry-safety` و مبنای PR14 در `5da6c4290e422162c13c3fe5260345770dde7ffa` است؛ **در main ادغام نشده و سرویس زنده اصلاح‌شده محسوب نمی‌شود**. استفاده از کد سالم موجود عمدی است؛ این PR ورود/خانواده/کتابخانه را بازسازی نمی‌کند. نسخه Backend همان0.7.1 است؛ تغییرات هنوز Unreleased هستند.
4 +
5 +## طراحی محدود و معیار پذیرش
6 +
7 +- شمار درخواست auth/session باید در دو فرایند و پس از restart مشترک بماند؛ شماره و IP محدودیت مستقل دارند. محدودیت شماره/OTP هش‌شده۵دقیقه‌ای/۵تلاش از مبنا حفظ می‌شود؛ IP اکنون DB-based است.
8 +- یک‌بارمصرف، refresh و OTP منقضی‌شده هنگام انتظار قفل نباید پذیرفته شوند. ساعت پس از گرفتن قفل‌ها در statement تازه خوانده شود؛ `now()` آغاز تراکنش کافی نیست.
9 +- داشتن credential پیامک به معنی اجازه ارسال نیست؛ تا تأیید مالک و الگو، وضعیت `APPROVAL_REQUIRED` و بدون شبکه باشد. development از adapter تزریقیِ fixture استفاده می‌کند؛ مسیر تولید OTP debug در پاسخ یا لاگ ندارد.
10 +- اجرای production باید از `npm start`/`src/entrypoint.js` باشد؛ listener مستقیم `server.js` نباید middleware مشترک را دور بزند.
11 +- بیست Migration اصلی و سه فایل Supabase تاریخی نباید تغییر کنند؛ هیچ داده/DDL/سرویس زنده در این بسته تغییر نکند.
12 +
13 +## تغییرات واقعی
14 +
15 +**VERIFIED-source/runtime محلی:** `auth_rate_limit.js` برای مسیرهای auth و session شمارنده اتمیک PostgreSQL دارد؛ کلید تنها HMAC دامنه‌دار IP canonical با JWT_SECRET موجود است. IPv4 و IPv6 معادل یک سهمیه دارند؛ هدر forwarding فقط طبق allowlist معتبر Express اثر دارد. ساعت DB پس از advisory lock خوانده می‌شود. خطای SQL/قفل پاسخ عمومی503 می‌دهد و به counter حافظه‌ای fallback نمی‌کند. share حافظه‌ای general/AI باقی است؛ auth دوباره شارژ نمی‌شود.
16 +
17 +Migration افزایشی `0023_auth_ip_rate_limit.sql` فقط profile،digest،window و count دارد؛ IP خام، شماره، OTP، userId یا body در آن ذخیره نمی‌شود.0021/0022 برای کار ناتمام قبلی در worktree دیگر رزرو مانده‌اند و وارد این PR نمی‌شوند. runtime-role allowlist جدول جدید را شامل می‌شود. `pruneExpiredAuthRateLimits` حداکثر۵۰۰ ردیف منقضی را با `SKIP LOCKED` پاک می‌کند؛ **هیچ cron/worker یا زمان‌بندی خارجی ایجاد نشده است**. JWT secret باید میان replicaها یکسان باشد؛ چرخش آن quota را هم عوض می‌کند.
18 +
19 +مصرف email/reset token، refresh و OTP پس از قفل account و row، انقضا را با `clock_timestamp()` در statement بعدی بررسی می‌کند. cooldown شماره نیز بعد از قفل با زمان تازه محاسبه می‌شود. Argon2id، digest tokenها، rotation نشست، schema و issuer/audience حفظ شدند.
20 +
21 +`SMS_PROVIDER` همچنان disabled است. انتخاب Kavenegar علاوه بر credential به دو مقدار دقیق `SMS_LIVE_ENABLED=true` و `KAVENEGAR_TEMPLATE_APPROVED=true` نیاز دارد؛ webhook نیز live flag می‌خواهد. `.env.example` هر دو را false می‌گذارد. این مقادیر هرگز توسط کلاینت تنظیم نمی‌شوند؛ نوشتن true مدرک تأیید یا مجوز عملیاتی نیست. هیچ ارسال واقعی انجام نشد.
22 +
23 +QA SQL builder اکنون **منبع۲۱تایی**۰۰۰۱–۰۰۲۰+۰۰۲۳ را صریح می‌پذیرد و lockdown را حفظ می‌کند؛ baseline زنده Supabase همچنان همان۲۰ Migration ممیزی‌شده است. SQL خروجی جدید روی QA اجرا نشده و برای اجرای دوباره روی schema موجود طراحی نشده است. گرفتن21entry از generator به معنی اعمال21migration نیست. hash همه۲۰ فایل اصلی و هر۳bundle تاریخی نسبت به مبنا یکسان تأیید شد.
24 +
25 +## RED → GREEN و شواهد اجرا
26 +
27 +**VERIFIED / Node24.19.0، PostgreSQL16.15، فقط fixture مصنوعی loopback:**
28 +
29 +|فرمان|خروجی واقعی|
30 +|---|---|
31 +|`node --test tests/auth_post_lock_expiry.test.js tests/sms_approval_gate.test.js` پیش از اصلاح، با اجرای ترتیبی|۶شکست/۱موفق؛۴مسیر منقضی به‌اشتباه200/204 و۲حالت SMS فعال بودند|
32 +|همان مسیرهای expiry/provider همراه تست‌های adapter پس از اصلاح|۲۳/۲۳ موفق؛ بدون provider زنده|
33 +|`node --test tests/auth_ip_rate_limit.test.js` پیش از اصلاح|دو فرایند۶درخواست پذیرفتند، انتظار۳؛ RED|
34 +|آزمون‌های جدید IP و رگرسیون NAT/proxy/operations|۱۴/۱۴ موفق؛۷تست جدید PG/HTTP؛ تکرار مستقل NAT نیز۱/۱ موفق|
35 +|تست واقعی `production_entrypoint.test.js`|RED: listener قدیمی باز ماند؛ GREEN: exit1 با دستور امن و بدون listener؛ بازبین مستقل هم۱/۱ موفق|
36 +|`npm run migrate`، تکرار، import کاتالوگ و تکرار|همه exit0؛۲۱migration محلی؛ کاتالوگ همچنان DRAFT|
37 +|چهار فایل `*schema_test.sql` با `psql -v ON_ERROR_STOP=1`|هر۴ اجرا exit0 و rollback fixture|
38 +|`npm test -- --test-concurrency=1`، بدون فیلتر فایل/نام|**۲۷۱تست،۲۷۱pass،۰fail/cancelled/skip**؛79.28s|
39 +|`npm run check` و `git diff --check`|هر دو exit0|
40 +|بازبینی مستقل|۲۳تست provider/bundle/direct-start، alias probe و مقایسه بایت Migrationها موفق؛ هیچ critical/important حل‌نشده در تغییرات محدود گزارش نشد|
41 +
42 +برای اجرای کامل، DB محلی قدیمیِ آزمایشی با نام مجاز موقتاً با catalog rename حفظ شد؛ DB تازه با همان نام برای fixtureها ساخته، پس از تست حذف و نام قبلی بازگردانده شد. داده کاربردی DB قبلی خوانده/تغییر نکرد. env محلی خصوصی بود و در Git/گزارش قرار نگرفت. اجرای اولیه filtered baseline به‌دلیل resourceهای moduleهای skipشده متوقف شد و موفق گزارش نمی‌شود؛ اجرای کامل بالا بدون فیلتر است. اولین harness تست expiry نیز مسیر HTTP اشتباه داشت؛ پس از اصلاح harness، RED واقعی با وضعیت200/204 مشاهده شد، سپس کد اصلاح شد.
43 +
44 +## محدودیت و ادامه
45 +
46 +**UNVERIFIED در این بسته:** Node22 محلی، ساخت تازه Flutter/APK، امضای release، Android/Safari، SMS واقعی/تأیید الگو، اتصال عملیاتی Express به Supabase، تست شبکه ایران، backup/restore و نقش runtime واقعی در اجرای محلی جدید. CI/دستگاه تا مشاهده خروجی خودشان تأیید نمی‌شوند. import/restore/CI قدیمی به این patch نسبت داده نمی‌شود.
47 +
48 +این اصلاح **فاز۱ کامل نیست**: سرپرستی/رضایت/QR کودک، مشتقات چت خصوصی در حالت حساس، cycle plaintext در حالت بازشده، باقی audit/validation و session-after-wait در مسیرهای دیگر هنوز به بسته و تصمیم جدا نیاز دارند. AI خارجی در مبنا خاموش و sensitive پیش‌فرض بسته بود؛ این PR سیاست آن‌ها را تغییر نداده است. private PWA session/retention و زیرساخت نیز نیازمند انتخاب ADR هستند. main/PWA عمومی همچنان نسخه معرفی‌اند.
49 +
50 +ادغام/انتشار بدون تأیید مالک ممنوع است. پس از ادغام‌های مصوب، ابتدا21migration در DB مصنوعی محلی، سپس آزمون‌ها اجرا شوند. قبل هر اتصال remote باید schema/search_path، نقش runtime، TLS معتبر و Migration افزایشی متناسب با QA موجود جدا بررسی/تأیید شوند؛ `migrate.js` عمومی را کورکورانه روی lifeguide_qa اجرا نکنید. برای تست توسعه از fixture محلی و `SMS_PROVIDER=disabled` استفاده کنید؛ فعال‌کردن هر دو flag پیامک و ارسال واقعی هنوز مجوز جدا می‌خواهد.