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 243 lines 10.4 KB
Raw
1 #!/usr/bin/env python3
2 """Read-only local signing preparation. Never signs, exports or delivers an APK."""
3
4 import argparse
5 import getpass
6 import json
7 import os
8 from pathlib import Path
9 import re
10 import shutil
11 import struct
12 import subprocess
13 import sys
14 import warnings
15
16 ROOT = Path(__file__).resolve().parents[1]
17 if __package__ in (None, ""):
18 sys.path.insert(0, str(ROOT))
19 sys.path.insert(0, str(ROOT / "apps/lifemate/tool"))
20
21 from check_standalone_update import load_baseline
22 from scripts.personal_recovery.common import RecoveryError
23 from scripts.personal_recovery.files import read_bounded
24
25 MAX_KEYSTORE_BYTES = 2 * 1024 * 1024
26 HELPER = ROOT / "scripts/java/LifeGuideKeyInspector.java"
27 REFUSALS = frozenset({"invalid_request", "keystore_unreadable", "private_key_unavailable",
28 "unsupported_key_algorithm", "key_proof_failed", "inspection_failed"})
29
30
31 class PreflightError(Exception):
32 def __init__(self, code):
33 self.code = code
34 super().__init__(code)
35
36
37 def _java_environment():
38 # Do not inherit arbitrary credentials or JVM agent/options injection.
39 allowed = {"PATH", "SYSTEMROOT", "WINDIR", "TEMP", "TMP", "TMPDIR", "LANG", "LC_ALL"}
40 return {key: value for key, value in os.environ.items() if key.upper() in allowed}
41
42
43 def _java_available():
44 java = shutil.which("java")
45 if java is None:
46 return False
47 try:
48 process = subprocess.run([java, "-version"], stdin=subprocess.DEVNULL,
49 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
50 env=_java_environment(), timeout=10, check=False)
51 if process.returncode != 0 or len(process.stdout) > 4096:
52 return False
53 version = re.search(rb'\bversion\s+"(\d+)(?:\.[^"\r\n]*)?"', process.stdout)
54 if version is None or int(version[1]) < 17:
55 return False
56 modules = subprocess.run([java, "--list-modules"], stdin=subprocess.DEVNULL,
57 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
58 env=_java_environment(), timeout=10, check=False)
59 if (modules.returncode != 0 or len(modules.stdout) > 32768
60 or not any(line.startswith(b"jdk.compiler@") for line in modules.stdout.splitlines())):
61 return False
62 # A stripped runtime can list jdk.compiler yet lack source17 support.
63 # Compile the fixed helper with empty input: no key/alias/password/file.
64 probe = subprocess.run([java, "-Xmx96m", "--source", "17", str(HELPER)],
65 input=b"", stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
66 timeout=30, env=_java_environment(), check=False)
67 try:
68 _helper_result(probe)
69 except PreflightError as failure:
70 return failure.code == "invalid_request"
71 return False
72 except (OSError, subprocess.TimeoutExpired, ValueError):
73 return False
74
75
76 def _baseline():
77 try:
78 return load_baseline()
79 except Exception:
80 raise PreflightError("delivered_baseline_invalid") from None
81
82
83 def _boundary_report():
84 return {"schemaVersion": 1, "delivery": "BLOCKED", "releaseReadiness": "UNVERIFIED",
85 "installedDeviceVerification": "UNVERIFIED", "dataPreservation": "UNVERIFIED"}
86
87
88 def _inspection_report(facts, baseline):
89 match = facts["certificateSha256"] == baseline["certificateSha256"]
90 reasons = []
91 if not match:
92 reasons.append("different_from_delivered_signer")
93 if facts["debugCertificate"]:
94 reasons.append("debug_certificate_not_for_release")
95 return dict(_boundary_report(), **facts, signerCompatibility="MATCH" if match else "DIFFERENT",
96 reasonCodes=reasons, keyInspection="VERIFIED_LOCAL_CHALLENGE")
97
98
99 def _encode(value, limit):
100 if not isinstance(value, str) or not value or any(c in value for c in "\x00\r\n"):
101 raise PreflightError("invalid_inspection_input")
102 try:
103 raw = value.encode("utf-8", errors="strict")
104 except UnicodeError:
105 raise PreflightError("invalid_inspection_input") from None
106 if len(raw) > limit:
107 raise PreflightError("invalid_inspection_input")
108 return raw
109
110
111 def _no_duplicate_keys(pairs):
112 result = {}
113 for key, value in pairs:
114 if key in result:
115 raise ValueError("duplicate_json_key")
116 result[key] = value
117 return result
118
119
120 def _helper_result(process):
121 try:
122 if not isinstance(process.stdout, bytes) or len(process.stdout) > 4096:
123 raise ValueError("invalid_output")
124 value = json.loads(process.stdout, object_pairs_hook=_no_duplicate_keys)
125 if not isinstance(value, dict) or type(value.get("schemaVersion")) is not int or value["schemaVersion"] != 1:
126 raise ValueError("invalid_schema")
127 if (process.returncode == 2 and set(value) == {"schemaVersion", "status", "reason"}
128 and value["status"] == "REFUSED" and value["reason"] in REFUSALS):
129 raise PreflightError(value["reason"])
130 if (process.returncode != 0 or set(value) != {"schemaVersion", "status", "certificateSha256",
131 "debugCertificate", "privateKeyProof", "certificateCurrentlyValid"}
132 or value["status"] != "INSPECTED"
133 or not isinstance(value["certificateSha256"], str)
134 or re.fullmatch(r"[0-9a-f]{64}", value["certificateSha256"]) is None
135 or type(value["privateKeyProof"]) is not bool or not value["privateKeyProof"]
136 or type(value["debugCertificate"]) is not bool
137 or type(value["certificateCurrentlyValid"]) is not bool):
138 raise ValueError("invalid_facts")
139 return value
140 except PreflightError:
141 raise
142 except (ValueError, TypeError, KeyError, UnicodeError):
143 raise PreflightError("inspector_invalid_response") from None
144
145
146 def _run_inspector(encrypted, alias, store_password, key_password):
147 fields = (encrypted, _encode(alias, 256), _encode(store_password, 4096), _encode(key_password, 4096))
148 if not isinstance(encrypted, bytes) or not encrypted or len(encrypted) > MAX_KEYSTORE_BYTES:
149 raise PreflightError("invalid_inspection_input")
150 java = shutil.which("java")
151 if java is None:
152 raise PreflightError("jdk17_required")
153 frame = b"LGKI" + b"".join(struct.pack(">I", len(field)) + field for field in fields)
154 try:
155 process = subprocess.run([java, "-Xmx96m", "--source", "17", str(HELPER)],
156 input=frame, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
157 timeout=30, env=_java_environment(), check=False)
158 except subprocess.TimeoutExpired:
159 raise PreflightError("inspector_timeout") from None
160 except OSError:
161 raise PreflightError("inspector_unavailable") from None
162 return _helper_result(process)
163
164
165 def inspect_key(path, alias, store_password, key_password):
166 """Internal read-only API. CLI additionally requires acknowledgement and TTY.
167
168 Callers must supply only an explicitly chosen local key, never auto-discover
169 owner files. Tests use this API with process-local synthetic fixtures only.
170 Python cannot guarantee zeroization of immutable strings/bytes in memory.
171 """
172 _encode(alias, 256)
173 _encode(store_password, 4096)
174 _encode(key_password, 4096)
175 baseline = _baseline()
176 try:
177 encrypted = read_bounded(Path(path), MAX_KEYSTORE_BYTES)
178 except RecoveryError as failure:
179 raise PreflightError(failure.code) from None
180 except (OSError, ValueError):
181 raise PreflightError("invalid_input_file") from None
182 return _inspection_report(_run_inspector(encrypted, alias, store_password, key_password), baseline)
183
184
185 def _passwords():
186 if not sys.stdin.isatty():
187 raise PreflightError("interactive_terminal_required")
188 with warnings.catch_warnings():
189 warnings.simplefilter("error", getpass.GetPassWarning)
190 try:
191 store = getpass.getpass("Local keystore password (hidden): ")
192 key = getpass.getpass("Local key password (Enter = same; hidden): ")
193 except (getpass.GetPassWarning, EOFError):
194 raise PreflightError("interactive_terminal_required") from None
195 return store, key or store
196
197
198 class _Parser(argparse.ArgumentParser):
199 def error(self, message):
200 # argparse's default interpolates unknown argument values into stderr.
201 raise PreflightError("arguments_invalid")
202
203
204 def main(argv=None):
205 parser = _Parser(description=__doc__, allow_abbrev=False)
206 commands = parser.add_subparsers(dest="command", parser_class=_Parser)
207 commands.add_parser("check", allow_abbrev=False,
208 help="Check public baseline and JDK only; no key access")
209 inspect = commands.add_parser("inspect", allow_abbrev=False,
210 help="Explicit owner-local read-only inspection; hidden passwords")
211 inspect.add_argument("--keystore", type=Path, required=True)
212 inspect.add_argument("--alias", required=True)
213 inspect.add_argument("--acknowledge-owner-local-inspection", action="store_true")
214 try:
215 args = parser.parse_args(argv)
216 if args.command == "inspect":
217 if not args.acknowledge_owner_local_inspection:
218 raise PreflightError("owner_local_acknowledgement_required")
219 if not sys.stdin.isatty():
220 raise PreflightError("interactive_terminal_required")
221 if not _java_available():
222 raise PreflightError("jdk17_required")
223 store, key = _passwords()
224 report = inspect_key(args.keystore, args.alias, store, key)
225 else:
226 baseline = _baseline()
227 if not _java_available():
228 raise PreflightError("jdk17_required")
229 report = dict(_boundary_report(), status="CHECKED", java17OrNewer=True,
230 keyInspection="UNVERIFIED", baselineCertificateSha256=baseline["certificateSha256"],
231 baselineVersionCode=baseline["versionCode"])
232 print(json.dumps(report, sort_keys=True))
233 return 0
234 except PreflightError as failure:
235 print(json.dumps(dict(_boundary_report(), status="REFUSED", reason=failure.code), sort_keys=True))
236 return 2
237 except KeyboardInterrupt:
238 print(json.dumps(dict(_boundary_report(), status="CANCELLED", reason="interrupted"), sort_keys=True))
239 return 130
240
241
242 if __name__ == "__main__":
243 raise SystemExit(main())