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 70 lines 2.58 KB
Raw
1 """Bounded authenticated envelopes for the synthetic recovery preparation tool.
2
3 Version 1 fixes the KDF parameters; archive bytes cannot choose their cost.
4 This module only handles in-memory bytes and never logs or writes their content.
5 """
6
7 import os
8
9 from cryptography.exceptions import InvalidTag
10 from cryptography.hazmat.primitives.ciphers.aead import AESGCM
11 from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
12
13 from .common import MAX_PAYLOAD_BYTES, RecoveryError
14
15
16 _MAGIC = b"LGRF\x01"
17 _SALT_BYTES = 16
18 _NONCE_BYTES = 12
19 _TAG_BYTES = 16
20 _HEADER_BYTES = len(_MAGIC) + _SALT_BYTES + _NONCE_BYTES
21 _MIN_ARCHIVE_BYTES = _HEADER_BYTES + _TAG_BYTES
22 _MAX_ARCHIVE_BYTES = MAX_PAYLOAD_BYTES + _MIN_ARCHIVE_BYTES
23
24
25 def _password_bytes(passphrase: str) -> bytes:
26 # Bound characters before encoding, then enforce the UTF-8 byte limit.
27 if not isinstance(passphrase, str) or not 12 <= len(passphrase) <= 1024:
28 raise RecoveryError("invalid_passphrase")
29 try:
30 encoded = passphrase.encode("utf-8")
31 except UnicodeEncodeError:
32 raise RecoveryError("invalid_passphrase") from None
33 if len(encoded) > 1024:
34 raise RecoveryError("invalid_passphrase")
35 return encoded
36
37
38 def _derive_key(password: bytes, salt: bytes) -> bytes:
39 return Scrypt(salt=salt, length=32, n=32768, r=8, p=1).derive(password)
40
41
42 def seal(payload: bytes, passphrase: str) -> bytes:
43 """Encrypt up to 8 MiB using a fresh salt and nonce for each envelope."""
44 if not isinstance(payload, bytes) or len(payload) > MAX_PAYLOAD_BYTES:
45 raise RecoveryError("invalid_payload")
46 password = _password_bytes(passphrase)
47 salt = os.urandom(_SALT_BYTES)
48 nonce = os.urandom(_NONCE_BYTES)
49 header = _MAGIC + salt + nonce
50 ciphertext = AESGCM(_derive_key(password, salt)).encrypt(nonce, payload, header)
51 return header + ciphertext
52
53
54 def open_archive(archive: bytes, passphrase: str) -> bytes:
55 """Authenticate before returning plaintext; reject invalid bounds before KDF."""
56 if (
57 not isinstance(archive, bytes)
58 or not _MIN_ARCHIVE_BYTES <= len(archive) <= _MAX_ARCHIVE_BYTES
59 or archive[: len(_MAGIC)] != _MAGIC
60 ):
61 raise RecoveryError("invalid_archive")
62 password = _password_bytes(passphrase)
63 salt = archive[len(_MAGIC) : len(_MAGIC) + _SALT_BYTES]
64 nonce = archive[len(_MAGIC) + _SALT_BYTES : _HEADER_BYTES]
65 try:
66 return AESGCM(_derive_key(password, salt)).decrypt(
67 nonce, archive[_HEADER_BYTES:], archive[:_HEADER_BYTES]
68 )
69 except InvalidTag:
70 raise RecoveryError("archive_authentication_failed") from None