LifeMate — Personal, Family & Learning Companion

feat/personal-encrypted-recovery
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 365 lines 16.4 KB
Raw
1 """Portable, synthetic-only recovery snapshots of the standalone SQLite v1 store.
2
3 The application_id marker is an accident-prevention gate, not authentication or
4 proof of provenance: anyone can set it. This kit must never be used on owner data.
5 Only closed rollback-journal fixtures without sidecars are accepted. WAL-mode
6 headers are refused even after their sidecars have been removed.
7 """
8 from datetime import date
9 import json
10 from pathlib import Path
11 import re
12 import sqlite3
13 import uuid
14
15 from .common import (
16 FIXTURE_APPLICATION_ID, MAX_PAYLOAD_BYTES, MAX_ROWS, RecoveryError, SCHEMA_VERSION,
17 )
18 from .files import read_bounded
19
20 FORMAT = 'LifeGuideSyntheticRecovery'
21 # Fixed statements mirror StandaloneStore._migrate v1. Source SQL is never run.
22 DDL = (
23 """CREATE TABLE local_profiles (
24 singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
25 id TEXT NOT NULL UNIQUE CHECK(length(id) = 36),
26 display_name TEXT NOT NULL CHECK(length(trim(display_name)) BETWEEN 1 AND 80),
27 category TEXT NOT NULL CHECK(category IN ('girl_minor','boy_minor','adult')),
28 companion_name TEXT NOT NULL CHECK(length(trim(companion_name)) BETWEEN 1 AND 40),
29 theme_key TEXT NOT NULL CHECK(theme_key IN ('violet','blue','mint','coral'))
30 )""",
31 """CREATE TABLE local_plans (
32 id TEXT PRIMARY KEY NOT NULL CHECK(length(id) = 36),
33 profile_id TEXT NOT NULL REFERENCES local_profiles(id),
34 title TEXT NOT NULL CHECK(length(trim(title)) BETWEEN 1 AND 200),
35 kind TEXT NOT NULL CHECK(kind IN ('task','event','routine')),
36 recurrence TEXT NOT NULL CHECK(recurrence IN ('once','daily','everyTwoDays','weekly')),
37 start_date TEXT NOT NULL CHECK(length(start_date) = 10),
38 until_date TEXT CHECK(until_date IS NULL OR (length(until_date) = 10 AND until_date >= start_date)),
39 start_minute INTEGER NOT NULL CHECK(start_minute BETWEEN 0 AND 1439),
40 end_minute INTEGER NOT NULL CHECK(end_minute BETWEEN 1 AND 1440 AND end_minute > start_minute),
41 reminder_minutes INTEGER CHECK(reminder_minutes IS NULL OR reminder_minutes IN (0,5,10,15,30)),
42 archived INTEGER NOT NULL DEFAULT 0 CHECK(archived IN (0,1))
43 )""",
44 """CREATE TABLE local_weekly_slots (
45 plan_id TEXT NOT NULL REFERENCES local_plans(id),
46 weekday INTEGER NOT NULL CHECK(weekday BETWEEN 1 AND 7),
47 start_minute INTEGER NOT NULL CHECK(start_minute BETWEEN 0 AND 1439),
48 end_minute INTEGER NOT NULL CHECK(end_minute BETWEEN 1 AND 1440 AND end_minute > start_minute),
49 PRIMARY KEY(plan_id, weekday)
50 )""",
51 """CREATE TABLE local_occurrences (
52 id TEXT PRIMARY KEY NOT NULL CHECK(length(id) = 36),
53 plan_id TEXT NOT NULL REFERENCES local_plans(id),
54 occurrence_date TEXT NOT NULL CHECK(length(occurrence_date) = 10),
55 title TEXT NOT NULL CHECK(length(trim(title)) BETWEEN 1 AND 200),
56 kind TEXT NOT NULL CHECK(kind IN ('task','event','routine')),
57 start_minute INTEGER NOT NULL CHECK(start_minute BETWEEN 0 AND 1439),
58 end_minute INTEGER NOT NULL CHECK(end_minute BETWEEN 1 AND 1440 AND end_minute > start_minute),
59 completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0,1)),
60 archived INTEGER NOT NULL DEFAULT 0 CHECK(archived IN (0,1)),
61 reminder_minutes INTEGER CHECK(reminder_minutes IS NULL OR reminder_minutes IN (0,5,10,15,30)),
62 UNIQUE(plan_id, occurrence_date)
63 )""",
64 'CREATE INDEX local_occurrences_date ON local_occurrences(occurrence_date)',
65 )
66 COLUMNS = {
67 'local_profiles': ('singleton', 'id', 'display_name', 'category', 'companion_name', 'theme_key'),
68 'local_plans': ('id', 'profile_id', 'title', 'kind', 'recurrence', 'start_date', 'until_date',
69 'start_minute', 'end_minute', 'reminder_minutes', 'archived'),
70 'local_weekly_slots': ('plan_id', 'weekday', 'start_minute', 'end_minute'),
71 'local_occurrences': ('id', 'plan_id', 'occurrence_date', 'title', 'kind', 'start_minute',
72 'end_minute', 'completed', 'archived', 'reminder_minutes'),
73 }
74 PRIMARY_KEYS = {
75 'local_profiles': ('singleton',), 'local_plans': ('id',),
76 'local_weekly_slots': ('plan_id', 'weekday'), 'local_occurrences': ('id',),
77 }
78 KINDS = ('task', 'event', 'routine')
79 RECURRENCES = ('once', 'daily', 'everyTwoDays', 'weekly')
80
81
82 def _require(condition):
83 if not condition:
84 raise RecoveryError('invalid_snapshot')
85
86
87 def _integer(value, minimum, maximum):
88 _require(type(value) is int and minimum <= value <= maximum)
89
90
91 def _text(value, maximum):
92 _require(type(value) is str and '\x00' not in value)
93 try:
94 length = len(value.strip().encode('utf-16-le')) // 2
95 except UnicodeError:
96 raise RecoveryError('invalid_snapshot') from None
97 _require(1 <= length <= maximum)
98
99
100 def _uuid(value):
101 _require(type(value) is str)
102 try:
103 parsed = uuid.UUID(value)
104 except (ValueError, AttributeError):
105 raise RecoveryError('invalid_snapshot') from None
106 _require(str(parsed) == value and parsed.version == 4 and parsed.variant == uuid.RFC_4122)
107
108
109 def _date(value):
110 _require(type(value) is str and re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value))
111 try:
112 date.fromisoformat(value)
113 except ValueError:
114 raise RecoveryError('invalid_snapshot') from None
115
116
117 def _time(row):
118 _integer(row['start_minute'], 0, 1439)
119 _integer(row['end_minute'], 1, 1440)
120 _require(row['end_minute'] > row['start_minute'])
121
122
123 def _reminder(value):
124 _require(value is None or (type(value) is int and value in (0, 5, 10, 15, 30)))
125
126
127 def _validate(document):
128 _require(type(document) is dict and set(document) == {'format', 'schemaVersion', 'syntheticOnly', 'tables'})
129 _require(document['format'] == FORMAT and type(document['format']) is str)
130 _require(type(document['schemaVersion']) is int and document['schemaVersion'] == SCHEMA_VERSION)
131 _require(document['syntheticOnly'] is True)
132 tables = document['tables']
133 _require(type(tables) is dict and set(tables) == set(COLUMNS))
134 total = 0
135 for table, columns in COLUMNS.items():
136 rows = tables[table]
137 _require(type(rows) is list)
138 total += len(rows)
139 _require(total <= MAX_ROWS)
140 for row in rows:
141 _require(type(row) is dict and set(row) == set(columns))
142 _require(len(tables['local_profiles']) <= 1)
143 profile_ids = set()
144 for row in tables['local_profiles']:
145 _integer(row['singleton'], 1, 1)
146 _uuid(row['id'])
147 _text(row['display_name'], 80)
148 _text(row['companion_name'], 40)
149 _require(row['category'] in ('girl_minor', 'boy_minor', 'adult'))
150 _require(row['theme_key'] in ('violet', 'blue', 'mint', 'coral'))
151 profile_ids.add(row['id'])
152 plans = {}
153 for row in tables['local_plans']:
154 _uuid(row['id'])
155 _uuid(row['profile_id'])
156 _require(row['id'] not in plans and row['profile_id'] in profile_ids)
157 _text(row['title'], 200)
158 _require(row['kind'] in KINDS and row['recurrence'] in RECURRENCES)
159 _date(row['start_date'])
160 if row['until_date'] is not None:
161 _date(row['until_date'])
162 _require(row['until_date'] >= row['start_date'])
163 _time(row)
164 _reminder(row['reminder_minutes'])
165 _integer(row['archived'], 0, 1)
166 plans[row['id']] = row
167 slots = set()
168 weekly_plan_ids = set()
169 for row in tables['local_weekly_slots']:
170 _uuid(row['plan_id'])
171 _require(row['plan_id'] in plans and plans[row['plan_id']]['recurrence'] == 'weekly')
172 _integer(row['weekday'], 1, 7)
173 _time(row)
174 key = (row['plan_id'], row['weekday'])
175 _require(key not in slots)
176 slots.add(key)
177 weekly_plan_ids.add(row['plan_id'])
178 _require(weekly_plan_ids == {p['id'] for p in plans.values() if p['recurrence'] == 'weekly'})
179 occurrence_ids = set()
180 occurrence_dates = set()
181 for row in tables['local_occurrences']:
182 _uuid(row['id'])
183 _uuid(row['plan_id'])
184 _require(row['plan_id'] in plans and row['id'] not in occurrence_ids)
185 _date(row['occurrence_date'])
186 key = (row['plan_id'], row['occurrence_date'])
187 _require(key not in occurrence_dates)
188 occurrence_dates.add(key)
189 occurrence_ids.add(row['id'])
190 _text(row['title'], 200)
191 _require(row['kind'] in KINDS)
192 _time(row)
193 _integer(row['completed'], 0, 1)
194 _integer(row['archived'], 0, 1)
195 _reminder(row['reminder_minutes'])
196 return {table: sorted(tables[table], key=lambda row: tuple(row[key] for key in PRIMARY_KEYS[table]))
197 for table in COLUMNS}
198
199
200 def _document(tables):
201 return {'format': FORMAT, 'schemaVersion': SCHEMA_VERSION, 'syntheticOnly': True, 'tables': tables}
202
203
204 def _canonical(document):
205 payload = json.dumps(document, ensure_ascii=False, sort_keys=True, separators=(',', ':'),
206 allow_nan=False).encode('utf-8')
207 if len(payload) > MAX_PAYLOAD_BYTES:
208 raise RecoveryError('payload_too_large')
209 return payload
210
211
212 def _new_database():
213 connection = sqlite3.connect(':memory:')
214 try:
215 connection.execute('PRAGMA foreign_keys = ON')
216 connection.execute(f'PRAGMA application_id = {FIXTURE_APPLICATION_ID}')
217 connection.execute(f'PRAGMA user_version = {SCHEMA_VERSION}')
218 for sql in DDL:
219 connection.execute(sql)
220 except BaseException:
221 connection.close()
222 raise
223 return connection
224
225
226 def _normalize_sql(sql):
227 if sql is None:
228 return None
229 # Preserve quoted literals exactly; ignore formatting between SQL tokens.
230 return ''.join(token if token.startswith("'") else re.sub(r'\s+', '', token).lower()
231 for token in re.findall(r"'(?:''|[^'])*'|[^']+", sql))
232
233
234 def _schema(connection):
235 return {(kind, name, table, _normalize_sql(sql)) for kind, name, table, sql in
236 connection.execute('SELECT type,name,tbl_name,sql FROM sqlite_schema')}
237
238
239 def _validate_source_header(prefix):
240 """Gate the first 100 bytes before reading any fixture body into memory."""
241 if len(prefix) != 100 or prefix[:16] != b'SQLite format 3\x00':
242 raise RecoveryError('invalid_source')
243 if int.from_bytes(prefix[68:72], 'big') != FIXTURE_APPLICATION_ID:
244 raise RecoveryError('synthetic_marker_required')
245 if int.from_bytes(prefix[60:64], 'big') != SCHEMA_VERSION:
246 raise RecoveryError('unsupported_schema')
247 # A standalone image cannot resolve WAL state. Require rollback-journal
248 # read/write versions rather than rewriting headers or ignoring WAL.
249 if prefix[18:20] != b'\x01\x01':
250 raise RecoveryError('source_not_closed')
251
252
253 def export_fixture(path: Path) -> bytes:
254 """Read an explicitly marked, closed fixture without changing its files."""
255 connection = None
256 try:
257 path = Path(path)
258 if any(Path(str(path) + suffix).exists() for suffix in ('-wal', '-shm', '-journal')):
259 raise RecoveryError('source_not_closed')
260 # The shared descriptor-based reader checks the opened file's identity and
261 # size. SQLite only sees these bounded bytes; it never reopens the path.
262 source = read_bounded(path, MAX_PAYLOAD_BYTES, prefix_validator=_validate_source_header)
263 connection = sqlite3.connect(':memory:')
264 connection.deserialize(source)
265 connection.execute('PRAGMA query_only = ON')
266 connection.execute('PRAGMA trusted_schema = OFF')
267 if connection.execute('PRAGMA application_id').fetchone() != (FIXTURE_APPLICATION_ID,):
268 raise RecoveryError('synthetic_marker_required')
269 if connection.execute('PRAGMA user_version').fetchone() != (SCHEMA_VERSION,):
270 raise RecoveryError('unsupported_schema')
271 reference = _new_database()
272 try:
273 expected_schema = _schema(reference)
274 finally:
275 reference.close()
276 actual_schema = _schema(connection)
277 android = ('table', 'android_metadata', 'android_metadata',
278 _normalize_sql('CREATE TABLE android_metadata (locale TEXT)'))
279 if actual_schema not in (expected_schema, expected_schema | {android}):
280 raise RecoveryError('unsupported_schema')
281 if connection.execute('PRAGMA integrity_check').fetchall() != [('ok',)]:
282 raise RecoveryError('invalid_source')
283 if connection.execute('PRAGMA foreign_key_check').fetchall():
284 raise RecoveryError('invalid_source')
285 tables = {}
286 total = 0
287 for table, columns in COLUMNS.items():
288 count = connection.execute(f'SELECT count(*) FROM {table}').fetchone()[0]
289 total += count
290 if total > MAX_ROWS:
291 raise RecoveryError('too_many_rows')
292 # All identifiers originate in this module's whitelist.
293 values = connection.execute(f'SELECT {",".join(columns)} FROM {table}').fetchall()
294 tables[table] = [dict(zip(columns, row)) for row in values]
295 return _canonical(_document(_validate(_document(tables))))
296 except (OSError, sqlite3.Error, ValueError, TypeError, UnicodeError, OverflowError):
297 raise RecoveryError('invalid_source') from None
298 finally:
299 if connection is not None:
300 connection.close()
301
302
303 def _unique_object(pairs):
304 result = {}
305 for key, value in pairs:
306 _require(key not in result)
307 result[key] = value
308 return result
309
310
311 def _reject_constant(_value):
312 raise RecoveryError('invalid_snapshot')
313
314
315 def database_from_snapshot(payload: bytes) -> bytes:
316 """Validate JSON and rebuild in memory; never execute payload-supplied SQL."""
317 if type(payload) is not bytes or len(payload) > MAX_PAYLOAD_BYTES:
318 raise RecoveryError('invalid_snapshot')
319 connection = None
320 try:
321 document = json.loads(payload.decode('utf-8'), object_pairs_hook=_unique_object,
322 parse_constant=_reject_constant)
323 tables = _validate(document)
324 connection = _new_database()
325 for table, columns in COLUMNS.items():
326 sql = f'INSERT INTO {table} ({",".join(columns)}) VALUES ({",".join("?" for _ in columns)})'
327 connection.executemany(sql, [tuple(row[key] for key in columns) for row in tables[table]])
328 connection.commit()
329 if connection.execute('PRAGMA integrity_check').fetchall() != [('ok',)]:
330 raise RecoveryError('invalid_snapshot')
331 if connection.execute('PRAGMA foreign_key_check').fetchall():
332 raise RecoveryError('invalid_snapshot')
333 result = connection.serialize()
334 if len(result) > MAX_PAYLOAD_BYTES:
335 raise RecoveryError('payload_too_large')
336 return result
337 except (ValueError, TypeError, UnicodeError, OverflowError, RecursionError, sqlite3.Error):
338 raise RecoveryError('invalid_snapshot') from None
339 finally:
340 if connection is not None:
341 connection.close()
342
343
344 def create_sample_database() -> bytes:
345 """Create explicit fictional QA records, all dated in 2024, entirely in memory."""
346 profile_id = '11111111-1111-4111-8111-111111111111'
347 plan_ids = [f'{n:08d}-2222-4222-8222-222222222222' for n in range(1, 5)]
348 tables = {table: [] for table in COLUMNS}
349 tables['local_profiles'] = [dict(zip(COLUMNS['local_profiles'],
350 (1, profile_id, 'Fictional آزمایشی', 'girl_minor', 'Fictional همراه', 'violet')))]
351 for index, recurrence in enumerate(RECURRENCES):
352 values = (plan_ids[index], profile_id, f'Fictional {recurrence}',
353 KINDS[index % len(KINDS)], recurrence, '2024-01-01',
354 None if index == 0 else '2024-02-29', 480 + index * 60,
355 510 + index * 60, (None, 5, 15, 30)[index], int(index == 3))
356 tables['local_plans'].append(dict(zip(COLUMNS['local_plans'], values)))
357 values = (f'{index + 1:08d}-3333-4333-8333-333333333333', plan_ids[index],
358 '2024-01-01', f'Fictional edited occurrence {index + 1}',
359 KINDS[(index + 1) % len(KINDS)], 800 + index * 20, 810 + index * 20,
360 int(index % 2 == 1), int(index == 3), (0, None, 10, 30)[index])
361 tables['local_occurrences'].append(dict(zip(COLUMNS['local_occurrences'], values)))
362 tables['local_weekly_slots'] = [dict(zip(COLUMNS['local_weekly_slots'],
363 (plan_ids[3], weekday, start, start + 45)))
364 for weekday, start in ((1, 600), (4, 900), (7, 1000))]
365 return database_from_snapshot(_canonical(_document(tables)))