Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions apps/mobile/modules/hermit-vault/index.ts
Original file line number Diff line number Diff line change
@@ -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). */
Expand All @@ -24,8 +25,16 @@ declare class HermitVaultNative extends NativeModule {
readDocument(uri: string, maxBytes: number): Promise<Uint8Array>;
/** Deletes the picked file through the picker's grant; false when its provider refuses or can't. */
deleteDocument(uri: string): Promise<boolean>;
/** #126, iOS only: flags each existing path as excluded from backup; the flag as read back, per path. */
excludeFromBackup(paths: string[]): Promise<Record<string, boolean>>;
/** #126, iOS only: a Keychain item's protection class (`ak`, `aku`, ...), without a prompt; null when absent. */
keychainAccessibility(service: string, key: string): Promise<string | null>;
/** #126, iOS only: moves the plain items under these services to WhenUnlockedThisDeviceOnly, in place. */
keychainToThisDevice(services: readonly string[]): Promise<KeychainMove[]>;
}

export type { KeychainMove };

export interface PickedDocument {
uri: string;
name: string | null;
Expand Down
106 changes: 106 additions & 0 deletions apps/mobile/modules/hermit-vault/ios/HermitVaultModule.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import ExpoModulesCore
import LocalAuthentication
import Security
import UIKit

/**
Expand All @@ -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<String> = [
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")

Expand Down Expand Up @@ -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
}
}
}
3 changes: 2 additions & 1 deletion apps/mobile/src/adapters/app-lock.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -16,7 +17,7 @@ export function appLockEnabled(): boolean {
}

export async function saveAppLock(on: boolean): Promise<void> {
if (on) await SecureStore.setItemAsync(KEY, "1");
if (on) await SecureStore.setItemAsync(KEY, "1", keychain());
else await SecureStore.deleteItemAsync(KEY);
}

Expand Down
43 changes: 43 additions & 0 deletions apps/mobile/src/adapters/backup.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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<void> {
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)}`);
}
}
9 changes: 5 additions & 4 deletions apps/mobile/src/adapters/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}$/;
Expand Down Expand Up @@ -35,9 +36,9 @@ async function item(id: string): Promise<Item | undefined> {
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[] = [];
Expand All @@ -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;
},
};
Expand Down
7 changes: 6 additions & 1 deletion apps/mobile/src/adapters/device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
}

Expand Down
5 changes: 4 additions & 1 deletion apps/mobile/src/adapters/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -127,7 +128,9 @@ export function openDatabase(): SqlPort | undefined {

export async function createPorts(approvals: HermitPorts["approvals"]): Promise<HermitPorts> {
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();
Expand Down
3 changes: 3 additions & 0 deletions apps/mobile/src/adapters/op-sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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<unknown> = Promise.resolve();
const port: SqlPort = {
async exec(sql, params) {
Expand Down
3 changes: 3 additions & 0 deletions apps/mobile/src/adapters/qvac-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<NonNullable<Parameters<typeof completion>[0]["tools"]>[number], { type: "function" }>;

Expand Down Expand Up @@ -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));
Expand Down
Loading
Loading