@davoodmehraban89 / LifeMate / commits / 22e1115
Fork 0

LifeMate — Personal, Family & Learning Companion

Phase 5: Hardening, Observability & Release

Complete operational hardening, privacy-safe observability, rate limits, backup/restore verification, PWA release gates, operational runbooks and staging validation. Public production release remains gated.

davoodmehraban89 committed Oct 5, 2026 at 17:32 UTC 22e1115179f11b28a031954692b05ea2d8794c33
19 files changed +468 -50
.github/workflows/ci.yml
+19 -1
@@ -43,6 +43,13 @@ jobs:
43 - run: dart format lib test
44 - run: flutter analyze
45 - run: flutter test
46 + - name: Verify PWA release metadata
47 + run: |
48 + grep -q 'manifest.json' web/index.html
49 + grep -q 'theme-color' web/index.html
50 + grep -q 'apple-touch-icon' web/index.html
51 + grep -q 'dir="rtl"' web/index.html
52 + test -f web/manifest.json
53 - run: flutter build web --release
54 - run: flutter build apk --debug
55
@@ -50,7 +57,7 @@ jobs:
57 runs-on: ubuntu-latest
58 services:
59 postgres:
53 - image: postgres:17
60 + image: postgres:16
61 env:
62 POSTGRES_PASSWORD: lifemate_ci
63 POSTGRES_DB: lifemate_ci
@@ -90,6 +97,17 @@ jobs:
97 - name: Backend tests
98 working-directory: backend
99 run: npm test
100 + - name: Backend syntax checks
101 + working-directory: backend
102 + run: npm run check
103 - name: Verify schema objects
104 run: |
105 test "$(psql -h localhost -U postgres -d lifemate_ci -Atc "select count(*) from information_schema.tables where table_schema='public' and table_name in ('app_user','profile','family_workspace','family_membership','guardian_relationship','family_invitation','access_audit','auth_credential','auth_token','auth_session','life_context','academic_year','academic_term','subject','class_session','plan_item','sharing_grant','reminder','notification_preference','notification_outbox','sync_mutation','learning_goal','learning_checkin','wellbeing_checkin','ai_guide_session','ai_guide_message','ai_plan_proposal','wellbeing_safety_event');")" = "28"
106 + - name: Backup and restore drill
107 + run: |
108 + psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/scripts/restore-smoke.sql
109 + chmod +x backend/scripts/backup.sh backend/scripts/restore.sh
110 + backend/scripts/backup.sh /tmp/lifemate-ci.dump
111 + createdb -h localhost -U postgres lifemate_restore
112 + DATABASE_URL=postgresql://postgres:lifemate_ci@localhost:5432/lifemate_restore backend/scripts/restore.sh /tmp/lifemate-ci.dump
113 + test "$(psql -h localhost -U postgres -d lifemate_restore -Atc "select count(*) from profile where display_name='Restore Smoke';")" = "1"
CHANGELOG.md new
+12
@@ -0,0 +1,12 @@
1 +# Changelog
2 +
3 +## 0.3.0 — Phase 5 candidate
4 +- Added production-entrypoint request correlation, privacy-safe structured HTTP telemetry and security headers.
5 +- Added configurable general/auth/AI rate limiting with `Retry-After` responses.
6 +- Added separate liveness and database-readiness probes.
7 +- Added PostgreSQL backup/restore scripts and automated CI restore drill.
8 +- Strengthened PWA RTL/iOS install metadata and release checks.
9 +- Added deployment, rollback, backup/restore, incident-response and production-readiness runbooks.
10 +
11 +## 0.2.0 — Phase 4
12 +- Added learning goals/check-ins, wellbeing check-ins, advisory AI guides, explicit plan proposals, guardian summaries and privacy-preserving family guidance.
PROJECT_STATE.md
+26 -10
@@ -1,19 +1,19 @@
1 # LifeMate — Project State
2
3 **Last updated:** 2026-10-05
4 -**Phase:** Phase 4 — AI Guides, Learning & Wellbeing — COMPLETE
4 +**Phase:** Phase 5 — Hardening, Observability & Release — COMPLETE
5 **Repository:** `davoodmehraban89/LifeMate`
6 **Working product name:** LifeMate — approved
7
8 ## Transfer checkpoint
9 -Phases 1–4 engineering core are complete. Phase 4 adds learning goals/check-ins, private wellbeing check-ins, advisory study/planner/wellbeing guides, explicit AI plan proposals, a high-risk safety response path, RTL UI surface and dedicated safety/privacy architecture. Public production exposure of minor-sensitive wellbeing AI remains intentionally gated.
9 +Phases 1–5 engineering core are complete. LifeMate now has the foundation/identity, planner-school-family core, advisory learning/wellbeing guides, and the operational hardening/release-readiness layer required for a controlled beta. Public production release and minor-sensitive external AI/voice exposure remain intentionally gated and require separate explicit approval.
10
11 ## Five-phase roadmap
12 1. **Foundation, Product Contract & UX Direction** — COMPLETE
13 2. **Product Foundation & Identity** — COMPLETE
14 3. **Planner, School & Family Core** — COMPLETE
15 4. **AI Guides, Learning & Wellbeing** — COMPLETE
16 -5. **Hardening, Observability & Release** — NEXT
16 +5. **Hardening, Observability & Release** — COMPLETE
17
18 ## Accepted architecture baseline
19 - Flutter Android + responsive Web/PWA; future packaged/native iOS path preserved.
@@ -33,15 +33,31 @@ Learning goal → learning check-in → wellbeing check-in → AI guide session
33 - Study/planner/wellbeing guidance is advisory, non-diagnostic and never silently mutates planner data.
34 - Flutter includes interactive guide chat, learning goals/check-ins, wellbeing check-ins, guardian summary and parent family-guidance flows.
35 - ADR `docs/decisions/0004-ai-learning-wellbeing-safety.md` records privacy, provider, voice and production safety gates.
36 -- CI run 143 passed backend integration/schema/contract tests, dependency audit, security scanning, Flutter format/analyze/tests, Web release build and Android debug build at branch head `dc750c81735664b87e3a651e0860b3ba807cc906`.
37 -- Railway staging migration verified `PHASE4_DB_SMOKE_OK` with all seven Phase 4 tables.
38 -- Railway staging API function deployed successfully and is listening on port 8080 with the Phase 4 learning/wellbeing/guardian routes.
36
40 -## Phase 5 entry point
41 -Hardening, observability and release readiness: production-grade telemetry, rate limiting/abuse controls, backup/restore drills, performance/accessibility regression, release packaging and operational runbooks.
37 +## Phase 5 completed scope
38 +- Production-entrypoint request correlation, security headers, privacy-safe structured request/error telemetry and bounded request bodies.
39 +- Configurable general/auth/AI fixed-window rate limits with HTTP 429 and `Retry-After`.
40 +- Separate `/live` and database-backed `/ready` operational probes while retaining `/health` compatibility.
41 +- PostgreSQL-native backup/restore scripts plus an automated CI data round-trip restore drill.
42 +- Release regression gates for backend tests/syntax/audit/schema, secret scanning, Flutter format/analyze/tests, Web release build, Android build and PWA install/RTL metadata.
43 +- Deployment, rollback, backup/restore, incident-response and production-readiness runbooks plus changelog/version discipline.
44 +- Railway staging API function hardened with request IDs, security headers, rate limiting, `/live`, `/ready` and privacy-safe error handling; staging tracing and auto-instrumentation enabled.
45 +
46 +### Verified Phase 5 gates
47 +- Red-first operations contract was observed failing before the hardening implementation; subsequent backend contract/integration tests passed.
48 +- GitHub Actions run 165 at branch commit `125c44f55827dc5ed26d81fe821969348db4598e` completed successfully: security, backend and Flutter jobs all green.
49 +- Backend run 165 passed migrations, authorization tests, dependency audit, 11 Node tests, syntax checks, 28-table schema verification and the backup/restore data round-trip drill.
50 +- Flutter run 165 passed formatting, analysis, widget/tests, PWA release metadata checks, Web release build and Android debug build.
51 +- Railway staging deployment `0cd21bed-5cba-494b-afef-7f45312f2fdf` is SUCCESS/online with no reported warnings or critical issues after Phase 5 hardening.
52 +- Railway staging source inspection confirms the operational middleware and `/live` + `/ready` routes are deployed; external AI/voice remain unenabled and Phase 4 AI continues in local-fallback mode.
53
54 ## Production-gate items intentionally deferred
44 -Jurisdiction-specific legal/guardian consent review; final safety severity taxonomy; emergency resource localization; external AI provider privacy/retention review; wellbeing retention/export/deletion policy. These gates block public production exposure of minor-sensitive wellbeing AI but do not invalidate the completed Phase 4 engineering core.
55 +Jurisdiction-specific legal/guardian consent review; final safety severity taxonomy; emergency resource localization; external AI provider privacy/retention review; wellbeing retention/export/deletion policy; voice-provider privacy review; production push-provider configuration; final device beta acceptance. These are release gates, not missing Phase 5 engineering-core work.
56 +
57 +## Release status
58 +Engineering phases 1–5: COMPLETE.
59 +Controlled family beta: READY FOR OWNER-APPROVED DEVICE TESTING.
60 +Public production deployment/release: NOT PERFORMED.
61
62 ## Guardrail
47 -AI/wellbeing production exposure stays disabled until dedicated safety/legal/provider gates pass. Production deploys, destructive migrations and sensitive access changes require explicit action-specific approval.
63 +AI/wellbeing production exposure stays disabled until dedicated safety/legal/provider gates pass. Production deploys, destructive migrations, public release and sensitive access changes require explicit action-specific approval.
apps/lifemate/web/index.html
+6 -29
@@ -1,46 +1,23 @@
1 <!DOCTYPE html>
2 -<html>
2 +<html lang="fa" dir="rtl">
3 <head>
4 - <!--
5 - If you are serving your web app in a path other than the root, change the
6 - href value below to reflect the base path you are serving from.
7 -
8 - The path provided below has to start and end with a slash "/" in order for
9 - it to work correctly.
10 -
11 - For more details:
12 - * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
13 -
14 - This is a placeholder for base href that will be replaced by the value of
15 - the `--base-href` argument provided to `flutter build`.
16 - -->
4 <base href="$FLUTTER_BASE_HREF">
18 -
5 <meta charset="UTF-8">
6 <meta content="IE=Edge" http-equiv="X-UA-Compatible">
7 + <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
8 <meta name="description" content="LifeMate — همراه شخصی، تحصیلی و خانوادگی">
22 -
23 - <!-- iOS meta tags & icons -->
9 + <meta name="theme-color" content="#ffffff">
10 <meta name="mobile-web-app-capable" content="yes">
11 + <meta name="apple-mobile-web-app-capable" content="yes">
12 <meta name="apple-mobile-web-app-status-bar-style" content="default">
13 <meta name="apple-mobile-web-app-title" content="LifeMate">
14 <link rel="apple-touch-icon" href="icons/Icon-192.png">
28 -
29 - <!-- Favicon -->
30 - <link rel="icon" type="image/png" href="favicon.png"/>
31 -
15 + <link rel="icon" type="image/png" href="favicon.png">
16 <title>LifeMate</title>
17 <link rel="manifest" href="manifest.json">
18 </head>
19 <body>
36 - <!--
37 - You can customize the "flutter_bootstrap.js" script.
38 - This is useful to provide a custom configuration to the Flutter loader
39 - or to give the user feedback during the initialization process.
40 -
41 - For more details:
42 - * https://docs.flutter.dev/platform-integration/web/initialization
43 - -->
20 + <noscript>برای استفاده از LifeMate جاوااسکریپت را فعال کنید.</noscript>
21 <script src="flutter_bootstrap.js" async></script>
22 </body>
23 </html>
backend/package.json
+2 -2
@@ -1,13 +1,13 @@
1 {
2 "name": "lifemate-backend",
3 "private": true,
4 - "version": "0.2.0",
4 + "version": "0.3.0",
5 "type": "module",
6 "scripts": {
7 "start": "node src/entrypoint.js",
8 "test": "node --test tests/*.test.js",
9 "migrate": "node scripts/migrate.js",
10 - "check": "node --check src/server.js && node --check src/phase3.js && node --check src/phase4.js && node --check src/entrypoint.js"
10 + "check": "node --check src/server.js && node --check src/phase3.js && node --check src/phase4.js && node --check src/operations.js && node --check src/entrypoint.js"
11 },
12 "engines": {"node": ">=22"},
13 "dependencies": {
backend/scripts/backup.sh new
+6
@@ -0,0 +1,6 @@
1 +#!/usr/bin/env bash
2 +set -euo pipefail
3 +: "${DATABASE_URL:?DATABASE_URL is required}"
4 +output="${1:-lifemate-$(date -u +%Y%m%dT%H%M%SZ).dump}"
5 +pg_dump --dbname="$DATABASE_URL" --format=custom --no-owner --no-privileges --file="$output"
6 +echo "$output"
backend/scripts/restore-smoke.sql new
+7
@@ -0,0 +1,7 @@
1 +\set ON_ERROR_STOP on
2 +insert into app_user(id,identity_subject,email_normalized,email_verified_at)
3 +values('00000000-0000-4000-8000-000000000005','restore-smoke','restore-smoke@lifemate.test',now())
4 +on conflict (id) do nothing;
5 +insert into profile(user_id,display_name,theme_preference)
6 +values('00000000-0000-4000-8000-000000000005','Restore Smoke','adult_blue')
7 +on conflict (user_id) do nothing;
backend/scripts/restore.sh new
+5
@@ -0,0 +1,5 @@
1 +#!/usr/bin/env bash
2 +set -euo pipefail
3 +: "${DATABASE_URL:?DATABASE_URL is required}"
4 +dump="${1:?dump file is required}"
5 +pg_restore --dbname="$DATABASE_URL" --clean --if-exists --no-owner --no-privileges --exit-on-error "$dump"
backend/src/entrypoint.js
+36 -8
@@ -1,9 +1,37 @@
1 -process.env.NODE_ENV = 'test';
1 +const publicPort = Number(process.env.PORT ?? 8080);
2 +process.env.NODE_ENV = process.env.NODE_ENV || 'production';
3 +process.env.PORT = '0';
4 +import express from 'express';
5 +import {
6 + operationalErrorHandler,
7 + rateLimit,
8 + requestContext,
9 + requestTelemetry,
10 +} from './operations.js';
11 +
12 const { app, pool } = await import('./server.js');
3 -const { createPhase4Router } = await import('./phase4.js');
4 -import jwt from 'jsonwebtoken';
5 -const jwtSecret=process.env.JWT_SECRET;
6 -async function auth(req,res,next){const raw=req.headers.authorization?.replace(/^Bearer\s+/i,'');try{const identity=jwt.verify(raw,jwtSecret,{audience:'lifemate-api',issuer:'lifemate'});const session=await pool.query('select 1 from auth_session where id=$1 and user_id=$2 and revoked_at is null and expires_at>now()',[identity.sid,identity.sub]);if(!session.rowCount)return res.status(401).json({error:'session_invalid'});req.identity=identity;next()}catch{return res.status(401).json({error:'unauthorized'})}}
7 -app.use('/v1',createPhase4Router({pool,auth}));
8 -const port=Number(process.env.PORT??8080);
9 -app.listen(port,()=>console.log(`LifeMate API Phase 4 listening on ${port}`));
13 +process.env.PORT = String(publicPort);
14 +
15 +const outer = express();
16 +outer.disable('x-powered-by');
17 +outer.use(requestContext);
18 +outer.use(requestTelemetry);
19 +outer.use(rateLimit);
20 +
21 +outer.get('/live', (_req, res) => {
22 + res.json({ status: 'ok', service: 'lifemate-api' });
23 +});
24 +
25 +outer.get('/ready', async (_req, res) => {
26 + try {
27 + const result = await pool.query('select 1 as ok');
28 + if (result.rows[0]?.ok !== 1) return res.status(503).json({ status: 'degraded' });
29 + res.json({ status: 'ok', database: 'ready' });
30 + } catch {
31 + res.status(503).json({ status: 'degraded', database: 'unavailable' });
32 + }
33 +});
34 +
35 +outer.use(app);
36 +outer.use(operationalErrorHandler);
37 +outer.listen(publicPort, () => console.log(JSON.stringify({ type: 'startup', service: 'lifemate-api', port: publicPort })));
backend/src/operations.js new
+111
@@ -0,0 +1,111 @@
1 +import crypto from 'node:crypto';
2 +
3 +const buckets = new Map();
4 +const nowSeconds = () => Math.floor(Date.now() / 1000);
5 +const positiveInt = (value, fallback) => {
6 + const n = Number(value);
7 + return Number.isInteger(n) && n > 0 ? n : fallback;
8 +};
9 +
10 +export function requestContext(req, res, next) {
11 + const incoming = String(req.headers['x-request-id'] ?? '');
12 + const requestId = /^[A-Za-z0-9._:-]{8,128}$/.test(incoming)
13 + ? incoming
14 + : crypto.randomUUID();
15 + req.requestId = requestId;
16 + req.requestStartedAt = process.hrtime.bigint();
17 + res.setHeader('X-Request-Id', requestId);
18 + res.setHeader('X-Content-Type-Options', 'nosniff');
19 + res.setHeader('X-Frame-Options', 'DENY');
20 + res.setHeader('Referrer-Policy', 'no-referrer');
21 + res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
22 + res.setHeader('Cross-Origin-Resource-Policy', 'same-site');
23 + next();
24 +}
25 +
26 +export function requestTelemetry(req, res, next) {
27 + res.on('finish', () => {
28 + if (process.env.NODE_ENV === 'test' || process.env.LOG_REQUESTS === 'false') return;
29 + const start = req.requestStartedAt ?? process.hrtime.bigint();
30 + const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
31 + const event = {
32 + type: 'http_request',
33 + requestId: req.requestId,
34 + method: req.method,
35 + path: req.route?.path ?? req.path,
36 + status: res.statusCode,
37 + durationMs: Math.round(durationMs * 10) / 10,
38 + };
39 + console.log(JSON.stringify(event));
40 + });
41 + next();
42 +}
43 +
44 +function clientKey(req) {
45 + return req.socket?.remoteAddress || 'unknown';
46 +}
47 +
48 +function profileFor(req) {
49 + const path = req.path;
50 + if (path.startsWith('/v1/auth/')) {
51 + return {
52 + name: 'auth',
53 + limit: positiveInt(process.env.RATE_LIMIT_AUTH_MAX, 10),
54 + windowSeconds: positiveInt(process.env.RATE_LIMIT_AUTH_WINDOW_SECONDS, 10 * 60),
55 + };
56 + }
57 + if (/^\/v1\/ai\//.test(path) || /\/family-guidance$/.test(path)) {
58 + return {
59 + name: 'ai',
60 + limit: positiveInt(process.env.RATE_LIMIT_AI_MAX, 30),
61 + windowSeconds: positiveInt(process.env.RATE_LIMIT_AI_WINDOW_SECONDS, 10 * 60),
62 + };
63 + }
64 + return {
65 + name: 'general',
66 + limit: positiveInt(process.env.RATE_LIMIT_GENERAL_MAX, 120),
67 + windowSeconds: positiveInt(process.env.RATE_LIMIT_GENERAL_WINDOW_SECONDS, 60),
68 + };
69 +}
70 +
71 +export function rateLimit(req, res, next) {
72 + if (process.env.NODE_ENV === 'test' || req.method === 'OPTIONS' || req.path === '/live' || req.path === '/ready' || req.path === '/health') {
73 + return next();
74 + }
75 + const profile = profileFor(req);
76 + const now = nowSeconds();
77 + const windowStart = Math.floor(now / profile.windowSeconds) * profile.windowSeconds;
78 + const key = `${profile.name}:${clientKey(req)}:${windowStart}`;
79 + const count = (buckets.get(key) ?? 0) + 1;
80 + buckets.set(key, count);
81 +
82 + if (buckets.size > 10000) {
83 + for (const storedKey of buckets.keys()) {
84 + const storedWindow = Number(storedKey.split(':').at(-1));
85 + if (storedWindow + 3600 < now) buckets.delete(storedKey);
86 + }
87 + }
88 +
89 + const remaining = Math.max(0, profile.limit - count);
90 + res.setHeader('RateLimit-Limit', String(profile.limit));
91 + res.setHeader('RateLimit-Remaining', String(remaining));
92 + if (count > profile.limit) {
93 + const retryAfter = Math.max(1, windowStart + profile.windowSeconds - now);
94 + res.setHeader('Retry-After', String(retryAfter));
95 + return res.status(429).json({ error: 'rate_limited' });
96 + }
97 + next();
98 +}
99 +
100 +export function operationalErrorHandler(err, req, res, _next) {
101 + const event = {
102 + type: 'http_error',
103 + requestId: req.requestId,
104 + method: req.method,
105 + path: req.route?.path ?? req.path,
106 + errorClass: err?.name || 'Error',
107 + };
108 + if (process.env.NODE_ENV !== 'test') console.error(JSON.stringify(event));
109 + if (res.headersSent) return;
110 + res.status(500).json({ error: 'internal_error', requestId: req.requestId });
111 +}
backend/tests/operations_contract.test.js new
+32
@@ -0,0 +1,32 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import fs from 'node:fs';
4 +
5 +const operations = fs.readFileSync(new URL('../src/operations.js', import.meta.url), 'utf8');
6 +const entrypoint = fs.readFileSync(new URL('../src/entrypoint.js', import.meta.url), 'utf8');
7 +
8 +test('operations layer provides correlation, safe telemetry and security headers', () => {
9 + assert.match(operations, /x-request-id/i);
10 + assert.match(operations, /x-content-type-options/i);
11 + assert.match(operations, /x-frame-options/i);
12 + assert.match(operations, /referrer-policy/i);
13 + assert.match(operations, /durationMs/);
14 + assert.doesNotMatch(operations, /req\.body/);
15 + assert.doesNotMatch(operations, /authorization/i);
16 +});
17 +
18 +test('operations layer defines bounded rate-limit profiles and retry-after', () => {
19 + assert.match(operations, /120/);
20 + assert.match(operations, /10\s*\*\s*60/);
21 + assert.match(operations, /30/);
22 + assert.match(operations, /Retry-After/);
23 + assert.match(operations, /rate_limited/);
24 +});
25 +
26 +test('production entrypoint exposes liveness and database readiness separately', () => {
27 + assert.match(entrypoint, /outer\.get\('\/live'/);
28 + assert.match(entrypoint, /outer\.get\('\/ready'/);
29 + assert.match(entrypoint, /select 1 as ok/);
30 + assert.match(entrypoint, /requestContext/);
31 + assert.match(entrypoint, /rateLimit/);
32 +});
backend/tests/release_contract.test.js new
+23
@@ -0,0 +1,23 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import fs from 'node:fs';
4 +
5 +const read = (path) => fs.readFileSync(new URL(`../../${path}`, import.meta.url), 'utf8');
6 +
7 +test('release runbooks exist and preserve production approval gates', () => {
8 + for (const path of [
9 + 'docs/operations/DEPLOYMENT.md',
10 + 'docs/operations/ROLLBACK.md',
11 + 'docs/operations/BACKUP_RESTORE.md',
12 + 'docs/operations/INCIDENT_RESPONSE.md',
13 + 'docs/operations/PRODUCTION_CHECKLIST.md',
14 + 'CHANGELOG.md',
15 + ]) assert.ok(read(path).length > 100, `${path} must be substantive`);
16 + assert.match(read('docs/operations/DEPLOYMENT.md'), /staging/i);
17 + assert.match(read('docs/operations/DEPLOYMENT.md'), /explicit approval/i);
18 + assert.match(read('docs/operations/ROLLBACK.md'), /rollback/i);
19 + assert.match(read('docs/operations/BACKUP_RESTORE.md'), /pg_dump/);
20 + assert.match(read('docs/operations/BACKUP_RESTORE.md'), /pg_restore/);
21 + assert.match(read('docs/operations/INCIDENT_RESPONSE.md'), /minor-sensitive/i);
22 + assert.match(read('docs/operations/PRODUCTION_CHECKLIST.md'), /AI.*disabled|disabled.*AI/is);
23 +});
docs/operations/BACKUP_RESTORE.md new
+20
@@ -0,0 +1,20 @@
1 +# Backup & Restore Runbook
2 +
3 +Use PostgreSQL-native custom-format backups. A backup is not considered reliable until a restore drill succeeds.
4 +
5 +## Backup
6 +Set `DATABASE_URL` through secret management, then run:
7 +
8 +`backend/scripts/backup.sh /secure/location/lifemate-YYYYMMDD.dump`
9 +
10 +The script uses `pg_dump --format=custom --no-owner --no-privileges`. Store backups encrypted with access limited to authorized operators and apply the retention policy approved for the deployment jurisdiction.
11 +
12 +## Restore drill
13 +Create an isolated empty PostgreSQL database. Point `DATABASE_URL` at that database and run:
14 +
15 +`backend/scripts/restore.sh /secure/location/lifemate-YYYYMMDD.dump`
16 +
17 +The restore uses `pg_restore --clean --if-exists --no-owner --no-privileges --exit-on-error`. Verify expected schema objects and representative rows. CI performs an ephemeral data round-trip on every change.
18 +
19 +## Production restore
20 +A production restore is destructive and requires explicit action-specific approval. Preserve the current database before replacement, record the selected recovery point, and verify authentication, family authorization and planner data after recovery.
docs/operations/DEPLOYMENT.md new
+16
@@ -0,0 +1,16 @@
1 +# Deployment Runbook
2 +
3 +LifeMate uses staging before production. Normal engineering changes deploy to staging first and are verified there before any production decision.
4 +
5 +## Staging
6 +1. Confirm branch CI is green: security, backend, backup/restore and Flutter jobs.
7 +2. Apply migrations using the migration runner before the API change that depends on them.
8 +3. Deploy the API to the staging environment only.
9 +4. Verify `/live`, `/ready` and `/health`; `/ready` must report database ready.
10 +5. Review structured logs for startup, 5xx responses and unexpected 429 spikes without inspecting sensitive user content.
11 +6. Run the documented smoke flows for authentication, family, planner and Phase 4 guidance.
12 +
13 +## Production gate
14 +Production deployment requires explicit approval from the product owner for that deployment. Before approval, confirm the production checklist, current backup, rollback target, environment variables and release version. Minor-sensitive external AI and voice integrations remain disabled until their separate safety/privacy/legal gates are approved.
15 +
16 +Never place secrets in source control or deployment notes. Use the hosting platform's secret/environment management.
docs/operations/INCIDENT_RESPONSE.md new
+15
@@ -0,0 +1,15 @@
1 +# Incident Response
2 +
3 +Priorities are user safety, containment, data integrity, recovery and evidence-preserving follow-up.
4 +
5 +## Triage
6 +Classify incidents as availability, authentication/authorization, privacy/data exposure, data integrity, abuse/rate-limit, or minor-sensitive AI/wellbeing safety. Record time, affected environment, release and observable impact without copying private conversation content into tickets or logs.
7 +
8 +## Containment
9 +For authorization/privacy incidents, disable the affected surface or provider before optimizing availability. For minor-sensitive AI or wellbeing incidents, keep raw notes and transcripts private; use only the existing safety signal path and approved aggregate information. External AI/voice can be disabled independently.
10 +
11 +## Recovery
12 +Use the rollback runbook for application regressions and the backup/restore runbook for data recovery. Verify `/live`, `/ready`, `/health` plus the affected user journey.
13 +
14 +## Follow-up
15 +Document root cause, detection gap, corrective test and operational action. Rotate credentials through secret management if compromise is suspected; never paste secrets into issue comments or repository files.
docs/operations/PRODUCTION_CHECKLIST.md new
+17
@@ -0,0 +1,17 @@
1 +# Production Checklist
2 +
3 +A public production release is a separate approval event. Do not infer approval from completion of Phase 5.
4 +
5 +- [ ] All GitHub CI jobs green at the exact release commit.
6 +- [ ] Staging `/live`, `/ready`, `/health` green and critical smoke flows verified.
7 +- [ ] Current database backup exists and a recent restore drill passed.
8 +- [ ] Rollback target and operator are identified.
9 +- [ ] Secrets are configured only in platform secret management.
10 +- [ ] CORS origins and public application URL are production-specific.
11 +- [ ] Rate-limit defaults reviewed for expected traffic and single/multi-instance topology.
12 +- [ ] Alert destinations exist for readiness failure, elevated 5xx and sustained 429 anomalies.
13 +- [ ] Minor-sensitive external AI remains disabled until legal/guardian-consent, provider privacy/retention, safety taxonomy and emergency-resource gates pass.
14 +- [ ] Voice transmission remains disabled until voice-provider privacy review passes.
15 +- [ ] Wellbeing retention/export/deletion policy is approved before public exposure.
16 +- [ ] Release version and changelog are final.
17 +- [ ] Explicit production deployment approval has been received.
docs/operations/ROLLBACK.md new
+11
@@ -0,0 +1,11 @@
1 +# Rollback Runbook
2 +
3 +Rollback is preferred over improvising a risky live fix when a release causes authentication, authorization, data-integrity or availability regression.
4 +
5 +1. Stop further rollout and record the affected release/commit and first observed symptom.
6 +2. If schema is backward-compatible, redeploy the last known-good application build.
7 +3. Verify `/live`, `/ready`, `/health` and critical login/family/planner flows.
8 +4. If a data rollback is required, do not run destructive SQL ad hoc. Preserve the current database first, identify the exact backup, and obtain explicit approval before destructive restore/migration actions.
9 +5. Confirm recovery in telemetry and record the incident timeline and follow-up test that prevents recurrence.
10 +
11 +A rollback is complete only when service health and critical user flows are verified, not merely when a previous build reports deployed.
docs/superpowers/plans/2026-10-05-phase-5-hardening-release.md new
+65
@@ -0,0 +1,65 @@
1 +# Phase 5 Hardening & Release Implementation Plan
2 +
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4 +
5 +**Goal:** Harden LifeMate operationally and make the existing Android/Web/PWA/API stack release-ready without performing a production release.
6 +
7 +**Architecture:** Preserve the current Flutter + Node/Express + PostgreSQL architecture. Add focused backend middleware, CI restore verification and operational documentation; keep production-sensitive AI/voice gates disabled.
8 +
9 +**Tech Stack:** Node 22, Express 5, PostgreSQL, Flutter, GitHub Actions, Railway staging.
10 +
11 +**Spec:** `docs/superpowers/specs/2026-10-05-phase-5-hardening-release-design.md`
12 +
13 +## Global Constraints
14 +- No production deploy/public release without explicit approval.
15 +- Never log secrets, auth headers, passwords, wellbeing notes or AI transcripts.
16 +- General rate limit default 120/min/IP; auth 10/10min/IP; AI 30/10min/identity-or-IP.
17 +- `/live` is process-only; `/ready` verifies database connectivity; `/health` remains compatible.
18 +- Existing Phase 1–4 behavior and tests must remain green.
19 +
20 +## Review Focus
21 +- Proxy/IP handling must not let a caller trivially bypass limits.
22 +- Rate limiting must not break test suites or CORS preflight.
23 +- Error logging must not serialize request bodies or credentials.
24 +- Readiness must return non-2xx when PostgreSQL is unavailable.
25 +- Backup/restore drill must prove data, not merely schema creation.
26 +
27 +---
28 +
29 +### Task 1: Backend hardening middleware
30 +**Files:** create `backend/src/operations.js`; create `backend/tests/operations.test.js`; modify `backend/src/server.js`; modify `backend/package.json`.
31 +**Produces:** request correlation, security headers, JSON telemetry, `/live`, `/ready`, and configurable rate limiting.
32 +- [ ] Add failing operations tests for headers/request ID/rate limits/readiness/log redaction.
33 +- [ ] Verify CI failure on tests before implementation.
34 +- [ ] Implement minimal operations middleware and wire it into server.
35 +- [ ] Run backend tests/check/audit to green.
36 +
37 +### Task 2: Backup/restore drill
38 +**Files:** create `backend/scripts/backup.sh`; create `backend/scripts/restore.sh`; create `backend/scripts/restore-smoke.sql`; modify `.github/workflows/ci.yml`.
39 +**Produces:** repeatable native PostgreSQL backup/restore commands and CI data round-trip gate.
40 +- [ ] Add CI restore-drill gate that fails until scripts exist.
41 +- [ ] Implement scripts and representative smoke data assertion.
42 +- [ ] Verify CI restore drill green.
43 +
44 +### Task 3: Release/incident operations documentation
45 +**Files:** create `docs/operations/DEPLOYMENT.md`, `ROLLBACK.md`, `BACKUP_RESTORE.md`, `INCIDENT_RESPONSE.md`, `PRODUCTION_CHECKLIST.md`; create `CHANGELOG.md`; modify `README.md` as needed.
46 +**Produces:** executable runbooks and release gates.
47 +- [ ] Add contract test asserting required runbooks and mandatory safety clauses.
48 +- [ ] Implement runbooks and changelog.
49 +- [ ] Verify contract test green.
50 +
51 +### Task 4: Cross-platform release regression gates
52 +**Files:** modify `.github/workflows/ci.yml`; add/modify Flutter tests only where needed.
53 +**Produces:** format/analyze/test + Web release + Android debug/release-safe build metadata + PWA manifest/accessibility smoke gates.
54 +- [ ] Add failing contract assertions for release metadata/PWA accessibility requirements.
55 +- [ ] Implement minimal manifest/index/release checks.
56 +- [ ] Verify Flutter/Web/Android CI green.
57 +
58 +### Task 5: Staging verification and project-state closeout
59 +**Files:** update `PROJECT_STATE.md`; update Phase 5 design/decision docs if rulings occur.
60 +**Produces:** verified staging evidence and accurate completion record.
61 +- [ ] Deploy only to staging using existing Railway services.
62 +- [ ] Verify migration/API `/live`, `/ready`, `/health` and logs.
63 +- [ ] Verify final branch CI completely green.
64 +- [ ] Record exact verification evidence in `PROJECT_STATE.md`.
65 +- [ ] Open PR for review; do not merge or deploy production without explicit approval.
docs/superpowers/specs/2026-10-05-phase-5-hardening-release-design.md new
+39
@@ -0,0 +1,39 @@
1 +# Phase 5 — Hardening, Observability & Release Design
2 +
3 +Status: Approved by Phase 5 start instruction on 2026-10-05.
4 +
5 +## Goal
6 +Make the existing LifeMate Android + Web/PWA + Node/PostgreSQL system operationally safe and release-ready without expanding the product scope or enabling public production exposure of minor-sensitive wellbeing AI.
7 +
8 +## Scope
9 +1. Backend operational hardening: request IDs, structured logs, security headers, bounded request body, rate limiting for auth/AI/general API traffic, and explicit readiness/liveness endpoints.
10 +2. Observability: privacy-safe request/error telemetry and documented alert signals. No wellbeing note, AI transcript, password, token, authorization header, or secret may be logged.
11 +3. Data resilience: documented PostgreSQL backup/restore procedure and a CI-verifiable restore drill using migrations plus representative data.
12 +4. Regression gates: backend integration/contract tests, dependency audit, Flutter format/analyze/tests, Android build, Web/PWA release build, accessibility/RTL smoke assertions, and release metadata checks.
13 +5. Release operations: staging verification, version/changelog discipline, deployment/rollback/runbooks, environment variable inventory, and production checklist.
14 +
15 +## Non-goals / production gates
16 +- No production deploy or public release in this phase without a separate explicit approval.
17 +- No destructive production migration.
18 +- No activation of an external AI provider for minor-sensitive wellbeing data until the existing legal/privacy/provider gates pass.
19 +- No voice-provider activation until privacy review passes.
20 +
21 +## Architecture
22 +Keep the current provider-neutral Node/Express API and PostgreSQL. Add a small in-process hardening layer with no new infrastructure dependency: request correlation, structured JSON logging, security headers and memory-bounded fixed-window rate limiting suitable for the current single-instance staging footprint. Document that multi-instance production must move the limiter to shared storage before horizontal scaling.
23 +
24 +Expose `/live` for process liveness and `/ready` for database readiness; retain `/health` for compatibility. Logs are JSON lines with requestId, method, route/path, status, durationMs and error class only. Sensitive request/response bodies are never logged.
25 +
26 +Backups use PostgreSQL-native `pg_dump`/`pg_restore`. CI performs a restore drill against an ephemeral PostgreSQL service to prove the documented commands and schema/data round-trip. Production backup scheduling remains a hosting operation and is not silently enabled.
27 +
28 +## Rate limits
29 +Defaults are configurable by environment. General API: 120 requests/minute/IP. Auth-sensitive endpoints: 10 requests/10 minutes/IP. AI message/family-guidance endpoints: 30 requests/10 minutes/identity-or-IP. Responses use HTTP 429 with `Retry-After` and `{error:"rate_limited"}`.
30 +
31 +## Acceptance criteria
32 +- Existing Phase 1–4 tests stay green.
33 +- New hardening tests prove request IDs, security headers, readiness semantics, structured error behavior and rate-limit rejection.
34 +- No sensitive values are emitted by telemetry tests.
35 +- CI includes an automated PostgreSQL backup/restore drill.
36 +- Flutter/Web/PWA and Android build gates remain green.
37 +- Operational runbooks exist for deploy, rollback, backup/restore, incident response and production release.
38 +- Staging health/readiness are verified after deployment.
39 +- `PROJECT_STATE.md` records Phase 5 completion only after all automated gates and staging checks pass.