From 0c5c31f4d53a11e792034b641766081a27e50867 Mon Sep 17 00:00:00 2001 From: Daniel Bejarano Date: Thu, 26 Nov 2026 18:49:12 -0600 Subject: [PATCH] iOS: Hermit's data and keys stay out of iCloud and computer backups On iOS, the documents folder (the model in models, QVAC's caches in .qvac) and the SQLCipher database with its journal siblings are flagged isExcludedFromBackup when each is created and again at every launch (HermitVault.excludeFromBackup, which reads the flag back). Every SecureStore write goes through keychain(), which adds WHEN_UNLOCKED_THIS_DEVICE_ONLY on iOS and leaves Android's options untouched; a test scans the adapters so no write can skip it. At launch, the plain items already written move to WhenUnlockedThisDeviceOnly in place (HermitVault.keychainToThisDevice: SecItemUpdate of the class only, never the value), then each class and value is read back. The biometric-gated approval key moves only right after the user's own authenticated read: deleted and added again with the value just read, so no extra Face ID prompt, and put back as it was if the add fails. docs/devices.md says a restore from backup starts Hermit empty and downloads the model again. Android is unchanged. Closes #126 Signed-off-by: Daniel Bejarano --- apps/mobile/modules/hermit-vault/index.ts | 9 ++ .../hermit-vault/ios/HermitVaultModule.swift | 106 ++++++++++++++++++ apps/mobile/src/adapters/app-lock.ts | 3 +- apps/mobile/src/adapters/backup.ts | 43 +++++++ apps/mobile/src/adapters/credentials.ts | 9 +- apps/mobile/src/adapters/device.ts | 7 +- apps/mobile/src/adapters/index.ts | 5 +- apps/mobile/src/adapters/op-sqlite.ts | 3 + apps/mobile/src/adapters/qvac-engine.ts | 3 + apps/mobile/src/adapters/secure.ts | 45 +++++++- apps/mobile/src/adapters/vault.ts | 4 +- apps/mobile/src/adapters/wallet.ts | 3 +- apps/mobile/src/backup-guard.test.ts | 92 +++++++++++++++ apps/mobile/src/backup-guard.ts | 104 +++++++++++++++++ docs/devices.md | 3 + 15 files changed, 427 insertions(+), 12 deletions(-) create mode 100644 apps/mobile/src/adapters/backup.ts create mode 100644 apps/mobile/src/backup-guard.test.ts create mode 100644 apps/mobile/src/backup-guard.ts diff --git a/apps/mobile/modules/hermit-vault/index.ts b/apps/mobile/modules/hermit-vault/index.ts index 12fa472..6c91d44 100644 --- a/apps/mobile/modules/hermit-vault/index.ts +++ b/apps/mobile/modules/hermit-vault/index.ts @@ -1,4 +1,5 @@ import { NativeModule, requireNativeModule } from "expo"; +import type { KeychainMove } from "../../src/backup-guard"; declare class HermitVaultNative extends NativeModule { /** A wrapped value and its Keystore key both exist (checked without a fingerprint prompt). */ @@ -24,8 +25,16 @@ declare class HermitVaultNative extends NativeModule { readDocument(uri: string, maxBytes: number): Promise; /** Deletes the picked file through the picker's grant; false when its provider refuses or can't. */ deleteDocument(uri: string): Promise; + /** #126, iOS only: flags each existing path as excluded from backup; the flag as read back, per path. */ + excludeFromBackup(paths: string[]): Promise>; + /** #126, iOS only: a Keychain item's protection class (`ak`, `aku`, ...), without a prompt; null when absent. */ + keychainAccessibility(service: string, key: string): Promise; + /** #126, iOS only: moves the plain items under these services to WhenUnlockedThisDeviceOnly, in place. */ + keychainToThisDevice(services: readonly string[]): Promise; } +export type { KeychainMove }; + export interface PickedDocument { uri: string; name: string | null; diff --git a/apps/mobile/modules/hermit-vault/ios/HermitVaultModule.swift b/apps/mobile/modules/hermit-vault/ios/HermitVaultModule.swift index b8e1e59..0344868 100644 --- a/apps/mobile/modules/hermit-vault/ios/HermitVaultModule.swift +++ b/apps/mobile/modules/hermit-vault/ios/HermitVaultModule.swift @@ -1,4 +1,6 @@ import ExpoModulesCore +import LocalAuthentication +import Security import UIKit /** @@ -11,12 +13,72 @@ import UIKit The two delete calls succeed with nothing to do: no Keystore key or preferences file is ever made on iOS. They must not throw, because Delete everything stops at the first step that fails, and the steps after this one remove the Keychain entries (database key, approval and wallet keys, connector tokens) that iOS keeps even after the app is deleted. + + #126: three calls keep Hermit out of iCloud and computer backups. `excludeFromBackup` flags files and folders; + `keychainAccessibility` reads an item's protection class without ever showing Face ID; `keychainToThisDevice` moves + the plain SecureStore items to WhenUnlockedThisDeviceOnly in place (the value is never read or rewritten). */ public class HermitVaultModule: Module { private static func unavailable() -> Exception { return Exception(name: "VaultUnavailable", description: "The vault is not available on iOS yet.", code: "ERR_UNAVAILABLE") } + /** expo-secure-store's item for `key` under `service` (its kSecAttrService, with the `:no-auth` or `:auth` suffix). */ + private static func itemQuery(service: String, key: String) -> [String: Any] { + let account = Data(key.utf8) + return [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrGeneric as String: account, + kSecAttrAccount as String: account, + ] + } + + /** A context that refuses any prompt: a call that would need Face ID fails instead of asking. */ + private static func silentContext() -> LAContext { + let context = LAContext() + context.interactionNotAllowed = true + return context + } + + /** The item's protection class (`ak`, `aku`, ...), nil when there is none, "unknown" when iOS won't say silently. */ + private static func accessibility(service: String, key: String) -> String? { + var query = itemQuery(service: service, key: key) + query[kSecMatchLimit as String] = kSecMatchLimitOne + query[kSecReturnAttributes as String] = kCFBooleanTrue + query[kSecUseAuthenticationContext as String] = silentContext() + var item: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &item) + if status == errSecItemNotFound { return nil } + guard status == errSecSuccess, let attrs = item as? [String: Any] else { return "unknown" } + return attrs[kSecAttrAccessible as String] as? String ?? "unknown" + } + + /** The classes that never leave this phone (the same list as backup-guard.ts). */ + private static let thisDeviceOnly: Set = [ + kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String, + kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as String, + kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as String, + "dku", + ] + + /** Every item's key (its kSecAttrAccount) under `service`, read from attributes only, never the values. */ + private static func keys(service: String) -> [String] { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecMatchLimit as String: kSecMatchLimitAll, + kSecReturnAttributes as String: true, + kSecUseAuthenticationContext as String: silentContext(), + ] + var items: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &items) == errSecSuccess, let list = items as? [[String: Any]] else { return [] } + return list.compactMap { attrs in + guard let account = attrs[kSecAttrAccount as String] as? Data else { return nil } + return String(data: account, encoding: .utf8) + } + } + public func definition() -> ModuleDefinition { Name("HermitVault") @@ -59,5 +121,49 @@ public class HermitVaultModule: Module { AsyncFunction("deleteDocument") { (_: String) -> Bool in throw HermitVaultModule.unavailable() } + + // #126: flags each path that exists as excluded from backup, then reads the flag back. Missing paths are left out. + AsyncFunction("excludeFromBackup") { (paths: [String]) -> [String: Bool] in + var out: [String: Bool] = [:] + for path in paths where FileManager.default.fileExists(atPath: path) { + var url = URL(fileURLWithPath: path) + var values = URLResourceValues() + values.isExcludedFromBackup = true + do { + try url.setResourceValues(values) + url.removeAllCachedResourceValues() + out[path] = try url.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup ?? false + } catch { + out[path] = false + } + } + return out + } + + AsyncFunction("keychainAccessibility") { (service: String, key: String) -> String? in + return HermitVaultModule.accessibility(service: service, key: key) + } + + // #126: each item under these (plain) services that could move with a backup gets WhenUnlockedThisDeviceOnly in + // place: SecItemUpdate changes the attribute only, so the value is never at risk. Its class is then read back. An + // item that would need Face ID fails silently (no prompt) and is reported as not ok. + AsyncFunction("keychainToThisDevice") { (services: [String]) -> [[String: Any]] in + var report: [[String: Any]] = [] + for service in services { + for key in HermitVaultModule.keys(service: service) { + let before = HermitVaultModule.accessibility(service: service, key: key) ?? "none" + var ok = true + if !HermitVaultModule.thisDeviceOnly.contains(before) { + var query = HermitVaultModule.itemQuery(service: service, key: key) + query[kSecUseAuthenticationContext as String] = HermitVaultModule.silentContext() + let change: [String: Any] = [kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly] + ok = SecItemUpdate(query as CFDictionary, change as CFDictionary) == errSecSuccess + } + let after = HermitVaultModule.accessibility(service: service, key: key) ?? "none" + report.append(["service": service, "key": key, "before": before, "after": after, "ok": ok]) + } + } + return report + } } } diff --git a/apps/mobile/src/adapters/app-lock.ts b/apps/mobile/src/adapters/app-lock.ts index 1f2bc8a..6ae06d3 100644 --- a/apps/mobile/src/adapters/app-lock.ts +++ b/apps/mobile/src/adapters/app-lock.ts @@ -1,5 +1,6 @@ import * as LocalAuthentication from "expo-local-authentication"; import * as SecureStore from "expo-secure-store"; +import { keychain } from "./secure"; /** * US-SET-09: the app lock's switch and its unlock. The switch lives in SecureStore, not the database, @@ -16,7 +17,7 @@ export function appLockEnabled(): boolean { } export async function saveAppLock(on: boolean): Promise { - if (on) await SecureStore.setItemAsync(KEY, "1"); + if (on) await SecureStore.setItemAsync(KEY, "1", keychain()); else await SecureStore.deleteItemAsync(KEY); } diff --git a/apps/mobile/src/adapters/backup.ts b/apps/mobile/src/adapters/backup.ts new file mode 100644 index 0000000..c86bf34 --- /dev/null +++ b/apps/mobile/src/adapters/backup.ts @@ -0,0 +1,43 @@ +import { Platform } from "react-native"; +import { Paths } from "expo-file-system"; +import * as SecureStore from "expo-secure-store"; +import { HermitVault } from "../../modules/hermit-vault"; +import { backupTargets, IOS_SECURE_STORE_SERVICES, migrationSummary } from "../backup-guard"; + +/** + * #126 (non-negotiable 1): on iOS, Hermit's files stay out of iCloud and computer backups, and its plain Keychain items + * move to a class that never leaves this phone. Android refuses backups already (`allowBackup` false): nothing runs there. + * Neither call throws: a failure is logged and tried again at the next launch, and never stops Hermit from starting. + */ + +let dbPath: string | undefined; + +/** Flags the documents folder, the model and QVAC folders and the database as excluded from backup. */ +export async function keepOutOfBackups(database?: string): Promise { + if (Platform.OS !== "ios") return; + if (database) dbPath = database; + try { + const flags = await HermitVault.excludeFromBackup(backupTargets(Paths.document.uri, dbPath)); + const missed = Object.entries(flags).filter(([, excluded]) => !excluded).map(([path]) => path.split("/").slice(-2).join("/")); + console.log(`[hermit:backup] excluded ${Object.keys(flags).length - missed.length} paths${missed.length ? `, not ${missed.join(", ")}` : ""}`); + } catch (err) { + console.log(`[hermit:backup] exclude failed: ${err instanceof Error ? err.message : String(err)}`); + } +} + +/** At launch: every plain SecureStore item moves to WhenUnlockedThisDeviceOnly in place. Gated ones move in ./secure. */ +export async function moveKeychainToThisDevice(): Promise { + if (Platform.OS !== "ios") return; + try { + const s = migrationSummary(await HermitVault.keychainToThisDevice(IOS_SECURE_STORE_SERVICES)); + // Only the class changed, in place; each moved item must still read back through SecureStore. + const unreadable: string[] = []; + for (const key of s.moved) if ((await SecureStore.getItemAsync(key).catch(() => null)) === null) unreadable.push(key); + console.log( + `[hermit:keychain] this device only: moved ${s.moved.length}, already ${s.kept.length}` + + `${s.failed.length ? `, not yet ${s.failed.join(", ")}` : ""}${unreadable.length ? `, unreadable ${unreadable.join(", ")}` : ""}`, + ); + } catch (err) { + console.log(`[hermit:keychain] move failed: ${err instanceof Error ? err.message : String(err)}`); + } +} diff --git a/apps/mobile/src/adapters/credentials.ts b/apps/mobile/src/adapters/credentials.ts index d4429a0..cbe43d1 100644 --- a/apps/mobile/src/adapters/credentials.ts +++ b/apps/mobile/src/adapters/credentials.ts @@ -2,6 +2,7 @@ // per credential plus an index of ids. The meta it returns never carries the secret. Delete everything wipes it all. import * as SecureStore from "expo-secure-store"; import type { CredentialMeta, CredentialSecret, CredentialStorePort } from "@hermit/core"; +import { keychain } from "./secure"; const INDEX = "hermit.cred.index"; const SAFE_ID = /^[A-Za-z0-9_-]{1,64}$/; @@ -35,9 +36,9 @@ async function item(id: string): Promise { export const phoneCredentials: CredentialStorePort = { async save(meta, secret) { if (meta.kind !== secret.kind) throw new Error(`credential ${meta.id}: a ${secret.kind} secret can't be saved as ${meta.kind}`); - await SecureStore.setItemAsync(keyOf(meta.id), JSON.stringify({ meta, secret })); + await SecureStore.setItemAsync(keyOf(meta.id), JSON.stringify({ meta, secret }), keychain()); const all = await ids(); - if (!all.includes(meta.id)) await SecureStore.setItemAsync(INDEX, JSON.stringify([...all, meta.id])); + if (!all.includes(meta.id)) await SecureStore.setItemAsync(INDEX, JSON.stringify([...all, meta.id]), keychain()); }, async list() { const out: CredentialMeta[] = []; @@ -56,14 +57,14 @@ export const phoneCredentials: CredentialStorePort = { async markUsed(id, at) { const i = await item(id); if (!i) return false; - await SecureStore.setItemAsync(keyOf(id), JSON.stringify({ ...i, meta: { ...i.meta, lastUsedAt: at } })); + await SecureStore.setItemAsync(keyOf(id), JSON.stringify({ ...i, meta: { ...i.meta, lastUsedAt: at } }), keychain()); return true; }, async delete(id) { const existed = (await item(id)) !== undefined; if (SAFE_ID.test(id)) await SecureStore.deleteItemAsync(keyOf(id)); const all = await ids(); - if (all.includes(id)) await SecureStore.setItemAsync(INDEX, JSON.stringify(all.filter((x) => x !== id))); + if (all.includes(id)) await SecureStore.setItemAsync(INDEX, JSON.stringify(all.filter((x) => x !== id)), keychain()); return existed; }, }; diff --git a/apps/mobile/src/adapters/device.ts b/apps/mobile/src/adapters/device.ts index da7960b..bf887f6 100644 --- a/apps/mobile/src/adapters/device.ts +++ b/apps/mobile/src/adapters/device.ts @@ -7,6 +7,7 @@ import { pausesFor, readResumeRecord, resumableBytes, resumePlan, resumeRecordTe import { nightDeviceState, type NightDeviceState } from "../night-device"; import { byteCount, hardwareFactsFor, hardwarePlatform, thermalFromNative, type NativeThermal } from "../platform-facts"; import { observedTokensPerSecond } from "./qvac-engine"; +import { keepOutOfBackups } from "./backup"; /** Calls back when the phone comes back online, so an interrupted download can resume. Returns unsubscribe. */ export function onReconnect(listener: () => void): () => void { @@ -58,7 +59,11 @@ const CHUNK = 4 * 1024 * 1024; /** The model file's home: app documents (not cache, which the system may clear). */ export function modelFile(name: string): File { const dir = new Directory(Paths.document, "models"); - if (!dir.exists) dir.create(); + if (!dir.exists) { + dir.create(); + // #126: on iOS the model folder stays out of backups from the moment it exists (and again at every launch). + void keepOutOfBackups(); + } return new File(dir, name); } diff --git a/apps/mobile/src/adapters/index.ts b/apps/mobile/src/adapters/index.ts index be56af8..a54f7f8 100644 --- a/apps/mobile/src/adapters/index.ts +++ b/apps/mobile/src/adapters/index.ts @@ -12,6 +12,7 @@ import { qvacEngine } from "./qvac-engine"; import type { CacheOwners } from "../cache-keys"; import { reminderNotifier, requestReminderAccess } from "./notifier"; import { plainSecret } from "./secure"; +import { moveKeychainToThisDevice } from "./backup"; import { deviceSigner } from "./signer"; import { calendarPermissionGranted, requestCalendarPermission } from "./calendar"; import { allowedCpus, loadPlan, modelFile, partialBytes, phoneDownload, phoneFacts, reloadPlan, runtimeConditions, verifiedSha256 } from "./device"; @@ -127,7 +128,9 @@ export function openDatabase(): SqlPort | undefined { export async function createPorts(approvals: HermitPorts["approvals"]): Promise { const profile = PROFILES[0]!; - const dbKey = Array.from(await plainSecret(SECRET_KEYS.db), (b) => b.toString(16).padStart(2, "0")).join(""); + // #126: on iOS, plain Keychain items written before ThisDeviceOnly move in place, before any of them is read. + await moveKeychainToThisDevice(); + const dbKey =Array.from(await plainSecret(SECRET_KEYS.db), (b) => b.toString(16).padStart(2, "0")).join(""); liveSql = encryptedSql(dbKey); const wallet = walletPorts(); logCoresOnAppState(); diff --git a/apps/mobile/src/adapters/op-sqlite.ts b/apps/mobile/src/adapters/op-sqlite.ts index 5231338..fb4c7e4 100644 --- a/apps/mobile/src/adapters/op-sqlite.ts +++ b/apps/mobile/src/adapters/op-sqlite.ts @@ -2,6 +2,7 @@ import { open, type DB } from "@op-engineering/op-sqlite"; import { File } from "expo-file-system"; import type { SqlPort } from "@hermit/core"; import { splitStatements } from "../sql-split"; +import { keepOutOfBackups } from "./backup"; /** * SL-10 (spike S2): SqlPort over op-sqlite built with SQLCipher and FTS5 (ADR-006). @@ -14,6 +15,8 @@ let live: DB | undefined; export function encryptedSql(encryptionKey: string): SqlPort { const db = open({ name: NAME, encryptionKey }); live = db; + // #126: on iOS the file (made here on the first run, opened here at every launch) stays out of backups. + void keepOutOfBackups(db.getDbPath()); let queue: Promise = Promise.resolve(); const port: SqlPort = { async exec(sql, params) { diff --git a/apps/mobile/src/adapters/qvac-engine.ts b/apps/mobile/src/adapters/qvac-engine.ts index 3c84fd3..fb39d74 100644 --- a/apps/mobile/src/adapters/qvac-engine.ts +++ b/apps/mobile/src/adapters/qvac-engine.ts @@ -5,6 +5,7 @@ import { afterWrite, botOfKey, cacheFailureLine, cacheSizeLine, engineCacheKey, evictKeys, forgetBotCachesOn, hermitTurnKey, loadCaches, MAX_NAMED_CACHES, touchCacheKey, type CacheDisk, type CacheFile, type CacheOwners, } from "../cache-keys"; +import { keepOutOfBackups } from "./backup"; type QvacTool = Extract[0]["tools"]>[number], { type: "function" }>; @@ -145,6 +146,8 @@ export async function qvacEngine(modelPath: string, profile: ModelProfile, tunin const keep = [hermitTurnKey(profile.id)]; const owners = await caches?.owners().catch((err: unknown) => void qvacDisk.failed("load", err)); let order = await loadCaches(qvacDisk, { keep, ...(owners ? { owners } : {}) }); + // #126: on iOS QVAC's folder (`.qvac`, made by the first load) stays out of backups, like the rest of documents. + void keepOutOfBackups(); const ledger = { drop(keys: readonly string[]) { order = order.filter((k) => !keys.includes(k)); diff --git a/apps/mobile/src/adapters/secure.ts b/apps/mobile/src/adapters/secure.ts index ebf04da..7a4d43a 100644 --- a/apps/mobile/src/adapters/secure.ts +++ b/apps/mobile/src/adapters/secure.ts @@ -1,19 +1,57 @@ +import { Platform } from "react-native"; import * as Crypto from "expo-crypto"; import * as LocalAuthentication from "expo-local-authentication"; import * as SecureStore from "expo-secure-store"; +import { HermitVault } from "../../modules/hermit-vault"; +import { deviceOnly, gatedNeedsMove } from "../backup-guard"; const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join(""); export const fromHex = (s: string) => new Uint8Array((s.match(/../g) ?? []).map((h) => parseInt(h, 16))); +/** + * #126: the options for every SecureStore write. On iOS the item is WhenUnlockedThisDeviceOnly, so it never moves to + * another phone through an iCloud or computer backup; on Android the options are passed through untouched. + */ +export function keychain(options?: T) { + return deviceOnly(Platform.OS, SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY, options); +} + +/** Only to put back a gated item whose move failed: the class it had before (expo-secure-store's default). */ +const keychainAsBefore = (options: T) => ({ ...options, keychainAccessible: SecureStore.WHEN_UNLOCKED }); + /** A 32-byte secret that needs no authentication (the audit seed). Created on first use. */ export async function plainSecret(key: string): Promise { const existing = await SecureStore.getItemAsync(key); if (existing) return fromHex(existing); const fresh = Crypto.getRandomBytes(32); - await SecureStore.setItemAsync(key, hex(fresh)); + await SecureStore.setItemAsync(key, hex(fresh), keychain()); return fresh; } +/** + * #126, iOS: a gated item written before ThisDeviceOnly moves right after the user's own authenticated read, so it never + * shows Face ID on its own. Changing it in place would ask for Face ID again, so it is deleted and added again with the + * value just read (adding one shows no prompt), then its class is read back. If the add fails it is added back as it was. + * Never throws: the approval that read it goes on either way. + */ +async function moveGated(key: string, value: string, prompt: string): Promise { + if (Platform.OS !== "ios") return; + try { + if (!gatedNeedsMove(await HermitVault.keychainAccessibility("app:auth", key))) return; + await SecureStore.deleteItemAsync(key); + try { + await SecureStore.setItemAsync(key, value, keychain({ requireAuthentication: true, authenticationPrompt: prompt })); + } catch (err) { + // Put back as it was (the old default class), so a failed move never loses the key. + await SecureStore.setItemAsync(key, value, keychainAsBefore({ requireAuthentication: true, authenticationPrompt: prompt })); + throw err; + } + console.log(`[hermit:keychain] ${key} moved: ${await HermitVault.keychainAccessibility("app:auth", key)}`); + } catch (err) { + console.log(`[hermit:keychain] ${key} not moved: ${err instanceof Error ? err.message : String(err)}`); + } +} + export class MissingSecretError extends Error { constructor(key: string) { super(`Secret ${key} is missing or was invalidated; it must be provisioned again behind a fingerprint.`); @@ -29,6 +67,7 @@ export class MissingSecretError extends Error { export async function gatedSecret(key: string, prompt: string): Promise { const value = await SecureStore.getItemAsync(key, { requireAuthentication: true, authenticationPrompt: prompt }); if (!value) throw new MissingSecretError(key); + await moveGated(key, value, prompt); return fromHex(value); } @@ -39,7 +78,9 @@ export async function gatedSecret(key: string, prompt: string): Promise { const auth = await LocalAuthentication.authenticateAsync({ promptMessage: prompt, biometricsSecurityLevel: "strong", disableDeviceFallback: true }); if (!auth.success) return false; - await SecureStore.setItemAsync(key, hex(Crypto.getRandomBytes(32)), { requireAuthentication: true, authenticationPrompt: prompt }); + // iOS: replacing a gated item in place would ask for Face ID again, and may keep its old class; it is replaced anyway. + if (Platform.OS === "ios") await SecureStore.deleteItemAsync(key); + await SecureStore.setItemAsync(key, hex(Crypto.getRandomBytes(32)), keychain({ requireAuthentication: true, authenticationPrompt: prompt })); return true; } diff --git a/apps/mobile/src/adapters/vault.ts b/apps/mobile/src/adapters/vault.ts index 8f61e6f..d868a57 100644 --- a/apps/mobile/src/adapters/vault.ts +++ b/apps/mobile/src/adapters/vault.ts @@ -3,7 +3,7 @@ import * as Crypto from "expo-crypto"; import * as SecureStore from "expo-secure-store"; import { VAULT_KEY, type SecureRandom, type VaultCipherPort, type VaultKeyPort } from "@hermit/core"; import { HermitVault, type PickedDocument } from "../../modules/hermit-vault"; -import { fromHex } from "./secure"; +import { fromHex, keychain } from "./secure"; import { trackPrompt } from "./app-lock"; /** @@ -33,7 +33,7 @@ export function wrappedKeyPort(entry: { key: string; service: string }): VaultKe if (!SecureStore.canUseBiometricAuthentication()) return "unavailable"; try { // trackPrompt: the app lock must not read the prompt's trip away as the user leaving. - await trackPrompt(() => SecureStore.setItemAsync(entry.key, hex(key), { ...OPTIONS, requireAuthentication: true, authenticationPrompt: prompt })); + await trackPrompt(() => SecureStore.setItemAsync(entry.key, hex(key), keychain({ ...OPTIONS, requireAuthentication: true, authenticationPrompt: prompt }))); return "stored"; } catch { return "cancelled"; diff --git a/apps/mobile/src/adapters/wallet.ts b/apps/mobile/src/adapters/wallet.ts index 438c3e3..1096e69 100644 --- a/apps/mobile/src/adapters/wallet.ts +++ b/apps/mobile/src/adapters/wallet.ts @@ -11,6 +11,7 @@ import { HermitVault } from "../../modules/hermit-vault"; import { landedAt } from "../mcp-request"; import { decodeBody, readCapped } from "../web-body"; import { counted, countOutbound } from "./net"; +import { keychain } from "./secure"; import { vaultOnScreen, vaultRandom, wrappedKeyPort } from "./vault"; import { sharedWalletClient, stopSharedWalletWorklet, walletBundleAvailable } from "./wallet-worklet"; import { LIST_MIN_DECIMALS } from "../wallet-view"; @@ -33,7 +34,7 @@ export const walletRecordPort: WalletRecordPort = { async read() { return (await SecureStore.getItemAsync(WALLET_RECORD_KEY)) ?? undefined; }, - write: (text) => SecureStore.setItemAsync(WALLET_RECORD_KEY, text), + write: (text) => SecureStore.setItemAsync(WALLET_RECORD_KEY, text, keychain()), remove: () => SecureStore.deleteItemAsync(WALLET_RECORD_KEY), }; diff --git a/apps/mobile/src/backup-guard.test.ts b/apps/mobile/src/backup-guard.test.ts new file mode 100644 index 0000000..6189281 --- /dev/null +++ b/apps/mobile/src/backup-guard.test.ts @@ -0,0 +1,92 @@ +/// +// #126 (non-negotiable 1): on iOS, Hermit's files and Keychain items stay out of iCloud and computer backups. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { backupTargets, deviceOnly, gatedNeedsMove, IOS_SECURE_STORE_SERVICES, isThisDeviceOnly, keychainWritesWithoutOptions, migrationSummary } from "./backup-guard.ts"; + +const WHEN_UNLOCKED_THIS_DEVICE_ONLY = 6; + +test("on iOS every SecureStore write gets a ThisDeviceOnly accessibility, and keeps its other options", () => { + assert.deepEqual(deviceOnly("ios", WHEN_UNLOCKED_THIS_DEVICE_ONLY), { keychainAccessible: 6 }); + assert.deepEqual(deviceOnly("ios", WHEN_UNLOCKED_THIS_DEVICE_ONLY, { requireAuthentication: true, authenticationPrompt: "p", keychainService: "s" }), { + requireAuthentication: true, authenticationPrompt: "p", keychainService: "s", keychainAccessible: 6, + }); +}); + +test("on Android the options are left exactly as they were", () => { + assert.equal(deviceOnly("android", WHEN_UNLOCKED_THIS_DEVICE_ONLY), undefined); + const gated = { requireAuthentication: true, authenticationPrompt: "p" }; + const out = deviceOnly("android", WHEN_UNLOCKED_THIS_DEVICE_ONLY, gated); + assert.deepEqual(out, gated); + assert.equal("keychainAccessible" in (out ?? {}), false); +}); + +test("only the ThisDeviceOnly protection classes count as kept on this phone", () => { + for (const kept of ["aku", "cku", "dku", "akpu"]) assert.equal(isThisDeviceOnly(kept), true, kept); + for (const moves of ["ak", "ck", "dk"]) assert.equal(isThisDeviceOnly(moves), false, moves); + assert.equal(isThisDeviceOnly(null), false); + assert.equal(isThisDeviceOnly("unknown"), false); +}); + +test("a gated item moves after its authenticated read only when it is known to migrate with backups", () => { + assert.equal(gatedNeedsMove("ak"), true); + assert.equal(gatedNeedsMove("ck"), true); + assert.equal(gatedNeedsMove("aku"), false); + assert.equal(gatedNeedsMove("akpu"), false); + // Absent, or iOS wouldn't say without a prompt: leave it alone rather than delete what can't be checked. + assert.equal(gatedNeedsMove(null), false); + assert.equal(gatedNeedsMove("unknown"), false); +}); + +test("the launch migration rewrites the plain SecureStore services, never the biometric-gated one", () => { + assert.deepEqual([...IOS_SECURE_STORE_SERVICES], ["app:no-auth", "app"]); + assert.equal(IOS_SECURE_STORE_SERVICES.some((s) => s.endsWith(":auth")), false); +}); + +test("the backup targets are the documents folder, the model and QVAC folders, and the database with its siblings", () => { + const docs = "file:///var/mobile/Containers/Data/Application/ABC/Documents/"; + const db = "/var/mobile/Containers/Data/Application/ABC/Library/hermit.db"; + assert.deepEqual(backupTargets(docs, db), [ + "/var/mobile/Containers/Data/Application/ABC/Documents", + "/var/mobile/Containers/Data/Application/ABC/Documents/models", + "/var/mobile/Containers/Data/Application/ABC/Documents/.qvac", + "/var/mobile/Containers/Data/Application/ABC/Library/hermit.db", + "/var/mobile/Containers/Data/Application/ABC/Library/hermit.db-wal", + "/var/mobile/Containers/Data/Application/ABC/Library/hermit.db-shm", + "/var/mobile/Containers/Data/Application/ABC/Library/hermit.db-journal", + ]); + // Before the database opens there is no path for it yet; file URLs with escapes come back as plain paths. + assert.deepEqual(backupTargets("file:///a%20b/Documents"), ["/a b/Documents", "/a b/Documents/models", "/a b/Documents/.qvac"]); +}); + +test("the migration summary names failures and items that are still not ThisDeviceOnly", () => { + const s = migrationSummary([ + { service: "app:no-auth", key: "hermit.db.key.v1", before: "ak", after: "aku", ok: true }, + { service: "app:no-auth", key: "hermit.audit.seed.v1", before: "aku", after: "aku", ok: true }, + { service: "app:no-auth", key: "hermit.cred.x", before: "ak", after: "ak", ok: false }, + ]); + assert.deepEqual(s, { moved: ["hermit.db.key.v1"], kept: ["hermit.audit.seed.v1"], failed: ["hermit.cred.x"] }); + assert.deepEqual(migrationSummary([{ service: "app", key: "k", before: "ak", after: "ak", ok: true }]).failed, ["k"]); +}); + +test("the scanner flags a SecureStore write without the device-only options", () => { + const src = [ + `await SecureStore.setItemAsync(KEY, "1");`, + `await SecureStore.setItemAsync(KEY, v, keychain());`, + `await SecureStore.setItemAsync(entry.key, hex(key), keychain({ ...OPTIONS, requireAuthentication: true }));`, + `write: (text) => SecureStore.setItemAsync(WALLET_RECORD_KEY, text),`, + `await SecureStore.setItemAsync(key, value, keychainAsBefore({ requireAuthentication: true }));`, + `await SecureStore.setItemAsync(key, value, { ...mykeychain() });`, + ].join("\n"); + assert.deepEqual(keychainWritesWithoutOptions(src), [1, 4, 6]); +}); + +test("every SecureStore write in the app goes through keychain()", () => { + const dir = new URL("./adapters/", import.meta.url).pathname; + const found = readdirSync(dir) + .filter((f) => f.endsWith(".ts")) + .flatMap((f) => keychainWritesWithoutOptions(readFileSync(join(dir, f), "utf8")).map((line) => `adapters/${f}:${line}`)); + assert.deepEqual(found, []); +}); diff --git a/apps/mobile/src/backup-guard.ts b/apps/mobile/src/backup-guard.ts new file mode 100644 index 0000000..bfc9e6b --- /dev/null +++ b/apps/mobile/src/backup-guard.ts @@ -0,0 +1,104 @@ +/** + * #126 (non-negotiable 1): on iOS, Hermit's files and Keychain items stay out of iCloud and computer backups. Android + * already refuses backups (`allowBackup` false), so nothing here changes it. These are the pure rules; the adapter + * (./adapters/backup.ts) runs them through the HermitVault module and expo-secure-store. + */ + +/** + * SecureStore options for a write. On iOS the item gets a ThisDeviceOnly accessibility (`accessible` is + * `SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY`), so it never moves to another phone through a backup. On Android the + * options are returned untouched. + */ +export function deviceOnly(platform: string, accessible: number, options?: T): (T & { keychainAccessible?: number }) | undefined { + if (platform !== "ios") return options; + return { ...(options ?? ({} as T)), keychainAccessible: accessible }; +} + +/** + * iOS's protection classes (`kSecAttrAccessible`, read back as `pdmn`) that never leave this phone: when unlocked, + * after first unlock, always, and when a passcode is set, each ThisDeviceOnly. + */ +const THIS_DEVICE_ONLY = new Set(["aku", "cku", "dku", "akpu"]); + +/** The class keeps the item on this phone. `null` is no item; `"unknown"` is an item iOS wouldn't describe. */ +export function isThisDeviceOnly(pdmn: string | null | undefined): boolean { + return pdmn !== null && pdmn !== undefined && THIS_DEVICE_ONLY.has(pdmn); +} + +/** + * A biometric-gated item is moved (deleted and added again with a ThisDeviceOnly class) only right after the user's own + * authenticated read, and only when iOS says it can migrate. Absent or unknown: it is left alone, since deleting what + * can't be checked could lose it. + */ +export function gatedNeedsMove(pdmn: string | null | undefined): boolean { + return pdmn !== null && pdmn !== undefined && pdmn !== "unknown" && !THIS_DEVICE_ONLY.has(pdmn); +} + +/** + * The Keychain services expo-secure-store writes plain items under: `app:no-auth` today, and `app`, its older name. The + * launch migration changes only their accessibility attribute, in place. The gated service (`app:auth`) is never in this + * list: changing one of those needs Face ID, so it moves after its own authenticated read instead. + */ +export const IOS_SECURE_STORE_SERVICES = ["app:no-auth", "app"] as const; + +/** A plain path from a file URL or a path, with no trailing slash. */ +function plainPath(uriOrPath: string): string { + const path = uriOrPath.startsWith("file://") ? decodeURI(uriOrPath.slice("file://".length)) : uriOrPath; + return path.length > 1 ? path.replace(/\/+$/, "") : path; +} + +/** + * What is excluded from backup, at launch and when each is created: the documents folder (QVAC's home: its caches live + * in `.qvac`, the model in `models`), those two folders by name in case the folder's flag is ever lost, and the + * database (op-sqlite keeps it in Library) with its journal siblings. Missing paths are skipped natively. + */ +export function backupTargets(documentUri: string, dbPath?: string): string[] { + const docs = plainPath(documentUri); + const out = [docs, `${docs}/models`, `${docs}/.qvac`]; + if (dbPath) { + const db = plainPath(dbPath); + out.push(...["", "-wal", "-shm", "-journal"].map((suffix) => `${db}${suffix}`)); + } + return out; +} + +/** One item the launch migration looked at, as the HermitVault module reports it. */ +export interface KeychainMove { + service: string; + key: string; + before: string; + after: string; + ok: boolean; +} + +/** Which keys moved, which were already kept on this phone, and which still aren't (to try again at the next launch). */ +export function migrationSummary(moves: readonly KeychainMove[]): { moved: string[]; kept: string[]; failed: string[] } { + const out = { moved: [] as string[], kept: [] as string[], failed: [] as string[] }; + for (const m of moves) { + if (!m.ok || !isThisDeviceOnly(m.after)) out.failed.push(m.key); + else if (isThisDeviceOnly(m.before)) out.kept.push(m.key); + else out.moved.push(m.key); + } + return out; +} + +/** + * Lines (1-based) of `SecureStore.setItemAsync(...)` calls whose options aren't built by `keychain(...)`, so a new write + * can't forget the ThisDeviceOnly class. The one other builder allowed is `keychainAsBefore(...)`, which puts a gated + * item back as it was when its move failed. A call is read up to its closing parenthesis. + */ +export function keychainWritesWithoutOptions(src: string): number[] { + const out: number[] = []; + const re = /SecureStore\.setItemAsync\(/g; + for (let m = re.exec(src); m; m = re.exec(src)) { + let depth = 1; + let i = m.index + m[0].length; + for (; i < src.length && depth > 0; i++) { + if (src[i] === "(") depth++; + else if (src[i] === ")") depth--; + } + const args = src.slice(m.index + m[0].length, i - 1); + if (!/\bkeychain(AsBefore)?\(/.test(args)) out.push(src.slice(0, m.index).split("\n").length); + } + return out; +} diff --git a/docs/devices.md b/docs/devices.md index 7a083e6..8fd8493 100644 --- a/docs/devices.md +++ b/docs/devices.md @@ -85,6 +85,9 @@ On an iPhone, Hermit is still missing pieces. Today: - There is no WhatsApp capture and no night shift. - **Delete everything** before you delete the app: iOS keeps an app's Keychain entries (Hermit's database key and tokens) after the app is gone. +- Nothing of Hermit's goes into an iCloud or computer backup: its database, the model and QVAC's caches are excluded + from backup, and its Keychain entries are kept on this phone only. Restoring a backup onto a phone starts Hermit + empty, and it downloads the model again. A backup made before this change may still hold them. - A stopped model download starts again from zero. - iOS thermal states are mapped onto Android's scale: nominal 0, fair 1, serious 3, critical 4. An iPhone report keeps both: the mapped state, and iOS's own name for it.