LifeMate — Personal, Family & Learning Companion

feat/local-signing-preflight
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
py 178 lines 7.4 KB
Raw
1 #!/usr/bin/env python3
2 """Fictional recovery rehearsal. Never use this QA entry point on owner data."""
3
4 import argparse
5 import getpass
6 import hashlib
7 import json
8 from pathlib import Path
9 import secrets
10 import sqlite3
11 import sys
12 import warnings
13
14 if __package__ in (None, ""):
15 sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
16
17 from scripts.personal_recovery.archive import open_archive, seal
18 from scripts.personal_recovery.common import MAX_PAYLOAD_BYTES, RecoveryError
19 from scripts.personal_recovery.files import publish_new, read_bounded
20 from scripts.personal_recovery.snapshot import (
21 create_sample_database,
22 database_from_snapshot,
23 export_fixture,
24 )
25
26
27 def pack_fixture(source: Path, destination: Path, passphrase: str) -> None:
28 # export_fixture refuses an unmarked DB before reading its profile/task data.
29 payload = export_fixture(source)
30 publish_new(destination, seal(payload, passphrase))
31
32
33 def restore_fixture(source: Path, destination: Path, passphrase: str) -> None:
34 raw = read_bounded(source, MAX_PAYLOAD_BYTES + 64)
35 payload = open_archive(raw, passphrase)
36 database = database_from_snapshot(payload)
37 publish_new(destination, database)
38
39
40 def _ask_password(confirm: bool) -> str:
41 if not sys.stdin.isatty():
42 raise RecoveryError("interactive_terminal_required")
43 # Refuse getpass's echoing fallback if a hidden terminal is unavailable.
44 with warnings.catch_warnings():
45 warnings.simplefilter("error", getpass.GetPassWarning)
46 try:
47 value = getpass.getpass("Synthetic QA passphrase (hidden): ")
48 if confirm and value != getpass.getpass("Repeat passphrase (hidden): "):
49 raise RecoveryError("passphrase_confirmation_mismatch")
50 return value
51 except (getpass.GetPassWarning, EOFError):
52 raise RecoveryError("interactive_terminal_required") from None
53
54
55 def _expect_refusal(operation, destination: Path) -> None:
56 try:
57 operation()
58 except RecoveryError:
59 if destination.exists():
60 raise RecoveryError("demo_failed") from None
61 return
62 raise RecoveryError("demo_failed")
63
64
65 def demo(directory: Path) -> dict:
66 """Exercise real disk SQLite, encryption and reopen with process-local secret."""
67 directory = Path(directory)
68 if directory.is_symlink():
69 raise RecoveryError("invalid_demo_directory")
70 if directory.exists():
71 if not directory.is_dir() or any(directory.iterdir()):
72 raise RecoveryError("demo_directory_not_empty")
73 else:
74 directory.mkdir(mode=0o700)
75 source = directory / "synthetic-source.sqlite"
76 archive = directory / "synthetic-transfer.lgrf"
77 restored = directory / "synthetic-restored.sqlite"
78 publish_new(source, create_sample_database())
79 original_hash = hashlib.sha256(source.read_bytes()).hexdigest()
80 before = export_fixture(source)
81 passphrase = secrets.token_urlsafe(32)
82 pack_fixture(source, archive, passphrase)
83 invalid_destination = directory / "must-not-exist.sqlite"
84 _expect_refusal(lambda: restore_fixture(archive, invalid_destination, secrets.token_urlsafe(32)), invalid_destination)
85 corrupted = bytearray(read_bounded(archive, MAX_PAYLOAD_BYTES + 64))
86 corrupted[-1] ^= 1
87 _expect_refusal(lambda: open_archive(bytes(corrupted), passphrase), invalid_destination)
88 restore_fixture(archive, restored, passphrase)
89 if export_fixture(restored) != before:
90 raise RecoveryError("demo_failed")
91 if hashlib.sha256(source.read_bytes()).hexdigest() != original_hash:
92 raise RecoveryError("demo_failed")
93 restored_hash = hashlib.sha256(restored.read_bytes()).hexdigest()
94 try:
95 restore_fixture(archive, restored, passphrase)
96 except RecoveryError as failure:
97 if failure.code != "destination_exists":
98 raise RecoveryError("demo_failed") from None
99 else:
100 raise RecoveryError("demo_failed")
101 if hashlib.sha256(restored.read_bytes()).hexdigest() != restored_hash:
102 raise RecoveryError("demo_failed")
103 with sqlite3.connect(f"{restored.resolve().as_uri()}?mode=ro", uri=True) as db:
104 if db.execute("PRAGMA quick_check").fetchone() != ("ok",):
105 raise RecoveryError("demo_failed")
106 if db.execute("PRAGMA foreign_key_check").fetchall():
107 raise RecoveryError("demo_failed")
108 tables = ("local_profiles", "local_plans", "local_weekly_slots", "local_occurrences")
109 counts = {table: db.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] for table in tables}
110 if any(count == 0 for count in counts.values()):
111 raise RecoveryError("demo_failed")
112 return {
113 "schemaVersion": 1,
114 "result": "PASS",
115 "syntheticOnly": True,
116 "scope": "host SQLite v1 encrypted recovery rehearsal; no device or owner data",
117 "counts": counts,
118 "canonicalSnapshotSha256": hashlib.sha256(before).hexdigest(),
119 "checks": {
120 "fullFieldRoundTripAfterCloseReopen": "PASS",
121 "sourceBytesUnchanged": "PASS",
122 "independentSqlIntegrityAndCounts": "PASS",
123 "invalidCredentialRejectedBeforeOutput": "PASS",
124 "tamperingRejected": "PASS",
125 "repeatRestoreRefusedWithoutOverwrite": "PASS",
126 },
127 "limitations": {
128 "androidSideBySide": "UNVERIFIED",
129 "subsequentSignedAppUpgrade": "UNVERIFIED",
130 "physicalDeviceOrOwnerData": "UNVERIFIED",
131 "WindowsAndUsb": "UNVERIFIED",
132 "powerLossDurability": "UNVERIFIED",
133 "ownerSigningKey": "UNVERIFIED",
134 },
135 }
136
137
138 def main(argv=None) -> int:
139 parser = argparse.ArgumentParser(description=__doc__)
140 subcommands = parser.add_subparsers(dest="command", required=True)
141 for name in ("create-fixture", "pack", "restore-fixture", "demo"):
142 command = subcommands.add_parser(name)
143 command.add_argument("--acknowledge-synthetic-only", action="store_true")
144 if name == "demo":
145 command.add_argument("--directory", type=Path, required=True)
146 else:
147 command.add_argument("--output", type=Path, required=True)
148 if name != "create-fixture":
149 command.add_argument("--source", type=Path, required=True)
150 args = parser.parse_args(argv)
151 try:
152 if not args.acknowledge_synthetic_only:
153 raise RecoveryError("synthetic_acknowledgement_required")
154 if args.command == "demo":
155 report = demo(args.directory)
156 else:
157 if args.command == "create-fixture":
158 publish_new(args.output, create_sample_database())
159 elif args.command == "pack":
160 pack_fixture(args.source, args.output, _ask_password(confirm=True))
161 else:
162 restore_fixture(args.source, args.output, _ask_password(confirm=False))
163 report = {"status": "PASS", "syntheticOnly": True}
164 print(json.dumps(report, ensure_ascii=True, sort_keys=True))
165 return 0
166 except RecoveryError as failure:
167 print(json.dumps({"status": "REFUSED", "reason": failure.code, "syntheticOnly": True}))
168 return 2
169 except (OSError, sqlite3.Error):
170 print(json.dumps({"status": "REFUSED", "reason": "file_io_error", "syntheticOnly": True}))
171 return 2
172 except KeyboardInterrupt:
173 print(json.dumps({"status": "CANCELLED", "reason": "interrupted", "syntheticOnly": True}))
174 return 130
175
176
177 if __name__ == "__main__":
178 raise SystemExit(main())