SPB Git

Repository Public

PendingItems.swift 4.4 KB 75 lines swift

1// Items created by the AutoFill extension (a new passkey registered from Safari or an app) on their way to the vault.2//3// Why a separate file and not the SQLite outbox: the engine in the app owns the database. It keeps the outbox in4// memory and rewrites it as a whole, so a second writer would be overwritten — or would corrupt a sync in flight.5// The extension therefore opens the database strictly read-only and drops each new item here instead, one file per6// item, sealed (HPKE, P-256 / AES-256-GCM) to this device's encryption key: only the Secure Enclave key of this7// device can open it, the plaintext never touches the disk, and the extension needs no vault key and no network.8// The app ingests the files through the engine (outbox → server) at its next unlock and deletes them.9// Until then the extension can still open them itself, so a passkey works right after it was created.10//11// HPKE base mode does not authenticate the sender: anything able to write in the app-group container (the app and12// its own extension, same team) could drop an item. That is the trust boundary of the app itself. The app shows13// what it ingested ("1 passkey saved from AutoFill").14import Foundation15import SharedVaultKit1617struct PendingItems: Sendable {18    struct Entry: Sendable, Equatable { let id: String; let item: Item }19    private struct Disk: Codable { var v: Int; var id: String; var at: String; var box: String }2021    static let maxEntries = 20022    static let maxBoxBytes = 256 * 10242324    let directory: URL2526    init(directory: URL) { self.directory = directory }27    init() throws { self.init(directory: try AppEnvironment.sharedDirectory().appendingPathComponent("pending", isDirectory: true)) }2829    private static func info(_ identity: DeviceIdentity) throws -> Data { try SPV1.ctx("pending-item", identity.accountId, identity.deviceId) }3031    private func files() -> [URL] {32        ((try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [])33            .filter { $0.pathExtension == "json" }.sorted { $0.lastPathComponent < $1.lastPathComponent }34    }3536    var count: Int { files().count }3738    /// Seals `item` for this device and stores it. `deviceEncPub` is the X9.63 public key of the device encryption key.39    @discardableResult40    func add(_ item: Item, identity: DeviceIdentity, deviceEncPub: Data) throws -> String {41        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)42        guard count < Self.maxEntries else { throw CocoaError(.fileWriteOutOfSpace, userInfo: [NSLocalizedDescriptionKey: "Too many items are waiting to be saved. Open SP Vault to save them."]) }43        let id = SPV1.uuid()44        let sealed = try SPV1.hpkeSeal(recipientPublicKey: deviceEncPub, info: try Self.info(identity), plaintext: item.jsonData)45        let disk = Disk(v: 1, id: id, at: ISO8601DateFormatter().string(from: Date()), box: SPV1.b64u(sealed))46        // the timestamp prefix keeps creation order; the id makes the name unique47        let name = String(format: "%013.0f-%@.json", Date().timeIntervalSince1970 * 1000, id)48        var options: Data.WritingOptions = [.atomic]49        #if os(iOS)50        options.insert(.completeFileProtectionUnlessOpen)51        #endif52        try JSONEncoder().encode(disk).write(to: directory.appendingPathComponent(name), options: options)53        return id54    }5556    /// Opens every pending item this device can authenticate. Files that fail to open are left alone (and reported by `count`).57    func load(identity: DeviceIdentity, keys: DeviceKeys) -> [Entry] {58        guard let info = try? Self.info(identity) else { return [] }59        var out: [Entry] = []60        for f in files() {61            guard let data = try? Data(contentsOf: f), data.count <= Self.maxBoxBytes * 2, let d = try? JSONDecoder().decode(Disk.self, from: data), d.v == 1,62                  let box = try? SPV1.unb64u(d.box), box.count <= Self.maxBoxBytes, let plain = try? keys.enc.hpkeOpen(info: info, sealed: box),63                  let item = try? Item(json: plain), !item.deleted else { continue }64            out.append(Entry(id: d.id, item: item))65        }66        return out67    }6869    func remove(ids: Set<String>) {70        for f in files() where ids.contains(where: { f.lastPathComponent.hasSuffix("-\($0).json") }) { try? FileManager.default.removeItem(at: f) }71    }7273    func removeAll() { try? FileManager.default.removeItem(at: directory) }74}75
Files main
Menu

Theme