LifeMate — Personal, Family & Learning Companion
feat(ops): package same-origin TLS stack with verified prebuilt web and backups
Codex committed
Oct 8, 2026 at 16:36 UTC
5167dc8eb819eb7bedb0b116b9a63df6db482c1e
30 files changed
+1001
-40
.dockerignore
new
+18
@@ -0,0 +1,18 @@
1
+.git
2
+**/.git
3
+.env
4
+.env.*
5
+!.env.example
6
+**/node_modules
7
+**/.dart_tool
8
+**/build
9
+**/.pub-cache
10
+**/*.pem
11
+**/*.key
12
+**/*.jks
13
+**/*.keystore
14
+**/*.p12
15
+**/*.dump
16
+deployment/downloads
17
+deployment/tls
18
+docs
.env.example
new
+34
@@ -0,0 +1,34 @@
1
+# LifeGuide self-hosted stack. Copy to .env; never commit .env or TLS keys.
2
+COMPOSE_PROJECT_NAME=lifeguide-stage0
3
+POSTGRES_DB=lifemate
4
+POSTGRES_USER=lifeguide
5
+POSTGRES_PASSWORD=CHANGE_ME_TO_A_RANDOM_SECRET
6
+JWT_SECRET=CHANGE_ME_TO_AT_LEAST_32_RANDOM_CHARACTERS
7
+PUBLIC_APP_URL=https://192.168.1.10
8
+CORS_ORIGINS=https://192.168.1.10
9
+HTTPS_BIND=0.0.0.0
10
+HTTPS_PORT=443
11
+# Dedicated API/gateway network; change both values if your LAN/VPN overlaps.
12
+PROXY_SUBNET=172.30.86.0/24
13
+GATEWAY_PROXY_IP=172.30.86.10
14
+TLS_CERT_PATH=./deployment/tls/server.pem
15
+TLS_KEY_PATH=./deployment/tls/server-key.pem
16
+API_IMAGE=lifeguide-api:local
17
+WEB_IMAGE=lifeguide-web:local
18
+NODE_ENV=production
19
+LOG_REQUESTS=false
20
+# Delivery is unavailable until an operator configures an approved provider.
21
+EMAIL_FROM=
22
+SMTP_HOST=
23
+SMTP_PORT=587
24
+SMTP_SECURE=false
25
+SMTP_USER=
26
+SMTP_PASSWORD=
27
+SMS_PROVIDER=disabled
28
+# Owner-selected generic HTTPS SMS webhook only; never configured automatically.
29
+# Leave these blank while disabled. Store the real token only in private env/secrets.
30
+SMS_PROVIDER_URL=
31
+SMS_PROVIDER_TOKEN=
32
+BACKUP_SCHEDULE=0 2 * * *
33
+BACKUP_KEEP_DAYS=14
34
+BACKUP_MAX_AGE_SECONDS=93600
.github/workflows/ci.yml
+11
-3
@@ -29,7 +29,7 @@ jobs:
29
POSTGRES_DB: lifemate_ci
30
ports: ['5432:5432']
31
options: >-
32
- --health-cmd 'pg_isready -U postgres -d lifemate_ci'
32
+ --health-cmd "pg_isready -U postgres -d lifemate_ci"
33
--health-interval 5s --health-timeout 5s --health-retries 10
34
env:
35
PGPASSWORD: synthetic_ci_only
@@ -67,6 +67,7 @@ jobs:
67
- uses: subosito/flutter-action@v2
68
with: {flutter-version: '3.47.6', channel: stable, cache: true}
69
- run: flutter pub get
70
+ - run: flutter --version --machine
71
- run: dart format --output=none --set-exit-if-changed lib test
72
- run: flutter analyze
73
- run: flutter test
@@ -75,11 +76,18 @@ jobs:
76
- run: node tool/test_web_bootstrap.mjs
77
- name: Bundle local resources and reject external runtime services
78
run: node tool/self_host_web.mjs build/web
79
+ - name: Check compiled browser requests for local fonts and CanvasKit
80
+ run: |
81
+ npm install --no-save --no-package-lock playwright@1.62.1
82
+ npx playwright install --with-deps chromium
83
+ node tool/test_web_runtime.cjs build/web
84
+ - name: Record checked prebuilt web provenance
85
+ run: node ../../scripts/prebuilt-web-check.mjs . --stamp-after-build
86
+ - uses: actions/upload-artifact@v4
87
+ with: {name: LifeGuide-web, path: apps/lifemate/build/web, if-no-files-found: error}
88
- name: Build test APK (debug certificate; not a release)
89
run: |
90
flutter build apk --debug
91
cp build/app/outputs/flutter-apk/app-debug.apk build/LifeGuide-debug.apk
82
- - uses: actions/upload-artifact@v4
83
- with: {name: LifeGuide-web, path: apps/lifemate/build/web, if-no-files-found: error}
92
- uses: actions/upload-artifact@v4
93
with: {name: LifeGuide-debug-apk, path: apps/lifemate/build/LifeGuide-debug.apk, if-no-files-found: error}
.gitignore
+13
@@ -20,3 +20,16 @@ build/
20
21
# Android local
22
**/android/local.properties
23
+
24
+# Local server/build dependencies and private deployment material
25
+node_modules/
26
+deployment/downloads/*.apk
27
+*.dump
28
+*.jks
29
+*.keystore
30
+*.p12
31
+deployment/tls/*
32
+!deployment/tls/.gitkeep
33
+
34
+__pycache__/
35
+*.pyc
apps/lifemate/.dockerignore
new
+13
@@ -0,0 +1,13 @@
1
+.dart_tool
2
+build
3
+.env*
4
+android
5
+ios
6
+test
7
+integration_test
8
+*.pem
9
+*.key
10
+*.jks
11
+*.keystore
12
+*.p12
13
+*.apk
apps/lifemate/Dockerfile
+38
-16
@@ -1,22 +1,44 @@
1
-FROM ghcr.io/cirruslabs/flutter:stable AS build
1
+# SDK pinned to the exact official Flutter revision used by CI.
2
+# Build dependencies may need developer-side network access;
3
+# the shipped client loads its resources from the deployment origin.
4
+FROM node:22-bookworm-slim AS node-tools
5
+FROM ubuntu:24.04 AS build
6
+ARG FLUTTER_REVISION=5fc346839b5d0eef006ed8404392afb4dfae428d
7
+ARG FLUTTER_VERSION=3.47.6
8
+ENV PATH="/opt/flutter/bin:${PATH}"
9
+RUN apt-get update && apt-get install -y --no-install-recommends \
10
+ ca-certificates curl git unzip xz-utils libglu1-mesa \
11
+ && rm -rf /var/lib/apt/lists/*
12
+RUN --mount=type=secret,id=build_ca \
13
+ if [ -s /run/secrets/build_ca ]; then \
14
+ cp /run/secrets/build_ca /usr/local/share/ca-certificates/build-proxy.crt \
15
+ && update-ca-certificates; fi \
16
+ && git init /opt/flutter \
17
+ && git -C /opt/flutter remote add origin https://github.com/flutter/flutter.git \
18
+ && git -C /opt/flutter fetch --depth 1 origin "$FLUTTER_REVISION" \
19
+ && git -C /opt/flutter checkout --detach FETCH_HEAD \
20
+ && git -C /opt/flutter fetch --depth 1 origin "refs/tags/$FLUTTER_VERSION:refs/tags/$FLUTTER_VERSION" \
21
+ && test "$(git -C /opt/flutter rev-parse "refs/tags/$FLUTTER_VERSION")" = "$FLUTTER_REVISION" \
22
+ && rm -f /opt/flutter/bin/cache/flutter.version.json \
23
+ && flutter config --enable-web --no-analytics \
24
+ && flutter precache --web
25
WORKDIR /src
3
-
4
-COPY pubspec.yaml ./
26
+COPY pubspec.yaml pubspec.lock ./
27
RUN flutter pub get
6
-
28
COPY . .
29
+RUN flutter build web --release --no-web-resources-cdn --pwa-strategy=none
30
9
-RUN flutter build web --release \
10
- --dart-define=LIFEMATE_API_URL=https://lifemate-api-fn-staging.up.railway.app
11
-
12
-RUN flutter build apk --release \
13
- --dart-define=LIFEMATE_API_URL=https://lifemate-api-fn-staging.up.railway.app
14
-
15
-FROM nginx:1.27-alpine
31
+# Process only the small shipped artifact in a separate Node stage. Keeping
32
+# Node out of the Flutter stage also avoids another SDK-sized builder snapshot.
33
+FROM node-tools AS web-artifact
34
+WORKDIR /artifact
35
+COPY --from=build /src/build/web ./web
36
+COPY tool/self_host_web.mjs ./self_host_web.mjs
37
+RUN node self_host_web.mjs web
38
39
+FROM nginx:1.28-alpine
40
COPY deploy/nginx.conf /etc/nginx/conf.d/default.conf
18
-COPY --from=build /src/build/web /usr/share/nginx/html
19
-RUN mkdir -p /usr/share/nginx/html/downloads
20
-COPY --from=build /src/build/app/outputs/flutter-apk/app-release.apk /usr/share/nginx/html/downloads/LifeMate.apk
21
-
22
-EXPOSE 80
41
+COPY deploy/security-headers.inc /etc/nginx/security-headers.inc
42
+COPY --from=web-artifact --chown=nginx:nginx /artifact/web /usr/share/nginx/html
43
+RUN mkdir -p /usr/share/nginx/html/downloads /etc/nginx/tls
44
+EXPOSE 443
apps/lifemate/deploy/Dockerfile.prebuilt
new
+6
@@ -0,0 +1,6 @@
1
+FROM nginx:1.28-alpine
2
+COPY deploy/nginx.conf /etc/nginx/conf.d/default.conf
3
+COPY deploy/security-headers.inc /etc/nginx/security-headers.inc
4
+COPY --chown=nginx:nginx build/web /usr/share/nginx/html
5
+RUN mkdir -p /usr/share/nginx/html/downloads /etc/nginx/tls
6
+EXPOSE 443
apps/lifemate/deploy/Dockerfile.prebuilt.dockerignore
new
+9
@@ -0,0 +1,9 @@
1
+**
2
+!build/
3
+!build/web/
4
+!build/web/**
5
+!deploy/
6
+!deploy/nginx.conf
7
+!deploy/security-headers.inc
8
+!deploy/Dockerfile.prebuilt
9
+!deploy/Dockerfile.prebuilt.dockerignore
apps/lifemate/deploy/nginx.conf
+67
-11
@@ -1,26 +1,82 @@
1
+# One HTTPS origin for PWA, API and operator-signed APK downloads.
2
+resolver 127.0.0.11 valid=10s ipv6=off;
3
+upstream lifeguide_api {
4
+ zone lifeguide_api 64k;
5
+ # nginx >=1.27.3 supports DNS refresh for open-source upstream servers.
6
+ server api-proxy:8080 resolve;
7
+}
8
+
9
+server {
10
+ listen 8081;
11
+ server_name localhost;
12
+ location = /gateway-health { access_log off; return 200 'ok'; }
13
+ location / { return 404; }
14
+}
15
+
16
server {
2
- listen 80;
17
+ listen 443 ssl;
18
server_name _;
19
+ ssl_certificate /etc/nginx/tls/server.pem;
20
+ ssl_certificate_key /etc/nginx/tls/server-key.pem;
21
+ ssl_protocols TLSv1.2 TLSv1.3;
22
+ ssl_session_cache shared:SSL:10m;
23
+ ssl_session_tickets off;
24
+ access_log off;
25
+ error_log /var/log/nginx/error.log crit;
26
27
root /usr/share/nginx/html;
28
index index.html;
7
-
8
- add_header X-Content-Type-Options nosniff always;
9
- add_header Referrer-Policy no-referrer always;
10
- add_header X-Frame-Options SAMEORIGIN always;
29
+ client_max_body_size 128k;
30
+ include /etc/nginx/security-headers.inc;
31
+ proxy_set_header Host $host;
32
+ proxy_set_header X-Forwarded-Proto https;
33
+ proxy_set_header X-Forwarded-For $remote_addr;
34
35
location = /health {
13
- access_log off;
14
- add_header Content-Type text/plain;
15
- return 200 'ok';
36
+ include /etc/nginx/security-headers.inc;
37
+ add_header Cache-Control 'no-store' always;
38
+ proxy_pass http://lifeguide_api/health;
39
+ }
40
+ location = /ready {
41
+ include /etc/nginx/security-headers.inc;
42
+ add_header Cache-Control 'no-store' always;
43
+ proxy_pass http://lifeguide_api/ready;
44
+ }
45
+ location = /live {
46
+ include /etc/nginx/security-headers.inc;
47
+ add_header Cache-Control 'no-store' always;
48
+ proxy_pass http://lifeguide_api/live;
49
+ }
50
+ location = /api { return 308 /api/; }
51
+ location /api/ {
52
+ include /etc/nginx/security-headers.inc;
53
+ add_header Cache-Control 'no-store' always;
54
+ proxy_pass http://lifeguide_api/;
55
+ proxy_set_header Host $host;
56
+ proxy_set_header X-Forwarded-Proto https;
57
+ proxy_set_header X-Forwarded-For $remote_addr;
58
+ proxy_connect_timeout 5s;
59
+ proxy_read_timeout 30s;
60
+ proxy_buffering off;
61
+ }
62
+ location = /config.json {
63
+ include /etc/nginx/security-headers.inc;
64
+ add_header Cache-Control 'no-store' always;
65
+ try_files $uri =404;
66
+ }
67
+ location ~* /(index\.html|manifest\.json|flutter_bootstrap\.js|flutter_service_worker\.js|lifeguide_service_worker\.js|main\.dart\.js)$ {
68
+ include /etc/nginx/security-headers.inc;
69
+ add_header Cache-Control 'no-cache, max-age=0, must-revalidate' always;
70
+ try_files $uri =404;
71
}
17
-
72
location /downloads/ {
19
- add_header Cache-Control "public, max-age=300";
73
+ include /etc/nginx/security-headers.inc;
74
+ add_header Cache-Control 'no-cache, max-age=0, must-revalidate' always;
75
try_files $uri =404;
76
}
22
-
77
location / {
78
+ include /etc/nginx/security-headers.inc;
79
+ add_header Cache-Control 'no-cache, max-age=0, must-revalidate' always;
80
try_files $uri $uri/ /index.html;
81
}
82
}
apps/lifemate/deploy/security-headers.inc
new
+5
@@ -0,0 +1,5 @@
1
+add_header X-Content-Type-Options nosniff always;
2
+add_header Referrer-Policy no-referrer always;
3
+add_header X-Frame-Options DENY always;
4
+add_header Permissions-Policy 'camera=(), microphone=(), geolocation=()' always;
5
+add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'" always;
backend/.dockerignore
new
+5
@@ -0,0 +1,5 @@
1
+node_modules
2
+.env*
3
+*.dump
4
+tests
5
+*.log
backend/Dockerfile
new
+15
@@ -0,0 +1,15 @@
1
+FROM node:22-bookworm-slim
2
+ENV NODE_ENV=production
3
+WORKDIR /app
4
+COPY --chown=node:node package.json package-lock.json ./
5
+RUN --mount=type=secret,id=build_ca \
6
+ if [ -s /run/secrets/build_ca ]; then \
7
+ NODE_EXTRA_CA_CERTS=/run/secrets/build_ca npm ci --omit=dev; \
8
+ else npm ci --omit=dev; fi \
9
+ && npm cache clean --force
10
+COPY --chown=node:node src ./src
11
+COPY --chown=node:node scripts ./scripts
12
+COPY --chown=node:node migrations ./migrations
13
+USER node
14
+EXPOSE 8080
15
+CMD ["node", "src/entrypoint.js"]
backend/scripts/seed-compose-smoke.js
new
+33
@@ -0,0 +1,33 @@
1
+// Explicitly synthetic fixture; not a registration/email-verification bypass.
2
+// Never call this against a live database. Compose runbook uses local Docker.
3
+import crypto from 'node:crypto';
4
+import argon2 from 'argon2';
5
+import pg from 'pg';
6
+if (process.env.ALLOW_SYNTHETIC_SEED !== 'yes') throw new Error('ALLOW_SYNTHETIC_SEED=yes is required');
7
+const password = process.env.SYNTHETIC_PASSWORD;
8
+if (typeof password !== 'string' || password.length < 10) throw new Error('Provide a synthetic password of at least 10 characters');
9
+const pool = new pg.Pool();
10
+const client = await pool.connect();
11
+try {
12
+ await client.query('begin');
13
+ const email = 'compose-smoke@lifeguide.test';
14
+ const existing = await client.query('select id,identity_subject from app_user where email_normalized=$1 for update', [email]);
15
+ let id;
16
+ if (existing.rowCount) {
17
+ if (!existing.rows[0].identity_subject.startsWith('compose-synthetic:')) throw new Error('Refusing to replace an existing non-fixture account');
18
+ id = existing.rows[0].id;
19
+ } else {
20
+ const user = await client.query('insert into app_user(identity_subject,email_normalized,email_verified_at) values($1,$2,now()) returning id', [`compose-synthetic:${crypto.randomUUID()}`, email]);
21
+ id = user.rows[0].id;
22
+ await client.query("insert into profile(user_id,display_name,theme_preference) values($1,'LifeGuide Synthetic Smoke','adult_blue')", [id]);
23
+ }
24
+ await client.query('insert into auth_credential(user_id,password_hash) values($1,$2) on conflict(user_id) do update set password_hash=excluded.password_hash', [id, await argon2.hash(password, { type: argon2.argon2id })]);
25
+ await client.query('commit');
26
+ console.log('Synthetic local fixture ready: compose-smoke@lifeguide.test (password not logged)');
27
+} catch (error) {
28
+ await client.query('rollback');
29
+ throw error;
30
+} finally {
31
+ client.release();
32
+ await pool.end();
33
+}
backend/scripts/seed-stage0-family.js
new
+43
@@ -0,0 +1,43 @@
1
+// Three synthetic accounts for local Android/PWA acceptance. Not a live seed.
2
+import argon2 from 'argon2';
3
+import pg from 'pg';
4
+if (process.env.ALLOW_SYNTHETIC_SEED !== 'yes') throw new Error('ALLOW_SYNTHETIC_SEED=yes required');
5
+const password = process.env.SYNTHETIC_PASSWORD;
6
+if (typeof password !== 'string' || password.length < 10) throw new Error('Provide a random synthetic password of at least 10 characters');
7
+const members = [
8
+ { id: 'a0000000-0000-4000-8000-000000000001', email: 'stage0-child@lifeguide.test', name: 'فرزند آزمایشی', role: 'teen_minor', theme: 'boy_blue', category: 'boy_minor' },
9
+ { id: 'a0000000-0000-4000-8000-000000000002', email: 'stage0-mother@lifeguide.test', name: 'مادر آزمایشی', role: 'parent_guardian', theme: 'adult_blue', category: 'adult' },
10
+ { id: 'a0000000-0000-4000-8000-000000000003', email: 'stage0-father@lifeguide.test', name: 'پدر آزمایشی', role: 'parent_guardian', theme: 'adult_blue', category: 'adult' },
11
+];
12
+const familyId = 'a1000000-0000-4000-8000-000000000001';
13
+const pool = new pg.Pool();
14
+const client = await pool.connect();
15
+try {
16
+ await client.query('begin');
17
+ const hash = await argon2.hash(password, { type: argon2.argon2id });
18
+ for (const member of members) {
19
+ const subject = `stage0-synthetic-family:${member.id}`;
20
+ const existing = await client.query('select id,identity_subject from app_user where id=$1 or email_normalized=$2 for update', [member.id, member.email]);
21
+ if (existing.rowCount && (existing.rowCount !== 1 || existing.rows[0].id !== member.id || existing.rows[0].identity_subject !== subject)) throw new Error('Refusing to modify a non-fixture account');
22
+ await client.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now()) on conflict(id) do nothing', [member.id, subject, member.email]);
23
+ await client.query('insert into profile(user_id,display_name,theme_preference,profile_category) values($1,$2,$3,$4) on conflict(user_id) do update set display_name=excluded.display_name,theme_preference=excluded.theme_preference,profile_category=excluded.profile_category', [member.id, member.name, member.theme, member.category]);
24
+ await client.query('insert into auth_credential(user_id,password_hash) values($1,$2) on conflict(user_id) do update set password_hash=excluded.password_hash', [member.id, hash]);
25
+ }
26
+ const family = await client.query('select created_by from family_workspace where id=$1 for update', [familyId]);
27
+ if (family.rowCount && family.rows[0].created_by !== members[1].id) throw new Error('Refusing to modify a non-fixture family');
28
+ await client.query("insert into family_workspace(id,name,created_by) values($1,'LifeGuide Synthetic Stage0 Family',$2) on conflict(id) do nothing", [familyId, members[1].id]);
29
+ for (const member of members) {
30
+ await client.query('insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,$4) on conflict(family_id,user_id) do update set role=excluded.role,ended_at=null,is_admin=excluded.is_admin', [familyId, member.id, member.role, member.role === 'parent_guardian']);
31
+ }
32
+ for (const parent of members.slice(1)) {
33
+ await client.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3) on conflict(family_id,guardian_user_id,minor_user_id) do update set active=true', [familyId, parent.id, members[0].id]);
34
+ }
35
+ await client.query('commit');
36
+ console.log('Synthetic Stage0 child/mother/father accounts and permitted guardian relationships ready. Password not logged.');
37
+} catch (error) {
38
+ await client.query('rollback');
39
+ throw error;
40
+} finally {
41
+ client.release();
42
+ await pool.end();
43
+}
deployment/backup/Dockerfile
new
+6
@@ -0,0 +1,6 @@
1
+FROM postgres:16-alpine
2
+RUN apk add --no-cache bash
3
+COPY backend/scripts/backup.sh backend/scripts/restore.sh /opt/lifeguide/
4
+COPY deployment/backup/entrypoint.sh deployment/backup/run-backup.sh /opt/lifeguide/
5
+RUN chmod +x /opt/lifeguide/*.sh
6
+ENTRYPOINT ["/opt/lifeguide/entrypoint.sh"]
deployment/backup/entrypoint.sh
new
+12
@@ -0,0 +1,12 @@
1
+#!/usr/bin/env bash
2
+set -euo pipefail
3
+umask 077
4
+mkdir -p /backups
5
+schedule="${BACKUP_SCHEDULE:-0 2 * * *}"
6
+if [[ ! "$schedule" =~ ^[0-9*/,-]+[[:space:]][0-9*/,-]+[[:space:]][0-9*/,-]+[[:space:]][0-9*/,-]+[[:space:]][0-9*/,-]+$ ]]; then
7
+ echo 'Invalid BACKUP_SCHEDULE: expected five numeric cron fields' >&2
8
+ exit 1
9
+fi
10
+printf '%s /opt/lifeguide/run-backup.sh\n' "$schedule" >/etc/crontabs/root
11
+/opt/lifeguide/run-backup.sh
12
+exec crond -f -l 8
deployment/backup/run-backup.sh
new
+14
@@ -0,0 +1,14 @@
1
+#!/usr/bin/env bash
2
+set -euo pipefail
3
+umask 077
4
+keep_days="${BACKUP_KEEP_DAYS:-14}"
5
+[[ "$keep_days" =~ ^[0-9]+$ && "$keep_days" -ge 1 ]] || { echo 'Invalid backup retention' >&2; exit 1; }
6
+output="$(mktemp "/backups/.LifeGuide-$(date -u +%Y%m%dT%H%M%SZ).XXXXXX")"
7
+trap 'rm -f "$output"' EXIT
8
+/opt/lifeguide/backup.sh "$output"
9
+pg_restore --list "$output" >/dev/null
10
+completed="/backups/LifeGuide-${output##*/.LifeGuide-}.dump"
11
+mv -n "$output" "$completed"
12
+[[ ! -e "$output" ]] || { echo 'Refusing to replace an existing backup' >&2; exit 1; }
13
+date -u +%Y-%m-%dT%H:%M:%SZ >/backups/last-success
14
+find /backups -maxdepth 1 -type f -name 'LifeGuide-*.dump' -mtime +"$keep_days" -delete
deployment/downloads/.gitkeep
deployment/restore-fixture.sql
new
+23
@@ -0,0 +1,23 @@
1
+\set ON_ERROR_STOP on
2
+-- Synthetic records only, inserted into a newly-created drill database.
3
+insert into app_user(id,identity_subject,email_normalized,email_verified_at) values
4
+ ('00000000-0000-4000-8000-000000000006','restore-child','restore-child@lifeguide.test',now()),
5
+ ('00000000-0000-4000-8000-000000000007','restore-other-parent','restore-other-parent@lifeguide.test',now());
6
+insert into profile(user_id,display_name,theme_preference) values
7
+ ('00000000-0000-4000-8000-000000000006','Synthetic child','boy_blue'),
8
+ ('00000000-0000-4000-8000-000000000007','Synthetic unrelated parent','adult_blue');
9
+insert into family_workspace(id,name,created_by) values
10
+ ('00000000-0000-4000-8000-000000000005','LifeGuide synthetic migration family','00000000-0000-4000-8000-000000000005');
11
+insert into family_membership(family_id,user_id,role,is_admin) values
12
+ ('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000005','parent_guardian',true),
13
+ ('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000006','teen_minor',false);
14
+insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values
15
+ ('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000006');
16
+insert into plan_item(id,owner_user_id,family_id,kind,title,visibility) values
17
+ ('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000006','00000000-0000-4000-8000-000000000005','assignment','Synthetic mathematics homework','parent_guardian'),
18
+ ('00000000-0000-4000-8000-000000000006','00000000-0000-4000-8000-000000000006','00000000-0000-4000-8000-000000000005','task','Synthetic private task','private');
19
+insert into study_session(id,child_user_id,plan_item_id,source,status,started_at,ended_at,last_event_at,recorded_duration_seconds) values
20
+ ('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000006','00000000-0000-4000-8000-000000000005','timer','completed','2026-01-01T10:00:00Z','2026-01-01T10:15:00Z','2026-01-01T10:15:00Z',600);
21
+insert into study_interval(session_id,starts_at,ends_at) values
22
+ ('00000000-0000-4000-8000-000000000005','2026-01-01T10:00:00Z','2026-01-01T10:05:00Z'),
23
+ ('00000000-0000-4000-8000-000000000005','2026-01-01T10:10:00Z','2026-01-01T10:15:00Z');
deployment/runtime-config.json
new
+1
@@ -0,0 +1 @@
1
+{"apiBaseUrl":"/api","apiFallbackUrls":[]}
deployment/tls/.gitkeep
docker-compose.build-proxy.yml
new
+25
@@ -0,0 +1,25 @@
1
+# Optional developer-only trusted proxy. Never needed by the deployed client.
2
+# Set BUILD_CA_FILE to the PUBLIC corporate/build proxy CA, never a private key.
3
+# Do not print rendered config if proxy environment variables contain credentials.
4
+services:
5
+ api:
6
+ build:
7
+ args:
8
+ HTTP_PROXY: ${HTTP_PROXY:-}
9
+ HTTPS_PROXY: ${HTTPS_PROXY:-}
10
+ secrets: [build_ca]
11
+ migrate:
12
+ build:
13
+ args:
14
+ HTTP_PROXY: ${HTTP_PROXY:-}
15
+ HTTPS_PROXY: ${HTTPS_PROXY:-}
16
+ secrets: [build_ca]
17
+ gateway:
18
+ build:
19
+ args:
20
+ HTTP_PROXY: ${HTTP_PROXY:-}
21
+ HTTPS_PROXY: ${HTTPS_PROXY:-}
22
+ secrets: [build_ca]
23
+secrets:
24
+ build_ca:
25
+ file: ${BUILD_CA_FILE:?Set public build-proxy CA path only}
docker-compose.prebuilt-web.yml
new
+7
@@ -0,0 +1,7 @@
1
+# Developer/CI artifact path: compile and self-host-check web first, then package
2
+# only the exact checked output with the same gateway/TLS configuration.
3
+services:
4
+ gateway:
5
+ build:
6
+ context: ./apps/lifemate
7
+ dockerfile: deploy/Dockerfile.prebuilt
docker-compose.yml
new
+145
@@ -0,0 +1,145 @@
1
+name: ${COMPOSE_PROJECT_NAME:-lifeguide-stage0}
2
+
3
+x-api-environment: &api-environment
4
+ NODE_ENV: ${NODE_ENV:-production}
5
+ PORT: 8080
6
+ PGHOST: postgres
7
+ PGPORT: 5432
8
+ PGDATABASE: ${POSTGRES_DB:-lifemate}
9
+ PGUSER: ${POSTGRES_USER:-lifeguide}
10
+ PGPASSWORD: ${POSTGRES_PASSWORD:?Generate POSTGRES_PASSWORD in .env}
11
+ JWT_SECRET: ${JWT_SECRET:?Generate JWT_SECRET in .env}
12
+ PUBLIC_APP_URL: ${PUBLIC_APP_URL:?Set the operator-approved HTTPS origin}
13
+ CORS_ORIGINS: ${CORS_ORIGINS:?Set the operator-approved HTTPS origin}
14
+ LOG_REQUESTS: ${LOG_REQUESTS:-false}
15
+ EMAIL_FROM: ${EMAIL_FROM:-}
16
+ SMTP_HOST: ${SMTP_HOST:-}
17
+ SMTP_PORT: ${SMTP_PORT:-587}
18
+ SMTP_SECURE: ${SMTP_SECURE:-false}
19
+ SMTP_USER: ${SMTP_USER:-}
20
+ SMTP_PASSWORD: ${SMTP_PASSWORD:-}
21
+ SMS_PROVIDER: ${SMS_PROVIDER:-disabled}
22
+ SMS_PROVIDER_URL: ${SMS_PROVIDER_URL:-}
23
+ SMS_PROVIDER_TOKEN: ${SMS_PROVIDER_TOKEN:-}
24
+ TRUSTED_PROXY_CIDRS: ${GATEWAY_PROXY_IP:-172.30.86.10}/32
25
+
26
+services:
27
+ postgres:
28
+ image: postgres:16
29
+ restart: unless-stopped
30
+ environment:
31
+ POSTGRES_DB: ${POSTGRES_DB:-lifemate}
32
+ POSTGRES_USER: ${POSTGRES_USER:-lifeguide}
33
+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Generate POSTGRES_PASSWORD in .env}
34
+ PGDATA: /var/lib/postgresql/data/pgdata
35
+ volumes:
36
+ - postgres-data:/var/lib/postgresql/data
37
+ healthcheck:
38
+ test: [CMD-SHELL, 'pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"']
39
+ interval: 5s
40
+ timeout: 5s
41
+ retries: 20
42
+ networks: [private]
43
+
44
+ migrate:
45
+ image: ${API_IMAGE:-lifeguide-api:local}
46
+ build:
47
+ context: ./backend
48
+ command: [node, scripts/migrate.js]
49
+ environment: *api-environment
50
+ depends_on:
51
+ postgres:
52
+ condition: service_healthy
53
+ restart: 'no'
54
+ networks: [private]
55
+
56
+ api:
57
+ image: ${API_IMAGE:-lifeguide-api:local}
58
+ build:
59
+ context: ./backend
60
+ restart: unless-stopped
61
+ environment: *api-environment
62
+ read_only: true
63
+ tmpfs: [/tmp]
64
+ security_opt: [no-new-privileges:true]
65
+ depends_on:
66
+ postgres:
67
+ condition: service_healthy
68
+ migrate:
69
+ condition: service_completed_successfully
70
+ healthcheck:
71
+ test: [CMD, node, -e, "fetch('http://127.0.0.1:8080/ready').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
72
+ interval: 10s
73
+ timeout: 5s
74
+ retries: 12
75
+ start_period: 10s
76
+ # Provider delivery may use outbound networking after owner configuration;
77
+ # no API host port is published. PostgreSQL remains private-only.
78
+ networks:
79
+ private:
80
+ edge:
81
+ proxy:
82
+ aliases: [api-proxy]
83
+
84
+ gateway:
85
+ image: ${WEB_IMAGE:-lifeguide-web:local}
86
+ build:
87
+ context: ./apps/lifemate
88
+ restart: unless-stopped
89
+ ports:
90
+ - '${HTTPS_BIND:-0.0.0.0}:${HTTPS_PORT:-443}:443'
91
+ volumes:
92
+ - ${TLS_CERT_PATH:-./deployment/tls/server.pem}:/etc/nginx/tls/server.pem:ro
93
+ - ${TLS_KEY_PATH:-./deployment/tls/server-key.pem}:/etc/nginx/tls/server-key.pem:ro
94
+ - ./deployment/runtime-config.json:/usr/share/nginx/html/config.json:ro
95
+ - ./deployment/downloads:/usr/share/nginx/html/downloads:ro
96
+ depends_on:
97
+ api:
98
+ condition: service_healthy
99
+ healthcheck:
100
+ test: [CMD-SHELL, 'wget -Y off -q -O /dev/null http://127.0.0.1:8081/gateway-health']
101
+ interval: 10s
102
+ timeout: 5s
103
+ retries: 6
104
+ networks:
105
+ edge:
106
+ proxy:
107
+ ipv4_address: ${GATEWAY_PROXY_IP:-172.30.86.10}
108
+
109
+ backup:
110
+ build:
111
+ context: .
112
+ dockerfile: deployment/backup/Dockerfile
113
+ restart: unless-stopped
114
+ environment:
115
+ DATABASE_URL: postgresql://${POSTGRES_USER:-lifeguide}@postgres:5432/${POSTGRES_DB:-lifemate}
116
+ PGPASSWORD: ${POSTGRES_PASSWORD:?Generate POSTGRES_PASSWORD in .env}
117
+ BACKUP_SCHEDULE: ${BACKUP_SCHEDULE:-0 2 * * *}
118
+ BACKUP_KEEP_DAYS: ${BACKUP_KEEP_DAYS:-14}
119
+ BACKUP_MAX_AGE_SECONDS: ${BACKUP_MAX_AGE_SECONDS:-93600}
120
+ volumes:
121
+ - backups:/backups
122
+ depends_on:
123
+ postgres:
124
+ condition: service_healthy
125
+ healthcheck:
126
+ test: [CMD-SHELL, 'kill -0 1 && test -f /backups/last-success && test "$$(( $$(date +%s) - $$(stat -c %Y /backups/last-success) ))" -lt "$${BACKUP_MAX_AGE_SECONDS:-93600}"']
127
+ interval: 60s
128
+ timeout: 5s
129
+ retries: 3
130
+ start_period: 60s
131
+ networks: [private]
132
+
133
+volumes:
134
+ postgres-data:
135
+ backups:
136
+
137
+networks:
138
+ private:
139
+ internal: true
140
+ edge:
141
+ proxy:
142
+ internal: true
143
+ ipam:
144
+ config:
145
+ - subnet: ${PROXY_SUBNET:-172.30.86.0/24}
docs/audits/2026-10-08-naming.md
+74
-10
@@ -4,39 +4,97 @@ Generated with `python3 scripts/audit-naming.py` from tracked source. Product di
4
5
| Location | Classification | Reason | Source excerpt |
6
| --- | --- | --- | --- |
7
+| .env.example:3 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | POSTGRES_DB=lifemate |
8
+| .gitattributes:2 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | apps/lifemate/assets/fonts/*.txt whitespace=-blank-at-eol |
9
| .github/workflows/ci.yml:29 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | POSTGRES_DB: lifemate_ci |
8
-| .github/workflows/ci.yml:32 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | --health-cmd 'pg_isready -U postgres -d lifemate_ci' |
10
+| .github/workflows/ci.yml:32 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | --health-cmd "pg_isready -U postgres -d lifemate_ci" |
11
| .github/workflows/ci.yml:36 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | DATABASE_URL: postgresql://postgres:synthetic_ci_only@localhost:5432/lifemate_ci |
12
| .github/workflows/ci.yml:62 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | run: {working-directory: apps/lifemate} |
11
-| .github/workflows/ci.yml:83 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | with: {name: LifeGuide-web, path: apps/lifemate/build/web, if-no-files-found: error} |
12
-| .github/workflows/ci.yml:85 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | with: {name: LifeGuide-debug-apk, path: apps/lifemate/build/LifeGuide-debug.apk, if-no-files-found: error} |
13
+| .github/workflows/ci.yml:87 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | with: {name: LifeGuide-web, path: apps/lifemate/build/web, if-no-files-found: error} |
14
+| .github/workflows/ci.yml:93 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | with: {name: LifeGuide-debug-apk, path: apps/lifemate/build/LifeGuide-debug.apk, if-no-files-found: error} |
15
| .github/workflows/release-build.yml:16 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | run: {working-directory: apps/lifemate} |
16
| .github/workflows/release-build.yml:40 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | with: {name: LifeGuide-signed-apk, path: apps/lifemate/build/LifeGuide.apk, if-no-files-found: error} |
17
| PROJECT_STATE.md:3 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | Updated: 2026-10-08. Backend version: **0.5.0**. Branch: **feat/online-family-stage0**, based on main 'abdc9d9d032bc6746c8390b902a2e52d82991530'. Repository remains 'davoodmehraban89/LifeMate'. |
18
| README.md:3 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | همراه فارسی و راستبهچپ خانواده و آموزش؛ Android و PWA والدین از یک API مبتنی بر Node/Express و PostgreSQL مشترک استفاده میکنند. نام مخزن 'davoodmehraban89/LifeMate' و قراردادهای قدیمی پایگاه داده و JWT تغییر نمیکنند. |
19
| README.md:36 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | cd apps/lifemate |
18
-| apps/lifemate/android/app/src/main/AndroidManifest.xml:7 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | android:icon="@drawable/lifemate_logo"> |
19
-| apps/lifemate/lib/main.dart:16 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | runApp(const LifeMateApp()); |
20
-| apps/lifemate/lib/main.dart:19 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | class LifeMateApp extends StatefulWidget { |
21
-| apps/lifemate/lib/main.dart:20 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | const LifeMateApp({super.key, this.api, this.runtime}); |
22
-| apps/lifemate/lib/main.dart:25 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | State<LifeMateApp> createState() => _LifeMateAppState(); |
23
-| apps/lifemate/lib/main.dart:28 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | class _LifeMateAppState extends State<LifeMateApp> { |
20
+| apps/lifemate/android/app/src/main/AndroidManifest.xml:8 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | android:icon="@drawable/lifemate_logo"> |
21
+| apps/lifemate/lib/main.dart:17 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | runApp(const LifeMateApp()); |
22
+| apps/lifemate/lib/main.dart:20 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | class LifeMateApp extends StatefulWidget { |
23
+| apps/lifemate/lib/main.dart:21 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | const LifeMateApp({super.key, this.api, this.runtime}); |
24
+| apps/lifemate/lib/main.dart:26 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | State<LifeMateApp> createState() => _LifeMateAppState(); |
25
+| apps/lifemate/lib/main.dart:29 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | class _LifeMateAppState extends State<LifeMateApp> { |
26
| apps/lifemate/pubspec.yaml:1 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | name: lifemate |
27
| apps/lifemate/test/app_test.dart:5 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/api.dart'; |
28
| apps/lifemate/test/app_test.dart:6 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/main.dart'; |
29
| apps/lifemate/test/app_test.dart:211 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | await tester.pumpWidget(LifeMateApp(api: FakeApi())); |
30
| apps/lifemate/test/app_test.dart:219 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | await tester.pumpWidget(LifeMateApp(api: FakeApi())); |
31
+| apps/lifemate/test/endpoint_settings_test.dart:3 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/endpoint_settings.dart'; |
32
+| apps/lifemate/test/endpoint_settings_test.dart:4 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/runtime_config.dart'; |
33
| apps/lifemate/test/iran_hub_test.dart:2 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/iran_hub.dart'; |
34
+| apps/lifemate/test/notification_delivery_test.dart:5 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/api.dart'; |
35
+| apps/lifemate/test/notification_delivery_test.dart:6 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/notification_delivery.dart'; |
36
+| apps/lifemate/test/notification_delivery_test.dart:7 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/session_store.dart'; |
37
+| apps/lifemate/test/online_sync_test.dart:3 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/api.dart'; |
38
+| apps/lifemate/test/online_sync_test.dart:4 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/offline_store.dart'; |
39
+| apps/lifemate/test/online_sync_test.dart:5 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/plan_sync.dart'; |
40
+| apps/lifemate/test/online_ui_test.dart:4 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/runtime_config.dart'; |
41
+| apps/lifemate/test/online_ui_test.dart:5 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/runtime_controller.dart'; |
42
+| apps/lifemate/test/online_ui_test.dart:6 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/session_store.dart'; |
43
+| apps/lifemate/test/online_ui_test.dart:7 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/offline_store.dart'; |
44
+| apps/lifemate/test/online_ui_test.dart:8 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/plan_sync.dart'; |
45
+| apps/lifemate/test/online_ui_test.dart:12 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/api.dart'; |
46
+| apps/lifemate/test/online_ui_test.dart:13 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/main.dart'; |
47
+| apps/lifemate/test/online_ui_test.dart:14 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/phase3_ui.dart'; |
48
+| apps/lifemate/test/online_ui_test.dart:15 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/phase4_ui.dart'; |
49
+| apps/lifemate/test/online_ui_test.dart:16 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/sync_changes_ui.dart'; |
50
+| apps/lifemate/test/online_ui_test.dart:141 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | await tester.pumpWidget(LifeMateApp()); |
51
+| apps/lifemate/test/online_ui_test.dart:154 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | await tester.pumpWidget(LifeMateApp(api: FakeApi())); |
52
+| apps/lifemate/test/online_ui_test.dart:239 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | await tester.pumpWidget(LifeMateApp(runtime: runtime)); |
53
+| apps/lifemate/test/online_ui_test.dart:473 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | await tester.pumpWidget(LifeMateApp(runtime: runtime)); |
54
+| apps/lifemate/test/online_ui_test.dart:520 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | await tester.pumpWidget(LifeMateApp(runtime: runtime)); |
55
| apps/lifemate/test/phase4_ui_test.dart:3 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/api.dart'; |
56
| apps/lifemate/test/phase4_ui_test.dart:4 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/phase4_ui.dart'; |
57
+| apps/lifemate/test/runtime_config_test.dart:6 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/api.dart'; |
58
+| apps/lifemate/test/runtime_config_test.dart:7 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/runtime_config.dart'; |
59
+| apps/lifemate/test/runtime_config_test.dart:8 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/runtime_controller.dart'; |
60
+| apps/lifemate/test/runtime_config_test.dart:9 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/session_store.dart'; |
61
+| apps/lifemate/test/study_ui_test.dart:7 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/api.dart'; |
62
+| apps/lifemate/test/study_ui_test.dart:8 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/session_store.dart'; |
63
+| apps/lifemate/test/study_ui_test.dart:9 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/study_coordinator.dart'; |
64
+| apps/lifemate/test/study_ui_test.dart:10 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/study_ui.dart'; |
65
+| apps/lifemate/test/study_ui_test.dart:11 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/dashboard_ui.dart'; |
66
+| apps/lifemate/test/study_ui_test.dart:12 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/phase3_ui.dart' show shortDate; |
67
+| apps/lifemate/test/sync_changes_test.dart:6 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/api.dart'; |
68
+| apps/lifemate/test/sync_changes_test.dart:7 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/offline_store.dart'; |
69
+| apps/lifemate/test/sync_changes_test.dart:8 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | import 'package:lifemate/sync_changes_ui.dart'; |
70
+| apps/lifemate/tool/export_brand_icons.py:7 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | source = ET.parse(ROOT / "android/app/src/main/res/drawable/lifemate_logo.xml").getroot() |
71
+| backend/package-lock.json:2 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | "name": "lifemate-backend", |
72
+| backend/package-lock.json:8 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | "name": "lifemate-backend", |
73
| backend/package.json:2 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | "name": "lifemate-backend", |
74
| backend/scripts/backup.sh:4 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | output="${1:-lifemate-$(date -u +%Y%m%dT%H%M%SZ).dump}" |
75
+| backend/scripts/migrate.js:32 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | await client.query("select pg_advisory_lock(hashtextextended('lifemate_schema_migration',0))"); |
76
| backend/scripts/restore-smoke.sql:3 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | values('00000000-0000-4000-8000-000000000005','restore-smoke','restore-smoke@lifemate.test',now()) |
77
+| backend/src/auth_router.js:59 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | accessToken: jwt.sign({ sub: userId, sid: result.rows[0].id, aud: 'lifemate-api' }, jwtSecret, { expiresIn: '15m', issuer: 'lifemate' }), |
78
+| backend/src/auth_router.js:275 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | identity = jwt.verify(req.headers.authorization?.replace(/^Bearer\s+/i, ''), jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' }); |
79
| backend/src/entrypoint.js:22 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | res.json({ status: 'ok', service: 'lifemate-api' }); |
80
| backend/src/entrypoint.js:37 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | outer.listen(publicPort, () => console.log(JSON.stringify({ type: 'startup', service: 'lifemate-api', port: publicPort }))); |
81
| backend/src/session_auth.js:9 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | audience: 'lifemate-api', |
82
| backend/src/session_auth.js:10 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | issuer: 'lifemate', |
39
-| backend/tests/request_safety.test.js:98 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | const token = jwt.sign({ sub: id, sid: sessionId, aud: 'lifemate-api' }, process.env.JWT_SECRET, { expiresIn: '15m', issuer: 'lifemate' }); |
83
+| backend/tests/auth_delivery.test.js:372 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | const identity = jwt.verify(verified.body.accessToken, jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' }); |
84
+| backend/tests/auth_delivery.test.js:378 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | const active = jwt.verify(login.body.accessToken, jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' }); |
85
+| backend/tests/auth_delivery.test.js:379 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | const expiredAccess = jwt.sign({ sub: active.sub, sid: active.sid, aud: 'lifemate-api' }, jwtSecret, { issuer: 'lifemate', expiresIn: -1 }); |
86
+| backend/tests/planner_sync.test.js:26 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) }; |
87
+| backend/tests/privacy_regression.test.js:69 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) }; |
88
+| backend/tests/profile_category.test.js:34 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, { issuer: 'lifemate', expiresIn: '15m' }) }; |
89
+| backend/tests/request_safety.test.js:100 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | const token = jwt.sign({ sub: id, sid: sessionId, aud: 'lifemate-api' }, process.env.JWT_SECRET, { expiresIn: '15m', issuer: 'lifemate' }); |
90
+| backend/tests/school_crud.test.js:63 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, { issuer: 'lifemate', expiresIn: '15m' }) }; |
91
+| backend/tests/study_sessions.test.js:50 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | return { id, sid, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, jwtSecret, { issuer: 'lifemate', expiresIn: '15m' }) }; |
92
+| backend/tests/study_sessions.test.js:251 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | const expired = { ...f.child, token: jwt.sign({ sub: f.child.id, sid: f.child.sid, aud: 'lifemate-api' }, jwtSecret, { issuer: 'lifemate', expiresIn: -1 }) }; |
93
+| docker-compose.prebuilt-web.yml:6 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | context: ./apps/lifemate |
94
+| docker-compose.yml:8 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | PGDATABASE: ${POSTGRES_DB:-lifemate} |
95
+| docker-compose.yml:31 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | POSTGRES_DB: ${POSTGRES_DB:-lifemate} |
96
+| docker-compose.yml:87 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | context: ./apps/lifemate |
97
+| docker-compose.yml:115 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | DATABASE_URL: postgresql://${POSTGRES_USER:-lifeguide}@postgres:5432/${POSTGRES_DB:-lifemate} |
98
| docs/ROADMAP.md:3 | historical — keep | snapshot/previous decision; not current deployment evidence | # LifeMate — Five-Phase Roadmap |
99
| docs/architecture/DOMAIN_MODEL_V1.md:3 | historical — keep | snapshot/previous decision; not current deployment evidence | # LifeMate — Conceptual Domain Model v1 |
100
| docs/architecture/PHASE_2_BLUEPRINT.md:3 | historical — keep | snapshot/previous decision; not current deployment evidence | # LifeMate — Phase 2 Implementation Blueprint |
@@ -73,6 +131,9 @@ Generated with `python3 scripts/audit-naming.py` from tracked source. Product di
131
| docs/operations/BACKUP_RESTORE.md:15 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | 'backend/scripts/restore.sh /secure/location/lifemate-YYYYMMDD.dump' |
132
| docs/operations/SELF_HOSTED_DEPLOYMENT.md:13 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | 3. '.env.example' را به '.env' کپی و secretها را در محیط/secret management میزبان تولید کنید. نام schemaها، JWT issuer='lifemate' و audience='lifemate-api' تغییر نمیکند. روی انتقال دیتابیس، secret JWT را مطابق سیاست نشس |
133
| docs/operations/STAGE0.md:30 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | Set-Location apps/lifemate |
134
+| docs/operations/STAGE0.md:42 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | Set-Location apps/lifemate |
135
+| docs/operations/STAGE0.md:46 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | node scripts/prebuilt-web-check.mjs apps/lifemate --stamp-after-build |
136
+| docs/operations/STAGE0.md:50 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | Linux محلی، پس از همین build و بررسی: 'bash scripts/local-deploy.sh --prebuilt-web --init https://192.168.1.10'. گزینه '--prebuilt-web' باید پیش از '--init' باشد. artifact CI بررسیشده را نیز میتوان در 'apps/lifemate/bu |
137
| docs/plans/PHASE_2_IMPLEMENTATION_PLAN.md:11 | historical — keep | snapshot/previous decision; not current deployment evidence | Supabase is no longer a required platform dependency. LifeMate uses provider-neutral backend ports with PostgreSQL as the durable relational core. Neon is the preferred managed PostgreSQL target when its connector is ope |
138
| docs/plans/PHASE_2_IMPLEMENTATION_PLAN.md:34 | historical — keep | snapshot/previous decision; not current deployment evidence | - Student IA uses MyStudyLife as benchmark: direct access to Today, Schedule, Calendar, Tasks, Exams/Grades, Focus and AI; LifeMate family/wellbeing extensions remain additive. |
139
| docs/plans/PHASE_3_IMPLEMENTATION_PLAN.md:23 | historical — keep | snapshot/previous decision; not current deployment evidence | - MyStudyLife remains the benchmark for student IA, but LifeMate adds family sharing and guardian support. |
@@ -121,3 +182,6 @@ Generated with `python3 scripts/audit-naming.py` from tracked source. Product di
182
| scripts/audit-naming.py:20 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | if not re.search('lifemate', line, re.I): continue |
183
| scripts/audit-naming.py:22 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | internal = re.search(r'LifeMateApp\|_LifeMateAppState\|davoodmehraban89/LifeMate\|/LifeMate\|apps/lifemate\|package:lifemate\|lifemate[-_]\|\blifemate\b\|LIFEMATE', line) |
184
| scripts/audit-naming.py:31 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | if name.startswith(('apps/lifemate/lib/', 'apps/lifemate/web/', '.github/workflows/')) and re.search(r"['\"][^'\"]*\bLifeMate\b[^'\"]*['\"]", line) and not re.search(r'LifeMateApp\|package:', line): |
185
+| scripts/local-deploy.ps1:72 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | & node scripts/prebuilt-web-check.mjs apps/lifemate |
186
+| scripts/local-deploy.sh:57 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | node scripts/prebuilt-web-check.mjs apps/lifemate |
187
+| scripts/prebuilt-web-check.mjs:8 | protocol-sensitive/internal — keep | repository/path/package/resource or JWT/service/test compatibility | const app = resolve(process.argv[2] ?? 'apps/lifemate'); |
scripts/local-deploy.ps1
new
+88
@@ -0,0 +1,88 @@
1
+param(
2
+ [Parameter(Mandatory = $true)][string]$Origin,
3
+ [string]$Certificate = 'deployment/tls/server.pem',
4
+ [string]$PrivateKey = 'deployment/tls/server-key.pem',
5
+ [switch]$PrebuiltWeb
6
+)
7
+$ErrorActionPreference = 'Stop'
8
+Set-Location (Split-Path $PSScriptRoot -Parent)
9
+$uri = [Uri]$Origin
10
+if ($uri.Scheme -ne 'https' -or $uri.AbsolutePath -ne '/' -or $uri.Query -or $uri.Fragment -or $uri.UserInfo) {
11
+ throw 'Origin must be one HTTPS origin without path, credentials, query or fragment.'
12
+}
13
+$Origin = $uri.GetLeftPart([UriPartial]::Authority)
14
+if (!(Test-Path $Certificate -PathType Leaf) -or !(Test-Path $PrivateKey -PathType Leaf)) {
15
+ throw 'Create TLS certificate/key with mkcert first. No automatic certificate service is contacted.'
16
+}
17
+if (!(Test-Path '.env')) {
18
+ $rng = [Security.Cryptography.RandomNumberGenerator]::Create()
19
+ try {
20
+ $dbBytes = New-Object byte[] 32
21
+ $jwtBytes = New-Object byte[] 48
22
+ $rng.GetBytes($dbBytes)
23
+ $rng.GetBytes($jwtBytes)
24
+ $dbSecret = ([BitConverter]::ToString($dbBytes)).Replace('-', '').ToLowerInvariant()
25
+ $jwtSecret = ([BitConverter]::ToString($jwtBytes)).Replace('-', '').ToLowerInvariant()
26
+ $contents = [IO.File]::ReadAllText((Join-Path (Get-Location) '.env.example'))
27
+ $contents = $contents -replace '(?m)^POSTGRES_PASSWORD=.*$', "POSTGRES_PASSWORD=$dbSecret"
28
+ $contents = $contents -replace '(?m)^JWT_SECRET=.*$', "JWT_SECRET=$jwtSecret"
29
+ $contents = $contents -replace '(?m)^PUBLIC_APP_URL=.*$', "PUBLIC_APP_URL=$Origin"
30
+ $contents = $contents -replace '(?m)^CORS_ORIGINS=.*$', "CORS_ORIGINS=$Origin"
31
+ $contents = $contents -replace '(?m)^HTTPS_PORT=.*$', "HTTPS_PORT=$($uri.Port)"
32
+ $certPath = (Resolve-Path $Certificate).Path.Replace('\', '/')
33
+ $keyPath = (Resolve-Path $PrivateKey).Path.Replace('\', '/')
34
+ $contents = $contents -replace '(?m)^TLS_CERT_PATH=.*$', "TLS_CERT_PATH=$certPath"
35
+ $contents = $contents -replace '(?m)^TLS_KEY_PATH=.*$', "TLS_KEY_PATH=$keyPath"
36
+ [IO.File]::WriteAllText((Join-Path (Get-Location) '.env'), $contents, (New-Object Text.UTF8Encoding $false))
37
+ } finally {
38
+ $rng.Dispose()
39
+ $dbSecret = $null
40
+ $jwtSecret = $null
41
+ }
42
+ Write-Host 'Created local .env with random secrets. Restrict this file to your Windows account.'
43
+} else {
44
+ Write-Host '.env exists and is preserved; Origin/certificate changes require a deliberate .env edit.'
45
+}
46
+if ((Get-Content '.env' -Raw) -match '(?m)^(POSTGRES_PASSWORD|JWT_SECRET)=CHANGE_ME') {
47
+ throw 'Replace placeholder secrets in .env.'
48
+}
49
+$endpoint = $null
50
+$dockerContextExit = 0
51
+if ($env:DOCKER_CONTEXT) {
52
+ $endpoint = docker context inspect $env:DOCKER_CONTEXT --format '{{.Endpoints.docker.Host}}'
53
+ $dockerContextExit = $LASTEXITCODE
54
+} elseif ($env:DOCKER_HOST) {
55
+ $endpoint = $env:DOCKER_HOST
56
+} else {
57
+ $endpoint = docker context inspect --format '{{.Endpoints.docker.Host}}'
58
+ $dockerContextExit = $LASTEXITCODE
59
+}
60
+if ($dockerContextExit -ne 0 -or $endpoint -notmatch '^(unix|npipe)://') {
61
+ throw 'Refusing a remote Docker endpoint; use local Docker Desktop.'
62
+}
63
+function Invoke-CheckedDocker {
64
+ param([string[]]$Arguments)
65
+ & docker @Arguments
66
+ if ($LASTEXITCODE -ne 0) { throw "Docker command failed with exit code $LASTEXITCODE" }
67
+}
68
+Invoke-CheckedDocker -Arguments @('info', '--format', '{{.ServerVersion}}')
69
+Invoke-CheckedDocker -Arguments @('compose', 'config', '--quiet')
70
+$composeBuild = @('compose', '-f', 'docker-compose.yml')
71
+if ($PrebuiltWeb) {
72
+ & node scripts/prebuilt-web-check.mjs apps/lifemate
73
+ if ($LASTEXITCODE -ne 0) { throw 'Prebuilt web artifact is missing, stale or has external resources.' }
74
+ $composeBuild += @('-f', 'docker-compose.prebuilt-web.yml')
75
+}
76
+if ($env:BUILD_CA_FILE) {
77
+ if (!(Test-Path $env:BUILD_CA_FILE -PathType Leaf) -or ((Get-Content $env:BUILD_CA_FILE -Raw) -match 'PRIVATE KEY')) {
78
+ throw 'BUILD_CA_FILE must contain a public CA certificate, never a private key.'
79
+ }
80
+ Invoke-CheckedDocker -Arguments ($composeBuild + @('-f', 'docker-compose.build-proxy.yml', 'build', 'api', 'gateway', 'backup'))
81
+} else {
82
+ Invoke-CheckedDocker -Arguments ($composeBuild + @('build', '--build-arg', 'HTTP_PROXY', '--build-arg', 'HTTPS_PROXY', 'api', 'gateway', 'backup'))
83
+}
84
+Invoke-CheckedDocker -Arguments @('compose', 'up', '-d', '--wait', '--wait-timeout', '120', 'postgres')
85
+Invoke-CheckedDocker -Arguments @('compose', 'run', '--rm', 'migrate')
86
+Invoke-CheckedDocker -Arguments @('compose', 'up', '-d', '--wait', '--wait-timeout', '180', 'api', 'gateway', 'backup')
87
+Invoke-CheckedDocker -Arguments @('compose', 'ps')
88
+Write-Host 'Local stack started. Run the HTTPS smoke test with synthetic accounts.'
scripts/local-deploy.sh
new
+72
@@ -0,0 +1,72 @@
1
+#!/usr/bin/env bash
2
+# Local Docker only. This script never SSHs, modifies DNS or creates accounts.
3
+set -euo pipefail
4
+cd "$(dirname "${BASH_SOURCE[0]}")/.."
5
+umask 077
6
+prebuilt_web=no
7
+if [[ "${1:-}" == '--prebuilt-web' ]]; then
8
+ prebuilt_web=yes
9
+ shift
10
+fi
11
+if [[ "${1:-}" == '--init' ]]; then
12
+ origin="${2:?Usage: scripts/local-deploy.sh --init https://LAN-IP}"
13
+ [[ "$origin" =~ ^https://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:]+\])(:[0-9]+)?$ ]] || { echo 'Use one HTTPS origin without a path or credentials' >&2; exit 1; }
14
+ https_port=443
15
+ if [[ "$origin" =~ :([0-9]+)$ ]]; then https_port="${BASH_REMATCH[1]}"; fi
16
+ [[ "$https_port" -ge 1 && "$https_port" -le 65535 ]] || { echo 'Invalid HTTPS port' >&2; exit 1; }
17
+ if [[ -f .env ]]; then
18
+ echo '.env already exists; preserving it. Edit it deliberately to change settings.'
19
+ else
20
+ command -v openssl >/dev/null || { echo 'openssl is required to generate secrets' >&2; exit 1; }
21
+ db_secret="$(openssl rand -hex 32)"
22
+ jwt_secret="$(openssl rand -hex 48)"
23
+ sed -e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=$db_secret|" \
24
+ -e "s|^JWT_SECRET=.*|JWT_SECRET=$jwt_secret|" \
25
+ -e "s|^PUBLIC_APP_URL=.*|PUBLIC_APP_URL=$origin|" \
26
+ -e "s|^CORS_ORIGINS=.*|CORS_ORIGINS=$origin|" \
27
+ -e "s|^HTTPS_PORT=.*|HTTPS_PORT=$https_port|" .env.example >.env
28
+ chmod 600 .env
29
+ unset db_secret jwt_secret
30
+ echo 'Created private .env with random local secrets.'
31
+ fi
32
+fi
33
+[[ -f .env ]] || { echo 'Create .env first, or use --init https://LAN-IP' >&2; exit 1; }
34
+if grep -Eq '^((POSTGRES_PASSWORD|JWT_SECRET)=CHANGE_ME|JWT_SECRET=.{0,31}$)' .env; then
35
+ echo 'Replace placeholder/short secrets in .env' >&2; exit 1
36
+fi
37
+if [[ -n "${DOCKER_CONTEXT:-}" ]]; then
38
+ endpoint="$(docker context inspect "$DOCKER_CONTEXT" --format '{{.Endpoints.docker.Host}}')"
39
+else
40
+ endpoint="${DOCKER_HOST:-$(docker context inspect --format '{{.Endpoints.docker.Host}}')}"
41
+fi
42
+case "$endpoint" in unix://*|npipe://*) ;; *) echo 'Refusing a remote Docker endpoint; this command is local only.' >&2; exit 1;; esac
43
+docker info >/dev/null
44
+docker compose config --quiet
45
+cert_file="$(sed -n 's/^TLS_CERT_PATH=//p' .env)"
46
+key_file="$(sed -n 's/^TLS_KEY_PATH=//p' .env)"
47
+[[ -f "$cert_file" && -f "$key_file" ]] || { echo 'Create the configured TLS certificate/key first' >&2; exit 1; }
48
+# These bind-mounted files contain public client configuration/downloads. Keep
49
+# private .env and TLS keys unchanged; nginx workers must read only this data.
50
+chmod 755 deployment deployment/downloads
51
+chmod 644 deployment/runtime-config.json
52
+find deployment/downloads -maxdepth 1 -type f -name '*.apk' -exec chmod 644 {} +
53
+# nginx validates the certificate/key pair on startup.
54
+compose_build=(-f docker-compose.yml)
55
+if [[ "$prebuilt_web" == yes ]]; then
56
+ command -v node >/dev/null || { echo 'Node >=22 required to validate the prebuilt web artifact' >&2; exit 1; }
57
+ node scripts/prebuilt-web-check.mjs apps/lifemate
58
+ compose_build+=(-f docker-compose.prebuilt-web.yml)
59
+fi
60
+if [[ -n "${BUILD_CA_FILE:-}" ]]; then
61
+ [[ -f "$BUILD_CA_FILE" ]] || { echo 'BUILD_CA_FILE must be a public CA certificate file' >&2; exit 1; }
62
+ if grep -q 'PRIVATE KEY' "$BUILD_CA_FILE"; then echo 'Private key forbidden in build CA input' >&2; exit 1; fi
63
+ compose_build+=(-f docker-compose.build-proxy.yml)
64
+ docker compose "${compose_build[@]}" build api gateway backup
65
+else
66
+ docker compose "${compose_build[@]}" build --build-arg HTTP_PROXY --build-arg HTTPS_PROXY api gateway backup
67
+fi
68
+docker compose up -d --wait --wait-timeout 120 postgres
69
+docker compose run --rm migrate
70
+docker compose up -d --wait --wait-timeout 180 api gateway backup
71
+docker compose ps
72
+echo 'Local stack started. Run the HTTPS smoke test; health alone does not prove family CRUD.'
scripts/prebuilt-web-check.mjs
new
+68
@@ -0,0 +1,68 @@
1
+#!/usr/bin/env node
2
+// This records build inputs only after the operator has actually run the build.
3
+// It does not compile Flutter and must never be reported as a build itself.
4
+import { readFile, readdir, writeFile } from 'node:fs/promises';
5
+import { resolve, join, relative, basename, sep } from 'node:path';
6
+import { createHash } from 'node:crypto';
7
+
8
+const app = resolve(process.argv[2] ?? 'apps/lifemate');
9
+const output = join(app, 'build/web');
10
+const stamp = process.argv.includes('--stamp-after-build');
11
+async function walk(directory) {
12
+ const files = [];
13
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
14
+ const path = join(directory, entry.name);
15
+ if (entry.isSymbolicLink()) throw new Error('Symlinks forbidden in web build inputs/artifact');
16
+ if (entry.isDirectory()) files.push(...await walk(path));
17
+ else if (entry.isFile()) files.push(path);
18
+ }
19
+ return files.sort();
20
+}
21
+function assert(condition, message) { if (!condition) throw new Error(message); }
22
+const inputs = [join(app, 'pubspec.yaml'), join(app, 'pubspec.lock'), join(app, 'tool/self_host_web.mjs')];
23
+for (const path of ['lib', 'assets', 'web']) inputs.push(...await walk(join(app, path)));
24
+const hash = createHash('sha256');
25
+for (const path of inputs.sort()) {
26
+ hash.update(relative(app, path).split(sep).join('/')); hash.update('\0');
27
+ hash.update(await readFile(path)); hash.update('\0');
28
+}
29
+const sourceDigest = hash.digest('hex');
30
+const files = await walk(output);
31
+for (const path of files.filter(path => /\.(js|json|html)$/.test(path))) {
32
+ const text = await readFile(path, 'utf8');
33
+ assert(!/https?:[^\s"'<>]*(?:gstatic\.com|googleapis\.com|up\.railway\.app)/i.test(text), `External runtime dependency: ${relative(output, path)}`);
34
+}
35
+for (const path of ['index.html', 'main.dart.js', 'flutter_bootstrap.js', 'lifeguide-sw.js', 'canvaskit/canvaskit.wasm']) {
36
+ assert(files.includes(join(output, path)), `Missing built resource: ${path}`);
37
+}
38
+for (const name of ['LifeGuidePersian.ttf', 'LifeGuideLatin.ttf', 'LifeGuideEmoji.ttf']) {
39
+ assert(files.some(path => basename(path) === name), `Missing local font: ${name}`);
40
+}
41
+const manifest = JSON.parse(await readFile(join(output, 'manifest.json'), 'utf8'));
42
+assert(manifest.name.includes('LifeGuide') && manifest.short_name === 'لایفگاید' && manifest.display === 'standalone', 'LifeGuide standalone manifest required');
43
+const config = JSON.parse(await readFile(join(output, 'config.json'), 'utf8'));
44
+assert(config.apiBaseUrl === '/api', 'Prebuilt default API must use runtime same-origin /api');
45
+const builtTitle = /<title>([^<]+)<\/title>/.exec(await readFile(join(output, 'index.html'), 'utf8'))?.[1];
46
+const sourceTitle = /<title>([^<]+)<\/title>/.exec(await readFile(join(app, 'web/index.html'), 'utf8'))?.[1];
47
+assert(builtTitle === sourceTitle && builtTitle?.includes('LifeGuide'), 'LifeGuide HTML title must match source');
48
+for (const path of ['manifest.json', 'favicon.png', 'icons/Icon-192.png', 'icons/Icon-512.png', 'icons/Icon-maskable-192.png', 'icons/Icon-maskable-512.png']) {
49
+ assert((await readFile(join(output, path))).equals(await readFile(join(app, 'web', path))), `Built branding differs from source: ${path}`);
50
+}
51
+const provenance = join(output, 'build-provenance.json');
52
+const artifactHash = createHash('sha256');
53
+for (const path of files.filter(path => path !== provenance)) {
54
+ artifactHash.update(relative(output, path).split(sep).join('/')); artifactHash.update('\0');
55
+ artifactHash.update(await readFile(path)); artifactHash.update('\0');
56
+}
57
+const artifactDigest = artifactHash.digest('hex');
58
+if (stamp) {
59
+ await writeFile(provenance, JSON.stringify({ sourceDigest, artifactDigest, inputFiles: inputs.length, recordedAt: new Date().toISOString(),
60
+ requiredFlutterVersion: '3.47.6', requiredFlutterRevision: '5fc346839b5d0eef006ed8404392afb4dfae428d',
61
+ command: 'flutter build web --release --no-web-resources-cdn --pwa-strategy=none; node tool/self_host_web.mjs build/web',
62
+ limitation: 'Recorded only after a real build; this checker does not compile or prove device acceptance.' }, null, 2) + '\n');
63
+} else {
64
+ const recorded = JSON.parse(await readFile(provenance, 'utf8'));
65
+ assert(recorded.sourceDigest === sourceDigest, 'Source changed after recorded build; rebuild and recheck web before packaging');
66
+ assert(recorded.artifactDigest === artifactDigest, 'Built artifact changed after its recorded check');
67
+}
68
+console.log(`PASS prebuilt LifeGuide web: ${inputs.length} input files, local fonts/CanvasKit, same-origin runtime config, current branding and matching source digest.`);
scripts/reachability-smoke.mjs
new
+86
@@ -0,0 +1,86 @@
1
+#!/usr/bin/env node
2
+// Node >=22. TLS verification always remains enabled. Never logs credentials.
3
+import https from 'node:https';
4
+import fs from 'node:fs';
5
+import crypto from 'node:crypto';
6
+
7
+const origin = new URL(process.argv[2] ?? process.env.SMOKE_ORIGIN ?? '');
8
+if (origin.protocol !== 'https:' || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== '/') {
9
+ throw new Error('Pass one HTTPS origin without credentials, path, query or fragment');
10
+}
11
+const ca = process.env.ROOT_CA_FILE ? fs.readFileSync(process.env.ROOT_CA_FILE) : undefined;
12
+const results = [];
13
+let currentCheck = 'TLS/connection';
14
+const record = (name, status, detail) => results.push({ name, status, detail });
15
+async function request(path, { method = 'GET', json, token } = {}) {
16
+ const url = new URL(path, origin);
17
+ if (url.origin !== origin.origin) throw new Error('Cross-origin request refused');
18
+ const body = json === undefined ? undefined : JSON.stringify(json);
19
+ return await new Promise((resolve, reject) => {
20
+ const req = https.request(url, { method, ca, timeout: 15000, headers: {
21
+ ...(body ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } : {}),
22
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
23
+ } }, res => {
24
+ const chunks = []; let size = 0;
25
+ res.on('data', chunk => { size += chunk.length; if (size > 4 * 1024 * 1024) req.destroy(new Error('Oversize response')); else chunks.push(chunk); });
26
+ res.on('end', () => resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString('utf8'), headers: res.headers, tls: res.socket?.authorized }));
27
+ });
28
+ req.on('timeout', () => req.destroy(new Error('Timeout')));
29
+ req.on('error', reject);
30
+ if (body) req.write(body);
31
+ req.end();
32
+ });
33
+}
34
+function assert(condition, message) { if (!condition) throw new Error(message); }
35
+try {
36
+ const health = await request('/health');
37
+ record('TLS', 'PASS', 'Certificate chain and hostname verified by Node TLS');
38
+ currentCheck = '/health';
39
+ assert(health.status === 200 && JSON.parse(health.text).status === 'ok', `health HTTP ${health.status}`);
40
+ record('/health', 'PASS', 'HTTP 200 and database-backed status ok');
41
+ currentCheck = 'PWA';
42
+ const pwa = await request('/');
43
+ assert(pwa.status === 200 && /LifeGuide|لایفگاید/.test(pwa.text), 'PWA title/content missing');
44
+ const manifest = await request('/manifest.json');
45
+ assert(manifest.status === 200 && JSON.parse(manifest.text).display === 'standalone', 'PWA manifest missing standalone');
46
+ record('PWA', 'PASS', 'HTTPS HTML and standalone manifest loaded; Safari installation UNVERIFIED');
47
+ currentCheck = 'runtime config';
48
+ const config = await request('/config.json');
49
+ assert(config.status === 200 && JSON.parse(config.text).apiBaseUrl === '/api', 'Same-origin runtime API config missing');
50
+ assert(String(config.headers['cache-control']).includes('no-store'), 'Runtime config can become stale');
51
+ record('runtime config', 'PASS', 'Same-origin /api; no-store');
52
+ currentCheck = 'API auth boundary';
53
+ const denied = await request('/api/v1/plan-items');
54
+ assert(denied.status === 401, `Anonymous planner unexpectedly returned HTTP ${denied.status}`);
55
+ record('API auth boundary', 'PASS', 'Anonymous planner request rejected with 401');
56
+ if (process.env.SMOKE_ALLOW_SYNTHETIC_WRITE !== 'yes') {
57
+ record('API round-trip', 'UNVERIFIED', 'Set SMOKE_ALLOW_SYNTHETIC_WRITE=yes and synthetic SMOKE_EMAIL/SMOKE_PASSWORD to run');
58
+ } else {
59
+ currentCheck = 'API round-trip';
60
+ assert(process.env.SMOKE_EMAIL && process.env.SMOKE_PASSWORD, 'Synthetic account credentials required');
61
+ const login = await request('/api/v1/auth/login', { method: 'POST', json: { email: process.env.SMOKE_EMAIL, password: process.env.SMOKE_PASSWORD } });
62
+ assert(login.status === 200, `Login HTTP ${login.status}`);
63
+ const token = JSON.parse(login.text).accessToken;
64
+ assert(token, 'Access token missing');
65
+ const title = `LifeGuide synthetic reachability ${crypto.randomUUID()}`;
66
+ const created = await request('/api/v1/plan-items', { method: 'POST', token, json: { kind: 'assignment', title, visibility: 'private', priority: 'normal' } });
67
+ assert(created.status === 201, `Create HTTP ${created.status}`);
68
+ const createdItem = JSON.parse(created.text);
69
+ const id = createdItem.id;
70
+ assert(id, 'Created record ID missing');
71
+ const read = await request('/api/v1/plan-items?kind=assignment', { token });
72
+ assert(read.status === 200 && JSON.parse(read.text).items.some(item => item.id === id && item.title === title), 'Independent read did not return created task');
73
+ const archived = await request(`/api/v1/plan-items/${id}`, { method: 'PATCH', token, json: { status: 'cancelled', expectedVersion: createdItem.version } });
74
+ assert(archived.status === 200 && JSON.parse(archived.text).status === 'cancelled', 'Safe archive failed');
75
+ const logout = await request('/api/v1/auth/logout', { method: 'POST', token, json: { refreshToken: JSON.parse(login.text).refreshToken } });
76
+ assert(logout.status === 204, 'Synthetic session logout failed');
77
+ const revoked = await request('/api/v1/plan-items', { token });
78
+ assert(revoked.status === 401, 'Logged-out session remains usable');
79
+ record('API round-trip', 'PASS', 'Synthetic private homework created, independently read, and archived on server');
80
+ record('session cleanup', 'PASS', 'Logout acknowledged; old access token rejected');
81
+ }
82
+} catch (error) {
83
+ record(currentCheck, 'FAIL', `${error.code ?? 'CHECK_FAILED'}: ${String(error.message).slice(0, 240)}`);
84
+ process.exitCode = 1;
85
+}
86
+console.log(JSON.stringify({ origin: origin.origin, at: new Date().toISOString(), results }, null, 2));
scripts/restore-drill.sh
new
+70
@@ -0,0 +1,70 @@
1
+#!/usr/bin/env bash
2
+# Only two newly-created local databases are restored/deleted, never the app DB.
3
+set -euo pipefail
4
+cd "$(dirname "${BASH_SOURCE[0]}")/.."
5
+[[ "${1:-}" == '--synthetic-only' ]] || { echo 'Usage: scripts/restore-drill.sh --synthetic-only' >&2; exit 1; }
6
+if [[ -n "${DOCKER_CONTEXT:-}" ]]; then
7
+ endpoint="$(docker context inspect "$DOCKER_CONTEXT" --format '{{.Endpoints.docker.Host}}')"
8
+else
9
+ endpoint="${DOCKER_HOST:-$(docker context inspect --format '{{.Endpoints.docker.Host}}')}"
10
+fi
11
+case "$endpoint" in unix://*|npipe://*) ;; *) echo 'Refusing remote Docker' >&2; exit 1;; esac
12
+suffix="$(date -u +%Y%m%d%H%M%S)_${RANDOM}${RANDOM}${RANDOM}"
13
+source_db="lifeguide_drill_source_$suffix"
14
+target_db="lifeguide_drill_target_$suffix"
15
+source_created=no
16
+target_created=no
17
+cleanup() {
18
+ if [[ "$target_created" == yes ]]; then
19
+ docker compose exec -T postgres sh -c 'dropdb --if-exists --username "$POSTGRES_USER" "$1"' sh "$target_db" >/dev/null 2>&1 || true
20
+ fi
21
+ if [[ "$source_created" == yes ]]; then
22
+ docker compose exec -T postgres sh -c 'dropdb --if-exists --username "$POSTGRES_USER" "$1"; rm -f "/tmp/$1.dump"' sh "$source_db" >/dev/null 2>&1 || true
23
+ fi
24
+}
25
+trap cleanup EXIT
26
+docker compose exec -T postgres sh -c 'createdb --username "$POSTGRES_USER" "$1"' sh "$source_db"
27
+source_created=yes
28
+docker compose exec -T postgres sh -c 'createdb --username "$POSTGRES_USER" "$1"' sh "$target_db"
29
+target_created=yes
30
+docker compose run --rm -e "PGDATABASE=$source_db" migrate
31
+docker compose exec -T postgres sh -c 'psql --username "$POSTGRES_USER" --dbname "$1" --set ON_ERROR_STOP=1' sh "$source_db" <backend/scripts/restore-smoke.sql
32
+docker compose exec -T postgres sh -c 'psql --username "$POSTGRES_USER" --dbname "$1" --set ON_ERROR_STOP=1' sh "$source_db" <deployment/restore-fixture.sql
33
+# Copy the already-existing repository backup/restore programs into this
34
+# disposable container, then run them against only the generated drill DBs.
35
+container_id="$(docker compose ps -q postgres)"
36
+docker cp backend/scripts/backup.sh "$container_id:/tmp/lifeguide-backup.sh"
37
+docker cp backend/scripts/restore.sh "$container_id:/tmp/lifeguide-restore.sh"
38
+docker compose exec -T postgres bash -c 'export DATABASE_URL="postgresql:///$1?user=$POSTGRES_USER"; bash /tmp/lifeguide-backup.sh "/tmp/$1.dump"' bash "$source_db"
39
+docker compose exec -T postgres bash -c 'export DATABASE_URL="postgresql:///$2?user=$POSTGRES_USER"; bash /tmp/lifeguide-restore.sh "/tmp/$1.dump"' bash "$source_db" "$target_db"
40
+docker compose exec -T postgres sh -c 'psql --username "$POSTGRES_USER" --dbname "$1" --set ON_ERROR_STOP=1' sh "$target_db" <<'SQL'
41
+do $$
42
+begin
43
+ if (select count(*) from app_user where identity_subject='restore-smoke') <> 1 then
44
+ raise exception 'Synthetic restore row missing';
45
+ end if;
46
+ if (select count(*) from profile where display_name='Restore Smoke') <> 1 then
47
+ raise exception 'Synthetic profile missing';
48
+ end if;
49
+ if not can_view_plan_item('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000005') then
50
+ raise exception 'Restored guardian cannot read permitted homework';
51
+ end if;
52
+ if can_view_plan_item('00000000-0000-4000-8000-000000000005','00000000-0000-4000-8000-000000000006') then
53
+ raise exception 'Restored private task exposed to guardian';
54
+ end if;
55
+ if can_view_plan_item('00000000-0000-4000-8000-000000000007','00000000-0000-4000-8000-000000000005') then
56
+ raise exception 'Restored homework exposed to unrelated parent';
57
+ end if;
58
+ if (select recorded_duration_seconds from study_session where id='00000000-0000-4000-8000-000000000005') <> 600
59
+ or (select sum(extract(epoch from ends_at-starts_at)) from study_interval where session_id='00000000-0000-4000-8000-000000000005') <> 600 then
60
+ raise exception 'Restored paused study intervals/duration changed';
61
+ end if;
62
+end $$;
63
+SQL
64
+expected_migrations=0
65
+for migration_file in backend/migrations/[0-9][0-9][0-9][0-9]_*.sql; do
66
+ [[ -f "$migration_file" ]] && expected_migrations=$((expected_migrations+1))
67
+done
68
+restored_migrations="$(docker compose exec -T postgres sh -c 'psql --username "$POSTGRES_USER" --dbname "$1" --tuples-only --no-align --command "select count(*) from schema_migration"' sh "$target_db")"
69
+[[ "$restored_migrations" -eq "$expected_migrations" ]] || { echo 'Migration ledger count differs from source version' >&2; exit 1; }
70
+echo "PASS synthetic PostgreSQL dump/restore: identity, family permissions, private task, paused study intervals and $restored_migrations migrations preserved."