Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(keyvault): per-app secret items with unattended locks, search and per-domain review (#4444)

ddupont7f1a03fbc3f2
diff --git a/.github/workflows/ci-cua-sdk.yml b/.github/workflows/ci-cua-sdk.yml
index 223104cf0d..858e003d11 100644
--- a/.github/workflows/ci-cua-sdk.yml
+++ b/.github/workflows/ci-cua-sdk.yml
@@ -81,12 +81,12 @@ jobs:
key: cua-sdk
- name: Format
if: runner.os == 'Linux'
- run: cargo fmt -p cua-sdk -p cua-daemon -p cua-cli -p cua-bindgen -p cua-media-protocol -p cua-media-transport -p cua-media-codec -p cua-media-client -p cua-viewer -p cua-logging -p cua-teleport -p cua-teleport-bundle -p cua-spaces-ext -p cua-spaces-ffi -p cua-spaces-cli -- --check
+ run: cargo fmt -p cua-sdk -p cua-daemon -p cua-cli -p cua-bindgen -p cua-media-protocol -p cua-media-transport -p cua-media-codec -p cua-media-client -p cua-viewer -p cua-logging -p cua-teleport -p cua-teleport-bundle -p cua-chromium-storage -p cua-spaces-ext -p cua-spaces-ffi -p cua-spaces-cli -- --check
- name: Clippy (native)
run: >
cargo clippy --locked -p cua-sdk -p cua-daemon -p cua-cli -p cua-bindgen
-p cua-media-protocol -p cua-media-transport -p cua-media-client -p cua-viewer -p cua-logging
- -p cua-teleport -p cua-teleport-bundle -p cua-volume
+ -p cua-teleport -p cua-teleport-bundle -p cua-chromium-storage -p cua-volume
-p cua-spaces-ext -p cua-spaces-ffi -p cua-spaces-cli
--all-targets --features cua-daemon/test-fixtures,cua-media-client/media-decode -- -D warnings
- name: Clippy (browser API, host metadata build)
@@ -98,7 +98,7 @@ jobs:
- name: Test (embedded, daemon over UDS and loopback, CLI, Cua Spaces extensions)
run: >
cargo test --locked --no-fail-fast -p cua-sdk -p cua-daemon -p cua-cli
- -p cua-teleport -p cua-teleport-bundle -p cua-volume
+ -p cua-teleport -p cua-teleport-bundle -p cua-chromium-storage -p cua-volume
-p cua-spaces-ext -p cua-spaces-ffi -p cua-spaces-cli -- --test-threads=4
env:
# Teleport send acts only on fake hosts in tests; anything that
diff --git a/.github/workflows/ci-cua-spacesd.yml b/.github/workflows/ci-cua-spacesd.yml
index 69e6fae901..8637f4dfdc 100644
--- a/.github/workflows/ci-cua-spacesd.yml
+++ b/.github/workflows/ci-cua-spacesd.yml
@@ -13,6 +13,7 @@ on:
- "libs/cua/crates/cua-proto/**"
- "libs/cua/crates/cua-spacesd-client/**"
- "libs/cua/crates/cua-teleport-bundle/**"
+ - "libs/cua/crates/cua-chromium-storage/**"
- "libs/cua/crates/cua-teleport/**"
- "libs/cua/crates/cua-media-protocol/**"
- "libs/cua/crates/cua-media-transport/**"
@@ -31,6 +32,7 @@ on:
- "libs/cua/crates/cua-proto/**"
- "libs/cua/crates/cua-spacesd-client/**"
- "libs/cua/crates/cua-teleport-bundle/**"
+ - "libs/cua/crates/cua-chromium-storage/**"
- "libs/cua/crates/cua-teleport/**"
- "libs/cua/crates/cua-media-protocol/**"
- "libs/cua/crates/cua-media-transport/**"
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift
index 00c8f468a3..ea8724c011 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift
@@ -71,6 +71,15 @@ public enum AppEnvironment {
}
}
let keyvault = KeyvaultModel(client: fixtures ? nil : KeyvaultClient(cuaHome: nil))
+ if !fixtures {
+ // Icons: caches survive restarts; fixtures never resolve apps or
+ // touch the network.
+ let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?
+ .appendingPathComponent("com.trycua.cua-spaces/icons")
+ keyvault.appIcons = AppIconCache(dir: caches?.appendingPathComponent("apps"))
+ keyvault.siteIconStore = SiteIconStore(dir: caches?.appendingPathComponent("sites"))
+ keyvault.iconScale = Int(NSScreen.main?.backingScaleFactor ?? 2)
+ }
let live = backend as? LiveSpacesBackend
// Fixtures never touch the host service, the account, the telemetry
// config or the coding agents' configs.
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index 69a372c79b..5afe3a297c 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -153,6 +153,7 @@ public final class AppModel {
// Live Keyvault sign-ins show left of the notch (and in the menu).
// Dismissed ones stay hidden across launches (Settings file).
keyvault.dismissed = settings.dismissedAccess
+ keyvault.siteIconsFromGoogle = { [weak self] in self?.settings.keyvaultSiteIcons ?? true }
keyvault.onSharing = { [weak self] _ in self?.syncNotchKeyvault() }
keyvault.onDismissed = { [weak self] ids in
guard let self else { return }
@@ -645,6 +646,8 @@ public final class AppModel {
telemetry: telemetryInput, agents: agentRows, agentsBusy: agentsBusy, agentsPending: agentsPending,
billing: identity == nil ? nil : billingStatus, loginItem: loginItemInput,
experiments: settings.experiments, keyvaultAutoWipe: keyvault.autoWipe,
+ keyvaultUnlockPrompt: keyvault.unlockPromptShows,
+ keyvaultSiteIcons: settings.keyvaultSiteIcons, keyvaultProtection: keyvault.page.protection,
autoConnect: settings.autoConnect))
}
@@ -791,6 +794,16 @@ public final class AppModel {
case "keyvault-auto-wipe":
await keyvault.setAutoWipe(option == "on")
if let error = keyvault.error { show(error: error) }
+ case "keyvault-site-icons":
+ settings.keyvaultSiteIcons = option == "on"
+ saveSettings()
+ // Turning it on asks for the rows' icons again.
+ if settings.keyvaultSiteIcons { await keyvault.loadIcons() }
+ case "keyvault-unlock-prompt":
+ // On shows the prompt (Never ask again off); off is the stored
+ // "Never ask again".
+ await keyvault.setSkipUnlockPrompt(option != "on")
+ if let error = keyvault.error { show(error: error) }
case "telemetry":
do {
telemetryInput = try telemetry?.setEnabled(option == "on")
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/IconCache.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/IconCache.swift
new file mode 100644
index 0000000000..61b817d9a7
--- /dev/null
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/IconCache.swift
@@ -0,0 +1,267 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import AppKit
+import Foundation
+
+/// Where an app's icon comes from, resolved once per app: its bundle id and
+/// version key the caches, `render` draws the PNG only on a cache miss.
+public struct AppIconSource: Sendable {
+ public let bundleId: String
+ public let version: String
+ public let render: @Sendable () -> Data?
+
+ public init(bundleId: String, version: String, render: @escaping @Sendable () -> Data?) {
+ self.bundleId = bundleId
+ self.version = version
+ self.render = render
+ }
+}
+
+/// App icons for the Keyvault list. NSWorkspace is asked once per app and
+/// version, never per render: a decoded image lives in an `NSCache`, the PNG
+/// on disk under the bundle id and version, so a restart (or an app update,
+/// which changes the key) costs one render at most.
+public final class AppIconCache: @unchecked Sendable {
+ public typealias Resolver = @Sendable (_ providerId: String, _ name: String) -> AppIconSource?
+
+ private let dir: URL?
+ private let resolver: Resolver
+ private let memory = NSCache<NSString, NSImage>()
+ private let lock = NSLock()
+ /// provider id to cache key (resolved once; "" when the app is not here).
+ private var keys: [String: String] = [:]
+ /// How often NSWorkspace was asked and an icon was drawn (the tests'
+ /// proof that nothing is resolved per render).
+ public private(set) var resolves = 0
+ public private(set) var renders = 0
+
+ public init(dir: URL?, resolver: @escaping Resolver = AppIconCache.workspace) {
+ self.dir = dir
+ self.resolver = resolver
+ memory.countLimit = 256
+ }
+
+ /// The icon of an app, or nil (the list draws its first letter).
+ public func image(providerId: String, name: String) -> NSImage? {
+ lock.lock()
+ defer { lock.unlock() }
+ if let key = keys[providerId] {
+ return key.isEmpty ? nil : memory.object(forKey: key as NSString) ?? loadDisk(key)
+ }
+ resolves += 1
+ guard let source = resolver(providerId, name) else {
+ keys[providerId] = ""
+ return nil
+ }
+ let key = AppIconCache.fileKey(source)
+ keys[providerId] = key
+ if let hit = memory.object(forKey: key as NSString) ?? loadDisk(key) { return hit }
+ guard let png = source.render(), let image = NSImage(data: png) else {
+ keys[providerId] = ""
+ return nil
+ }
+ renders += 1
+ memory.setObject(image, forKey: key as NSString)
+ if let url = file(key) {
+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try? png.write(to: url, options: .atomic)
+ }
+ return image
+ }
+
+ static func fileKey(_ s: AppIconSource) -> String {
+ let safe = { (v: String) in v.map { $0.isLetter || $0.isNumber || ".-_".contains($0) ? String($0) : "_" }.joined() }
+ return "\(safe(s.bundleId))-\(safe(s.version))"
+ }
+
+ private func file(_ key: String) -> URL? { dir?.appendingPathComponent("\(key).png") }
+
+ private func loadDisk(_ key: String) -> NSImage? {
+ guard let url = file(key), let data = try? Data(contentsOf: url), let image = NSImage(data: data) else { return nil }
+ memory.setObject(image, forKey: key as NSString)
+ return image
+ }
+
+ /// The bundle ids an app may have (the provider catalog's ids).
+ static let bundleIds: [String: [String]] = [
+ "chrome": ["com.google.Chrome"],
+ "firefox": ["org.mozilla.firefox"],
+ "slack": ["com.tinyspeck.slackmacgap"],
+ "discord": ["com.hnc.Discord"],
+ "steam": ["com.valvesoftware.steam"],
+ "whatsapp": ["net.whatsapp.WhatsApp", "desktop.WhatsApp"],
+ "claude-code": ["com.anthropic.claudefordesktop"],
+ ]
+
+ /// The real resolver: Launch Services for the app's location, its
+ /// bundle for the version, NSWorkspace for the icon.
+ public static let workspace: Resolver = { providerId, name in
+ let ws = NSWorkspace.shared
+ var url: URL?
+ var id = ""
+ for candidate in bundleIds[providerId] ?? [] {
+ if let found = ws.urlForApplication(withBundleIdentifier: candidate) { url = found; id = candidate; break }
+ }
+ if url == nil {
+ let guess = URL(fileURLWithPath: "/Applications/\(name).app")
+ if FileManager.default.fileExists(atPath: guess.path) {
+ url = guess
+ id = Bundle(url: guess)?.bundleIdentifier ?? providerId
+ }
+ }
+ guard let url else { return nil }
+ let info = Bundle(url: url)?.infoDictionary
+ let version = (info?["CFBundleShortVersionString"] as? String) ?? (info?["CFBundleVersion"] as? String) ?? "0"
+ return AppIconSource(bundleId: id, version: version) {
+ let icon = ws.icon(forFile: url.path)
+ return AppIconCache.png(icon, side: 64)
+ }
+ }
+
+ static func png(_ image: NSImage, side: Int) -> Data? {
+ guard let rep = NSBitmapImageRep(
+ bitmapDataPlanes: nil, pixelsWide: side, pixelsHigh: side, bitsPerSample: 8, samplesPerPixel: 4,
+ hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) else { return nil }
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
+ image.draw(in: NSRect(x: 0, y: 0, width: side, height: side))
+ NSGraphicsContext.restoreGraphicsState()
+ return rep.representation(using: .png, properties: [:])
+ }
+}
+
+/// How a site icon is downloaded (a stub in tests).
+public typealias IconFetch = @Sendable (URL) async throws -> (Data, Int)
+
+/// Site icons for the Keyvault rows, in order: the icon the source browser
+/// held (read locally when the items were saved, handed in through
+/// `remember`), then Google's favicon service when the switch is on, then the
+/// globe (nil here). Fetched lazily as rows appear, a few at a time with a
+/// short timeout, successes and misses kept on disk (a miss is retried after
+/// a week), so a domain is asked for at most once. Only the registrable
+/// domain is ever sent. Nothing here blocks a render.
+public final class SiteIconStore: @unchecked Sendable {
+ private let dir: URL?
+ private let fetcher: IconFetch
+ private let now: @Sendable () -> Date
+ private let retryAfter: TimeInterval
+ private let gate: Gate
+ private let memory = NSCache<NSString, NSImage>()
+ private let lock = NSLock()
+ private var inFlight: Set<String> = []
+ /// Requests that left (the tests count them).
+ public private(set) var requests: [URL] = []
+
+ public init(dir: URL?, maxConcurrent: Int = 3, retryAfter: TimeInterval = 7 * 86_400,
+ now: @escaping @Sendable () -> Date = Date.init, fetch: @escaping IconFetch = SiteIconStore.network) {
+ self.dir = dir
+ self.fetcher = fetch
+ self.now = now
+ self.retryAfter = retryAfter
+ self.gate = Gate(limit: maxConcurrent)
+ memory.countLimit = 512
+ }
+
+ /// A registrable domain that is safe to send: letters, digits, dots and
+ /// hyphens, at least two labels, not an address and not a local name.
+ public static func sendable(_ site: String) -> Bool {
+ let s = site.lowercased()
+ let labels = s.split(separator: ".", omittingEmptySubsequences: false)
+ guard labels.count >= 2, s.count <= 253, !labels.contains(where: { $0.isEmpty || $0.count > 63 }) else { return false }
+ guard s.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "." || $0 == "-") }) else { return false }
+ guard !labels.last!.allSatisfy(\.isNumber) else { return false }
+ return !["local", "localhost", "internal", "lan", "home", "corp", "test", "invalid"].contains(String(labels.last!))
+ }
+
+ public static func url(for site: String, scale: Int) -> URL? {
+ guard sendable(site) else { return nil }
+ let size = scale >= 2 ? 128 : 64
+ return URL(string: "https://www.google.com/s2/favicons?domain=\(site.lowercased())&sz=\(size)")
+ }
+
+ private func key(_ site: String) -> String { site.lowercased() }
+ private func file(_ site: String, _ ext: String) -> URL? { dir?.appendingPathComponent("\(key(site)).\(ext)") }
+
+ /// A downloaded icon already on hand (memory, then disk). No network.
+ public func cached(_ site: String) -> NSImage? {
+ if let m = memory.object(forKey: key(site) as NSString) { return m }
+ guard let url = file(site, "png"), let data = try? Data(contentsOf: url), let image = NSImage(data: data) else { return nil }
+ memory.setObject(image, forKey: key(site) as NSString)
+ return image
+ }
+
+ /// A miss newer than the retry window (do not ask again yet).
+ public func recentMiss(_ site: String) -> Bool {
+ guard let url = file(site, "miss"),
+ let at = (try? FileManager.default.attributesOfItem(atPath: url.path))?[.modificationDate] as? Date else { return false }
+ return now().timeIntervalSince(at) < retryAfter
+ }
+
+ /// Looks the icon up on the network unless it is cached, was missed
+ /// lately or is already being fetched. Returns the image or nil.
+ public func load(_ site: String, scale: Int) async -> NSImage? {
+ if let hit = cached(site) { return hit }
+ guard !recentMiss(site), let url = SiteIconStore.url(for: site, scale: scale) else { return nil }
+ lock.lock()
+ if inFlight.contains(key(site)) { lock.unlock(); return nil }
+ inFlight.insert(key(site))
+ lock.unlock()
+ defer { lock.lock(); inFlight.remove(key(site)); lock.unlock() }
+ await gate.enter()
+ lock.lock(); requests.append(url); lock.unlock()
+ let result: (Data, Int)?
+ do { result = try await fetcher(url) } catch { result = nil }
+ await gate.leave()
+ do {
+ guard let (data, status) = result else { throw CancellationError() }
+ guard status == 200, data.count <= 64 * 1024, let image = NSImage(data: data), image.isValid else {
+ markMiss(site)
+ return nil
+ }
+ memory.setObject(image, forKey: key(site) as NSString)
+ if let f = file(site, "png") {
+ try? FileManager.default.createDirectory(at: f.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try? data.write(to: f, options: .atomic)
+ if let m = file(site, "miss") { try? FileManager.default.removeItem(at: m) }
+ }
+ return image
+ } catch {
+ // A timeout or no network is not the site's fault; ask again
+ // next launch rather than remembering a miss for a week.
+ return nil
+ }
+ }
+
+ private func markMiss(_ site: String) {
+ guard let url = file(site, "miss") else { return }
+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try? Data().write(to: url)
+ try? FileManager.default.setAttributes([.modificationDate: now()], ofItemAtPath: url.path)
+ }
+
+ /// The real download: no cookies, no cache, four seconds.
+ public static let network: IconFetch = { url in
+ let config = URLSessionConfiguration.ephemeral
+ config.timeoutIntervalForRequest = 4
+ config.timeoutIntervalForResource = 6
+ config.httpCookieStorage = nil
+ config.urlCache = nil
+ let (data, response) = try await URLSession(configuration: config).data(from: url)
+ return (data, (response as? HTTPURLResponse)?.statusCode ?? 0)
+ }
+
+ actor Gate {
+ private let limit: Int
+ private var active = 0
+ private var waiting: [CheckedContinuation<Void, Never>] = []
+ init(limit: Int) { self.limit = max(1, limit) }
+ func enter() async {
+ if active < limit { active += 1; return }
+ await withCheckedContinuation { waiting.append($0) }
+ }
+ func leave() {
+ if waiting.isEmpty { active -= 1 } else { waiting.removeFirst().resume() }
+ }
+ }
+}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/KeyvaultModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/KeyvaultModel.swift
index 3f31c43feb..a1c8a9dc33 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/KeyvaultModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/KeyvaultModel.swift
@@ -1,11 +1,29 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
+import AppKit
import CuaSDK
import CuaSpacesFFI
import Foundation
import Observation
+/// Items waiting for the user's answer to the unlock prompt.
+public struct PendingUnlock: Identifiable, Equatable {
+ public let ids: [String]
+ public let prompt: KvUnlockPrompt
+ public var id: String { ids.joined(separator: ",") }
+}
+
+/// What the user answered.
+public enum UnlockAnswer { case deny, allow, neverAskAgain }
+
+/// Items waiting for the user's confirmation to delete.
+public struct PendingDelete: Identifiable, Equatable {
+ public let ids: [String]
+ public let confirm: KvDeleteConfirm
+ public var id: String { ids.joined(separator: ",") }
+}
+
/// The Keyvault browser: the broker's overview (through the core's
/// `KeyvaultClient`) and the core's views of it. The app never reads secret
/// values (the broker has none to give), never runs its own Touch ID prompt
@@ -15,9 +33,52 @@ import Observation
@Observable
public final class KeyvaultModel {
let client: KeyvaultClientProtocol?
- public private(set) var overview: KeyvaultOverview
- public var selection: KvSelection = .category(category: .all)
- public var query = ""
+ public private(set) var overview: KeyvaultOverview { didSet { changed() } }
+ /// The sidebar's pick. An app narrows the vault list to it.
+ public var selection: KvSelection = .category(category: .all) {
+ didSet { changed(); applySelection() }
+ }
+ /// The vault list's own state (search, selection, open groups); the
+ /// core's reducer owns it.
+ public private(set) var vault = KvVaultState(query: "", selected: [], expanded: [], app: nil) {
+ didSet { changed() }
+ }
+ /// Items to unlock once the user answers the prompt (nil: no prompt).
+ public var unlockPrompt: PendingUnlock?
+ /// Items to delete once the user confirms (nil: nothing to confirm).
+ public var deleteConfirm: PendingDelete?
+ /// App icons: NSWorkspace once per app and version, then memory and disk
+ /// (`AppIconCache`). Nil in tests that do not draw icons.
+ public var appIcons: AppIconCache?
+ public private(set) var icons: [String: NSImage] = [:]
+ @ObservationIgnored private var iconsAsked: Set<String> = []
+ /// Site icons: the browser's own, read locally and kept in the vault,
+ /// then Google's service when the setting allows it, then the globe.
+ public var siteIconStore: SiteIconStore?
+ /// The "Load site icons from Google" setting.
+ public var siteIconsFromGoogle: @MainActor () -> Bool = { true }
+ public private(set) var siteIcons: [String: NSImage] = [:]
+ @ObservationIgnored private var localSiteIcons: [String: Int] = [:]
+ @ObservationIgnored private var siteIconsAsked: Set<String> = []
+ /// The backing scale the icons are fetched for.
+ public var iconScale = 2
+
+ /// Bumped when the overview, the list state or the sidebar pick change:
+ /// the memoized views below recompute only then. Reading it in a view's
+ /// getter keeps the view observing even when the memo answers.
+ private(set) var revision = 0
+ @ObservationIgnored private var memo: [String: (rev: Int, value: Any)] = [:]
+ /// How many times each memoized view was computed (the tests' proof).
+ @ObservationIgnored public private(set) var computes: [String: Int] = [:]
+ private func changed() { revision &+= 1 }
+ private func memoized<T>(_ name: String, _ make: () -> T) -> T {
+ let rev = revision
+ if let hit = memo[name], hit.rev == rev, let v = hit.value as? T { return v }
+ let v = make()
+ memo[name] = (rev, v)
+ computes[name, default: 0] += 1
+ return v
+ }
public var approval: KvApprovalState?
public private(set) var busy = false
public var error: String?
@@ -35,13 +96,14 @@ public final class KeyvaultModel {
self.clock = clock
self.overview = overview ?? KeyvaultOverview(
availability: "not_running", message: "The Cua daemon is not running, so the Keyvault is unavailable.",
- status: nil, serverVerified: false, items: [], pending: [], grants: [], rules: [],
+ status: nil, serverVerified: false, items: [], namesVisible: false, itemsTotal: 0,
+ pending: [], grants: [], rules: [],
deliveries: [], audit: [], auditVerification: nil, partialErrors: [])
}
var nowMs: Int64 { Int64(clock().timeIntervalSince1970 * 1000) }
- public var page: KvPage { kvPage(overview: overview, nowMs: nowMs) }
+ public var page: KvPage { memoized("page") { kvPage(overview: overview, nowMs: nowMs) } }
/// The always-visible signal while sign-ins are live in a Space (nil
/// when nothing is): the notch indicator and the menu bar line.
@@ -88,11 +150,136 @@ public final class KeyvaultModel {
public func isDismissed(_ row: KvAccessRow) -> Bool {
!row.imports.isEmpty && row.imports.allSatisfy(dismissed.contains)
}
- public var sidebar: KvSidebar { kvSidebar(overview: overview, nowMs: nowMs) }
- public var list: KvListView { kvList(overview: overview, selection: selection, nowMs: nowMs, query: query) }
+ public var sidebar: KvSidebar { memoized("sidebar") { kvSidebar(overview: overview, nowMs: nowMs) } }
+ public var list: KvListView { memoized("list") { kvList(overview: overview, selection: selection, nowMs: nowMs) } }
+
+ // MARK: - The vault list (the core's grouping, selection and search)
+
+ /// The vault list as drawn: apps, sites and items with their locks.
+ public var vaultView: KvVaultView { memoized("vaultView") { kvVaultView(overview: overview, state: vault, nowMs: nowMs) } }
+
+ /// The search text.
+ public var query: String {
+ get { vault.query }
+ set { send(.query(text: newValue)) }
+ }
- public func siteDetail(_ key: String) -> KvSiteDetail? {
- kvSiteDetail(overview: overview, key: key, nowMs: nowMs)
+ /// Feeds one input to the list (search, select, open or close).
+ public func send(_ action: KvVaultAction) {
+ vault = kvVaultReduce(overview: overview, state: vault, action: action)
+ }
+
+ private func applySelection() {
+ var next = vault
+ switch selection {
+ case .app(let key): next.app = key
+ case .category: next.app = nil
+ }
+ if next.app != vault.app { next.selected = [] }
+ vault = kvVaultReduce(overview: overview, state: next, action: .query(text: next.query))
+ }
+
+ /// An app the list has not shown before opens, so its sites are in view;
+ /// one the user closed stays closed.
+ @ObservationIgnored private var seenApps: Set<String> = []
+
+ private func openNewApps() {
+ for id in Set(overview.items.map(\.providerId)).subtracting(seenApps).sorted() {
+ seenApps.insert(id)
+ if !vault.expanded.contains(id) { send(.toggleOpen(key: id)) }
+ }
+ }
+
+ /// Shows the items' names (Touch ID, asked by the daemon).
+ public func showItems() async { await run(.browse) }
+
+ // MARK: - Locks (one prompt and one Touch ID for a batch)
+
+ /// A click on a lock, or the batch bar's Unlock: asks first (unless the
+ /// user chose Never ask again), then the daemon asks for Touch ID once.
+ public func requestUnlock(ids: [String], name: String? = nil) async {
+ guard !ids.isEmpty else { return }
+ if let prompt = kvUnlockPrompt(overview: overview, count: UInt32(ids.count), name: name) {
+ unlockPrompt = PendingUnlock(ids: ids, prompt: prompt)
+ } else {
+ await run(kvUnlockCommand(ids: ids))
+ }
+ }
+
+ /// The prompt's answers: Allow, Never ask again (stored in the vault,
+ /// revertible in Settings), Deny.
+ public func answerUnlock(_ answer: UnlockAnswer) async {
+ guard let pending = unlockPrompt else { return }
+ unlockPrompt = nil
+ switch answer {
+ case .deny: return
+ case .allow:
+ await run(kvUnlockCommand(ids: pending.ids))
+ case .neverAskAgain:
+ await run(.setSkipUnlockPrompt(on: true))
+ await run(kvUnlockCommand(ids: pending.ids))
+ }
+ }
+
+ /// Locks items (narrowing: no prompt, no Touch ID).
+ public func lock(ids: [String]) async {
+ guard !ids.isEmpty else { return }
+ await run(kvLockCommand(ids: ids))
+ }
+
+ /// The batch bar's and a row's delete: confirm first.
+ public func requestDelete(ids: [String]) {
+ guard !ids.isEmpty else { return }
+ let copies = kvLiveCopySpaces(overview: overview, ids: ids, nowMs: nowMs)
+ deleteConfirm = PendingDelete(ids: ids, confirm: kvDeleteConfirm(count: UInt32(ids.count), liveCopies: copies))
+ }
+
+ /// Deletes the items and wipes their live copies in Spaces.
+ public func confirmDelete() async {
+ guard let pending = deleteConfirm else { return }
+ deleteConfirm = nil
+ await run(kvDeleteCommand(ids: pending.ids))
+ }
+
+ /// "Never ask again" is on (Settings turns it back off).
+ public var unlockPromptShows: Bool? { overview.status?.skipUnlockPrompt.map { !$0 } }
+
+ public func setSkipUnlockPrompt(_ on: Bool) async { await run(.setSkipUnlockPrompt(on: on)) }
+
+ // MARK: - App icons
+
+ /// Icons for what the list shows, each asked for once: app icons from
+ /// the cache, the browser's own site icons from the vault, and site icons
+ /// already on disk. Nothing here touches the network (`siteIcon` does,
+ /// lazily, as a row appears).
+ public func loadIcons() async {
+ if let cache = appIcons {
+ var seen: [String: String] = [:]
+ for i in overview.items { seen[i.providerId] = i.appDisplay }
+ for (id, name) in seen.sorted(by: { $0.key < $1.key }) where !iconsAsked.contains(id) {
+ iconsAsked.insert(id)
+ if let image = cache.image(providerId: id, name: name) { icons[id] = image }
+ }
+ }
+ guard overview.namesVisible, let client else { return }
+ for f in await client.favicons() {
+ // Decoded once: a changed icon (a different size) decodes again.
+ guard localSiteIcons[f.site] != f.png.count, let data = Data(base64Encoded: f.png),
+ let image = NSImage(data: data) else { continue }
+ localSiteIcons[f.site] = f.png.count
+ siteIcons[f.site] = image
+ }
+ }
+
+ /// Called as a site row first appears: the downloaded icon on hand, else
+ /// (when the setting allows it and the browser had none) one lookup of
+ /// the domain. Never blocks drawing; the globe stands in meanwhile.
+ public func siteIcon(_ site: String) async {
+ guard siteIcons[site] == nil, let store = siteIconStore else { return }
+ if let hit = store.cached(site) { siteIcons[site] = hit; return }
+ guard siteIconsFromGoogle(), !siteIconsAsked.contains(site) else { return }
+ siteIconsAsked.insert(site)
+ if let image = await store.load(site, scale: iconScale) { siteIcons[site] = image }
}
public var approvalView: KvApprovalView? {
@@ -103,6 +290,8 @@ public final class KeyvaultModel {
public func refresh() async {
guard let client else { return }
overview = await client.overview()
+ vault = kvVaultPrune(overview: overview, state: vault)
+ openNewApps()
// Forget dismissals of copies that were wiped or expired (only
// when the broker answered: an unavailable page lists none).
if overview.availability == "ready" {
@@ -202,14 +391,6 @@ public final class KeyvaultModel {
public func setAutoWipe(_ on: Bool) async { await run(.setAutoWipe(on: on)) }
- public func setUnattended(itemIds: [String], on: Bool) async {
- await run(.setUnattended(itemIds: itemIds, unattended: on))
- }
-
- public func toggleSite(_ group: KvSiteGroup, on: Bool) async {
- await run(kvSiteToggle(group: group, on: on))
- }
-
public func run(_ command: KvCommand) async {
guard let client else { return }
busy = true
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TeleportModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TeleportModel.swift
index 12d7b5089f..21954a3074 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TeleportModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TeleportModel.swift
@@ -355,14 +355,103 @@ public final class TeleportModel {
scope: nil, launch: nil))
sdkPlan = plan
send(.planned(plan: appTeleportPlan(plan: plan)))
+ await loadChoices()
} catch {
fail(error)
}
}
+ // MARK: - The review's choices: sites, items, the Keyvault as the source
+
+ /// The Keyvault the review reads saved items and site counts from (the
+ /// app's; the opener sets it).
+ public var keyvault: KeyvaultModel?
+ /// What was sent to each Space last time (the app's settings).
+ public var rememberedChoices: [AppRememberedChoice] = []
+ /// Told the choices to keep after a teleport.
+ public var onRemember: (([AppRememberedChoice]) -> Void)?
+ /// The saved-items list's own state while sending from the Keyvault.
+ public private(set) var reviewVault = KvVaultState(query: "", selected: [], expanded: [], app: nil)
+ /// The sites are being read (Touch ID may be asked).
+ public private(set) var readingSites = false
+
+ var providerId: String? { state.entry?.providerId }
+
+ /// The key a choice is remembered under: the app and this Space.
+ var rememberKey: String? {
+ providerId.map { appReviewRememberKey(app: $0, space: state.spaceName) }
+ }
+
+ /// Reads what the review lets the user choose: the app's saved Keyvault
+ /// items (counts only, no Touch ID) and, for a browser that sends its
+ /// cookies, its sites with counts (nothing decrypted; the daemon asks for
+ /// Touch ID to show names).
+ public func loadChoices() async {
+ guard let provider = providerId, let review else { return }
+ if let keyvault {
+ await keyvault.refresh()
+ let source = kvVaultSource(overview: keyvault.overview, providerId: provider)
+ reviewVault = KvVaultState(query: "", selected: source.ids, expanded: [provider], app: provider)
+ send(.vaultItems(count: source.count, newestMs: source.newestMs,
+ nowMs: Int64(keyvault.clock().timeIntervalSince1970 * 1000), selected: source.ids,
+ passwordIds: source.passwordIds))
+ }
+ guard review.needsDomains else { return }
+ guard let client = keyvault?.client else { send(.domainsFailed); return }
+ readingSites = true
+ defer { readingSites = false }
+ do {
+ let inventory = try await client.inventory(app: provider, profile: nil)
+ let remembered = rememberKey.flatMap { appReviewRemembered(choices: rememberedChoices, key: $0) }
+ send(.domainsLoaded(inventory: inventory, remembered: remembered))
+ } catch {
+ send(.domainsFailed)
+ }
+ }
+
+ /// Where the review sends from. The saved items' names need Touch ID the
+ /// first time (the Keyvault's browse window).
+ public func sendFrom(_ source: AppSendSource) async {
+ send(.sendFrom(source: source))
+ if source == .vault, let keyvault, !keyvault.overview.namesVisible { await keyvault.showItems() }
+ }
+
+ /// The Keyvault as the review lists it: what a teleport can send. Saved
+ /// passwords are never delivered (they sign in through site login), so
+ /// they are not offered here.
+ var reviewOverview: KeyvaultOverview? {
+ guard var o = keyvault?.overview else { return nil }
+ o.items.removeAll { $0.kind == "password" }
+ return o
+ }
+
+ /// Next time the review starts from the sites sent now (to this Space).
+ func rememberChoice() {
+ let consent = appPickerConsent(state: state)
+ guard let domains = consent.cookieDomains, consent.fromVault == nil, let key = rememberKey else { return }
+ rememberedChoices = appReviewRemember(choices: rememberedChoices, key: key, domains: domains)
+ onRemember?(rememberedChoices)
+ }
+
+ /// The saved items as the review lists them.
+ public var reviewVaultView: KvVaultView? {
+ guard let keyvault, let overview = reviewOverview else { return nil }
+ return kvVaultView(overview: overview, state: reviewVault,
+ nowMs: Int64(keyvault.clock().timeIntervalSince1970 * 1000))
+ }
+
+ /// Search, select and open groups in the saved items; the core keeps the
+ /// ones to send.
+ public func sendVault(_ action: KvVaultAction) {
+ guard let overview = reviewOverview else { return }
+ reviewVault = kvVaultReduce(overview: overview, state: reviewVault, action: action)
+ send(.vaultSelection(selected: reviewVault.selected))
+ }
+
public func confirm() async {
guard let review, review.canConfirm, let teleport, let space, let plan = sdkPlan else { return }
let consent = appPickerConsent(state: state)
+ rememberChoice()
send(.confirm)
onTransfer?(true)
defer { onTransfer?(false) }
@@ -419,5 +508,9 @@ func sdkConsent(_ consent: AppTeleportConsent) -> TeleportConsent {
TeleportConsent(approved: consent.approved,
acknowledgeSensitive: consent.acknowledgeSensitive,
saveToKeyvault: consent.saveToKeyvault,
- acknowledgeRelayPlaintext: consent.acknowledgeRelayPlaintext)
+ acknowledgeRelayPlaintext: consent.acknowledgeRelayPlaintext,
+ cookieDomains: consent.cookieDomains,
+ exclude: consent.exclude,
+ fromVault: consent.fromVault,
+ includePasswords: consent.includePasswords)
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/KeyvaultViews.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/KeyvaultViews.swift
index 0f5b4d7454..661a199e39 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/KeyvaultViews.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/KeyvaultViews.swift
@@ -5,10 +5,11 @@ import CuaSDK
import CuaSpacesFFI
import SwiftUI
-/// The Keyvault, as a sidebar and list: the sidebar picks a category or a
-/// site; this pane lists it. Everything shown is derived by the core from
-/// what the broker returned; nothing here decides access and no secret value
-/// is ever here.
+/// The Keyvault, as a sidebar and list: the sidebar picks a category or an
+/// app; this pane lists it. The vault list is a password manager's: items
+/// grouped by the app they came from, each with a lock. Everything shown is
+/// derived by the core from what the broker returned; nothing here decides
+/// access and no secret value is ever here.
struct KeyvaultDetail: View {
@Bindable var keyvault: KeyvaultModel
let selection: KvSelection
@@ -19,19 +20,18 @@ struct KeyvaultDetail: View {
if !page.ready {
unavailable(page)
} else {
- switch selection {
- case .site(let key):
- if let detail = keyvault.siteDetail(key) {
- SiteDetailView(keyvault: keyvault, detail: detail, blocked: page.disabled)
- } else {
- ContentUnavailableView { Text(keyvault.list.emptyText ?? "") }
- }
- case .category:
+ let list = keyvault.list
+ if list.vault {
+ VaultList(keyvault: keyvault, page: page)
+ } else if case .app = selection {
+ ContentUnavailableView { Text(list.emptyText ?? "") }
+ } else {
CategoryList(keyvault: keyvault, page: page)
}
}
}
.navigationTitle(keyvault.list.title.isEmpty ? "Keyvault" : keyvault.list.title)
+ .task(id: keyvault.overview.items.count) { await keyvault.loadIcons() }
.onAppear { keyvault.selection = selection }
.onChange(of: selection) { _, new in keyvault.selection = new }
.task(id: "kv-poll") {
@@ -46,6 +46,7 @@ struct KeyvaultDetail: View {
@ViewBuilder private func banners(_ page: KvPage) -> some View {
VStack(spacing: 0) {
if let banner = page.disabledBanner { Banner(text: banner, error: true) }
+ if let notice = page.resetNotice { Banner(text: notice, error: false) }
if let error = keyvault.error { Banner(text: error, error: true) }
if let key = keyvault.recoveryKey { Banner(text: kvRecoveryKeyText(key: key), error: false) }
}
@@ -107,7 +108,469 @@ struct Banner: View {
}
}
-/// All, Waiting, Access or Recent.
+/// The vault list: apps, their sites and items, each with a lock; checkboxes
+/// select items, a site or a whole app for the batch bar (lock, unlock,
+/// delete). Search matches a domain, a key, an app or a type.
+struct VaultList: View {
+ @Bindable var keyvault: KeyvaultModel
+ let page: KvPage
+
+ var body: some View {
+ let view = keyvault.vaultView
+ VStack(spacing: 0) {
+ SearchBar(keyvault: keyvault, view: view)
+ if view.namesHidden { HiddenNames(view: view, keyvault: keyvault) }
+ if let empty = view.emptyText {
+ ContentUnavailableView { Text(empty) }
+ } else {
+ List {
+ ForEach(VaultLine.lines(view), id: \.id) { line in
+ VaultLineRow(line: line, keyvault: keyvault, blocked: page.disabled)
+ .listRowSeparator(.visible)
+ }
+ }
+ .listStyle(.inset)
+ .accessibilityIdentifier("vault-list")
+ }
+ }
+ .safeAreaInset(edge: .bottom) {
+ if view.selection.count > 0 { BatchBar(keyvault: keyvault, selection: view.selection, blocked: page.disabled) }
+ }
+ .sheet(item: $keyvault.unlockPrompt) { pending in
+ UnlockPromptSheet(prompt: pending.prompt) { answer in Task { await keyvault.answerUnlock(answer) } }
+ }
+ .sheet(item: $keyvault.deleteConfirm) { pending in
+ DeleteConfirmSheet(confirm: pending.confirm,
+ onDelete: { Task { await keyvault.confirmDelete() } },
+ onCancel: { keyvault.deleteConfirm = nil })
+ }
+ }
+}
+
+/// Search by domain, key, app or type, and Select All.
+struct SearchBar: View {
+ let keyvault: KeyvaultModel
+ let view: KvVaultView
+
+ var body: some View {
+ HStack(spacing: 10) {
+ HStack(spacing: 6) {
+ Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
+ TextField(view.searchPrompt, text: Binding(get: { keyvault.query }, set: { keyvault.query = $0 }))
+ .textFieldStyle(.plain)
+ .accessibilityIdentifier("vault-search")
+ if !keyvault.query.isEmpty {
+ Button { keyvault.query = "" } label: {
+ Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Clear search")
+ }
+ }
+ .padding(.horizontal, 8).padding(.vertical, 5)
+ .background(RoundedRectangle(cornerRadius: 7).fill(Color.secondary.opacity(0.12)))
+ if view.canSelectAll {
+ Button(view.selection.count == view.shown ? "Select None" : "Select All") {
+ keyvault.send(view.selection.count == view.shown ? .clear : .selectAll)
+ }
+ .buttonStyle(.link)
+ .accessibilityIdentifier("vault-select-all")
+ }
+ }
+ .padding(.horizontal, 16).padding(.vertical, 10)
+ }
+}
+
+/// The names are hidden until the user confirms with Touch ID.
+struct HiddenNames: View {
+ let view: KvVaultView
+ let keyvault: KeyvaultModel
+
+ var body: some View {
+ HStack(spacing: 10) {
+ Image(systemName: "eye.slash").foregroundStyle(.secondary)
+ Text(view.hiddenNote ?? "").foregroundStyle(.secondary).lineLimit(2)
+ Spacer()
+ Button(view.showNamesLabel) { Task { await keyvault.showItems() } }
+ .disabled(keyvault.busy)
+ .accessibilityIdentifier("vault-show-items")
+ }
+ .padding(.horizontal, 16).padding(.vertical, 10)
+ .background(.bar)
+ .overlay(alignment: .bottom) { Divider() }
+ }
+}
+
+/// One line of the flattened list: an app, a site, the files of an app, or
+/// an item. The core decides what is open.
+enum VaultLine: Identifiable {
+ case app(KvVaultApp)
+ case site(KvVaultApp, KvVaultSite)
+ case files(KvVaultApp, KvVaultFiles)
+ case item(KvVaultRow, indent: Int)
+
+ var id: String {
+ switch self {
+ case .app(let a): return "app:\(a.key)"
+ case .site(_, let s): return "site:\(s.key)"
+ case .files(_, let f): return "files:\(f.key)"
+ case .item(let r, _): return "item:\(r.id)"
+ }
+ }
+
+ static func lines(_ view: KvVaultView) -> [VaultLine] {
+ var out: [VaultLine] = []
+ for app in view.apps {
+ out.append(.app(app))
+ guard app.open else { continue }
+ for site in app.sites {
+ out.append(.site(app, site))
+ if site.open { out += site.rows.map { .item($0, indent: 2) } }
+ }
+ if let files = app.files {
+ out.append(.files(app, files))
+ if files.open { out += files.rows.map { .item($0, indent: 2) } }
+ }
+ }
+ return out
+ }
+}
+
+struct VaultLineRow: View {
+ let line: VaultLine
+ let keyvault: KeyvaultModel
+ let blocked: Bool
+
+ var body: some View {
+ switch line {
+ case .app(let app):
+ GroupRow(indent: 0, selected: app.selected, open: app.open,
+ onSelect: { keyvault.send(.toggleGroup(key: app.key)) },
+ onOpen: { keyvault.send(.toggleOpen(key: app.key)) }) {
+ AppIcon(keyvault: keyvault, providerId: app.providerId, name: app.name)
+ } title: {
+ Text(app.name).font(.headline).lineLimit(1)
+ } detail: {
+ Text(app.summary)
+ } trailing: {
+ updated(app.updated)
+ LockButton(state: app.lock, name: app.name, unlock: app.unlockIds, lock: app.lockIds,
+ keyvault: keyvault, blocked: blocked)
+ }
+ case .site(_, let site):
+ GroupRow(indent: 1, selected: site.selected, open: site.open,
+ onSelect: { keyvault.send(.toggleGroup(key: site.key)) },
+ onOpen: { keyvault.send(.toggleOpen(key: site.key)) }) {
+ SiteIcon(keyvault: keyvault, site: site.site)
+ } title: {
+ Text(site.site).lineLimit(1)
+ } detail: {
+ Text(site.counts)
+ } trailing: {
+ updated(site.updated)
+ LockButton(state: site.lock, name: site.site, unlock: site.unlockIds, lock: site.lockIds,
+ keyvault: keyvault, blocked: blocked)
+ }
+ case .files(_, let files):
+ GroupRow(indent: 1, selected: files.selected, open: files.open,
+ onSelect: { keyvault.send(.toggleGroup(key: files.key)) },
+ onOpen: { keyvault.send(.toggleOpen(key: files.key)) }) {
+ Image(systemName: "folder").foregroundStyle(.secondary).frame(width: 20)
+ } title: {
+ Text("Files").lineLimit(1)
+ } detail: {
+ Text("\(files.count) file\(files.count == 1 ? "" : "s")")
+ } trailing: {
+ LockButton(state: files.lock, name: "files", unlock: files.unlockIds, lock: files.lockIds,
+ keyvault: keyvault, blocked: blocked)
+ }
+ case .item(let row, let indent):
+ ItemRow(row: row, indent: indent, keyvault: keyvault, blocked: blocked)
+ }
+ }
+
+ private func updated(_ text: String) -> some View {
+ Text(text).font(.caption).foregroundStyle(.secondary).lineLimit(1)
+ }
+}
+
+/// A checkbox that is one of off, on or mixed.
+struct TriCheckbox: View {
+ let state: KvTri
+ let label: String
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: action) {
+ Image(systemName: state == .on ? "checkmark.square.fill" : state == .mixed ? "minus.square.fill" : "square")
+ .foregroundStyle(state == .off ? Color.secondary : Color.accentColor)
+ .imageScale(.large)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(label)
+ .accessibilityValue(state == .on ? "selected" : state == .mixed ? "some selected" : "not selected")
+ }
+}
+
+/// An app, a site or a file group: checkbox, disclosure, icon, name, detail.
+struct GroupRow<Icon: View, Title: View, Detail: View, Trailing: View>: View {
+ let indent: Int
+ let selected: KvTri
+ let open: Bool
+ let onSelect: () -> Void
+ let onOpen: () -> Void
+ @ViewBuilder let icon: Icon
+ @ViewBuilder let title: Title
+ @ViewBuilder let detail: Detail
+ @ViewBuilder let trailing: Trailing
+
+ init(indent: Int, selected: KvTri, open: Bool, onSelect: @escaping () -> Void, onOpen: @escaping () -> Void,
+ @ViewBuilder icon: () -> Icon, @ViewBuilder title: () -> Title, @ViewBuilder detail: () -> Detail,
+ @ViewBuilder trailing: () -> Trailing) {
+ self.indent = indent; self.selected = selected; self.open = open
+ self.onSelect = onSelect; self.onOpen = onOpen
+ self.icon = icon(); self.title = title(); self.detail = detail(); self.trailing = trailing()
+ }
+
+ var body: some View {
+ HStack(spacing: 8) {
+ TriCheckbox(state: selected, label: "Select", action: onSelect)
+ Button(action: onOpen) {
+ Image(systemName: open ? "chevron.down" : "chevron.right")
+ .font(.caption.weight(.semibold)).foregroundStyle(.secondary).frame(width: 12)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(open ? "Collapse" : "Expand")
+ icon
+ title
+ detail.font(.callout).foregroundStyle(.secondary).lineLimit(1)
+ Spacer(minLength: 8)
+ trailing
+ }
+ .padding(.leading, CGFloat(indent) * 22)
+ .padding(.vertical, 3)
+ .contentShape(Rectangle())
+ .onTapGesture(perform: onOpen)
+ }
+}
+
+/// One secret: its type icon, its key, its domain in grey, when it was
+/// saved in grey, and its lock. Never its value.
+struct ItemRow: View {
+ let row: KvVaultRow
+ let indent: Int
+ let keyvault: KeyvaultModel
+ let blocked: Bool
+
+ var body: some View {
+ HStack(spacing: 8) {
+ TriCheckbox(state: row.selected ? .on : .off, label: "Select \(row.title)") {
+ keyvault.send(.toggle(id: row.id))
+ }
+ Image(systemName: row.symbol).foregroundStyle(.secondary).frame(width: 20)
+ .help(row.kindLabel)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(row.title).lineLimit(1).truncationMode(.middle)
+ if !row.subtitle.isEmpty {
+ Text(row.subtitle).font(.caption).foregroundStyle(.secondary).lineLimit(1)
+ }
+ }
+ Spacer(minLength: 8)
+ Text(row.updated).font(.caption).foregroundStyle(.secondary).lineLimit(1)
+ LockButton(state: row.locked ? .locked : .unlocked, name: row.title,
+ unlock: row.locked && !row.identityProvider ? [row.id] : [],
+ lock: row.locked ? [] : [row.id], keyvault: keyvault, blocked: blocked,
+ help: row.lockHelp)
+ }
+ .padding(.leading, CGFloat(indent) * 22)
+ .padding(.vertical, 2)
+ .contentShape(Rectangle())
+ .onTapGesture { keyvault.send(.toggle(id: row.id)) }
+ .accessibilityElement(children: .contain)
+ .accessibilityIdentifier("vault-item-\(row.id)")
+ }
+}
+
+/// The lock: closed while every use needs approval, open once unattended
+/// access is allowed. A click flips it for what it stands for (an item, a
+/// site, an app); unlocking asks first, then Touch ID once.
+struct LockButton: View {
+ let state: KvLock
+ let name: String
+ let unlock: [String]
+ let lock: [String]
+ let keyvault: KeyvaultModel
+ let blocked: Bool
+ var help: String?
+
+ var body: some View {
+ Button {
+ Task {
+ if state == .unlocked { await keyvault.lock(ids: lock) }
+ else if !unlock.isEmpty { await keyvault.requestUnlock(ids: unlock, name: unlock.count == 1 ? name : nil) }
+ }
+ } label: {
+ Image(systemName: state.symbol)
+ .imageScale(.medium)
+ .foregroundStyle(state == .locked ? Color.secondary : Color.orange)
+ .opacity(state == .mixed ? 0.55 : 1)
+ .frame(width: 22, height: 22)
+ }
+ .buttonStyle(.plain)
+ .disabled(blocked || keyvault.busy || (state == .locked && unlock.isEmpty))
+ .help(help ?? (state == .unlocked ? "Unlocked. Click to lock." : state == .mixed ? "Some unlocked. Click to unlock the rest." : "Locked. Click to allow unattended access."))
+ .accessibilityLabel(state == .unlocked ? "Lock \(name)" : "Unlock \(name)")
+ .accessibilityValue(state == .unlocked ? "unlocked" : state == .mixed ? "partly unlocked" : "locked")
+ }
+}
+
+extension KvLock {
+ /// The SF Symbol: the core's, mirrored here for the closed and open lock.
+ var symbol: String {
+ switch self {
+ case .locked: return "lock.fill"
+ case .unlocked: return "lock.open"
+ case .mixed: return "lock.open"
+ }
+ }
+}
+
+/// The batch bar: what the selection can do, together.
+struct BatchBar: View {
+ let keyvault: KeyvaultModel
+ let selection: KvVaultSelection
+ let blocked: Bool
+
+ var body: some View {
+ HStack(spacing: 10) {
+ Text(selection.title).fontWeight(.medium)
+ Button("Clear") { keyvault.send(.clear) }.buttonStyle(.link)
+ Spacer()
+ Button { Task { await keyvault.lock(ids: selection.lockIds) } } label: {
+ Label("Lock", systemImage: "lock.fill")
+ }
+ .disabled(!selection.canLock || keyvault.busy)
+ .accessibilityIdentifier("batch-lock")
+ Button { Task { await keyvault.requestUnlock(ids: selection.unlockIds) } } label: {
+ Label("Unlock", systemImage: "lock.open")
+ }
+ .disabled(!selection.canUnlock || blocked || keyvault.busy)
+ .help(selection.alwaysAsk > 0 ? "Identity provider sessions always ask and stay locked." : "")
+ .accessibilityIdentifier("batch-unlock")
+ Button(role: .destructive) { keyvault.requestDelete(ids: selection.ids) } label: {
+ Label("Delete", systemImage: "trash")
+ }
+ .disabled(keyvault.busy)
+ .accessibilityIdentifier("batch-delete")
+ }
+ .padding(.horizontal, 16).padding(.vertical, 10)
+ .background(.bar)
+ .overlay(alignment: .top) { Divider() }
+ }
+}
+
+/// A site's icon (the browser's own, else Google's when allowed), else the
+/// globe. It asks for the icon once, as it first appears.
+struct SiteIcon: View {
+ let keyvault: KeyvaultModel
+ let site: String
+
+ var body: some View {
+ Group {
+ if let image = keyvault.siteIcons[site] {
+ Image(nsImage: image).resizable().interpolation(.high).clipShape(RoundedRectangle(cornerRadius: 3))
+ .frame(width: 16, height: 16)
+ } else {
+ Image(systemName: "globe").foregroundStyle(.secondary)
+ }
+ }
+ .frame(width: 20)
+ .accessibilityHidden(true)
+ .task(id: site) { await keyvault.siteIcon(site) }
+ }
+}
+
+/// An app's icon from the cache, else its first letter.
+struct AppIcon: View {
+ let keyvault: KeyvaultModel
+ let providerId: String
+ let name: String
+
+ var body: some View {
+ Group {
+ if let image = keyvault.icons[providerId] {
+ Image(nsImage: image).resizable().interpolation(.high)
+ } else {
+ RoundedRectangle(cornerRadius: 5).fill(Color.secondary.opacity(0.18))
+ .overlay(Text(String(name.prefix(1)).uppercased()).font(.system(size: 11, weight: .semibold)))
+ }
+ }
+ .frame(width: 22, height: 22)
+ .accessibilityHidden(true)
+ }
+}
+
+/// "Allow unattended access?": what unlocking allows, then Deny, Allow or
+/// Never ask again. Touch ID comes next, from the daemon.
+struct UnlockPromptSheet: View {
+ let prompt: KvUnlockPrompt
+ let onAnswer: (UnlockAnswer) -> Void
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(alignment: .top, spacing: 12) {
+ Image(systemName: "lock.open.fill").font(.system(size: 26)).foregroundStyle(.orange)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(prompt.title).font(.headline)
+ Text(prompt.subject).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)
+ }
+ }
+ Text(prompt.message).fixedSize(horizontal: false, vertical: true)
+ HStack {
+ Button(prompt.neverAsk) { onAnswer(.neverAskAgain) }
+ .accessibilityIdentifier("unlock-never-ask")
+ Spacer()
+ Button(prompt.deny) { onAnswer(.deny) }
+ .keyboardShortcut(.cancelAction)
+ .accessibilityIdentifier("unlock-deny")
+ Button(prompt.allow) { onAnswer(.allow) }
+ .keyboardShortcut(.defaultAction)
+ .buttonStyle(.borderedProminent)
+ .accessibilityIdentifier("unlock-allow")
+ }
+ }
+ .padding(20)
+ .frame(width: 440)
+ }
+}
+
+/// "Delete 3 items?": says when live copies in Spaces are wiped too.
+struct DeleteConfirmSheet: View {
+ let confirm: KvDeleteConfirm
+ let onDelete: () -> Void
+ let onCancel: () -> Void
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(alignment: .top, spacing: 12) {
+ Image(systemName: "trash").font(.system(size: 24)).foregroundStyle(.red)
+ Text(confirm.title).font(.headline)
+ }
+ Text(confirm.message).fixedSize(horizontal: false, vertical: true)
+ HStack {
+ Spacer()
+ Button(confirm.cancel, action: onCancel).keyboardShortcut(.cancelAction)
+ Button(confirm.confirm, role: .destructive, action: onDelete)
+ .keyboardShortcut(.defaultAction)
+ .accessibilityIdentifier("delete-confirm")
+ }
+ }
+ .padding(20)
+ .frame(width: 420)
+ }
+}
+
+/// Waiting, Access or Recent.
struct CategoryList: View {
@Bindable var keyvault: KeyvaultModel
let page: KvPage
@@ -116,15 +579,6 @@ struct CategoryList: View {
let list = keyvault.list
ScrollViewReader { proxy in
Form {
- if !list.sites.isEmpty {
- ForEach(list.sites, id: \.key) { group in
- Section(group.title) {
- ForEach(group.rows, id: \.item.id) { row in
- AccountRow(keyvault: keyvault, group: group, row: row, blocked: page.disabled)
- }
- }
- }
- }
if !list.pending.isEmpty {
Section {
ForEach(list.pending, id: \.id) { p in
@@ -181,14 +635,8 @@ struct CategoryList: View {
if let empty = list.emptyText {
Text(empty).foregroundStyle(.secondary)
}
- if keyvault.selection == .category(category: .all), !page.protection.isEmpty {
- Section(page.labels.protectionTitle) {
- ForEach(page.protection, id: \.label) { LabeledContent($0.label, value: $0.value) }
- }
- }
}
.formStyle(.grouped)
- .searchable(text: $keyvault.query)
.task(id: keyvault.focusKey) {
// A Space's "Signed in" badge: bring its row forward, then let
// the highlight go.
@@ -201,64 +649,6 @@ struct CategoryList: View {
}
}
-/// One account: its line and its unattended switch (identity providers
-/// always ask; turning it on makes the daemon ask for Touch ID).
-struct AccountRow: View {
- let keyvault: KeyvaultModel
- let group: KvSiteGroup
- let row: KvItemRow
- let blocked: Bool
-
- var body: some View {
- let state = row.consent.first { $0.kind != .asks }
- Toggle(isOn: Binding(
- get: { row.item.policy.unattended },
- set: { on in Task { await keyvault.setUnattended(itemIds: [row.item.id], on: on) } })) {
- HStack {
- Text(row.account).lineLimit(1)
- if let state {
- Text(state.text).foregroundStyle(.secondary).lineLimit(1)
- }
- }
- }
- .toggleStyle(.switch)
- .disabled(!row.toggleEnabled || blocked || keyvault.busy)
- .help(row.toggleHelp)
- .accessibilityLabel("Allow \(row.account) on \(group.title) unattended")
- }
-}
-
-/// A site: every account, with the site-wide switch when there is more
-/// than one.
-struct SiteDetailView: View {
- let keyvault: KeyvaultModel
- let detail: KvSiteDetail
- let blocked: Bool
-
- var body: some View {
- let labels = keyvault.page.labels
- Form {
- Section {
- LabeledContent(labels.appLabel, value: detail.group.app)
- if detail.siteSwitch {
- Toggle(labels.everyAccount, isOn: Binding(
- get: { detail.siteState == .on },
- set: { on in Task { await keyvault.toggleSite(detail.group, on: on) } }))
- .toggleStyle(.switch)
- .disabled(!detail.siteSwitchEnabled || blocked || keyvault.busy)
- .help(detail.siteSwitchHelp)
- }
- }
- Section(labels.accountsTitle) {
- ForEach(detail.group.rows, id: \.item.id) { row in
- AccountRow(keyvault: keyvault, group: detail.group, row: row, blocked: blocked)
- }
- }
- }
- .formStyle(.grouped)
- }
-}
-
/// The approval sheet: nothing is selected until the user ticks items;
/// Approve sends exactly those, and the Cua daemon confirms with Touch ID.
struct ApprovalSheet: View {
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift
index c0fb8d54cb..24fe2490a0 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift
@@ -143,10 +143,14 @@ struct Sidebar: View {
.badge(badge(row))
.tag(MainSelection.keyvault(.category(category: row.category)))
}
- ForEach(kv.sidebar.sites, id: \.key) { site in
- Text(site.title)
- .lineLimit(1)
- .tag(MainSelection.keyvault(.site(key: site.key)))
+ ForEach(kv.sidebar.apps, id: \.key) { app in
+ HStack(spacing: 8) {
+ AppIcon(keyvault: kv, providerId: app.key, name: app.title)
+ .frame(width: 18, height: 18)
+ Text(app.title).lineLimit(1)
+ }
+ .badge(Int(app.items))
+ .tag(MainSelection.keyvault(.app(key: app.key)))
}
} header: {
KeyvaultHeader(keyvault: kv, title: model.chrome.keyvaultTitle)
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SpaceDetailView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SpaceDetailView.swift
index e13500fc4e..bdee710d2e 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SpaceDetailView.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/SpaceDetailView.swift
@@ -339,6 +339,14 @@ struct SpaceDetailView: View {
do {
let context = try await model.backend.teleportContext(id: space.id)
let t = TeleportModel(spaceName: space.name, teleport: context?.0, space: context?.1)
+ // The review reads saved Keyvault items and a browser's sites
+ // from the Keyvault, and starts from what was sent last time.
+ t.keyvault = model.keyvault
+ t.rememberedChoices = model.settings.teleportChoices
+ t.onRemember = { [weak model] choices in
+ model?.settings.teleportChoices = choices
+ model?.saveSettings()
+ }
// From <Space>: the window's own stream, here, in a floating panel.
t.onStreamWindow = { [weak t] id in
if let w = streams?.window(id: id) ?? session?.windows.first(where: { $0.id == id }) {
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/TeleportPickerSheet.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/TeleportPickerSheet.swift
index dd3af7fc81..e8e8c4e32a 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/TeleportPickerSheet.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/TeleportPickerSheet.swift
@@ -101,43 +101,7 @@ struct TeleportPickerSheet: View {
@ViewBuilder private var review: some View {
if let review = teleport.review {
- Form {
- Section {
- ForEach(review.items, id: \.key) { item in
- LabeledContent(item.label) {
- Text(item.sensitive ? "Secret" : item.detail).foregroundStyle(.secondary)
- }
- }
- }
- if review.needsAcknowledgement {
- Toggle("Send the secrets listed above", isOn: Binding(
- get: { review.acknowledged },
- set: { teleport.send(.acknowledge(value: $0)) }))
- .toggleStyle(.checkbox)
- }
- if review.offersSaveToKeyvault {
- Toggle("Save to Keyvault for reuse", isOn: Binding(
- get: { review.saveToKeyvault },
- set: { teleport.send(.saveToKeyvault(value: $0)) }))
- .toggleStyle(.checkbox)
- .help("Keep this signed-in session sealed in your Cua Keyvault so it can " +
- "be delivered again without asking again.")
- }
- if review.needsRelayPlaintextAcknowledgement {
- Section {
- VStack(alignment: .leading, spacing: 4) {
- Toggle("Send without end-to-end encryption", isOn: Binding(
- get: { review.acknowledgedRelayPlaintext },
- set: { teleport.send(.acknowledgeRelayPlaintext(value: $0)) }))
- .toggleStyle(.checkbox)
- Text("This Space predates end-to-end sealing. The relay could read these secrets in transit.")
- .font(.caption)
- .foregroundStyle(.secondary)
- }
- }
- }
- }
- .formStyle(.grouped)
+ TeleportReview(teleport: teleport, review: review)
}
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/TeleportReviewViews.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/TeleportReviewViews.swift
new file mode 100644
index 0000000000..5885395924
--- /dev/null
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/TeleportReviewViews.swift
@@ -0,0 +1,267 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import CuaSpacesFFI
+import SwiftUI
+
+/// The consent review, as the vault list again: where it sends from (the
+/// live app, or the app's saved Keyvault items), which sites of a browser
+/// and which other items, with counts. What the review shows and what is
+/// sent are the core's; the SDK's approval check enforces them.
+struct TeleportReview: View {
+ @Bindable var teleport: TeleportModel
+ let review: AppReviewView
+
+ var body: some View {
+ Form {
+ if review.offersVault { source }
+ switch review.source {
+ case .vault:
+ Section("Saved in the Keyvault") { SavedItemsChoice(teleport: teleport) }
+ case .live:
+ if review.offersDomains { Section { sites } header: { Text("Sites") } }
+ if !review.toggles.isEmpty { Section("Also sent") { items } }
+ }
+ if review.offersPasswords {
+ Section {
+ Toggle(review.passwordsLabel, isOn: Binding(
+ get: { review.includePasswords },
+ set: { teleport.send(.togglePasswords(value: $0)) }))
+ .toggleStyle(.checkbox)
+ .accessibilityIdentifier("review-passwords")
+ Text("Off by default. Passwords are re-encrypted for the browser in the Space and need " +
+ "that browser to have been opened once.")
+ .font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ Section { summary }
+ if review.needsAcknowledgement {
+ Toggle("Send the secrets listed above", isOn: Binding(
+ get: { review.acknowledged },
+ set: { teleport.send(.acknowledge(value: $0)) }))
+ .toggleStyle(.checkbox)
+ }
+ if review.offersSaveToKeyvault && review.source == .live {
+ Toggle("Save to Keyvault for reuse", isOn: Binding(
+ get: { review.saveToKeyvault },
+ set: { teleport.send(.saveToKeyvault(value: $0)) }))
+ .toggleStyle(.checkbox)
+ .help("Keep these items sealed in your Cua Keyvault, grouped by app. Saving again " +
+ "updates them instead of adding copies.")
+ }
+ if review.needsRelayPlaintextAcknowledgement {
+ Section {
+ VStack(alignment: .leading, spacing: 4) {
+ Toggle("Send without end-to-end encryption", isOn: Binding(
+ get: { review.acknowledgedRelayPlaintext },
+ set: { teleport.send(.acknowledgeRelayPlaintext(value: $0)) }))
+ .toggleStyle(.checkbox)
+ Text("This Space predates end-to-end sealing. The relay could read these secrets in transit.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+ .formStyle(.grouped)
+ }
+
+ /// Live app or saved items.
+ private var source: some View {
+ Section {
+ Picker("Send from", selection: Binding(get: { review.source }, set: { s in
+ Task { await teleport.sendFrom(s) }
+ })) {
+ Text(review.liveLabel).tag(AppSendSource.live)
+ Text(review.vaultLabel).tag(AppSendSource.vault)
+ }
+ .pickerStyle(.radioGroup)
+ .accessibilityIdentifier("review-source")
+ if !review.sourceNote.isEmpty {
+ Text(review.sourceNote).font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ }
+
+ /// The browser's sites, with counts.
+ @ViewBuilder private var sites: some View {
+ if review.needsDomains {
+ HStack(spacing: 8) {
+ ProgressView().controlSize(.small)
+ Text("Reading the sites\u{2026}").foregroundStyle(.secondary)
+ }
+ } else if review.domains.isEmpty && review.domainQuery.isEmpty {
+ Text("No sites to choose. The cookies listed under Also sent are sent as they are.")
+ .font(.callout).foregroundStyle(.secondary)
+ } else {
+ HStack(spacing: 8) {
+ Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
+ TextField("Search sites", text: Binding(get: { review.domainQuery },
+ set: { teleport.send(.domainQuery(text: $0)) }))
+ .textFieldStyle(.plain)
+ Text(review.domainSummary).font(.caption).foregroundStyle(.secondary)
+ Button("All") { teleport.send(.selectShownDomains(value: true)) }.buttonStyle(.link)
+ Button("None") { teleport.send(.selectShownDomains(value: false)) }.buttonStyle(.link)
+ }
+ .accessibilityIdentifier("review-sites-search")
+ List {
+ ForEach(review.domains, id: \.domain) { d in
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 8) {
+ TriCheckbox(state: d.selected ? .on : .off, label: "Send \(d.domain)") {
+ teleport.send(.toggleDomain(domain: d.domain))
+ }
+ .disabled(!d.selectable)
+ Image(systemName: "globe").foregroundStyle(.secondary).frame(width: 18)
+ Text(d.domain).lineLimit(1)
+ Text(d.counts).font(.callout).foregroundStyle(.secondary).lineLimit(1)
+ Spacer(minLength: 8)
+ if d.identityProvider {
+ Text("Identity provider").font(.caption).foregroundStyle(.orange)
+ .help("Its session signs in to other apps. Send it only if you mean to.")
+ } else if d.signin {
+ Text("Signs you in").font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ // What cannot be read, greyed, with why.
+ if d.unavailable > 0 {
+ Text(d.unavailableNote).font(.caption).foregroundStyle(.tertiary).lineLimit(2)
+ .padding(.leading, 52)
+ .accessibilityIdentifier("review-site-unavailable-\(d.domain)")
+ }
+ }
+ .opacity(d.selectable ? 1 : 0.55)
+ .contentShape(Rectangle())
+ .onTapGesture { if d.selectable { teleport.send(.toggleDomain(domain: d.domain)) } }
+ .accessibilityElement(children: .contain)
+ .accessibilityIdentifier("review-site-\(d.domain)")
+ }
+ }
+ .listStyle(.inset)
+ .frame(height: min(CGFloat(max(review.domains.count, 1)) * 26 + CGFloat(review.domains.filter { $0.unavailable > 0 }.count) * 14 + 8, 190))
+ .accessibilityIdentifier("review-sites")
+ }
+ }
+
+ /// The other lines the user can turn off.
+ private var items: some View {
+ ForEach(review.toggles, id: \.key) { t in
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ TriCheckbox(state: t.selected ? .on : .off, label: "Send \(t.label)") {
+ teleport.send(.toggleItem(key: t.key))
+ }
+ VStack(alignment: .leading, spacing: 1) {
+ Text(t.label)
+ if !t.detail.isEmpty { Text(t.detail).font(.caption).foregroundStyle(.secondary) }
+ }
+ Spacer()
+ if t.sensitive { Text("Secret").font(.caption).foregroundStyle(.secondary) }
+ else if t.bytes > 0 { Text(ByteCountFormatter.string(fromByteCount: Int64(t.bytes), countStyle: .file)).font(.caption).foregroundStyle(.secondary) }
+ }
+ .contentShape(Rectangle())
+ .onTapGesture { teleport.send(.toggleItem(key: t.key)) }
+ }
+ }
+
+ private var summary: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ ForEach(review.items.filter { $0.kind == .install }, id: \.key) { i in
+ LabeledContent(i.label) { Text(i.detail).foregroundStyle(.secondary) }
+ }
+ ForEach(review.warnings, id: \.self) { Text($0).font(.caption).foregroundStyle(.secondary) }
+ }
+ }
+}
+
+/// The app's saved Keyvault items, to choose from: grouped by site with
+/// checkboxes, search and the names behind Touch ID.
+struct SavedItemsChoice: View {
+ @Bindable var teleport: TeleportModel
+
+ var body: some View {
+ if let view = teleport.reviewVaultView {
+ if view.namesHidden {
+ HStack(spacing: 10) {
+ Image(systemName: "eye.slash").foregroundStyle(.secondary)
+ Text(view.hiddenNote ?? "").foregroundStyle(.secondary)
+ Spacer()
+ Button(view.showNamesLabel) { Task { await teleport.keyvault?.showItems() } }
+ }
+ } else {
+ HStack(spacing: 8) {
+ Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
+ TextField("Search saved items", text: Binding(get: { teleport.reviewVault.query },
+ set: { teleport.sendVault(.query(text: $0)) }))
+ .textFieldStyle(.plain)
+ .lineLimit(1)
+ Text("\(view.selection.count) of \(view.shown) selected")
+ .font(.caption).foregroundStyle(.secondary)
+ Button("All") { teleport.sendVault(.selectAll) }.buttonStyle(.link)
+ Button("None") { teleport.sendVault(.clear) }.buttonStyle(.link)
+ }
+ List {
+ ForEach(VaultLine.lines(view).filter { line in
+ if case .app = line { return false }; return true
+ }, id: \.id) { line in
+ SavedLine(line: line, teleport: teleport)
+ }
+ }
+ .listStyle(.inset)
+ .frame(height: 190)
+ .accessibilityIdentifier("review-vault-list")
+ }
+ }
+ }
+}
+
+/// A site or an item of the saved list: a checkbox, no lock.
+struct SavedLine: View {
+ let line: VaultLine
+ let teleport: TeleportModel
+
+ var body: some View {
+ switch line {
+ case .site(_, let site):
+ row(selected: site.selected, key: site.key, icon: "globe", title: site.site, detail: site.counts,
+ open: site.open)
+ case .files(_, let files):
+ row(selected: files.selected, key: files.key, icon: "folder", title: "Files",
+ detail: "\(files.count) file\(files.count == 1 ? "" : "s")", open: files.open)
+ case .item(let item, _):
+ HStack(spacing: 8) {
+ TriCheckbox(state: item.selected ? .on : .off, label: "Send \(item.title)") {
+ teleport.sendVault(.toggle(id: item.id))
+ }
+ Image(systemName: item.symbol).foregroundStyle(.secondary).frame(width: 18)
+ VStack(alignment: .leading, spacing: 0) {
+ Text(item.title).lineLimit(1).truncationMode(.middle)
+ if !item.subtitle.isEmpty { Text(item.subtitle).font(.caption).foregroundStyle(.secondary).lineLimit(1) }
+ }
+ Spacer()
+ Text(item.updated).font(.caption).foregroundStyle(.secondary)
+ }
+ .padding(.leading, 40)
+ .contentShape(Rectangle())
+ .onTapGesture { teleport.sendVault(.toggle(id: item.id)) }
+ case .app:
+ EmptyView()
+ }
+ }
+
+ private func row(selected: KvTri, key: String, icon: String, title: String, detail: String, open: Bool) -> some View {
+ HStack(spacing: 8) {
+ TriCheckbox(state: selected, label: "Send \(title)") { teleport.sendVault(.toggleGroup(key: key)) }
+ Button { teleport.sendVault(.toggleOpen(key: key)) } label: {
+ Image(systemName: open ? "chevron.down" : "chevron.right").font(.caption.weight(.semibold))
+ .foregroundStyle(.secondary).frame(width: 12)
+ }
+ .buttonStyle(.plain)
+ Image(systemName: icon).foregroundStyle(.secondary).frame(width: 18)
+ Text(title).lineLimit(1)
+ Text(detail).font(.callout).foregroundStyle(.secondary).lineLimit(1)
+ Spacer()
+ }
+ .contentShape(Rectangle())
+ .onTapGesture { teleport.sendVault(.toggleOpen(key: key)) }
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultFixtures.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultFixtures.swift
new file mode 100644
index 0000000000..e3b383156f
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultFixtures.swift
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import CuaSDK
+import CuaSpacesFFI
+@testable import CuaSpacesMacKit
+import Foundation
+
+/// A simulated vault for the Keyvault tests and screenshots: realistic apps
+/// (Chrome, Slack, Arc), domains, cookies, localStorage values, passwords
+/// and files, and no real secret anywhere. The broker never returns a value,
+/// so a fixture has none either.
+enum KeyvaultFixtures {
+ static let now: Int64 = 1_800_000_000_000
+ static let minute: Int64 = 60_000
+ static let hour: Int64 = 3_600_000
+ static let day: Int64 = 86_400_000
+
+ static func item(_ id: String, app: (String, String), kind: String, domain: String?, key: String,
+ path: String? = nil, open: Bool = false, idp: Bool = false,
+ ago: Int64 = 3 * hour) -> KvItem {
+ KvItem(id: id, kind: kind, providerId: app.0, appDisplay: app.1, domain: domain, key: key, path: path,
+ source: "Default", session: false, expiresMs: nil, bytes: 64, blob: nil, identityProvider: idp,
+ policy: KvItemPolicy(allowedTargets: [], ttlSecs: 3600, unattended: open),
+ createdMs: UInt64(now - 9 * day), updatedMs: UInt64(now - ago), rev: 1, recordDigest: "00")
+ }
+
+ static let chrome = ("chrome", "Google Chrome")
+ static let slack = ("slack", "Slack")
+ static let arc = ("arc", "Arc")
+
+ /// Three apps, a dozen sites, one identity provider, a few unlocked.
+ static func items() -> [KvItem] {
+ var out: [KvItem] = []
+ func cookie(_ id: String, _ app: (String, String), _ domain: String, _ key: String, open: Bool = false,
+ idp: Bool = false, ago: Int64 = 3 * hour) {
+ out.append(item(id, app: app, kind: "cookie", domain: domain, key: key, path: "/", open: open, idp: idp, ago: ago))
+ }
+ cookie("c-gh-1", chrome, ".github.com", "user_session", open: true, ago: 5 * minute)
+ cookie("c-gh-2", chrome, ".github.com", "logged_in", open: true, ago: 5 * minute)
+ cookie("c-gh-3", chrome, "api.github.com", "_gh_sess", ago: 5 * minute)
+ cookie("c-gh-4", chrome, ".github.com", "dotcom_user", ago: 5 * minute)
+ out.append(item("p-gh", app: chrome, kind: "password", domain: "https://github.com", key: "octocat", ago: 2 * day))
+ out.append(item("l-gh", app: chrome, kind: "local_storage", domain: "https://github.com", key: "color_mode", ago: 5 * minute))
+ cookie("c-no-1", chrome, ".notion.so", "token_v2", ago: 2 * hour)
+ cookie("c-no-2", chrome, ".notion.so", "notion_user_id", ago: 2 * hour)
+ out.append(item("l-no", app: chrome, kind: "local_storage", domain: "https://www.notion.so", key: "LRU:spaceId", ago: 2 * hour))
+ cookie("c-li-1", chrome, ".linear.app", "linear_session", open: true, ago: 26 * hour)
+ cookie("c-am-1", chrome, ".amazon.com", "session-id", ago: 3 * day)
+ cookie("c-am-2", chrome, ".amazon.com", "ubid-main", ago: 3 * day)
+ cookie("c-go-1", chrome, ".google.com", "SID", idp: true, ago: 4 * hour)
+ cookie("c-go-2", chrome, ".google.com", "__Secure-1PSID", idp: true, ago: 4 * hour)
+ out.append(item("p-li", app: chrome, kind: "password", domain: "https://linear.app", key: "[email protected]", ago: 4 * day))
+ out.append(item("f-bm", app: chrome, kind: "file", domain: nil, key: "Default/Bookmarks", ago: 5 * minute))
+ out.append(item("f-pr", app: chrome, kind: "file", domain: nil, key: "Default/Preferences", ago: 5 * minute))
+ out.append(item("f-ls", app: chrome, kind: "file", domain: nil, key: "Local State", ago: 5 * minute))
+ cookie("c-sl-1", slack, ".slack.com", "d", open: true, ago: 40 * minute)
+ cookie("c-sl-2", slack, ".slack.com", "d-s", open: true, ago: 40 * minute)
+ out.append(item("l-sl", app: slack, kind: "local_storage", domain: "https://app.slack.com", key: "localConfig_v2", ago: 40 * minute))
+ out.append(item("f-sl-1", app: slack, kind: "file", domain: nil, key: "storage/root-state.json", ago: 40 * minute))
+ out.append(item("f-sl-2", app: slack, kind: "file", domain: nil, key: "storage/slack-workspaces", ago: 40 * minute))
+ cookie("c-fi-1", arc, ".figma.com", "__Host-figma.authn", ago: 6 * day)
+ cookie("c-fi-2", arc, ".figma.com", "figma.st", ago: 6 * day)
+ cookie("c-vc-1", arc, ".vercel.com", "authorization", ago: 6 * day)
+ out.append(item("f-arc", app: arc, kind: "file", domain: nil, key: "StorableSidebar.json", ago: 6 * day))
+ return out
+ }
+
+ static func status(skipPrompt: Bool = false) -> KvStatus {
+ KvStatus(version: "0.1.0", initialized: true, unlocked: true, disabled: false, callerFirstParty: true,
+ callerDisplay: "Cua Spaces", items: 27, pending: 0, unlockPolicy: "auto", autoWipe: false,
+ osProtectorAvailable: true, passphraseAvailable: true, unlockProtectors: ["macos-keychain"],
+ browseUntilMs: nil, skipUnlockPrompt: skipPrompt, resetNotice: nil)
+ }
+
+ /// The vault as the broker serves it (`namesVisible`: the user opened
+ /// the browse window with Touch ID).
+ static func overview(namesVisible: Bool = true, skipPrompt: Bool = false) -> KeyvaultOverview {
+ var all = items()
+ if !namesVisible {
+ all = all.map { i in
+ var r = i
+ r.domain = nil
+ r.key = ""
+ r.path = nil
+ r.source = ""
+ return r
+ }
+ }
+ return KeyvaultOverview(availability: "ready", message: nil, status: status(skipPrompt: skipPrompt),
+ serverVerified: true, items: all, namesVisible: namesVisible,
+ itemsTotal: UInt32(all.count), pending: [], grants: [], rules: [], deliveries: [],
+ audit: [], auditVerification: nil, partialErrors: [])
+ }
+
+ /// A Chrome inventory with counts per site, as the review shows it.
+ static func chromeInventory() -> KvInventory {
+ func d(_ domain: String, cookies: UInt32, ls: UInt32 = 0, session: UInt32 = 0, passwords: UInt32 = 0,
+ unavailable: UInt32 = 0, signin: Bool, idp: Bool = false) -> KvDomainCount {
+ KvDomainCount(domain: domain, cookies: cookies, sessionCookies: session, localStorage: ls,
+ passwords: passwords, signin: signin, identityProvider: idp, unavailable: unavailable,
+ unavailableReason: unavailable == 0 ? "" :
+ "Chrome protects it with app-bound encryption, which only Chrome itself can unlock on this PC")
+ }
+ return KvInventory(providerId: "chrome", appDisplay: "Google Chrome", domains: [
+ d("amazon.com", cookies: 14, signin: true),
+ d("bank.example", cookies: 0, unavailable: 3, signin: true),
+ d("doubleclick.net", cookies: 9, signin: false),
+ d("github.com", cookies: 12, ls: 3, session: 4, passwords: 2, signin: true),
+ d("google.com", cookies: 31, signin: true, idp: true),
+ d("linear.app", cookies: 6, ls: 2, signin: true),
+ d("notion.so", cookies: 8, ls: 5, signin: true),
+ d("nytimes.com", cookies: 22, signin: false),
+ d("slack.com", cookies: 5, signin: true),
+ ], notes: [])
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultIconTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultIconTests.swift
new file mode 100644
index 0000000000..f6ce1dc883
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultIconTests.swift
@@ -0,0 +1,241 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import AppKit
+import CuaSpacesFFI
+@testable import CuaSpacesMacKit
+import Foundation
+import Testing
+
+/// Icons and memoization: app icons resolved once per app and version, site
+/// icons from the browser's own store first, then one capped lookup, then the
+/// globe; and the list model recomputed only when the vault or search change.
+@MainActor
+@Suite("Keyvault icons")
+struct KeyvaultIconTests {
+ nonisolated static func png(_ side: Int = 8, _ shade: CGFloat = 0.3) -> Data {
+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: side, pixelsHigh: side, bitsPerSample: 8,
+ samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,
+ bytesPerRow: 0, bitsPerPixel: 0)!
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
+ NSColor(white: shade, alpha: 1).setFill()
+ NSRect(x: 0, y: 0, width: side, height: side).fill()
+ NSGraphicsContext.restoreGraphicsState()
+ return rep.representation(using: .png, properties: [:])!
+ }
+
+ func tempDir() -> URL {
+ FileManager.default.temporaryDirectory.appendingPathComponent("cua-icons-\(UUID().uuidString)")
+ }
+
+ /// Counts what a fetch asked for.
+ final class Net: @unchecked Sendable {
+ let lock = NSLock()
+ var urls: [URL] = []
+ var status = 200
+ var body = KeyvaultIconTests.png()
+ var inFlight = 0
+ var peak = 0
+ func fetch(_ url: URL) async throws -> (Data, Int) {
+ lock.lock(); urls.append(url); inFlight += 1; peak = max(peak, inFlight); lock.unlock()
+ try await Task.sleep(nanoseconds: 20_000_000)
+ lock.lock(); inFlight -= 1; let r = (body, status); lock.unlock()
+ return r
+ }
+ }
+
+ // MARK: App icons
+
+ @Test func anAppIsResolvedOnceNotPerRenderAndSurvivesARestart() throws {
+ let dir = tempDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ final class Count: @unchecked Sendable { var resolved = 0; var drawn = 0 }
+ let count = Count()
+ let make: @Sendable (String) -> AppIconCache.Resolver = { version in
+ { _, _ in
+ count.resolved += 1
+ return AppIconSource(bundleId: "com.google.Chrome", version: version) { count.drawn += 1; return Self.png() }
+ }
+ }
+ let cache = AppIconCache(dir: dir, resolver: make("131.0"))
+ for _ in 0..<50 { #expect(cache.image(providerId: "chrome", name: "Google Chrome") != nil) }
+ #expect(count.resolved == 1 && count.drawn == 1, "50 renders, one NSWorkspace lookup and one drawing")
+ #expect(FileManager.default.fileExists(atPath: dir.appendingPathComponent("com.google.Chrome-131.0.png").path))
+ // A restart reads the PNG from disk: the app is looked up, not drawn.
+ let again = AppIconCache(dir: dir, resolver: make("131.0"))
+ #expect(again.image(providerId: "chrome", name: "Google Chrome") != nil)
+ #expect(count.drawn == 1)
+ // An update changes the version, so the icon is drawn again.
+ let updated = AppIconCache(dir: dir, resolver: make("132.0"))
+ #expect(updated.image(providerId: "chrome", name: "Google Chrome") != nil)
+ #expect(count.drawn == 2)
+ // An app that is not installed stays a letter and is not asked again.
+ let none = AppIconCache(dir: dir, resolver: { _, _ in count.resolved += 1; return nil })
+ let before = count.resolved
+ #expect(none.image(providerId: "arc", name: "Arc") == nil)
+ #expect(none.image(providerId: "arc", name: "Arc") == nil)
+ #expect(count.resolved == before + 1)
+ }
+
+ // MARK: Site icons
+
+ @Test func onlyAPlainRegistrableDomainIsEverSent() {
+ for good in ["github.com", "notion.so", "linear.app", "bbc.co.uk", "xn--bcher-kva.example.org"] {
+ #expect(SiteIconStore.sendable(good), "\(good)")
+ }
+ for bad in ["", "localhost", "intranet", "router.local", "192.168.0.1", "10.0.0.5", "a.com/path", "a b.com",
+ "[email protected]", "x.com?y=1", ".com", "a..com", "https://github.com"] {
+ #expect(!SiteIconStore.sendable(bad), "\(bad)")
+ }
+ let url = SiteIconStore.url(for: "GitHub.com", scale: 2)?.absoluteString
+ #expect(url == "https://www.google.com/s2/favicons?domain=github.com&sz=128")
+ #expect(SiteIconStore.url(for: "github.com", scale: 1)?.absoluteString.hasSuffix("&sz=64") == true)
+ }
+
+ @Test func aDomainIsFetchedAtMostOnceAndCachedAcrossRestarts() async {
+ let dir = tempDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let net = Net()
+ let store = SiteIconStore(dir: dir, fetch: net.fetch)
+ #expect(store.cached("github.com") == nil)
+ #expect(await store.load("github.com", scale: 2) != nil)
+ #expect(await store.load("github.com", scale: 2) != nil)
+ #expect(net.urls.count == 1)
+ let restarted = SiteIconStore(dir: dir, fetch: net.fetch)
+ #expect(restarted.cached("github.com") != nil, "from disk, no network")
+ #expect(await restarted.load("github.com", scale: 2) != nil)
+ #expect(net.urls.count == 1)
+ }
+
+ @Test func aMissIsRememberedForAWeekThenRetried() async {
+ let dir = tempDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let net = Net()
+ net.status = 404
+ final class Clock: @unchecked Sendable { var now = Date() }
+ let clock = Clock()
+ let store = SiteIconStore(dir: dir, now: { clock.now }, fetch: net.fetch)
+ #expect(await store.load("nosuch.example.org", scale: 2) == nil)
+ #expect(store.recentMiss("nosuch.example.org"))
+ #expect(await store.load("nosuch.example.org", scale: 2) == nil)
+ #expect(net.urls.count == 1, "a miss is not asked again")
+ clock.now = clock.now.addingTimeInterval(6 * 86_400)
+ #expect(await store.load("nosuch.example.org", scale: 2) == nil)
+ #expect(net.urls.count == 1)
+ clock.now = clock.now.addingTimeInterval(2 * 86_400)
+ net.status = 200
+ #expect(await store.load("nosuch.example.org", scale: 2) != nil, "retried after a week")
+ #expect(net.urls.count == 2)
+ }
+
+ @Test func aFailedNetworkIsNotRememberedAsAMiss() async {
+ let dir = tempDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ struct Offline: Error {}
+ let store = SiteIconStore(dir: dir, fetch: { _ in throw Offline() })
+ #expect(await store.load("github.com", scale: 2) == nil)
+ #expect(!store.recentMiss("github.com"))
+ }
+
+ @Test func nothingElseThanAPlainImageIsKept() async {
+ let dir = tempDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let net = Net()
+ net.body = Data("<html>not an icon</html>".utf8)
+ let store = SiteIconStore(dir: dir, fetch: net.fetch)
+ #expect(await store.load("github.com", scale: 2) == nil)
+ #expect(store.cached("github.com") == nil)
+ #expect(store.recentMiss("github.com"))
+ }
+
+ @Test func fetchesRunAFewAtATime() async {
+ let net = Net()
+ let store = SiteIconStore(dir: tempDir(), maxConcurrent: 3, fetch: net.fetch)
+ await withTaskGroup(of: Void.self) { group in
+ for i in 0..<12 { group.addTask { _ = await store.load("site\(i).com", scale: 2) } }
+ }
+ #expect(net.urls.count == 12)
+ #expect(net.peak <= 3, "peak \(net.peak)")
+ }
+
+ // MARK: The model: local first, then Google when allowed, then the globe
+
+ func model(favicons: [KvFavicon] = [], net: Net, google: Bool = true) async -> (KeyvaultModel, FakeKeyvault) {
+ let fake = FakeKeyvault(KeyvaultFixtures.overview())
+ fake.favicons = favicons
+ let m = KeyvaultModel(client: fake, clock: { Date(timeIntervalSince1970: Double(KeyvaultFixtures.now) / 1000) })
+ m.siteIconStore = SiteIconStore(dir: tempDir(), fetch: net.fetch)
+ m.siteIconsFromGoogle = { google }
+ await m.refresh()
+ return (m, fake)
+ }
+
+ @Test func theBrowsersOwnIconWinsAndNeedsNoNetwork() async {
+ let net = Net()
+ let local = KvFavicon(site: "github.com", png: Self.png(16, 0.8).base64EncodedString())
+ let (m, _) = await model(favicons: [local], net: net)
+ await m.loadIcons()
+ #expect(m.siteIcons["github.com"] != nil)
+ await m.siteIcon("github.com")
+ #expect(net.urls.isEmpty)
+ // Another site the browser had none for: one lookup of that domain.
+ await m.siteIcon("notion.so")
+ #expect(net.urls.map(\.absoluteString) == ["https://www.google.com/s2/favicons?domain=notion.so&sz=128"])
+ #expect(m.siteIcons["notion.so"] != nil)
+ await m.siteIcon("notion.so")
+ #expect(net.urls.count == 1)
+ }
+
+ @Test func withTheSettingOffOnlyLocalIconsShowAndNothingIsSent() async {
+ let net = Net()
+ let local = KvFavicon(site: "github.com", png: Self.png().base64EncodedString())
+ let (m, _) = await model(favicons: [local], net: net, google: false)
+ await m.loadIcons()
+ await m.siteIcon("github.com")
+ await m.siteIcon("notion.so")
+ await m.siteIcon("linear.app")
+ #expect(net.urls.isEmpty)
+ #expect(m.siteIcons["github.com"] != nil)
+ #expect(m.siteIcons["notion.so"] == nil, "the globe stands in")
+ }
+
+ @Test func theGoogleSwitchIsASettingOnByDefault() async throws {
+ let fake = FakeKeyvault(KeyvaultFixtures.overview())
+ let app = ViewModelTests().makeModel(kv: fake)
+ await app.keyvault.refresh()
+ await app.loadSettings()
+ let row = try #require(app.settingsPage.sections.first { $0.id == "keyvault" }?.rows.first { $0.id == "keyvault-site-icons" })
+ #expect(row.label == "Load site icons from Google")
+ #expect(row.options.first { $0.id == "on" }?.active == true)
+ await app.choose(row: "keyvault-site-icons", option: "off")
+ #expect(app.settings.keyvaultSiteIcons == false)
+ #expect(app.keyvault.siteIconsFromGoogle() == false)
+ let again = try #require(app.settingsPage.sections.first { $0.id == "keyvault" }?.rows.first { $0.id == "keyvault-site-icons" })
+ #expect(again.options.first { $0.id == "off" }?.active == true)
+ }
+
+ // MARK: Memoization
+
+ @Test func theListModelRecomputesOnlyWhenTheVaultOrSearchChange() async {
+ let (m, _) = await model(net: Net())
+ let k = m
+ let base = k.computes["vaultView", default: 0]
+ for _ in 0..<40 { _ = k.vaultView; _ = k.sidebar; _ = k.page }
+ #expect(k.computes["vaultView", default: 0] <= base + 1, "40 renders, one computation")
+ #expect(k.computes["sidebar", default: 0] <= 1)
+ let once = k.computes["vaultView", default: 0]
+ k.query = "github"
+ _ = k.vaultView
+ _ = k.vaultView
+ #expect(k.computes["vaultView"] == once + 1, "a search recomputes once")
+ k.send(KvVaultAction.toggleGroup(key: "chrome|github.com"))
+ _ = k.vaultView
+ #expect(k.computes["vaultView"] == once + 2)
+ await k.refresh()
+ _ = k.vaultView
+ _ = k.vaultView
+ #expect(k.computes["vaultView"] == once + 3, "a refresh recomputes once")
+ #expect(k.vaultView.apps.flatMap(\.sites).allSatisfy { $0.site.contains("github") })
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultReviewTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultReviewTests.swift
new file mode 100644
index 0000000000..2c2804ba8f
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultReviewTests.swift
@@ -0,0 +1,280 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import AppKit
+import CuaSDK
+import CuaSpacesFFI
+@testable import CuaSpacesMacKit
+import SwiftUI
+import Testing
+
+/// The teleport review as the vault list again: a browser's sites with
+/// counts and a minimal default, what was picked last time, the Keyvault as
+/// the source, and the choices reaching the SDK consent. With
+/// `KEYVAULT_EXPORT_DIR` set, the screenshots and GIFs of the redesign are
+/// exported too (see KeyvaultSnapshotTests).
+@MainActor
+@Suite("Keyvault review", .serialized)
+struct KeyvaultReviewTests {
+ let snap = SnapshotTests()
+ static let list = CGSize(width: 780, height: 560)
+
+ func model(_ overview: KeyvaultOverview = KeyvaultFixtures.overview(),
+ icons: Bool = false) async -> (AppModel, FakeKeyvault) {
+ await KeyvaultSnapshotTests().model(overview, icons: icons)
+ }
+
+ var useRealIcons: Bool { ProcessInfo.processInfo.environment["KEYVAULT_REAL_ICONS"] == "1" }
+
+ func vault(_ m: AppModel) -> some View {
+ VaultList(keyvault: m.keyvault, page: m.keyvault.page)
+ }
+
+ static let chromePlan = """
+ {"app":{"id":"com.google.Chrome","name":"Google Chrome","capability":"full","moves":["app_only","app_with_state"],
+ "providerId":"chrome","sensitiveGroups":["sign_ins"],"json":"{}"},
+ "spaceId":"local:aurora","moves":"app_with_state","steps":[],
+ "consent":[
+ {"kind":"install","key":"chrome","label":"Google Chrome","detail":"pinned, verified by sha256 0cfabe56","bytes":0,"sensitive":false},
+ {"kind":"state","key":"Default/Bookmarks","label":"Bookmarks","detail":"212 bookmarks","bytes":184320,"sensitive":false},
+ {"kind":"state","key":"Default/Preferences","label":"Preferences","detail":"Settings and extensions","bytes":22016,"sensitive":false},
+ {"kind":"secret","key":".config/google-chrome/Default/Cookies","label":"Cookies","detail":"Keeps you signed in","bytes":1228800,"sensitive":true}],
+ "sensitive":true,"totalBytes":1435136,"warnings":[],"relayUnsealed":false,"json":"{}"}
+ """
+
+ /// A review of Chrome's state on its way to Aurora, as the picker reaches
+ /// it: planned, with the sites and the saved items asked for.
+ func reviewModel(vault: Bool = false) async throws -> (TeleportModel, FakeKeyvault) {
+ let (m, fake) = await model(icons: useRealIcons)
+ let t = TeleportModel(spaceName: "aurora", teleport: nil, space: nil)
+ t.keyvault = m.keyvault
+ let entry = try #require(try appCatalogEntriesFromJson(json: """
+ [{"id":"com.google.Chrome","name":"Google Chrome","capability":"full","moves":["app_only","app_with_state"],
+ "providerId":"chrome","sensitiveGroups":["sign_ins"],"json":"{}"}]
+ """).first)
+ t.send(.preselect(entry: entry, files: []))
+ t.send(.move(moves: .appWithState))
+ t.send(.sensitive(group: .signIns, value: true))
+ t.send(.plan)
+ t.send(.planned(plan: try appTeleportPlanFromJson(json: Self.chromePlan)))
+ await t.loadChoices()
+ t.send(.acknowledge(value: true))
+ if vault {
+ await t.sendFrom(.vault)
+ t.sendVault(.toggleOpen(key: "chrome|github.com"))
+ }
+ return (t, fake)
+ }
+
+ @Test func reviewListsSitesWithCountsAndStartsMinimal() async throws {
+ let (t, fake) = try await reviewModel()
+ let review = try #require(t.review)
+ #expect(fake.inventoryAsks == 1)
+ #expect(review.offersDomains && !review.needsDomains)
+ #expect(review.domainSummary == "5 of 9 sites", "sign-in sites, never the identity provider")
+ #expect(!review.selectedDomains.contains("google.com") && !review.selectedDomains.contains("doubleclick.net"))
+ #expect(review.domains.first { $0.domain == "github.com" }?.counts == "12 cookies, 3 storage values, 2 passwords")
+ #expect(review.offersVault && review.vault.items == 16, "Chrome has 16 saved items a teleport can send (not its 2 passwords)")
+ #expect(review.source == .live)
+ let consent = appPickerConsent(state: t.state)
+ #expect(consent.cookieDomains == review.selectedDomains && consent.fromVault == nil)
+ try snap.assertSnapshot(TeleportReview(teleport: t, review: review), "keyvault-review-sites",
+ size: CGSize(width: 640, height: 760))
+ }
+
+ @Test func cookiesTheBrowserCannotReleaseAreGreyedWithWhyAndNeverSent() async throws {
+ let (t, _) = try await reviewModel()
+ let bank = try #require(t.review?.domains.first { $0.domain == "bank.example" })
+ #expect(!bank.selectable && bank.unavailable == 3)
+ #expect(bank.unavailableNote.hasPrefix("3 cookies cannot be sent: Chrome protects it with app-bound encryption"))
+ // It starts unchecked and a tap does nothing.
+ #expect(!bank.selected)
+ t.send(.toggleDomain(domain: "bank.example"))
+ #expect(appPickerConsent(state: t.state).cookieDomains?.contains("bank.example") == false)
+ t.send(.selectShownDomains(value: true))
+ #expect(appPickerConsent(state: t.state).cookieDomains?.contains("bank.example") == false)
+ }
+
+ @Test func savedPasswordsAreAnExplicitOffByDefaultChoice() async throws {
+ // From the app: the chosen sites' passwords (github.com has 2).
+ let (t, _) = try await reviewModel()
+ let review = try #require(t.review)
+ #expect(review.offersPasswords && !review.includePasswords)
+ #expect(review.passwordsLabel == "Also send 2 saved passwords")
+ #expect(!appPickerConsent(state: t.state).includePasswords)
+ t.send(.togglePasswords(value: true))
+ #expect(appPickerConsent(state: t.state).includePasswords)
+ #expect(sdkConsent(appPickerConsent(state: t.state)).includePasswords, "carried over to the SDK consent")
+ // Dropping the only site that has passwords takes the offer away.
+ t.send(.toggleDomain(domain: "github.com"))
+ #expect(t.review?.offersPasswords == false)
+ #expect(!appPickerConsent(state: t.state).includePasswords)
+ // From the Keyvault: its saved passwords, only when ticked.
+ let (v, _) = try await reviewModel(vault: true)
+ #expect(v.review?.passwordsLabel == "Also send 2 saved passwords")
+ #expect(appPickerConsent(state: v.state).fromVault?.count == 16)
+ v.send(.togglePasswords(value: true))
+ #expect(appPickerConsent(state: v.state).fromVault?.count == 18)
+ }
+
+ @Test func reviewCanSendFromTheSavedItemsWithoutReadingTheApp() async throws {
+ let (t, _) = try await reviewModel(vault: true)
+ let review = try #require(t.review)
+ #expect(review.source == .vault)
+ #expect(review.sourceNote == "Nothing is read from this Mac, so macOS does not ask for Keychain access.")
+ let consent = appPickerConsent(state: t.state)
+ #expect(consent.cookieDomains == nil)
+ #expect(consent.fromVault?.count == 16)
+ // Deselect a site's items: only the rest are sent.
+ t.sendVault(.toggleGroup(key: "chrome|github.com"))
+ #expect(appPickerConsent(state: t.state).fromVault?.count == 11, "github.com has 5 items a teleport can send")
+ t.sendVault(.toggleGroup(key: "chrome|github.com"))
+ try snap.assertSnapshot(TeleportReview(teleport: t, review: try #require(t.review)),
+ "keyvault-review-vault", size: CGSize(width: 640, height: 760))
+ }
+
+ @Test func aFailedSiteReadFallsBackToThePlanAsListed() async throws {
+ let (m, fake) = await model()
+ fake.inventoryFails = true
+ let t = TeleportModel(spaceName: "aurora", teleport: nil, space: nil)
+ t.keyvault = m.keyvault
+ let entry = try #require(try appCatalogEntriesFromJson(json: """
+ [{"id":"com.google.Chrome","name":"Google Chrome","capability":"full","moves":["app_only","app_with_state"],
+ "providerId":"chrome","sensitiveGroups":["sign_ins"],"json":"{}"}]
+ """).first)
+ t.send(.preselect(entry: entry, files: []))
+ t.send(.move(moves: .appWithState))
+ t.send(.plan)
+ t.send(.planned(plan: try appTeleportPlanFromJson(json: Self.chromePlan)))
+ await t.loadChoices()
+ let review = try #require(t.review)
+ #expect(!review.needsDomains && review.domains.isEmpty)
+ #expect(appPickerConsent(state: t.state).cookieDomains == nil, "sent exactly as the plan lists it")
+ #expect(review.toggles.contains { $0.key.hasSuffix("Cookies") }, "the cookie line is a plain line")
+ }
+
+ @Test func whatWasPickedLastTimeStartsTheNextReview() async throws {
+ let (m, _) = await model()
+ let t = TeleportModel(spaceName: "aurora", teleport: nil, space: nil)
+ t.keyvault = m.keyvault
+ t.rememberedChoices = appReviewRemember(choices: [], key: appReviewRememberKey(app: "chrome", space: "aurora"),
+ domains: ["doubleclick.net", "nytimes.com"])
+ let entry = try #require(try appCatalogEntriesFromJson(json: """
+ [{"id":"com.google.Chrome","name":"Google Chrome","capability":"full","moves":["app_only","app_with_state"],
+ "providerId":"chrome","sensitiveGroups":["sign_ins"],"json":"{}"}]
+ """).first)
+ t.send(.preselect(entry: entry, files: []))
+ t.send(.move(moves: .appWithState))
+ t.send(.plan)
+ t.send(.planned(plan: try appTeleportPlanFromJson(json: Self.chromePlan)))
+ await t.loadChoices()
+ #expect(t.review?.selectedDomains == ["doubleclick.net", "nytimes.com"])
+ var saved: [AppRememberedChoice] = []
+ t.onRemember = { saved = $0 }
+ t.send(.toggleDomain(domain: "github.com"))
+ t.rememberChoice()
+ #expect(saved.first?.domains == ["doubleclick.net", "github.com", "nytimes.com"])
+ }
+
+ // MARK: - Exported screenshots and GIFs (KEYVAULT_EXPORT_DIR)
+
+ @Test func exportScreenshotsAndGifs() async throws {
+ guard let dir = ProcessInfo.processInfo.environment["KEYVAULT_EXPORT_DIR"], !dir.isEmpty else { return }
+ let out = URL(fileURLWithPath: dir)
+ try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)
+ let size = Self.list
+ let recorder = Recorder(snap: snap, size: size, dir: out)
+
+ // Unlock a batch: select a site, Unlock, the prompt, Allow.
+ do {
+ let (m, _) = await model(icons: true)
+ m.keyvault.send(.toggleOpen(key: "chrome|github.com"))
+ recorder.frame("Vault list: apps, sites, items. Locked by default.", vault(m), delay: 1.4)
+ m.keyvault.send(.toggleGroup(key: "chrome|github.com"))
+ recorder.frame("Select a site: its 6 items are selected.", vault(m), delay: 1.4)
+ let ids = m.keyvault.vaultView.selection.unlockIds
+ await m.keyvault.requestUnlock(ids: ids)
+ let prompt = try #require(m.keyvault.unlockPrompt?.prompt)
+ recorder.frame("Unlock asks first, once for the whole batch.", vault(m), over: UnlockPromptSheet(prompt: prompt) { _ in },
+ sheetSize: CGSize(width: 440, height: 220), delay: 2.4)
+ await m.keyvault.answerUnlock(.allow)
+ recorder.frame("Allow: Touch ID is asked once, then the items are unlocked.", vault(m), delay: 2.0)
+ try recorder.finish("keyvault-unlock-batch")
+ }
+ // Search filters by domain, key, app or type.
+ do {
+ let (m, _) = await model(icons: true)
+ for q in ["", "n", "no", "not", "notion", "cookie github", "slack"] {
+ m.keyvault.query = q
+ recorder.frame(q.isEmpty ? "Search by domain, key, app or type." : "Search: \(q)", vault(m), delay: q.isEmpty ? 1.2 : 1.0)
+ }
+ try recorder.finish("keyvault-search")
+ }
+ // Delete wipes live copies too.
+ do {
+ var o = KeyvaultFixtures.overview()
+ o.deliveries = [KvDelivery(importId: "imp-1", target: "local:aurora", providerId: "chrome",
+ items: ["c-gh-1", "c-gh-2"], callerFp: "fp", deliveredMs: UInt64(KeyvaultFixtures.now - 600_000),
+ expiresMs: 0, wiped: false)]
+ let (m, _) = await model(o, icons: true)
+ m.keyvault.send(.toggleGroup(key: "arc|figma.com"))
+ recorder.frame("Select Figma's cookies in Arc.", vault(m), delay: 1.2)
+ m.keyvault.send(.clear)
+ m.keyvault.send(.toggleGroup(key: "chrome|github.com"))
+ recorder.frame("Select github.com in Chrome and delete it.", vault(m), delay: 1.2)
+ m.keyvault.requestDelete(ids: m.keyvault.vaultView.selection.ids)
+ let c = try #require(m.keyvault.deleteConfirm?.confirm)
+ recorder.frame("The confirmation says live copies are wiped too.", vault(m),
+ over: DeleteConfirmSheet(confirm: c, onDelete: {}, onCancel: {}),
+ sheetSize: CGSize(width: 420, height: 170), delay: 2.4)
+ await m.keyvault.confirmDelete()
+ recorder.frame("Deleted. The copy in Aurora was wiped.", vault(m), delay: 2.0)
+ try recorder.finish("keyvault-delete")
+ }
+ // The review: per-site choice, counts, then the Keyvault as the source.
+ do {
+ let rec = Recorder(snap: snap, size: CGSize(width: 640, height: 760), dir: out)
+ let (t, _) = try await reviewModel()
+ func review() -> some View { TeleportReview(teleport: t, review: t.review!) }
+ rec.frame("Review: the sites to send, with counts. Minimal by default.", review(), delay: 2.2)
+ t.send(.toggleDomain(domain: "amazon.com"))
+ rec.frame("Pick another site.", review(), delay: 1.4)
+ t.send(.toggleDomain(domain: "github.com"))
+ rec.frame("Drop one.", review(), delay: 1.4)
+ t.send(.domainQuery(text: "n"))
+ rec.frame("Search the sites.", review(), delay: 1.4)
+ t.send(.domainQuery(text: ""))
+ await t.sendFrom(.vault)
+ t.sendVault(.toggleOpen(key: "chrome|github.com"))
+ rec.frame("Or send the saved Keyvault items. Nothing is read from this Mac.", review(), delay: 2.6)
+ try rec.finish("keyvault-review")
+ }
+ // Stills.
+ do {
+ let (m, _) = await model(icons: true)
+ m.keyvault.send(.toggleOpen(key: "chrome|github.com"))
+ m.keyvault.send(.toggleOpen(key: "chrome|\u{1}files"))
+ try recorder.still("vault-grouped", vault(m))
+ m.keyvault.send(.toggleGroup(key: "chrome|github.com"))
+ m.keyvault.send(.toggle(id: "c-no-1"))
+ try recorder.still("vault-multiselect", vault(m))
+ m.keyvault.send(.clear)
+ m.keyvault.query = "notion"
+ try recorder.still("vault-search", vault(m))
+ let (h, _) = await model(KeyvaultFixtures.overview(namesVisible: false), icons: true)
+ try recorder.still("vault-names-hidden", vault(h))
+ let one = kvUnlockPromptAlways(count: 1, name: "user_session")
+ try recorder.still("unlock-prompt", UnlockPromptSheet(prompt: one) { _ in }, size: CGSize(width: 440, height: 220))
+ let batch = kvUnlockPromptAlways(count: 6, name: nil)
+ try recorder.still("unlock-prompt-batch", UnlockPromptSheet(prompt: batch) { _ in }, size: CGSize(width: 440, height: 220))
+ try recorder.still("delete-confirm", DeleteConfirmSheet(confirm: kvDeleteConfirm(count: 6, liveCopies: 1), onDelete: {}, onCancel: {}),
+ size: CGSize(width: 420, height: 170))
+ let (t, _) = try await reviewModel()
+ try recorder.still("review-sites", TeleportReview(teleport: t, review: t.review!),
+ size: CGSize(width: 640, height: 760))
+ let (v, _) = try await reviewModel(vault: true)
+ try recorder.still("review-vault", TeleportReview(teleport: v, review: v.review!),
+ size: CGSize(width: 640, height: 760))
+ }
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultSnapshotTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultSnapshotTests.swift
new file mode 100644
index 0000000000..0675ce522f
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultSnapshotTests.swift
@@ -0,0 +1,196 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import AppKit
+import CuaSDK
+import CuaSpacesFFI
+import ImageIO
+@testable import CuaSpacesMacKit
+import SwiftUI
+import Testing
+import UniformTypeIdentifiers
+
+/// Snapshots of the vault list (grouped, multi-select, search, names hidden),
+/// the unlock prompt and the delete confirmation, on the simulated vault of
+/// `KeyvaultFixtures` (no real secret anywhere), rendered offscreen. The
+/// `Recorder` collects frames, one real state of the real views each, into
+/// the GIFs `KeyvaultReviewTests.exportScreenshotsAndGifs` writes.
+@MainActor
+@Suite("Keyvault snapshots", .serialized)
+struct KeyvaultSnapshotTests {
+ let snap = SnapshotTests()
+ static let list = CGSize(width: 780, height: 560)
+
+ func model(_ overview: KeyvaultOverview = KeyvaultFixtures.overview(),
+ icons: Bool = false) async -> (AppModel, FakeKeyvault) {
+ let fake = FakeKeyvault(overview)
+ let m = ViewModelTests().makeModel(kv: fake)
+ if icons {
+ m.keyvault.appIcons = AppIconCache(
+ dir: FileManager.default.temporaryDirectory.appendingPathComponent("cua-snap-icons-\(UUID().uuidString)"),
+ resolver: { id, name in
+ var r = AppIconCache.workspace(id, name)
+ if r == nil, id == "arc", let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "company.thebrowser.Browser") {
+ r = AppIconSource(bundleId: "company.thebrowser.Browser", version: "0") {
+ AppIconCache.png(NSWorkspace.shared.icon(forFile: url.path), side: 64)
+ }
+ }
+ return r
+ })
+ }
+ await m.keyvault.refresh()
+ if icons { await m.keyvault.loadIcons() }
+ return (m, fake)
+ }
+
+ var useRealIcons: Bool { ProcessInfo.processInfo.environment["KEYVAULT_REAL_ICONS"] == "1" }
+
+ func vault(_ m: AppModel) -> some View {
+ VaultList(keyvault: m.keyvault, page: m.keyvault.page)
+ }
+
+ // MARK: - The list
+
+ @Test func vaultGroupedByApp() async throws {
+ let (m, _) = await model(icons: useRealIcons)
+ // Open one site and the files of Chrome, the way a user browses.
+ m.keyvault.send(.toggleOpen(key: "chrome|github.com"))
+ m.keyvault.send(.toggleOpen(key: "chrome|\u{1}files"))
+ try snap.assertSnapshot(vault(m), "keyvault-vault-grouped", size: Self.list)
+ }
+
+ @Test func vaultMultiSelectWithTheBatchBar() async throws {
+ let (m, _) = await model(icons: useRealIcons)
+ m.keyvault.send(.toggleOpen(key: "chrome|github.com"))
+ m.keyvault.send(.toggleGroup(key: "chrome|github.com"))
+ m.keyvault.send(.toggle(id: "c-no-1"))
+ #expect(m.keyvault.vaultView.selection.title == "7 selected")
+ try snap.assertSnapshot(vault(m), "keyvault-vault-multiselect", size: Self.list)
+ }
+
+ @Test func vaultSearch() async throws {
+ let (m, _) = await model(icons: useRealIcons)
+ m.keyvault.query = "notion"
+ try snap.assertSnapshot(vault(m), "keyvault-vault-search", size: Self.list)
+ m.keyvault.query = "cookie github"
+ try snap.assertSnapshot(vault(m), "keyvault-vault-search-type", size: Self.list)
+ }
+
+ @Test func vaultNamesHidden() async throws {
+ let (m, _) = await model(KeyvaultFixtures.overview(namesVisible: false), icons: useRealIcons)
+ try snap.assertSnapshot(vault(m), "keyvault-vault-hidden", size: Self.list)
+ }
+
+ // MARK: - The prompts
+
+ @Test func unlockPrompt() async throws {
+ let one = kvUnlockPromptAlways(count: 1, name: "user_session")
+ try snap.assertSnapshot(UnlockPromptSheet(prompt: one) { _ in }, "keyvault-unlock-prompt",
+ size: CGSize(width: 440, height: 220))
+ let batch = kvUnlockPromptAlways(count: 6, name: nil)
+ try snap.assertSnapshot(UnlockPromptSheet(prompt: batch) { _ in }, "keyvault-unlock-prompt-batch",
+ size: CGSize(width: 440, height: 220))
+ }
+
+ @Test func deleteConfirm() async throws {
+ let c = kvDeleteConfirm(count: 6, liveCopies: 1)
+ try snap.assertSnapshot(DeleteConfirmSheet(confirm: c, onDelete: {}, onCancel: {}), "keyvault-delete-confirm",
+ size: CGSize(width: 420, height: 170))
+ }
+}
+
+/// Collects frames (a view and a caption under it) and writes a GIF.
+@MainActor
+final class Recorder {
+ let snap: SnapshotTests
+ let size: CGSize
+ let dir: URL
+ private var frames: [(CGImage, Double)] = []
+
+ init(snap: SnapshotTests, size: CGSize, dir: URL) {
+ self.snap = snap
+ self.size = size
+ self.dir = dir
+ }
+
+ /// One frame: `view`, a sheet over it (the window dimmed behind, the way
+ /// macOS presents one) and the caption under both. The sheet is rendered
+ /// on its own and composited as an image, so the text field under it
+ /// draws as it does without a sheet.
+ func frame<V: View, O: View>(_ caption: String, _ view: V, over sheet: O, sheetSize: CGSize, delay: Double) {
+ let base = snap.render(view.frame(width: size.width, height: size.height), size: size)
+ let top = snap.render(sheet.background(Color(nsColor: .windowBackgroundColor)), size: sheetSize)
+ let scale: CGFloat = 2
+ let out = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * scale), pixelsHigh: Int(size.height * scale),
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
+ out.size = size
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: out)
+ NSColor.white.setFill()
+ CGRect(origin: .zero, size: size).fill()
+ base.draw(in: CGRect(origin: .zero, size: size))
+ NSColor.black.withAlphaComponent(0.28).setFill()
+ CGRect(origin: .zero, size: size).fill()
+ let rect = CGRect(x: (size.width - sheetSize.width) / 2, y: size.height - sheetSize.height - 96,
+ width: sheetSize.width, height: sheetSize.height)
+ let shadow = NSShadow()
+ shadow.shadowBlurRadius = 24
+ shadow.shadowColor = NSColor.black.withAlphaComponent(0.35)
+ shadow.shadowOffset = NSSize(width: 0, height: -6)
+ NSGraphicsContext.saveGraphicsState()
+ shadow.set()
+ NSBezierPath(roundedRect: rect, xRadius: 12, yRadius: 12).addClip()
+ top.draw(in: rect)
+ NSGraphicsContext.restoreGraphicsState()
+ NSGraphicsContext.restoreGraphicsState()
+ add(caption, Image(nsImage: NSImage(cgImage: out.cgImage!, size: size)).resizable().frame(width: size.width, height: size.height),
+ delay: delay)
+ }
+
+ func frame<V: View>(_ caption: String, _ view: V, delay: Double) { add(caption, view, delay: delay) }
+
+ private func add<V: View>(_ caption: String, _ view: V, delay: Double) {
+ let bar: CGFloat = 34
+ let composed = VStack(spacing: 0) {
+ view.frame(width: size.width, height: size.height)
+ Text(caption)
+ .font(.system(size: 13, weight: .medium))
+ .foregroundStyle(.white)
+ .frame(width: size.width, height: bar)
+ .background(Color(white: 0.12))
+ }
+ let rep = snap.render(composed, size: CGSize(width: size.width, height: size.height + bar))
+ if let cg = rep.cgImage, let flat = Self.opaque(cg) { frames.append((flat, delay)) }
+ }
+
+ /// The frame on white, with no alpha: a GIF has none, and what the render
+ /// left transparent would show black.
+ static func opaque(_ image: CGImage) -> CGImage? {
+ guard let ctx = CGContext(data: nil, width: image.width, height: image.height, bitsPerComponent: 8,
+ bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }
+ ctx.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))
+ ctx.fill(CGRect(x: 0, y: 0, width: image.width, height: image.height))
+ ctx.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
+ return ctx.makeImage()
+ }
+
+ func finish(_ name: String) throws {
+ defer { frames = [] }
+ guard let dest = CGImageDestinationCreateWithURL(dir.appendingPathComponent("\(name).gif") as CFURL,
+ UTType.gif.identifier as CFString, frames.count, nil)
+ else { throw CocoaError(.fileWriteUnknown) }
+ CGImageDestinationSetProperties(dest, [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFLoopCount: 0]] as CFDictionary)
+ for (image, delay) in frames {
+ CGImageDestinationAddImage(dest, image, [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFDelayTime: delay]] as CFDictionary)
+ }
+ guard CGImageDestinationFinalize(dest) else { throw CocoaError(.fileWriteUnknown) }
+ }
+
+ func still<V: View>(_ name: String, _ view: V, size: CGSize? = nil) throws {
+ let s = size ?? self.size
+ let rep = snap.render(view, size: s)
+ try rep.representation(using: .png, properties: [:])!.write(to: dir.appendingPathComponent("\(name).png"))
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultVaultTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultVaultTests.swift
new file mode 100644
index 0000000000..6cace39abc
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/KeyvaultVaultTests.swift
@@ -0,0 +1,186 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import AppKit
+import CuaSDK
+import CuaSpacesFFI
+@testable import CuaSpacesMacKit
+import SwiftUI
+import Testing
+
+/// The vault list a password manager has, grouped by source app: items
+/// (cookie, localStorage value, password, file) under sites under apps, a
+/// lock on each, multi-select with a batch bar, search by domain, key, app
+/// or type, one prompt and one Touch ID for a batch unlock, and delete that
+/// wipes live copies. Behavior through the view model and the core; looks as
+/// snapshots (see KeyvaultSnapshotTests).
+@MainActor
+@Suite("Keyvault vault list")
+struct KeyvaultVaultTests {
+ func model(_ overview: KeyvaultOverview = KeyvaultFixtures.overview()) async -> (AppModel, FakeKeyvault) {
+ let fake = FakeKeyvault(overview)
+ let m = ViewModelTests().makeModel(kv: fake)
+ await m.keyvault.refresh()
+ return (m, fake)
+ }
+
+ /// Selects every item of a site the way a click on its checkbox does.
+ func selectSite(_ m: AppModel, _ app: String, _ site: String) {
+ m.keyvault.send(.toggleGroup(key: "\(app)|\(site)"))
+ }
+
+ @Test func groupsByAppThenSiteWithFilesApart() async throws {
+ let (m, _) = await model()
+ let v = m.keyvault.vaultView
+ #expect(v.apps.map(\.name) == ["Arc", "Google Chrome", "Slack"])
+ let chrome = try #require(v.apps.first { $0.providerId == "chrome" })
+ #expect(chrome.open, "an app opens the first time it is shown")
+ #expect(chrome.sites.map(\.site) == ["amazon.com", "github.com", "google.com", "linear.app", "notion.so"])
+ #expect(chrome.sites.first { $0.site == "github.com" }?.counts == "1 password, 4 cookies, 1 storage value")
+ #expect(chrome.files?.count == 3)
+ #expect(!v.namesHidden)
+ // The sidebar has an app row for each, by name.
+ #expect(m.keyvault.sidebar.apps.map(\.title) == ["Arc", "Google Chrome", "Slack"])
+ }
+
+ @Test func searchMatchesDomainKeyAppAndType() async throws {
+ let (m, _) = await model()
+ func shown(_ q: String) -> UInt32 { m.keyvault.query = q; return m.keyvault.vaultView.shown }
+ #expect(shown("notion") == 3, "domain")
+ #expect(shown("token_v2") == 1, "key")
+ #expect(shown("slack") == 5, "app and domain")
+ #expect(shown("password") == 2, "type")
+ #expect(shown("local storage") == 3, "type, two words")
+ #expect(shown("cookie github") == 4)
+ #expect(shown("nothing like this") == 0)
+ #expect(m.keyvault.vaultView.emptyText == "No matches")
+ #expect(shown("") == 27)
+ }
+
+ @Test func selectingASiteAnAppOrItemsAndTheBatchBar() async throws {
+ let (m, _) = await model()
+ selectSite(m, "chrome", "github.com")
+ #expect(m.keyvault.vaultView.selection.count == 6)
+ m.keyvault.send(.toggle(id: "c-no-1"))
+ #expect(m.keyvault.vaultView.selection.title == "7 selected")
+ m.keyvault.send(.clear)
+ m.keyvault.send(.toggleGroup(key: "slack"))
+ #expect(m.keyvault.vaultView.selection.count == 5)
+ // Switching the sidebar to another app starts a fresh selection.
+ m.keyvault.selection = .app(key: "arc")
+ #expect(m.keyvault.vaultView.selection.count == 0)
+ #expect(m.keyvault.vaultView.apps.map(\.name) == ["Arc"])
+ m.keyvault.selection = .category(category: .all)
+ #expect(m.keyvault.vaultView.apps.count == 3)
+ }
+
+ @Test func aBatchUnlockAsksOnceThenTheDaemonAsksTouchIdOnce() async throws {
+ let (m, fake) = await model()
+ selectSite(m, "chrome", "github.com")
+ let sel = m.keyvault.vaultView.selection
+ #expect(sel.canUnlock && sel.canLock)
+ await m.keyvault.requestUnlock(ids: sel.unlockIds)
+ // The prompt: the user's words, three answers, and nothing sent yet.
+ let pending = try #require(m.keyvault.unlockPrompt)
+ #expect(pending.prompt.title == "Allow unattended access?")
+ #expect(pending.prompt.message == "This will allow any agent with access to the Cua Spaces MCP to write these keys into your connected Spaces. The secrets are not sent directly to any agents.")
+ #expect([pending.prompt.deny, pending.prompt.allow, pending.prompt.neverAsk] == ["Deny", "Allow", "Never ask again"])
+ #expect(fake.commands.isEmpty)
+ await m.keyvault.answerUnlock(.allow)
+ #expect(m.keyvault.unlockPrompt == nil)
+ #expect(fake.commands == [.setLocked(itemIds: sel.unlockIds, locked: false)], "one request for the whole batch")
+ #expect(m.keyvault.vaultView.apps.flatMap(\.sites).first { $0.site == "github.com" }?.lock == .unlocked)
+ }
+
+ @Test func denyChangesNothing() async throws {
+ let (m, fake) = await model()
+ await m.keyvault.requestUnlock(ids: ["c-gh-3"], name: "_gh_sess")
+ #expect(m.keyvault.unlockPrompt?.prompt.subject == "_gh_sess")
+ #expect(m.keyvault.unlockPrompt?.prompt.message.contains("write this key") == true)
+ await m.keyvault.answerUnlock(.deny)
+ #expect(fake.commands.isEmpty)
+ #expect(m.keyvault.unlockPrompt == nil)
+ }
+
+ @Test func neverAskAgainIsStoredShownAndRevertibleInSettings() async throws {
+ let (m, fake) = await model()
+ await m.keyvault.requestUnlock(ids: ["c-gh-3"], name: "_gh_sess")
+ await m.keyvault.answerUnlock(.neverAskAgain)
+ #expect(fake.commands == [.setSkipUnlockPrompt(on: true), .setLocked(itemIds: ["c-gh-3"], locked: false)],
+ "it still unlocks, and the daemon still asks for Touch ID")
+ #expect(m.keyvault.unlockPromptShows == false)
+ // The next unlock skips the prompt and goes straight to Touch ID.
+ await m.keyvault.requestUnlock(ids: ["c-am-1"])
+ #expect(m.keyvault.unlockPrompt == nil)
+ #expect(fake.commands.last == .setLocked(itemIds: ["c-am-1"], locked: false))
+ // Settings shows it, off, and turning it on restores the prompt.
+ await m.loadSettings()
+ let row = try #require(m.settingsPage.sections.first { $0.id == "keyvault" }?.rows.first { $0.id == "keyvault-unlock-prompt" })
+ #expect(row.options.first { $0.id == "on" }?.active == false)
+ await m.choose(row: "keyvault-unlock-prompt", option: "on")
+ #expect(fake.commands.last == .setSkipUnlockPrompt(on: false))
+ #expect(m.keyvault.unlockPromptShows == true)
+ await m.keyvault.requestUnlock(ids: ["c-am-2"])
+ #expect(m.keyvault.unlockPrompt != nil)
+ }
+
+ @Test func protectionLivesInSettingsNotTheList() async throws {
+ let (m, _) = await model()
+ await m.loadSettings()
+ let section = try #require(m.settingsPage.sections.first { $0.id == "keyvault" })
+ let facts = section.rows.filter { $0.id.hasPrefix("keyvault-protection:") }
+ #expect(facts.map(\.label).contains("Touch ID"))
+ #expect(facts.allSatisfy { $0.value != nil })
+ }
+
+ @Test func anIdentityProviderStaysLocked() async throws {
+ let (m, fake) = await model()
+ selectSite(m, "chrome", "google.com")
+ let sel = m.keyvault.vaultView.selection
+ #expect(!sel.canUnlock && sel.alwaysAsk == 2)
+ await m.keyvault.requestUnlock(ids: sel.unlockIds)
+ #expect(m.keyvault.unlockPrompt == nil && fake.commands.isEmpty)
+ }
+
+ @Test func lockingNeedsNoPrompt() async throws {
+ let (m, fake) = await model()
+ let open = m.keyvault.overview.items.filter(\.policy.unattended).map(\.id)
+ await m.keyvault.lock(ids: open)
+ #expect(m.keyvault.unlockPrompt == nil)
+ #expect(fake.commands == [.setLocked(itemIds: open, locked: true)])
+ #expect(m.keyvault.overview.items.allSatisfy { !$0.policy.unattended })
+ }
+
+ @Test func deleteConfirmsNamesTheCopiesItWipesAndWipesThem() async throws {
+ var o = KeyvaultFixtures.overview()
+ o.deliveries = [KvDelivery(importId: "imp-1", target: "local:aurora", providerId: "chrome",
+ items: ["c-gh-1", "c-gh-2"], callerFp: "fp", deliveredMs: 1_799_999_000_000,
+ expiresMs: 0, wiped: false)]
+ let (m, fake) = await model(o)
+ selectSite(m, "chrome", "github.com")
+ let ids = m.keyvault.vaultView.selection.ids
+ m.keyvault.requestDelete(ids: ids)
+ let confirm = try #require(m.keyvault.deleteConfirm)
+ #expect(confirm.confirm.title == "Delete 6 items?")
+ #expect(confirm.confirm.message.contains("Copies delivered to a Space will be wiped as well."))
+ #expect(fake.commands.isEmpty, "nothing happens until it is confirmed")
+ await m.keyvault.confirmDelete()
+ #expect(fake.commands == [.deleteItems(itemIds: ids)])
+ #expect(m.keyvault.overview.items.count == 21)
+ #expect(m.keyvault.overview.deliveries[0].wiped, "the live copy was wiped")
+ #expect(m.keyvault.vaultView.selection.count == 0, "the selection forgets what is gone")
+ #expect(!m.keyvault.vaultView.apps.flatMap(\.sites).contains { $0.site == "github.com" })
+ }
+
+ @Test func namesStayHiddenUntilTheUserConfirmsWithTouchId() async throws {
+ let (m, fake) = await model(KeyvaultFixtures.overview(namesVisible: false))
+ let v = m.keyvault.vaultView
+ #expect(v.namesHidden)
+ #expect(v.hiddenNote == "Names are hidden. Confirm with Touch ID to see what is saved.")
+ #expect(v.apps.map(\.count) == [4, 18, 5], "counts survive while names are hidden")
+ await m.keyvault.showItems()
+ #expect(fake.commands == [.browse])
+ #expect(!m.keyvault.vaultView.namesHidden)
+ #expect(m.keyvault.vaultView.apps.contains { $0.sites.contains { $0.site == "github.com" } })
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ParityTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ParityTests.swift
index 5f6f0111b8..4e1718eed1 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ParityTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ParityTests.swift
@@ -788,7 +788,7 @@ struct ParityTests {
func kvSidebarFrame(_ v: KvSidebar) -> [String: Any] {
[
"categories": v.categories.map { c in c.count.map { "\(c.title):\($0)" } ?? c.title },
- "sites": v.sites.map { "\($0.title) (\($0.accounts))\($0.waiting ? " waiting" : "")" },
+ "apps": v.apps.map { "\($0.title) (\($0.items))\($0.waiting ? " waiting" : "")" },
]
}
@@ -803,12 +803,7 @@ struct ParityTests {
func kvListFrame(_ v: KvListView) -> [String: Any] {
[
"title": v.title,
- "sites": v.sites.map { g in
- "\(g.title) [\(word(g.unattended))]: " + g.rows.map { r in
- "\(r.account) \(r.item.policy.unattended ? "on" : "off")\(r.toggleEnabled ? "" : " locked") <"
- + r.consent.map { "\(word($0.kind)):\($0.text)" }.joined(separator: "; ") + ">"
- }.joined(separator: " | ")
- },
+ "vault": v.vault,
"pending": v.pending.map { "\($0.caller) (\($0.badge.text)) \($0.summary) for \($0.wants)" },
"access": v.access.map { "\($0.text) / \($0.detail) [\($0.actionLabel)]" },
"recent": v.recent.map { "\($0.decision.verb) \($0.decision.what) (\(word($0.decision.tone))) \($0.age)" },
@@ -816,6 +811,76 @@ struct ParityTests {
]
}
+ func lockWord(_ l: KvLock) -> String {
+ switch l {
+ case .locked: return "locked"
+ case .unlocked: return "unlocked"
+ case .mixed: return "mixed"
+ }
+ }
+
+ func triMark(_ t: KvTri) -> String {
+ switch t {
+ case .on: return "[x]"
+ case .mixed: return "[-]"
+ case .off: return "[ ]"
+ }
+ }
+
+ func vaultRowLine(_ r: KvVaultRow) -> String {
+ "\(r.selected ? "[x]" : "[ ]") \(r.kindLabel) \(r.title) | \(r.subtitle) | \(r.lockSymbol) | \(r.updated)"
+ + (r.identityProvider ? " | always asks" : "")
+ }
+
+ func kvVaultFrame(_ v: KvVaultView) -> [String: Any] {
+ var lines: [String] = []
+ for a in v.apps {
+ lines.append("\(triMark(a.selected)) \(a.name) \(a.providerId) | \(a.summary) | \(lockWord(a.lock)) | \(a.updated)")
+ for s in a.sites {
+ lines.append(" \(triMark(s.selected)) \(s.site) | \(s.counts) | \(lockWord(s.lock)) | \(s.updated)\(s.open ? " | open" : "")")
+ for r in s.rows { lines.append(" " + vaultRowLine(r)) }
+ }
+ if let f = a.files {
+ lines.append(" \(triMark(f.selected)) files (\(f.count)) | \(lockWord(f.lock))\(f.open ? " | open" : "")")
+ for r in f.rows { lines.append(" " + vaultRowLine(r)) }
+ }
+ }
+ let sel = v.selection
+ return [
+ "shown": "\(v.shown)/\(v.total)",
+ "lines": lines,
+ "empty": opt(v.emptyText),
+ "selection": "\(sel.title) (unlock \(sel.unlockIds.count) / lock \(sel.lockIds.count) / always ask \(sel.alwaysAsk))",
+ "canUnlock": sel.canUnlock,
+ "canLock": sel.canLock,
+ ]
+ }
+
+ func kvUnlockPromptFrame(_ p: KvUnlockPrompt?) -> Any {
+ guard let p else { return NSNull() }
+ return [p.title, p.message, p.subject, "\(p.deny) / \(p.allow) / \(p.neverAsk)"]
+ }
+
+ func kvDeleteConfirmFrame(_ c: KvDeleteConfirm) -> Any {
+ [c.title, c.message, "\(c.confirm) / \(c.cancel)"]
+ }
+
+ func vaultAction(_ a: [String: Any]) -> KvVaultAction {
+ switch a["type"] as! String {
+ case "query": return .query(text: a["text"] as! String)
+ case "toggle": return .toggle(id: a["id"] as! String)
+ case "toggle-group": return .toggleGroup(key: a["key"] as! String)
+ case "select-all": return .selectAll
+ case "toggle-open": return .toggleOpen(key: a["key"] as! String)
+ default: return .clear
+ }
+ }
+
+ func vaultState(_ s: [String: Any]) -> KvVaultState {
+ KvVaultState(query: s["query"] as! String, selected: s["selected"] as! [String],
+ expanded: s["expanded"] as! [String], app: s["app"] as? String)
+ }
+
func approvalFrame(_ v: KvApprovalView) -> [String: Any] {
[
"title": v.title, "badge": v.badge.text,
@@ -830,13 +895,14 @@ struct ParityTests {
case .approve(let id, let items)?: return ["type": "approve", "requestId": id, "items": items.map { $0 as Any } ?? NSNull()]
case .deny(let id)?: return ["type": "deny", "requestId": id]
case .setUnattended(let ids, let on)?: return ["type": "set-unattended", "itemIds": ids, "unattended": on]
+ case .setLocked(let ids, let locked)?: return ["type": "set-locked", "itemIds": ids, "locked": locked]
case nil: return NSNull()
default: return "unmapped"
}
}
func selection(_ s: [String: Any]) -> KvSelection {
- if (s["kind"] as! String) == "site" { return .site(key: s["key"] as! String) }
+ if (s["kind"] as! String) == "app" { return .app(key: s["key"] as! String) }
let c: KvCategory = switch s["category"] as! String {
case "waiting": .waiting
case "access": .access
@@ -861,7 +927,7 @@ struct ParityTests {
frames.append(["sidebar": kvSidebarFrame(kvSidebar(overview: o, nowMs: now))])
frames.append(["page": kvPageFrame(kvPage(overview: o, nowMs: now))])
for sel in f["selections"] as! [[String: Any]] {
- frames.append(["list": sel, "frame": kvListFrame(kvList(overview: o, selection: selection(sel), nowMs: now, query: ""))])
+ frames.append(["list": sel, "frame": kvListFrame(kvList(overview: o, selection: selection(sel), nowMs: now))])
}
for a in f["approvals"] as! [[String: Any]] {
let req = a["request"] as! String
@@ -874,12 +940,27 @@ struct ParityTests {
frames.append(["approval": req, "approveCommand": command(kvApprovalApproveCommand(overview: o, state: st))])
}
frames.append(["denyCommand": command(kvApprovalDenyCommand(state: KvApprovalState(requestId: f["deny"] as! String, selected: [])))])
- let t = f["siteToggle"] as! [String: Any]
- let detail = kvSiteDetail(overview: o, key: t["key"] as! String, nowMs: now)!
- frames.append([
- "siteDetail": ["switch": detail.siteSwitch, "state": word(detail.siteState), "enabled": detail.siteSwitchEnabled],
- "siteToggle": command(kvSiteToggle(group: detail.group, on: t["on"] as! Bool)),
- ])
+ let vault = f["vault"] as! [String: Any]
+ var vst = vaultState(vault["state"] as! [String: Any])
+ frames.append(["vault": "open", "frame": kvVaultFrame(kvVaultView(overview: o, state: vst, nowMs: now))])
+ for action in vault["actions"] as! [[String: Any]] {
+ vst = kvVaultReduce(overview: o, state: vst, action: vaultAction(action))
+ frames.append(["vault": action, "frame": kvVaultFrame(kvVaultView(overview: o, state: vst, nowMs: now))])
+ }
+ var one = vaultState(vault["state"] as! [String: Any])
+ one.app = (vault["app"] as! String)
+ frames.append(["vaultApp": vault["app"] as! String, "frame": kvVaultFrame(kvVaultView(overview: o, state: one, nowMs: now))])
+ for u in vault["unlock"] as! [[String: Any]] {
+ let p = kvUnlockPrompt(overview: o, count: UInt32(u["count"] as! Int), name: u["name"] as? String)
+ frames.append(["unlockPrompt": u, "frame": kvUnlockPromptFrame(p)])
+ }
+ var skip = o
+ skip.status?.skipUnlockPrompt = true
+ frames.append(["unlockPromptSkipped": kvUnlockPromptFrame(kvUnlockPrompt(overview: skip, count: 1, name: nil))])
+ for d in vault["delete"] as! [[String: Any]] {
+ let c = kvDeleteConfirm(count: UInt32(d["count"] as! Int), liveCopies: UInt32(d["liveCopies"] as! Int))
+ frames.append(["deleteConfirm": d, "frame": kvDeleteConfirmFrame(c)])
+ }
var off = o
off.status?.disabled = true
frames.append(["page": kvPageFrame(kvPage(overview: off, nowMs: now))])
@@ -899,8 +980,7 @@ struct ParityTests {
"labels": [
"deny: \(l.deny)", "review: \(l.review)", "cancel: \(l.cancel)", "setUp: \(l.setUp)",
"unlock: \(l.unlock)", "revokeAll: \(l.revokeAll)", "confirmNote: \(l.confirmNote)",
- "protectionTitle: \(l.protectionTitle)", "accountsTitle: \(l.accountsTitle)",
- "appLabel: \(l.appLabel)", "everyAccount: \(l.everyAccount)",
+ "protectionTitle: \(l.protectionTitle)",
],
"killSwitchHelp": [on.killSwitchHelp, offPage.killSwitchHelp],
"badges": kvSidebar(overview: o, nowMs: now).categories.map { "\($0.title):\($0.badge.map { String($0) } ?? "-")" },
@@ -1745,7 +1825,6 @@ struct ParityTests {
func word(_ v: AppConsentKind) -> String { "\(v)" }
func word(_ v: AppNotchPhase) -> String { "\(v)" }
func word(_ v: KvTri) -> String { "\(v)" }
- func word(_ v: KvConsentChipKind) -> String { "\(v)" }
func word(_ v: KvDecisionTone) -> String { "\(v)" }
// MARK: - your-cloud
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/SnapshotTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/SnapshotTests.swift
index 014e310c02..c21d34a6db 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/SnapshotTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/SnapshotTests.swift
@@ -389,14 +389,14 @@ struct SnapshotTests {
let m = try await model()
let sel = KvSelection.category(category: .all)
m.keyvault.selection = sel
- try assertSnapshot(CategoryList(keyvault: m.keyvault, page: m.keyvault.page), "keyvault-all",
+ try assertSnapshot(VaultList(keyvault: m.keyvault, page: m.keyvault.page), "keyvault-all",
size: CGSize(width: 640, height: 520))
}
@Test func approvalSheet() async throws {
let m = try await model()
m.keyvault.openApproval("req-1")
- m.keyvault.sendApproval(.toggle(key: "gh-ada"))
+ m.keyvault.sendApproval(.toggle(key: "chrome|example.test"))
try assertSnapshot(ApprovalSheet(keyvault: m.keyvault), "approval", size: CGSize(width: 480, height: 360))
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/approval.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/approval.png
index bd706266c4..093b35dce4 100644
Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/approval.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/approval.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-access.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-access.png
index a501dc1172..a9797878a0 100644
Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-access.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-access.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-all.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-all.png
index 66566c20b2..bdcfe63fe2 100644
Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-all.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-all.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-delete-confirm.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-delete-confirm.png
new file mode 100644
index 0000000000..5eed4dbc17
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-delete-confirm.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-review-sites.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-review-sites.png
new file mode 100644
index 0000000000..09079a74ce
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-review-sites.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-review-vault.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-review-vault.png
new file mode 100644
index 0000000000..d1f7d10672
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-review-vault.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-unlock-prompt-batch.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-unlock-prompt-batch.png
new file mode 100644
index 0000000000..34daedb090
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-unlock-prompt-batch.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-unlock-prompt.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-unlock-prompt.png
new file mode 100644
index 0000000000..93e91c2ede
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-unlock-prompt.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-grouped.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-grouped.png
new file mode 100644
index 0000000000..c41456f234
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-grouped.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-hidden.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-hidden.png
new file mode 100644
index 0000000000..f2cce9b3ce
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-hidden.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-multiselect.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-multiselect.png
new file mode 100644
index 0000000000..3ffabfcbb9
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-multiselect.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-search-type.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-search-type.png
new file mode 100644
index 0000000000..e0497a7bf3
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-search-type.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-search.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-search.png
new file mode 100644
index 0000000000..6fc6f8d716
Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/keyvault-vault-search.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png
index 7cf1f00252..85487f6aba 100644
Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png differ
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TeleportConsentTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TeleportConsentTests.swift
index 5fb05d69e1..33e1cfcae1 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TeleportConsentTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TeleportConsentTests.swift
@@ -14,12 +14,30 @@ struct TeleportConsentTests {
@Test func saveToKeyvaultReachesTheSdkConsent() {
let c = sdkConsent(AppTeleportConsent(
approved: true, acknowledgeSensitive: true,
- saveToKeyvault: true, acknowledgeRelayPlaintext: true))
+ saveToKeyvault: true, acknowledgeRelayPlaintext: true,
+ cookieDomains: nil, exclude: [], fromVault: nil, includePasswords: false))
#expect(c == TeleportConsent(approved: true, acknowledgeSensitive: true,
saveToKeyvault: true, acknowledgeRelayPlaintext: true))
let off = sdkConsent(AppTeleportConsent(
approved: true, acknowledgeSensitive: true,
- saveToKeyvault: false, acknowledgeRelayPlaintext: false))
+ saveToKeyvault: false, acknowledgeRelayPlaintext: false,
+ cookieDomains: nil, exclude: [], fromVault: nil, includePasswords: false))
#expect(!off.saveToKeyvault)
}
+
+ /// The review's choices must reach the SDK consent, or the review would
+ /// show a selection the teleport then ignores: the sites, the lines
+ /// turned off, and the Keyvault as the source.
+ @Test func theReviewsChoicesReachTheSdkConsent() {
+ let c = sdkConsent(AppTeleportConsent(
+ approved: true, acknowledgeSensitive: true, saveToKeyvault: false, acknowledgeRelayPlaintext: false,
+ cookieDomains: ["github.com", "notion.so"], exclude: ["Default/Bookmarks"], fromVault: nil, includePasswords: false))
+ #expect(c.cookieDomains == ["github.com", "notion.so"])
+ #expect(c.exclude == ["Default/Bookmarks"])
+ #expect(c.fromVault == nil)
+ let v = sdkConsent(AppTeleportConsent(
+ approved: true, acknowledgeSensitive: true, saveToKeyvault: false, acknowledgeRelayPlaintext: false,
+ cookieDomains: nil, exclude: [], fromVault: ["a", "b"], includePasswords: true))
+ #expect(v.fromVault == ["a", "b"] && v.cookieDomains == nil && v.includePasswords)
+ }
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
index 09d4cd6f42..6dceb63d8e 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
@@ -17,17 +17,55 @@ final class FakeKeyvault: KeyvaultClientProtocol, @unchecked Sendable {
func overview() async -> KeyvaultOverview { current }
+ /// The icons the vault holds (the browser's own, read locally).
+ var favicons: [KvFavicon] = []
+ func favicons() async -> [KvFavicon] { favicons }
+
func execute(command: KvCommand) async throws -> KvOutcome {
commands.append(command)
switch command {
case .setDisabled(let disabled): current.status?.disabled = disabled
case .setAutoWipe(let on): current.status?.autoWipe = on
case .approve(let id, _), .deny(let id): current.pending.removeAll { $0.id == id }
+ case .setLocked(let ids, let locked):
+ // The broker's rule: an identity provider always asks.
+ var changed: [String] = [], skipped: [String] = []
+ for i in current.items.indices where ids.contains(current.items[i].id) {
+ if !locked && current.items[i].identityProvider { skipped.append(current.items[i].id); continue }
+ if current.items[i].policy.unattended == locked { changed.append(current.items[i].id) }
+ current.items[i].policy.unattended = !locked
+ }
+ return .locked(changed: changed, skipped: skipped)
+ case .deleteItems(let ids):
+ current.items.removeAll { ids.contains($0.id) }
+ current.itemsTotal = UInt32(current.items.count)
+ let wiped = current.deliveries.filter { d in d.items.contains { ids.contains($0) } }.map(\.importId)
+ for i in current.deliveries.indices where wiped.contains(current.deliveries[i].importId) {
+ current.deliveries[i].wiped = true
+ }
+ return .deleted(count: UInt32(ids.count), wiped: wiped)
+ case .setSkipUnlockPrompt(let on): current.status?.skipUnlockPrompt = on
+ case .browse:
+ current.namesVisible = true
+ current.items = KeyvaultFixtures.items().filter { n in current.items.contains { $0.id == n.id } }
+ .map { n in var m = n; m.policy = current.items.first { $0.id == n.id }!.policy; return m }
+ return .browsing(untilMs: UInt64(KeyvaultFixtures.now + 300_000))
default: break
}
return .done
}
+ /// What the Keyvault would list for an app (the review's sites).
+ var inventoryResult: KvInventory = KeyvaultFixtures.chromeInventory()
+ var inventoryFails = false
+ var inventoryAsks = 0
+
+ func inventory(app: String, profile: String?) async throws -> KvInventory {
+ inventoryAsks += 1
+ if inventoryFails { throw CuaError.InvalidArgument(message: "no cookies") }
+ return inventoryResult
+ }
+
/// Passphrases the page sent (test fixtures, never real secrets).
var passphrases: [String] = []
@@ -990,10 +1028,11 @@ struct ViewModelTests {
#expect(!v.canApprove)
await model.keyvault.approve()
#expect(fake.commands.isEmpty, "nothing ticked, nothing sent")
- model.keyvault.sendApproval(.toggle(key: "gh-bob"))
+ // Rows are sites; ticking one approves exactly its items.
+ model.keyvault.sendApproval(.toggle(key: "chrome|example.test"))
#expect(model.keyvault.approvalView?.canApprove == true)
await model.keyvault.approve()
- #expect(fake.commands == [.approve(requestId: "req-1", items: ["gh-bob"])])
+ #expect(fake.commands == [.approve(requestId: "req-1", items: ["gh-ada", "gh-bob"])])
#expect(model.keyvault.approval == nil)
}
@@ -1009,12 +1048,12 @@ struct ViewModelTests {
#expect(model.keyvault.approvalView?.blockedReason == "Keyvault is off. Turn it on to approve.")
}
- @Test func keyvaultCategoriesAndSites() async throws {
+ @Test func keyvaultCategoriesAndApps() async throws {
let model = makeModel(kv: FakeKeyvault(try fixtureOverview()))
await model.keyvault.refresh()
let sidebar = model.keyvault.sidebar
- #expect(sidebar.categories.map(\.title) == ["All", "Waiting", "Access", "Recent"])
- #expect(sidebar.sites.map(\.title).contains("github.example.test"))
+ #expect(sidebar.categories.map(\.title) == ["All Items", "Waiting", "Access", "Recent"])
+ #expect(sidebar.apps.map(\.title) == ["Chrome", "Slack"])
model.keyvault.selection = .category(category: .waiting)
#expect(model.keyvault.list.pending.count == 2)
}
diff --git a/apps/cua-spaces-macos/UITests/CuaSpacesMacUITests.swift b/apps/cua-spaces-macos/UITests/CuaSpacesMacUITests.swift
index 25f46a69c6..fe43e0b006 100644
--- a/apps/cua-spaces-macos/UITests/CuaSpacesMacUITests.swift
+++ b/apps/cua-spaces-macos/UITests/CuaSpacesMacUITests.swift
@@ -28,7 +28,7 @@ final class CuaSpacesMacUITests: XCTestCase {
XCTAssertTrue(app.staticTexts["Aurora"].waitForExistence(timeout: 10))
XCTAssertTrue(app.staticTexts["Cua Cloud"].exists)
XCTAssertTrue(app.staticTexts["Connected"].exists)
- XCTAssertTrue(app.staticTexts["All"].exists, "the Keyvault categories are in the sidebar")
+ XCTAssertTrue(app.staticTexts["All Items"].exists, "the Keyvault categories are in the sidebar")
}
func testNewSpaceWalksToCreate() {
diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lock
index 602f380a5b..120968276f 100644
--- a/apps/cua-spaces/src-tauri/Cargo.lock
+++ b/apps/cua-spaces/src-tauri/Cargo.lock
@@ -1026,6 +1026,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crc32c"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
+dependencies = [
+ "rustc_version",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.1"
@@ -1190,6 +1199,18 @@ dependencies = [
"url",
]
+[[package]]
+name = "cua-chromium-storage"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "cua-teleport-bundle",
+ "rusty-leveldb",
+ "tempfile",
+ "thiserror 2.0.20",
+ "tracing",
+]
+
[[package]]
name = "cua-daemon"
version = "0.1.0"
@@ -1580,6 +1601,7 @@ dependencies = [
"chrono",
"cua-agents",
"cua-auth",
+ "cua-chromium-storage",
"cua-daemon",
"cua-fleet",
"cua-home",
@@ -1668,6 +1690,7 @@ dependencies = [
"core-foundation 0.10.1",
"core-graphics",
"cua-agents",
+ "cua-chromium-storage",
"cua-home",
"cua-icon-cache",
"cua-machine-seal",
@@ -2257,6 +2280,17 @@ dependencies = [
"typeid",
]
+[[package]]
+name = "errno"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1"
+dependencies = [
+ "errno-dragonfly",
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -2267,6 +2301,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "errno-dragonfly"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
+dependencies = [
+ "cc",
+ "libc",
+]
+
[[package]]
name = "event-listener"
version = "5.4.2"
@@ -2426,6 +2470,16 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "fs2"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
+dependencies = [
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -3393,6 +3447,12 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "integer-encoding"
+version = "3.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -5397,7 +5457,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags 2.13.1",
- "errno",
+ "errno 0.3.14",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
@@ -5486,6 +5546,21 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+[[package]]
+name = "rusty-leveldb"
+version = "4.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43ddda8f34100fca4bf1b0bbf743d12d27b5d84c35c74a52f392aac26f54e82d"
+dependencies = [
+ "bytes",
+ "crc32c",
+ "errno 0.2.8",
+ "fs2",
+ "integer-encoding",
+ "rand 0.8.8",
+ "snap",
+]
+
[[package]]
name = "ryu"
version = "1.0.23"
@@ -5939,7 +6014,7 @@ version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
- "errno",
+ "errno 0.3.14",
"libc",
]
@@ -5989,6 +6064,12 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100"
+[[package]]
+name = "snap"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886"
+
[[package]]
name = "socket2"
version = "0.6.5"
diff --git a/apps/cua-spaces/src-tauri/examples/keyvault_fixture.rs b/apps/cua-spaces/src-tauri/examples/keyvault_fixture.rs
index 7572c385b5..6d4dd65c4a 100644
--- a/apps/cua-spaces/src-tauri/examples/keyvault_fixture.rs
+++ b/apps/cua-spaces/src-tauri/examples/keyvault_fixture.rs
@@ -10,7 +10,7 @@
//! keyvault_fixture request <socket> <label> <target> <reason>
//! any caller: file an access request
//! keyvault_fixture answer <socket> <allow|deny> <n> first party: answer the n-th pending request
-//! keyvault_fixture unattended <socket> <label> first party: allow an item in unattended rules
+//! keyvault_fixture unattended <socket> <key|site> first party: unlock an item (allow unattended access)
//! keyvault_fixture use <socket> <label> <target> third party: request, wait up to 60 s, then
//! teleport with the granted token
//! ```
@@ -27,64 +27,38 @@ use std::time::Duration;
use cua_keyvault::broker::{AccessRequest, Decision, Selector, TeleportRequest, UnlockRequest};
use cua_keyvault::client::{KeyvaultClient, ServerCheck};
use cua_keyvault::ipc::Request;
-use cua_keyvault::model::{
- CookieInfo, ItemKind, ItemMeta, ItemPayload, ItemPolicy, ItemSummary, PayloadEntry,
-};
+use cua_keyvault::model::{ItemMeta, ItemPayload};
use cua_keyvault::protector::PassphraseProtector;
+use cua_keyvault::record::{self, CookieRecord};
use cua_keyvault::rollback::FileGenerationAnchor;
use cua_keyvault::Vault;
-fn fake(
- kind: ItemKind,
- app: &str,
- site: Option<&str>,
- account: Option<&str>,
- idp: bool,
-) -> (ItemMeta, ItemPayload) {
- let label = match (site, kind) {
- (Some(s), _) => format!("{s} ({app}, Default)"),
- (None, _) => format!("{app} (whole app session)"),
- };
+/// One fake item: a site's session cookie, or (no site) a file of the app.
+fn fake(app: &str, site: Option<&str>, name: &str) -> (ItemMeta, ItemPayload) {
let provider = app.to_ascii_lowercase();
- let meta = ItemMeta {
- id: String::new(),
- kind,
- label,
- provider_id: provider.clone(),
- app_display: app.into(),
- site: site.map(Into::into),
- account: account.map(Into::into),
- source: "Default".into(),
- summary: ItemSummary {
- cookies: vec![CookieInfo {
- name: "fixture_session".into(),
- domain: format!(".{}", site.unwrap_or("example.test")),
- session: true,
- expires_ms: None,
- }],
- ..Default::default()
- },
- warnings: vec![],
- identity_provider: idp,
- policy: ItemPolicy {
- ttl_secs: if idp { 15 * 60 } else { 3600 },
- ..Default::default()
- },
- created_ms: 0,
- updated_ms: 0,
- rev: 0,
- record_digest: String::new(),
- };
- let payload = ItemPayload {
- provider_id: provider,
- scope: "full".into(),
- entries: vec![PayloadEntry {
- rel_path: format!("fixture/{}", site.unwrap_or(app)),
- mode: 0o600,
+ let new = match site {
+ Some(s) => record::cookie_record(&CookieRecord {
+ creation_utc: None,
+ expires_utc: 0,
+ host_key: format!(".{s}"),
+ http_only: true,
+ last_update_utc: None,
+ name: name.into(),
+ partition_key: None,
+ path: "/".into(),
+ priority: None,
+ same_site: -1,
+ secure: true,
+ source_port: None,
+ source_scheme: None,
// "FIXTURE-NOT-A-SECRET"
- data: "RklYVFVSRS1OT1QtQS1TRUNSRVQ=".into(),
- }],
+ value: b"FIXTURE-NOT-A-SECRET".to_vec(),
+ })
+ .unwrap(),
+ None => record::file_record(name, 0o600, b"FIXTURE-NOT-A-SECRET").unwrap(),
};
+ let (mut meta, payload) = new.into_item(&provider, app, "Default", "full");
+ meta.identity_provider = site.is_some_and(cua_keyvault::model::is_identity_provider);
(meta, payload)
}
@@ -97,46 +71,14 @@ fn seed(dir: &Path, passphrase: &str) -> Result<(), String> {
let mut v = Vault::create(dir, &[&p])
.and_then(|v| v.with_anchor(Box::new(FileGenerationAnchor::new(anchor))))
.map_err(|e| e.to_string())?;
- let items = [
- fake(
- ItemKind::BrowserSite,
- "Chrome",
- Some("github.com"),
- false,
- ),
- fake(
- ItemKind::BrowserSite,
- "Chrome",
- Some("github.com"),
- false,
- ),
- fake(
- ItemKind::BrowserSite,
- "Chrome",
- Some("linear.app"),
- false,
- ),
- fake(
- ItemKind::BrowserSite,
- "Firefox",
- Some("accounts.google.com"),
- true,
- ),
- fake(
- ItemKind::AppSession,
- "Slack",
- None,
- Some("Example Workspace"),
- false,
- ),
+ let items = vec![
+ fake("Chrome", Some("github.com"), "user_session"),
+ fake("Chrome", Some("github.com"), "logged_in"),
+ fake("Chrome", Some("linear.app"), "linear_session"),
+ fake("Firefox", Some("accounts.google.com"), "SID"),
+ fake("Slack", None, "storage/root-state.json"),
];
- for (meta, payload) in items {
- v.put_item(meta, &payload).map_err(|e| e.to_string())?;
- }
+ v.upsert_items(items).map_err(|e| e.to_string())?;
Ok(())
}
@@ -147,10 +89,12 @@ async fn client(sock: &Path) -> Result<KeyvaultClient, String> {
}
async fn item_by_label(c: &mut KeyvaultClient, label: &str) -> Result<String, String> {
- let items = c.list_items().await.map_err(|e| e.to_string())?;
- items
+ // Names show only inside the browse window.
+ c.browse().await.map_err(|e| e.to_string())?;
+ let page = c.list_items().await.map_err(|e| e.to_string())?;
+ page.items
.into_iter()
- .find(|i| i.label.contains(label) || i.account.as_deref() == Some(label))
+ .find(|i| i.key == label || i.domain.as_deref().is_some_and(|d| d.contains(label)))
.map(|i| i.id)
.ok_or_else(|| format!("no item matching {label:?}"))
}
@@ -179,7 +123,6 @@ async fn main() -> Result<(), String> {
selectors: vec![Selector::Site {
app: "chrome".into(),
site,
- account: None,
}],
targets: vec![arg(3)?],
reason: arg(4)?,
@@ -209,10 +152,9 @@ async fn main() -> Result<(), String> {
"unattended" => {
let mut c = client(Path::new(&arg(1)?)).await?;
let id = item_by_label(&mut c, &arg(2)?).await?;
- let items = c.list_items().await.map_err(|e| e.to_string())?;
- let mut policy = items.iter().find(|i| i.id == id).unwrap().policy.clone();
- policy.unattended = true;
- c.call(&Request::SetItemPolicy { id, policy })
+ // Unlocked means "allow unattended access"; the daemon asks for
+ // presence.
+ c.set_locked(vec![id], false)
.await
.map(|_| ())
.map_err(|e| e.to_string())
@@ -224,7 +166,6 @@ async fn main() -> Result<(), String> {
selectors: vec![Selector::Site {
app: "chrome".into(),
site: arg(2)?,
- account: None,
}],
targets: vec![arg(3)?],
reason: "fixture".into(),
diff --git a/apps/cua-spaces/src-tauri/tests/keyvault.rs b/apps/cua-spaces/src-tauri/tests/keyvault.rs
index 38376d16fc..49ce3b151d 100644
--- a/apps/cua-spaces/src-tauri/tests/keyvault.rs
+++ b/apps/cua-spaces/src-tauri/tests/keyvault.rs
@@ -15,9 +15,8 @@ use cua_keyvault::broker::{
AccessRequest, Backend, Broker, Captured, Decision, DeliveryOutcome, FakePresence, ImportSpec,
InitRequest, Inventory, Selector, SiteChoice, TeleportRequest,
};
-use cua_keyvault::model::{
- CookieInfo, ItemKind, ItemMeta, ItemPayload, ItemPolicy, ItemSummary, PayloadEntry,
-};
+use cua_keyvault::model::PayloadEntry;
+use cua_keyvault::record::{self, CookieRecord};
use cua_keyvault::CallerIdentity;
use cua_spaces_ext::daemon::keyvault::Keyvault;
use cua_spaces_lib::keyvault::{DirectTransport, KeyvaultCommands, SocketTransport};
@@ -28,54 +27,31 @@ struct FakeBackend {
wiped: Mutex<Vec<(String, String)>>,
}
-fn fixture(app: &str, site: Option<&str>, account: Option<&str>) -> Captured {
- let kind = if site.is_some() {
- ItemKind::BrowserSite
- } else {
- ItemKind::AppSession
- };
- let label = match site {
- Some(s) => format!("{s} ({app}, Default)"),
- None => format!("{app} (whole app session)"),
+/// One captured item: a site's session cookie, or (no site) a file of the
+/// whole app. Fixture bytes only; nothing here is a secret.
+fn fixture(app: &str, site: Option<&str>) -> Captured {
+ let new = match site {
+ Some(s) => record::cookie_record(&CookieRecord {
+ creation_utc: None,
+ expires_utc: 0,
+ host_key: format!(".{s}"),
+ http_only: true,
+ last_update_utc: None,
+ name: "fixture_session".into(),
+ partition_key: None,
+ path: "/".into(),
+ priority: None,
+ same_site: -1,
+ secure: true,
+ source_port: None,
+ source_scheme: None,
+ value: b"FIXTURE-NOT-A-SECRET".to_vec(),
+ })
+ .unwrap(),
+ None => record::file_record("fixture/state.json", 0o600, b"FIXTURE-NOT-A-SECRET").unwrap(),
};
- Captured {
- meta: ItemMeta {
- id: String::new(),
- kind,
- label,
- provider_id: app.into(),
- app_display: app.into(),
- site: site.map(Into::into),
- account: account.map(Into::into),
- source: "Default".into(),
- summary: ItemSummary {
- cookies: vec![CookieInfo {
- name: "fixture_session".into(),
- domain: format!(".{}", site.unwrap_or("example.test")),
- session: true,
- expires_ms: None,
- }],
- ..Default::default()
- },
- warnings: vec![],
- identity_provider: site == Some("accounts.example-idp.test"),
- policy: ItemPolicy::default(),
- created_ms: 0,
- updated_ms: 0,
- rev: 0,
- record_digest: String::new(),
- },
- payload: ItemPayload {
- provider_id: app.into(),
- scope: "full".into(),
- entries: vec![PayloadEntry {
- rel_path: format!("fixture/{}", site.unwrap_or(app)),
- mode: 0o600,
- // "FIXTURE-NOT-A-SECRET"
- data: "RklYVFVSRS1OT1QtQS1TRUNSRVQ=".into(),
- }],
- },
- }
+ let (meta, payload) = new.into_item(app, app, "Default", "full");
+ Captured { meta, payload }
}
#[async_trait::async_trait]
@@ -92,10 +68,10 @@ impl Backend for FakeBackend {
let mut out: Vec<Captured> = spec
.sites
.iter()
- .map(|s| fixture(&spec.app, Some(&s.site), Some("[email protected]")))
+ .map(|s| fixture(&spec.app, Some(&s.site)))
.collect();
if spec.whole_app {
- out.push(fixture(&spec.app, None, Some("Example Workspace")));
+ out.push(fixture(&spec.app, None));
}
Ok(out)
}
@@ -104,13 +80,11 @@ impl Backend for FakeBackend {
&self,
target: &str,
_provider_id: &str,
- payloads: Vec<ItemPayload>,
+ _scope: &str,
+ entries: Vec<PayloadEntry>,
_expires_ms: u64,
) -> cua_keyvault::Result<DeliveryOutcome> {
- let paths: Vec<String> = payloads
- .iter()
- .flat_map(|p| p.entries.iter().map(|e| e.rel_path.clone()))
- .collect();
+ let paths: Vec<String> = entries.iter().map(|e| e.rel_path.clone()).collect();
let mut d = self.delivered.lock().unwrap();
d.push((target.into(), paths.clone()));
Ok(DeliveryOutcome {
@@ -180,7 +154,7 @@ async fn rig() -> Rig {
include_passwords: false,
},
SiteChoice {
- site: "accounts.example-idp.test".into(),
+ site: "accounts.google.com".into(),
include_storage: false,
include_passwords: false,
},
@@ -218,15 +192,28 @@ async fn rig() -> Rig {
}
}
-fn item_id(items: &[cua_spaces_app_core::keyvault::KvItem], label_prefix: &str) -> String {
+/// The id of the item whose site (or, for a file, whose app) starts with
+/// `prefix`. Names show only inside the browse window.
+fn item_id(items: &[cua_spaces_app_core::keyvault::KvItem], prefix: &str) -> String {
items
.iter()
- .find(|i| i.label.starts_with(label_prefix))
- .unwrap_or_else(|| panic!("no item {label_prefix}"))
+ .find(|i| {
+ i.domain
+ .as_deref()
+ .is_some_and(|d| d.trim_start_matches('.').starts_with(prefix))
+ || (i.domain.is_none() && i.provider_id == prefix)
+ })
+ .unwrap_or_else(|| panic!("no item {prefix}"))
.id
.clone()
}
+/// The items with their names (opens the browse window first).
+async fn named_items(r: &Rig) -> Vec<cua_spaces_app_core::keyvault::KvItem> {
+ r.page.browse().await.unwrap();
+ r.page.overview().await.items
+}
+
/// A grant for `item` to `target`, requested by the third party and approved
/// through the page.
async fn granted_token(r: &Rig, item: &str, target: &str) -> String {
@@ -267,23 +254,29 @@ async fn overview_lists_items_with_nothing_selected_by_default() {
assert!(o.items.iter().all(|i| !i.policy.unattended));
assert!(o.rules.is_empty() && o.grants.is_empty());
assert!(o.pending.is_empty() && o.deliveries.is_empty());
- // Per site and per account, never values: ListItems is the redacted view.
- let gh = o
+ // Names stay hidden until the browse window opens; values never show.
+ assert!(!o.names_visible);
+ assert!(o
.items
.iter()
- .find(|i| i.site.as_deref() == Some("github.example.test"))
- .unwrap();
- assert_eq!(gh.account.as_deref(), Some("[email protected]"));
- assert!(gh
- .summary
- .cookies
- .iter()
- .all(|c| c.name.is_empty() && c.domain.is_empty()));
+ .all(|i| i.domain.is_none() && i.key.is_empty()));
let json = serde_json::to_string(&o).unwrap();
assert!(
- !json.contains("RklYVFVSRS1OT1QtQS1TRUNSRVQ"),
+ !json.contains("RklYVFVSRS1OT1QtQS1TRUNSRVQ") && !json.contains("FIXTURE-NOT-A-SECRET"),
"payload leaked"
);
+ let named = named_items(&r).await;
+ let gh = named
+ .iter()
+ .find(|i| i.domain.as_deref() == Some(".github.example.test"))
+ .unwrap();
+ assert_eq!(
+ (gh.kind.as_str(), gh.key.as_str()),
+ ("cookie", "fixture_session")
+ );
+ assert!(!serde_json::to_string(&named)
+ .unwrap()
+ .contains("FIXTURE-NOT-A-SECRET"));
// The audit log records the imports and the chain verifies.
assert!(o.audit.iter().any(|e| e.kind == "item.import"));
assert!(o.audit_verification.as_ref().unwrap().ok);
@@ -293,7 +286,7 @@ async fn overview_lists_items_with_nothing_selected_by_default() {
#[tokio::test]
async fn kill_switch_refuses_teleport_app_and_outstanding_grants() {
let r = rig().await;
- let items = r.page.overview().await.items;
+ let items = named_items(&r).await;
let gh = item_id(&items, "github.example.test");
let token = granted_token(&r, &gh, "dev-1").await;
@@ -362,10 +355,10 @@ async fn kill_switch_refuses_teleport_app_and_outstanding_grants() {
#[tokio::test]
async fn per_item_toggles_narrow_freely_and_widen_only_with_presence() {
let r = rig().await;
- let items = r.page.overview().await.items;
+ let items = named_items(&r).await;
let gh = item_id(&items, "github.example.test");
let slack = item_id(&items, "slack");
- let idp = item_id(&items, "accounts.example-idp.test");
+ let idp = item_id(&items, "accounts.google.com");
// Widening (on) goes through the daemon's presence gate.
r.presence.set(false);
@@ -375,32 +368,37 @@ async fn per_item_toggles_narrow_freely_and_widen_only_with_presence() {
.await
.is_err());
r.presence.set(true);
- let out = r
- .page
+ r.page
.set_unattended(&[gh.clone(), slack.clone()], true)
.await
.unwrap();
- assert!(out.iter().all(|i| i.policy.unattended));
let asked = r.presence.asked.lock().unwrap().len();
- assert_eq!(asked, 3, "one declined prompt, then one per widened item");
+ assert_eq!(
+ asked, 3,
+ "browsing, one declined prompt, then one for the whole batch"
+ );
// Narrowing (off) never prompts, and touches only the named item.
- let out = r
- .page
+ r.page
.set_unattended(std::slice::from_ref(&gh), false)
.await
.unwrap();
- assert!(!out[0].policy.unattended);
assert_eq!(r.presence.asked.lock().unwrap().len(), asked);
+ r.page.browse().await.unwrap();
let o = r.page.overview().await;
let by_id = |id: &str| o.items.iter().find(|i| i.id == id).unwrap().clone();
assert!(!by_id(&gh).policy.unattended);
assert!(by_id(&slack).policy.unattended);
- assert!(o.audit.iter().filter(|e| e.kind == "item.policy").count() >= 3);
+ assert!(o.audit.iter().any(|e| e.kind == "item.unlock"));
+ assert!(o.audit.iter().any(|e| e.kind == "item.lock"));
- // Identity providers always ask: the page refuses to widen them.
- let err = r.page.set_unattended(&[idp], true).await.unwrap_err();
- assert_eq!(err.code, "forbidden");
+ // Identity providers always ask: the vault skips them when widening.
+ let out = r
+ .page
+ .set_locked(std::slice::from_ref(&idp), false)
+ .await
+ .unwrap();
+ assert_eq!(out.skipped, vec![idp]);
// An empty selection is a no-op.
assert!(r.page.set_unattended(&[], true).await.unwrap().is_empty());
@@ -409,7 +407,7 @@ async fn per_item_toggles_narrow_freely_and_widen_only_with_presence() {
#[tokio::test]
async fn pending_requests_can_be_denied_and_grants_revoked() {
let r = rig().await;
- let items = r.page.overview().await.items;
+ let items = named_items(&r).await;
let gh = item_id(&items, "github.example.test");
let pending = r
@@ -456,7 +454,7 @@ async fn pending_requests_can_be_denied_and_grants_revoked() {
#[tokio::test]
async fn a_delivery_can_be_wiped_from_the_page() {
let r = rig().await;
- let items = r.page.overview().await.items;
+ let items = named_items(&r).await;
let gh = item_id(&items, "github.example.test");
let token = granted_token(&r, &gh, "dev-1").await;
r.broker
diff --git a/apps/cua-spaces/src/components/desktop/KeyvaultView.test.tsx b/apps/cua-spaces/src/components/desktop/KeyvaultView.test.tsx
deleted file mode 100644
index b86a325ec6..0000000000
--- a/apps/cua-spaces/src/components/desktop/KeyvaultView.test.tsx
+++ /dev/null
@@ -1,270 +0,0 @@
-// SPDX-License-Identifier: FSL-1.1-MIT
-// Copyright (c) 2026 Cua AI, Inc.
-
-import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
-
-import type { SpaceRow } from "../../model/spaces";
-import { createFakeHostBridge } from "../../native/host";
-import { createFakeInstallerBridge } from "../../native/installer";
-import type { KeyvaultBridge, KeyvaultOverview } from "../../native/keyvault";
-import { fakeFleetBridge } from "../../test/fakeFleet";
-import { createFakeKeyvaultBridge, fixtureOverview, NOW } from "../../test/fakeKeyvault";
-import { MainWindow } from "./MainWindow";
-
-const ROWS: SpaceRow[] = [
- { id: "cloud:aurora", name: "aurora", provider: "cloud", spacesdVersion: "0.4.0", features: [], os: "linux", reachable: true },
-];
-
-function setup(keyvault: KeyvaultBridge = createFakeKeyvaultBridge()) {
- const fleet = fakeFleetBridge({
- isNative: true,
- listSpaces: async () => ROWS,
- status: async () => ({ configured: true, authMode: "user", baseUrl: "", tokenUrl: "", identity: "[email protected]" }),
- screenshot: async () => "data:image/png;base64,AAAA",
- });
- const host = createFakeHostBridge({ onboarding: { completed: true, mode: "client" } });
- const installer = createFakeInstallerBridge({ plan: { installed: true, upToDate: true, onPath: true } });
- render(<MainWindow fleet={fleet} host={host} installer={installer} keyvault={keyvault} now={() => NOW} />);
- return { keyvault };
-}
-
-async function openKeyvault(category = "All") {
- const kv = await screen.findByRole("listbox", { name: "Keyvault" });
- fireEvent.click(await within(kv).findByRole("option", { name: new RegExp(`^${category}`) }));
- return screen.findByRole("heading", { level: 1, name: category });
-}
-
-function switches(scope: HTMLElement = document.body) {
- return within(scope).getAllByRole("switch");
-}
-
-describe("Keyvault", () => {
- it("is a sidebar section after the Spaces: categories, then one row per site, with the Waiting badge", async () => {
- setup();
- const kv = await screen.findByRole("listbox", { name: "Keyvault" });
- await waitFor(() => expect(within(kv).getByLabelText("1 waiting")).toBeInTheDocument());
- const names = within(kv)
- .getAllByRole("option")
- .map((o) => o.textContent);
- expect(names.slice(0, 4)).toEqual(["All", "Waiting1", "Access", "Recent"]);
- expect(names.slice(4)).toEqual(["accounts.example-idp.test", "github.example.test", "Slack"]);
- await openKeyvault();
- expect(within(kv).getByRole("option", { name: /^All/ })).toHaveAttribute("aria-selected", "true");
- fireEvent.click(await screen.findByRole("option", { name: /Aurora/ }));
- expect(await screen.findByRole("heading", { level: 1, name: "Aurora" })).toBeInTheDocument();
- });
-
- it("All lists every site's accounts with nothing allowed unattended by default", async () => {
- setup();
- await openKeyvault();
- const list = await screen.findByRole("list", { name: "Saved items" });
- const gh = within(list).getByRole("listitem", { name: "github.example.test" });
- expect(within(gh).getByText("[email protected]")).toBeInTheDocument();
- expect(within(gh).getByText("[email protected]")).toBeInTheDocument();
- expect(within(list).getByRole("listitem", { name: "Slack" })).toHaveTextContent("Example Workspace");
- for (const t of switches(list)) expect(t).toHaveAttribute("aria-checked", "false");
- // The strongest consent state of each account; "asks" is the default and is not spelled out.
- expect(within(gh).getByText("Waiting: com.example.koalabot")).toBeInTheDocument();
- expect(within(gh).queryByText("Asks every time")).toBeNull();
- // Protection, stated as it is, at the bottom of All.
- const facts = screen.getByRole("region", { name: "Protection" });
- expect(facts).toHaveTextContent("Asked by the Cua daemon to widen access");
- expect(facts).toHaveTextContent("Not used: needs a provisioning-signed build");
- expect(facts).toHaveTextContent("Verified as Cua");
- expect(facts).toHaveTextContent("Signature verified");
- });
-
- it("toggles one account; a site's page toggles every account on it", async () => {
- const keyvault = createFakeKeyvaultBridge();
- setup(keyvault);
- await openKeyvault();
- fireEvent.click(
- await screen.findByRole("switch", { name: "Allow [email protected] on github.example.test unattended" }),
- );
- await waitFor(() => expect(keyvault.calls).toContain("setUnattended:gh-ada:true"));
- const kv = screen.getByRole("listbox", { name: "Keyvault" });
- fireEvent.click(within(kv).getByRole("option", { name: "github.example.test" }));
- fireEvent.click(await screen.findByRole("switch", { name: "Allow every github.example.test account unattended" }));
- await waitFor(() => expect(keyvault.calls).toContain("setUnattended:gh-ada,gh-bob:true"));
- await waitFor(() =>
- expect(screen.getByRole("switch", { name: "Allow every github.example.test account unattended" })).toHaveAttribute(
- "aria-checked",
- "true",
- ),
- );
- // Identity providers always ask: their switch is off and disabled.
- fireEvent.click(within(kv).getByRole("option", { name: "accounts.example-idp.test" }));
- await screen.findByRole("heading", { level: 1, name: "accounts.example-idp.test" });
- expect(switches(screen.getByRole("list", { name: "Saved items" }))[0]).toBeDisabled();
- });
-
- it("shows a declined Touch ID prompt as an error and changes nothing", async () => {
- const keyvault = createFakeKeyvaultBridge();
- keyvault.state.presence = false;
- setup(keyvault);
- await openKeyvault();
- fireEvent.click(await screen.findByRole("switch", { name: "Allow [email protected] on github.example.test unattended" }));
- expect(await screen.findByRole("alert")).toHaveTextContent("user presence was not confirmed");
- expect(keyvault.state.overview.items.every((i) => !i.policy.unattended)).toBe(true);
- });
-
- it("Waiting approves exactly the ticked items, showing the caller's verified identity", async () => {
- const keyvault = createFakeKeyvaultBridge();
- setup(keyvault);
- await openKeyvault("Waiting");
- const pending = await screen.findByRole("list", { name: "Waiting" });
- expect(pending).toHaveTextContent("com.example.koalabot (signed, team ABCDE12345) · github.example.test → dev-1 · 15 min");
- expect(within(pending).getByTitle(/Says: "open the pull request" \(unverified\)/)).toBeInTheDocument();
- fireEvent.click(within(pending).getByRole("button", { name: "Review…" }));
- // Nothing is selected by default: Approve stays off until an item is ticked.
- expect(within(pending).getByRole("button", { name: "Approve" })).toBeDisabled();
- const box = within(pending).getByRole("checkbox", { name: "github.example.test [email protected]" });
- expect(box).not.toBeChecked();
- fireEvent.click(box);
- fireEvent.click(within(pending).getByRole("button", { name: "Approve 1 item" }));
- await waitFor(() => expect(screen.getByText("Nothing is waiting.")).toBeInTheDocument());
- expect(keyvault.calls).toContain("approve:req-1");
- expect(keyvault.calls).toContain("approve-items:gh-ada");
- await openKeyvault("Access");
- expect(await screen.findByRole("list", { name: "Access" })).toHaveTextContent("com.example.koalabot → dev-1");
- });
-
- it("Waiting denies a request", async () => {
- const keyvault = createFakeKeyvaultBridge();
- setup(keyvault);
- await openKeyvault("Waiting");
- fireEvent.click(within(await screen.findByRole("list", { name: "Waiting" })).getByRole("button", { name: "Deny" }));
- await waitFor(() => expect(keyvault.calls).toContain("deny:req-1"));
- });
-
- it("Access revokes a grant", async () => {
- const keyvault = createFakeKeyvaultBridge();
- setup(keyvault);
- await openKeyvault("Access");
- const access = await screen.findByRole("list", { name: "Access" });
- fireEvent.click(within(access).getByRole("button", { name: "Revoke" }));
- await waitFor(() => expect(screen.getByText("No live access.")).toBeInTheDocument());
- expect(keyvault.calls).toEqual(["revokeGrant:grant-1"]);
- });
-
- it("the switch in the sidebar turns the Keyvault off and blocks approvals and toggles", async () => {
- const keyvault = createFakeKeyvaultBridge();
- setup(keyvault);
- await openKeyvault();
- const kill = await screen.findByRole("switch", { name: "Keyvault" });
- expect(kill).toHaveAttribute("aria-checked", "true");
- expect(kill).toHaveAttribute("title", "Stops every teleport, import and approval");
- fireEvent.click(kill);
- await waitFor(() => expect(kill).toHaveAttribute("aria-checked", "false"));
- expect(keyvault.calls).toEqual(["setDisabled:true"]);
- expect(screen.getByText("Keyvault is off. Nothing can be teleported.")).toBeInTheDocument();
- expect(kill).toHaveAttribute("title", "Turning it back on asks for Touch ID");
- for (const t of switches(screen.getByRole("list", { name: "Saved items" }))) expect(t).toBeDisabled();
- // Turning it back on goes through presence; a declined prompt keeps it off.
- keyvault.state.presence = false;
- fireEvent.click(kill);
- expect(await screen.findByRole("alert")).toHaveTextContent("user presence was not confirmed");
- expect(kill).toHaveAttribute("aria-checked", "false");
- });
-
- it("Recent shows decisions from the audit log with the chain check", async () => {
- setup();
- await openKeyvault("Recent");
- const log = await screen.findByRole("list", { name: "Audit log" });
- const rows = within(log).getAllByRole("listitem");
- expect(rows[0]).toHaveTextContent("Refused");
- expect(rows[1]).toHaveTextContent("Approved");
- expect(screen.getByText("Log verified")).toBeInTheDocument();
- });
-
- it("flags a tampered audit log", async () => {
- setup(createFakeKeyvaultBridge(fixtureOverview({ auditVerification: { ok: false, entries: 5, unauthenticated: 0, tampered_line: 3 } })));
- await openKeyvault("Recent");
- expect(await screen.findByText("Log tampered at #3")).toBeInTheDocument();
- });
-
- it.each<[Partial<KeyvaultOverview>, string]>([
- [{ availability: "not_first_party", message: "The Keyvault only shows items to apps signed by Cua." }, "This app is not signed by Cua"],
- [{ availability: "not_running", message: "The Cua daemon is not running." }, "The Keyvault is not running"],
- [{ availability: "locked", message: "The Keyvault is locked." }, "The Keyvault is locked"],
- ])("explains why it cannot show items (%o)", async (over, title) => {
- setup(createFakeKeyvaultBridge(fixtureOverview({ ...over, items: [], pending: [] })));
- const kv = await screen.findByRole("listbox", { name: "Keyvault" });
- fireEvent.click(await within(kv).findByRole("option", { name: /^All/ }));
- expect(await screen.findByRole("heading", { level: 2, name: title })).toBeInTheDocument();
- expect(screen.getByText(over.message!)).toBeInTheDocument();
- expect(screen.queryByRole("list", { name: "Saved items" })).not.toBeInTheDocument();
- });
-
- it("sets up a new Keyvault and shows the recovery key once", async () => {
- const over = fixtureOverview({ availability: "no_vault", message: "No Keyvault yet.", items: [], pending: [] });
- over.status = { ...over.status!, initialized: false, unlocked: false, os_protector_available: true };
- const keyvault = createFakeKeyvaultBridge(over);
- setup(keyvault);
- const kv = await screen.findByRole("listbox", { name: "Keyvault" });
- fireEvent.click(await within(kv).findByRole("option", { name: /^All/ }));
- fireEvent.click(await screen.findByRole("button", { name: "Set up Keyvault" }));
- expect(
- await screen.findByText("Recovery key, shown once: ABCDE-FGHIJ-KLMNO-PQRST-UVWXY-Z2345-67ABC-DEFGH"),
- ).toBeInTheDocument();
- expect(keyvault.calls).toEqual(["setup"]);
- fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
- expect(screen.queryByText(/ABCDE-FGHIJ/)).not.toBeInTheDocument();
- });
-
- it("unlocks a locked Keyvault", async () => {
- const over = fixtureOverview({ availability: "locked", message: "The Keyvault is locked.", items: [] });
- over.status = { ...over.status!, unlocked: false, unlock_protectors: ["macos-keychain", "recovery"] };
- const keyvault = createFakeKeyvaultBridge(over);
- setup(keyvault);
- const kv = await screen.findByRole("listbox", { name: "Keyvault" });
- fireEvent.click(await within(kv).findByRole("option", { name: /^All/ }));
- expect(screen.queryByLabelText("Passphrase")).not.toBeInTheDocument();
- fireEvent.click(await screen.findByRole("button", { name: "Unlock" }));
- expect(await screen.findByRole("list", { name: "Saved items" })).toBeInTheDocument();
- expect(keyvault.calls).toEqual(["unlock"]);
- });
-
- it("sets up with a passphrase when the daemon has no OS key store", async () => {
- const over = fixtureOverview({ availability: "no_vault", message: "No Keyvault yet.", items: [], pending: [] });
- over.status = { ...over.status!, initialized: false, unlocked: false, os_protector_available: false };
- const keyvault = createFakeKeyvaultBridge(over);
- setup(keyvault);
- const kv = await screen.findByRole("listbox", { name: "Keyvault" });
- fireEvent.click(await within(kv).findByRole("option", { name: /^All/ }));
- const pass = await screen.findByLabelText("Passphrase");
- const again = screen.getByLabelText("Confirm passphrase");
- expect(pass).toHaveAttribute("type", "password");
- expect(again).toHaveAttribute("type", "password");
- const button = screen.getByRole("button", { name: "Set up Keyvault" });
- fireEvent.change(pass, { target: { value: "orbit" } });
- expect(screen.getByText("At least 12 characters")).toBeInTheDocument();
- expect(button).toBeDisabled();
- fireEvent.change(pass, { target: { value: "orbit lantern pickle harbor" } });
- fireEvent.change(again, { target: { value: "orbit lantern" } });
- expect(screen.getByText("The passphrases don't match")).toBeInTheDocument();
- expect(button).toBeDisabled();
- fireEvent.change(again, { target: { value: "orbit lantern pickle harbor" } });
- expect(button).toBeEnabled();
- fireEvent.click(button);
- expect(await screen.findByText(/^Recovery key, shown once/)).toBeInTheDocument();
- expect(keyvault.calls).toEqual(["setupWithPassphrase"]);
- expect(keyvault.passphrases).toEqual(["orbit lantern pickle harbor"]);
- });
-
- it("unlocks with the passphrase", async () => {
- const over = fixtureOverview({ availability: "locked", message: "The Keyvault is locked.", items: [] });
- over.status = { ...over.status!, unlocked: false, unlock_protectors: ["passphrase", "recovery"] };
- const keyvault = createFakeKeyvaultBridge(over);
- setup(keyvault);
- const kv = await screen.findByRole("listbox", { name: "Keyvault" });
- fireEvent.click(await within(kv).findByRole("option", { name: /^All/ }));
- const pass = await screen.findByLabelText("Passphrase");
- expect(screen.queryByLabelText("Confirm passphrase")).not.toBeInTheDocument();
- fireEvent.change(pass, { target: { value: "orbit lantern pickle harbor" } });
- fireEvent.click(screen.getByRole("button", { name: "Unlock" }));
- expect(await screen.findByRole("list", { name: "Saved items" })).toBeInTheDocument();
- expect(keyvault.calls).toEqual(["unlockWithPassphrase"]);
- });
-});
diff --git a/apps/cua-spaces/src/components/desktop/KeyvaultView.tsx b/apps/cua-spaces/src/components/desktop/KeyvaultView.tsx
deleted file mode 100644
index f1524a06e5..0000000000
--- a/apps/cua-spaces/src/components/desktop/KeyvaultView.tsx
+++ /dev/null
@@ -1,695 +0,0 @@
-// SPDX-License-Identifier: FSL-1.1-MIT
-// Copyright (c) 2026 Cua AI, Inc.
-
-import { useCallback, useEffect, useRef, useState } from "react";
-
-import {
- approvalItems,
- approvalView,
- kvList,
- kvPage,
- kvPassphraseCheck,
- kvRecoveryKeyText,
- kvSidebar,
- kvSiteDetail,
- kvSiteToggle,
- openApproval,
- reduceApproval,
- type ApprovalState,
- type ItemRow,
- type KvCommand,
- type KvCredentialForm,
- type KvPage,
- type KvSelection,
- type SiteGroup,
-} from "../../model/keyvault";
-import type { KeyvaultBridge, KeyvaultOverview } from "../../native/keyvault";
-import { Sym } from "./Sym";
-
-/** How often the page re-reads the broker while it is open. */
-export const KEYVAULT_POLL_MS = 5_000;
-/** How often the sidebar badge re-reads it otherwise. */
-export const KEYVAULT_IDLE_POLL_MS = 30_000;
-
-/**
- * Keeps the broker's overview fresh: every [`KEYVAULT_POLL_MS`] while the
- * page is open, every [`KEYVAULT_IDLE_POLL_MS`] for the sidebar badge.
- */
-export function useKeyvaultOverview(bridge: KeyvaultBridge, active: boolean) {
- const [overview, setOverview] = useState<KeyvaultOverview | null>(null);
- const alive = useRef(true);
- const refresh = useCallback(async () => {
- try {
- const next = await bridge.overview();
- if (alive.current) setOverview(next);
- } catch (error) {
- if (alive.current)
- setOverview({
- availability: "error",
- message: error instanceof Error ? error.message : String(error),
- serverVerified: false,
- items: [],
- pending: [],
- grants: [],
- rules: [],
- deliveries: [],
- audit: [],
- partialErrors: [],
- });
- }
- }, [bridge]);
- useEffect(() => {
- alive.current = true;
- if (!bridge.isNative && !active) return;
- void refresh();
- const timer = window.setInterval(() => void refresh(), active ? KEYVAULT_POLL_MS : KEYVAULT_IDLE_POLL_MS);
- return () => {
- alive.current = false;
- window.clearInterval(timer);
- };
- }, [bridge, active, refresh]);
- return { overview, refresh };
-}
-
-/** One broker request at a time, its error, and the recovery key after setup. */
-export function useKeyvaultActions(bridge: KeyvaultBridge, refresh: () => Promise<void>) {
- const [busy, setBusy] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [recoveryKey, setRecoveryKey] = useState<string | null>(null);
- const run = useCallback(
- async (key: string, action: () => Promise<unknown>) => {
- setBusy(key);
- setError(null);
- try {
- await action();
- } catch (e) {
- setError(e instanceof Error ? e.message : String(e));
- } finally {
- setBusy(null);
- await refresh();
- }
- },
- [refresh],
- );
- /** Runs a core command against the broker. */
- const command = useCallback(
- (cmd: KvCommand) => {
- switch (cmd.type) {
- case "setup":
- return run("setup", async () => setRecoveryKey(await bridge.setup()));
- case "unlock":
- return run("unlock", () => bridge.unlock());
- case "set-disabled":
- return run("kill", () => bridge.setDisabled(cmd.disabled));
- case "set-unattended":
- return run(`toggle:${cmd.itemIds.join(",")}`, () => bridge.setUnattended(cmd.itemIds, cmd.unattended));
- case "revoke-grant":
- return run(`revoke:${cmd.id}`, () => bridge.revokeGrant(cmd.id));
- case "remove-rule":
- return run(`rule:${cmd.id}`, () => bridge.removeRule(cmd.id));
- case "release":
- return run(`wipe:${cmd.target}`, () => bridge.release(cmd.target));
- case "approve":
- return run(`approve:${cmd.requestId}`, () => bridge.approve(cmd.requestId, cmd.items));
- case "deny":
- return run(`deny:${cmd.requestId}`, () => bridge.deny(cmd.requestId));
- }
- },
- [bridge, run],
- );
- /** Sets up or unlocks the way the form offers. The passphrase goes to
- * the shell's broker client only; nothing here keeps it. */
- const submitCredential = useCallback(
- (form: KvCredentialForm, passphrase: string) => {
- if (form.mode === "setup")
- return run("setup", async () =>
- setRecoveryKey(
- form.method === "passphrase" ? await bridge.setupWithPassphrase(passphrase) : await bridge.setup(),
- ),
- );
- return run("unlock", () =>
- form.method === "passphrase" ? bridge.unlockWithPassphrase(passphrase) : bridge.unlock(),
- );
- },
- [bridge, run],
- );
- return { busy, error, setError, recoveryKey, setRecoveryKey, command, submitCredential };
-}
-
-export type KeyvaultActions = ReturnType<typeof useKeyvaultActions>;
-
-/**
- * The Keyvault's sidebar section: the title with the
- * global switch (on while the Keyvault works; turning it back on asks for
- * Touch ID in the Cua daemon), then the categories and one row per site.
- */
-export function KeyvaultSidebarSection({
- title,
- overview,
- now,
- selection,
- active,
- actions,
- onSelect,
-}: {
- title: string;
- overview: KeyvaultOverview | null;
- now: number;
- selection: KvSelection;
- active: boolean;
- actions: KeyvaultActions;
- onSelect: (selection: KvSelection) => void;
-}) {
- const page = overview ? kvPage(overview, now) : null;
- const sb = overview ? kvSidebar(overview, now) : null;
- const isSel = (s: KvSelection) =>
- active &&
- s.kind === selection.kind &&
- (s.kind === "category"
- ? selection.kind === "category" && s.category === selection.category
- : selection.kind === "site" && s.key === selection.key);
- return (
- <div className="dw-kv-section">
- <div className="dw-nav-section dw-kv-head">
- <span>{title}</span>
- {page?.killSwitchVisible && (
- <button
- type="button"
- role="switch"
- className="kv-switch"
- aria-checked={!page.disabled}
- aria-label={title}
- title={page.killSwitchHelp}
- disabled={actions.busy !== null || !page.killSwitchEnabled}
- onClick={() => void actions.command({ type: "set-disabled", disabled: !page.disabled })}
- />
- )}
- </div>
- <ul className="dw-nav-list" role="listbox" aria-label={title}>
- {(sb?.categories ?? []).map((c) => {
- const s: KvSelection = { kind: "category", category: c.category };
- return (
- <li key={c.category}>
- <button
- type="button"
- role="option"
- aria-selected={isSel(s)}
- className="dw-row"
- onClick={() => onSelect(s)}
- >
- <Sym name={c.symbol} size={13} />
- <span className="dw-row-name">{c.title}</span>
- {c.badge ? (
- <span className="dw-primary-count" data-tone="accent" aria-label={`${c.badge} waiting`}>
- {c.badge}
- </span>
- ) : null}
- </button>
- </li>
- );
- })}
- {(sb?.sites ?? []).map((site) => {
- const s: KvSelection = { kind: "site", key: site.key };
- return (
- <li key={site.key}>
- <button type="button" role="option" aria-selected={isSel(s)} className="dw-row" onClick={() => onSelect(s)}>
- <span className="dw-row-name">{site.title}</span>
- </button>
- </li>
- );
- })}
- </ul>
- </div>
- );
-}
-
-export interface KeyvaultViewProps {
- overview: KeyvaultOverview | null;
- selection: KvSelection;
- actions: KeyvaultActions;
- now?: () => number;
-}
-
-/**
- * The Keyvault pane for the sidebar's selection: a category (All, Waiting,
- * Access, Recent) or one site. What shows is the app core's
- * (`keyvault::browse`); the page asks the Cua daemon's broker for
- * everything, and anything that widens access (approve, turn the Keyvault
- * back on, allow an item unattended) is confirmed by the daemon with Touch
- * ID or the login password, not by this window.
- */
-export function KeyvaultView({ overview, selection, actions, now = Date.now }: KeyvaultViewProps) {
- const [query, setQuery] = useState("");
- const [approval, setApproval] = useState<ApprovalState | null>(null);
- const t = now();
- const page = overview ? kvPage(overview, t) : null;
- const list = overview && page?.ready ? kvList(overview, selection, t, query) : null;
- const site = overview && page?.ready && selection.kind === "site" ? kvSiteDetail(overview, selection.key, t) : null;
- const busy = actions.busy !== null;
- const blocked = Boolean(page?.disabled);
- const labels = page?.labels;
- const title = list?.title || "Keyvault";
-
- return (
- <>
- <header className="dw-toolbar" data-tauri-drag-region>
- <div className="dw-toolbar-title" data-tauri-drag-region>
- <h1>{title}</h1>
- </div>
- </header>
-
- {page?.disabledBanner && (
- <div className="dw-banner" data-tone="error" role="status">
- <span>{page.disabledBanner}</span>
- </div>
- )}
- {actions.recoveryKey && (
- <div className="dw-banner" role="status">
- <span>{kvRecoveryKeyText(actions.recoveryKey)}</span>
- <button type="button" className="dw-icon-btn" aria-label="Dismiss" onClick={() => actions.setRecoveryKey(null)}>
- <Sym name="xmark" size={12} />
- </button>
- </div>
- )}
- {actions.error && (
- <div className="dw-banner" data-tone="error" role="alert">
- <span>{actions.error}</span>
- <button type="button" className="dw-icon-btn" aria-label="Dismiss" onClick={() => actions.setError(null)}>
- <Sym name="xmark" size={12} />
- </button>
- </div>
- )}
-
- <div className="dw-content">
- {!overview || !page || !labels ? null : !page.ready ? (
- <div className="dw-content-inner kv">
- <h2 className="kv-empty" title={page.message ?? undefined}>
- {page.unavailableTitle}
- </h2>
- {page.message && <p className="kv-none">{page.message}</p>}
- {page.form && (
- <CredentialForm
- key={`${page.form.mode}:${page.form.method}`}
- form={page.form}
- busy={busy}
- onSubmit={(passphrase) => void actions.submitCredential(page.form!, passphrase)}
- />
- )}
- </div>
- ) : selection.kind === "site" ? (
- <div className="dw-content-inner kv">
- {site ? (
- <>
- <dl className="dw-list" aria-label={site.group.title}>
- <div>
- <dt>{labels.appLabel}</dt>
- <dd>{site.group.app}</dd>
- </div>
- </dl>
- {site.siteSwitch && (
- <div className="kv-row">
- <span className="kv-text">{labels.everyAccount}</span>
- <Switch
- label={`Allow every ${site.group.title} account unattended`}
- checked={site.siteState === "on" ? true : site.siteState === "off" ? false : "mixed"}
- disabled={busy || blocked || !site.siteSwitchEnabled}
- title={site.siteSwitchHelp}
- onChange={(on) => void actions.command(kvSiteToggle(site.group, on))}
- />
- </div>
- )}
- <section className="dw-section" aria-label={labels.accountsTitle}>
- <h2 className="kv-h">{labels.accountsTitle}</h2>
- <div className="kv-group" role="list" aria-label="Saved items">
- {site.group.rows.map((row) => (
- <AccountRow key={row.item.id} group={site.group} row={row} busy={busy} blocked={blocked} actions={actions} />
- ))}
- </div>
- </section>
- </>
- ) : (
- <p className="kv-none">{list?.emptyText}</p>
- )}
- </div>
- ) : (
- list && (
- <div className="dw-content-inner kv">
- {page.partialErrors.length > 0 && (
- <p className="dw-error" role="alert">
- {page.partialErrors.join(" · ")}
- </p>
- )}
- {selection.category === "all" && page.searchVisible && (
- <input
- className="dw-input kv-search"
- type="search"
- placeholder="Search"
- aria-label="Search items"
- value={query}
- spellCheck={false}
- onChange={(e) => setQuery(e.target.value)}
- />
- )}
- {list.sites.length > 0 && (
- <div role="list" aria-label="Saved items">
- {list.sites.map((g) => (
- <section className="dw-section" key={g.key} role="listitem" aria-label={g.title}>
- <h2 className="kv-h">{g.title}</h2>
- <div className="kv-group">
- {g.rows.map((row) => (
- <AccountRow key={row.item.id} group={g} row={row} busy={busy} blocked={blocked} actions={actions} />
- ))}
- </div>
- </section>
- ))}
- </div>
- )}
- {list.pending.length > 0 && overview && (
- <div className="kv-group" role="list" aria-label={list.title}>
- {list.pending.map((p) => (
- <div key={p.id} role="listitem">
- <div className="kv-row" title={p.claims.join("\n") || undefined}>
- <span className="kv-text">
- {p.caller}{" "}
- <span className="kv-trust" data-tone={p.badge.tone}>
- ({p.badge.text})
- </span>{" "}
- · {p.summary} · {p.wants}
- </span>
- <button
- type="button"
- className="dw-btn"
- disabled={busy}
- onClick={() => {
- setApproval(null);
- void actions.command({ type: "deny", requestId: p.id });
- }}
- >
- {labels.deny}
- </button>
- <button
- type="button"
- className="dw-btn dw-btn-primary"
- disabled={busy || blocked}
- onClick={() => setApproval(openApproval(p.id))}
- >
- {labels.review}
- </button>
- </div>
- {approval?.requestId === p.id && (
- <ApprovalSheet
- overview={overview}
- page={page}
- state={approval}
- busy={busy}
- onChange={setApproval}
- onCancel={() => setApproval(null)}
- onDeny={() => {
- setApproval(null);
- void actions.command({ type: "deny", requestId: p.id });
- }}
- onApprove={(items) => {
- setApproval(null);
- void actions.command({ type: "approve", requestId: p.id, items });
- }}
- />
- )}
- </div>
- ))}
- </div>
- )}
- {list.access.length > 0 && (
- <>
- {page.revokeAll && (
- <div className="kv-head">
- <button
- type="button"
- className="dw-btn dw-btn-quiet"
- disabled={busy}
- onClick={() => void actions.command({ type: "revoke-grant", id: "*" })}
- >
- {labels.revokeAll}
- </button>
- </div>
- )}
- <div className="kv-group" role="list" aria-label={list.title}>
- {list.access.map((a) => (
- <div className="kv-row" role="listitem" key={a.key}>
- <span className="kv-text">
- {a.text}
- {a.detail && <span className="kv-muted"> · {a.detail}</span>}
- </span>
- <button
- type="button"
- className="dw-btn"
- disabled={busy}
- onClick={() => void actions.command(a.command)}
- >
- {a.actionLabel}
- </button>
- </div>
- ))}
- </div>
- </>
- )}
- {list.recent.length > 0 && (
- <>
- <ol className="kv-group" aria-label="Audit log">
- {list.recent.map((r) => (
- <li className="kv-row" key={r.decision.entry.seq}>
- <span className="kv-verb" data-tone={r.decision.tone}>
- {r.decision.verb}
- </span>
- <span className="kv-text">{r.decision.what}</span>
- <span className="kv-muted">{r.age}</span>
- </li>
- ))}
- </ol>
- {page.logStatus && (
- <p className="kv-muted" data-tone={page.logTampered ? "danger" : undefined} title="Hash-chained, MAC'd audit log">
- {page.logStatus}
- </p>
- )}
- </>
- )}
- {list.emptyText && <p className="kv-none">{list.emptyText}</p>}
- {selection.category === "all" && page.protection.length > 0 && (
- <section className="dw-section" aria-label={labels.protectionTitle}>
- <h2 className="kv-h">{labels.protectionTitle}</h2>
- <dl className="dw-list">
- {page.protection.map((f) => (
- <div key={f.label}>
- <dt>{f.label}</dt>
- <dd>{f.value}</dd>
- </div>
- ))}
- </dl>
- </section>
- )}
- </div>
- )
- )}
- </div>
- </>
- );
-}
-
-/** One account: its line, its state and its unattended switch. */
-/**
- * Set up or unlock: one button for Touch ID, or password fields (twice for
- * setup) when the daemon cannot use the OS key store. The fields live only
- * in this component's state and are cleared when sent.
- */
-function CredentialForm({
- form,
- busy,
- onSubmit,
-}: {
- form: KvCredentialForm;
- busy: boolean;
- onSubmit: (passphrase: string) => void;
-}) {
- const [passphrase, setPassphrase] = useState("");
- const [confirm, setConfirm] = useState("");
- const usesPassphrase = form.method === "passphrase";
- const check = usesPassphrase ? kvPassphraseCheck(form.mode, passphrase, confirm) : null;
- const canSubmit = !busy && (!usesPassphrase || Boolean(check?.canSubmit));
- const submit = () => {
- if (!canSubmit) return;
- const secret = passphrase;
- setPassphrase("");
- setConfirm("");
- onSubmit(secret);
- };
- return (
- <form
- className="kv-credential"
- onSubmit={(event) => {
- event.preventDefault();
- submit();
- }}
- >
- {usesPassphrase && (
- <>
- <label className="dw-field">
- <span>{form.passphraseLabel}</span>
- <input
- type="password"
- className="dw-input"
- autoComplete={form.mode === "setup" ? "new-password" : "current-password"}
- value={passphrase}
- onChange={(event) => setPassphrase(event.target.value)}
- autoFocus
- />
- </label>
- {form.confirmLabel && (
- <label className="dw-field">
- <span>{form.confirmLabel}</span>
- <input
- type="password"
- className="dw-input"
- autoComplete="new-password"
- value={confirm}
- onChange={(event) => setConfirm(event.target.value)}
- />
- </label>
- )}
- </>
- )}
- <div>
- <button type="submit" className="dw-btn dw-btn-primary" disabled={!canSubmit}>
- {form.submitLabel}
- </button>
- </div>
- <p className="kv-none">{check?.hint ?? form.help}</p>
- </form>
- );
-}
-
-function AccountRow({
- group,
- row,
- busy,
- blocked,
- actions,
-}: {
- group: SiteGroup;
- row: ItemRow;
- busy: boolean;
- blocked: boolean;
- actions: KeyvaultActions;
-}) {
- const state = row.consent.find((c) => c.kind !== "asks");
- return (
- <div className="kv-row" role="listitem" aria-label={row.account}>
- <span className="kv-text" title={row.item.warnings[0]}>
- {row.account}
- </span>
- {state && (
- <span className="kv-state" data-kind={state.kind}>
- {state.text}
- </span>
- )}
- <Switch
- label={`Allow ${row.account} on ${group.title} unattended`}
- checked={row.item.policy.unattended}
- disabled={busy || blocked || !row.toggleEnabled}
- title={row.toggleHelp}
- onChange={(on) => void actions.command({ type: "set-unattended", itemIds: [row.item.id], unattended: on })}
- />
- </div>
- );
-}
-
-/** Approve exactly the items the user ticks; nothing is ticked at first. */
-function ApprovalSheet({
- overview,
- page,
- state,
- busy,
- onChange,
- onCancel,
- onDeny,
- onApprove,
-}: {
- overview: KeyvaultOverview;
- page: KvPage;
- state: ApprovalState;
- busy: boolean;
- onChange: (next: ApprovalState) => void;
- onCancel: () => void;
- onDeny: () => void;
- onApprove: (items: string[] | null) => void;
-}) {
- const v = approvalView(overview, state);
- const items = approvalItems(overview, state);
- return (
- <div className="kv-approval" role="group" aria-label={v.title}>
- <p className="kv-text">
- <strong>{v.title}</strong>
- </p>
- <p className="kv-muted" title={v.claims.join("\n") || undefined}>
- {v.badge.text} · to {v.targets} · {v.wants}
- </p>
- {v.rows.map((row) => (
- <label className="kv-row kv-sub" key={row.key}>
- <input
- type="checkbox"
- checked={row.selected}
- aria-label={`${row.title} ${row.account}`}
- onChange={() => onChange(reduceApproval(overview, state, { type: "toggle", key: row.key }))}
- />
- <span className="kv-text">
- {row.title}
- <span className="kv-muted"> · {row.account}</span>
- </span>
- </label>
- ))}
- {v.blockedReason && <p className="kv-none">{v.blockedReason}</p>}
- <div className="kv-row">
- <span className="kv-text kv-muted">{page.labels.confirmNote}</span>
- <button type="button" className="dw-btn" onClick={onCancel}>
- {page.labels.cancel}
- </button>
- <button type="button" className="dw-btn" disabled={busy} onClick={onDeny}>
- {page.labels.deny}
- </button>
- <button
- type="button"
- className="dw-btn dw-btn-primary"
- disabled={busy || !v.canApprove || items === undefined}
- onClick={() => items !== undefined && onApprove(items)}
- >
- {v.approveLabel}
- </button>
- </div>
- </div>
- );
-}
-
-function Switch({
- label,
- checked,
- disabled,
- title,
- onChange,
-}: {
- label: string;
- checked: boolean | "mixed";
- disabled?: boolean;
- title?: string;
- onChange: (next: boolean) => void;
-}) {
- return (
- <button
- type="button"
- role="switch"
- className="kv-switch"
- aria-checked={checked === "mixed" ? "mixed" : checked}
- aria-label={label}
- title={title}
- disabled={disabled}
- onClick={() => onChange(checked !== true)}
- />
- );
-}
diff --git a/apps/cua-spaces/src/components/desktop/MainWindow.tsx b/apps/cua-spaces/src/components/desktop/MainWindow.tsx
index f5c1fab9ff..4ca5e88ef0 100644
--- a/apps/cua-spaces/src/components/desktop/MainWindow.tsx
+++ b/apps/cua-spaces/src/components/desktop/MainWindow.tsx
@@ -4,7 +4,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { FIXTURE_SPACES } from '../../model/fixtures';
-import type { KvSelection } from '../../model/keyvault';
import type { Space } from '../../model/types';
import {
deleteFailedText,
@@ -35,7 +34,6 @@ import {
type OnboardingState,
} from '../../native/host';
import { createInstallerBridge, type InstallerBridge } from '../../native/installer';
-import { createKeyvaultBridge, type KeyvaultBridge } from '../../native/keyvault';
import { createAgentsBridge, type AgentsBridge } from '../../native/persistent';
import { createDriveBridge, type DriveBridge } from '../../native/drive';
import { AgentsPage, DrivePage, NotificationsPage, useAgentNotifications } from './AgentsPages';
@@ -74,12 +72,6 @@ import TeleportDropZone from '../TeleportDropZone';
import { ThisMachinePanel } from '../ThisMachinePanel';
import { THIS_MACHINE_ID } from '../../model/host';
import { Thumbnail } from '../Thumbnail';
-import {
- KeyvaultSidebarSection,
- KeyvaultView,
- useKeyvaultActions,
- useKeyvaultOverview,
-} from './KeyvaultView';
import { NewSpaceWizard, type CreatePlan, type SpaceHost } from './NewSpaceWizard';
import type { Experiments } from '../../model/experiments';
import { useExperiments } from '../../state/experiments';
@@ -94,7 +86,6 @@ export interface MainWindowProps {
teleport?: TeleportBridge;
fileSend?: FileSendBridge;
windowDrag?: WindowDragBridge;
- keyvault?: KeyvaultBridge;
/** This device on the relay (Settings → Devices, approvals). */
devices?: DevicesBridge;
/** Sharing a Space with other accounts (the Share sheet). */
@@ -149,7 +140,6 @@ export function MainWindow({
teleport: teleportProp,
fileSend: fileSendProp,
windowDrag: windowDragProp,
- keyvault: keyvaultProp,
devices: devicesProp,
share: shareProp,
cloud: cloudProp,
@@ -166,7 +156,6 @@ export function MainWindow({
const teleport = useMemo(() => teleportProp ?? createTeleportBridge(), [teleportProp]);
const fileSend = useMemo(() => fileSendProp ?? createFileSendBridge(), [fileSendProp]);
const windowDrag = useMemo(() => windowDragProp ?? createWindowDragBridge(), [windowDragProp]);
- const keyvault = useMemo(() => keyvaultProp ?? createKeyvaultBridge(), [keyvaultProp]);
const devicesBridge = useMemo(() => devicesProp ?? createDevicesBridge(), [devicesProp]);
const shareBridge = useMemo(() => shareProp ?? createShareBridge(), [shareProp]);
const cloudBridge = useMemo(() => cloudProp ?? createCloudBridge(), [cloudProp]);
@@ -236,7 +225,7 @@ export function MainWindow({
const [hosts, setHosts] = useState<SpaceHost[]>([]);
// Settings, Experiments: what the window shows (Share, your clouds).
const experiments = useExperiments();
- // `?view=new-space|settings|keyvault|this-machine|host-setup|drive|onboarding-presentation|onboarding-drive|onboarding-done` opens that
+ // `?view=new-space|settings|this-machine|host-setup|drive|onboarding-presentation|onboarding-drive|onboarding-done` opens that
// view on load (the shell sets it from CUA_SPACES_START_VIEW, for demos
// and captures), as the SwiftUI app's start views do.
const startView =
@@ -268,30 +257,18 @@ export function MainWindow({
});
const [banner, setBanner] = useState<Banner>(null);
const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
- const [view, setView] = useState<'spaces' | 'settings' | 'keyvault' | 'agents' | 'drive' | 'notifications'>(
+ const [view, setView] = useState<'spaces' | 'settings' | 'agents' | 'drive' | 'notifications'>(
startView === 'settings'
? 'settings'
- : startView === 'keyvault'
- ? 'keyvault'
- : startView === 'drive'
- ? 'drive'
- : 'spaces'
+ : startView === 'drive'
+ ? 'drive'
+ : 'spaces'
);
- const [kvSelection, setKvSelection] = useState<KvSelection>({
- kind: 'category',
- category: 'all',
- });
- const kv = useKeyvaultOverview(keyvault, view === 'keyvault');
- const kvActions = useKeyvaultActions(keyvault, kv.refresh);
const [menuBar, setMenuBar] = useState<boolean>(() => readMenuBar());
const openSpace = useCallback((id: string) => {
setSelectedId(id);
setView('spaces');
}, []);
- const openKeyvault = useCallback((selection: KvSelection) => {
- setKvSelection(selection);
- setView('keyvault');
- }, []);
useEffect(() => {
if (!host.isNative) return;
@@ -421,16 +398,14 @@ export function MainWindow({
});
const b = await listen('main:new-space', () => setWizard(true));
const c = await listen('main:settings', () => setView('settings'));
- const d = await listen('main:keyvault', () => setView('keyvault'));
// The menu bar item's Cua Volume conflicts.
- const e = await listen('main:volume', () => setView('drive'));
+ const d = await listen('main:volume', () => setView('drive'));
if (cancelled) {
a();
b();
c();
d();
- e();
- } else offs.push(a, b, c, d, e);
+ } else offs.push(a, b, c, d);
})
.catch(() => {});
return () => {
@@ -675,15 +650,6 @@ export function MainWindow({
{sidebar.emptyText && !sidebar.thisMachine && (
<p className="dw-hint dw-nav-section">{sidebar.emptyText}</p>
)}
- <KeyvaultSidebarSection
- title={chrome.keyvaultTitle}
- overview={kv.overview}
- now={now()}
- selection={kvSelection}
- active={view === 'keyvault'}
- actions={kvActions}
- onSelect={openKeyvault}
- />
<ul className="dw-nav-list" aria-label="Agents">
{(
[
@@ -731,13 +697,6 @@ export function MainWindow({
<DrivePage bridge={agentsBridge} />
) : view === 'notifications' ? (
<NotificationsPage feed={feed} bridge={agentsBridge} now={now} />
- ) : view === 'keyvault' ? (
- <KeyvaultView
- overview={kv.overview}
- selection={kvSelection}
- actions={kvActions}
- now={now}
- />
) : (
<>
<header className="dw-toolbar" data-tauri-drag-region>
diff --git a/apps/cua-spaces/src/model/keyvault.test.ts b/apps/cua-spaces/src/model/keyvault.test.ts
deleted file mode 100644
index e9681c5923..0000000000
--- a/apps/cua-spaces/src/model/keyvault.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-// SPDX-License-Identifier: FSL-1.1-MIT
-// Copyright (c) 2026 Cua AI, Inc.
-
-import { describe, expect, it } from "vitest";
-
-import { fixtureOverview, kvItem, NOW } from "../test/fakeKeyvault";
-import { groupItems, pendingSummary, recentDecisions, shortCaller } from "./keyvault";
-
-describe("keyvault model", () => {
- it("groups items per site and per account, with nothing allowed unattended by default", () => {
- const groups = groupItems(fixtureOverview(), NOW);
- expect(groups.map((g) => g.title)).toEqual(["accounts.example-idp.test", "github.example.test", "Slack"]);
- const gh = groups.find((g) => g.title === "github.example.test")!;
- expect(gh.rows.map((r) => r.account)).toEqual(["[email protected]", "[email protected]"]);
- expect(groups.every((g) => g.unattended === "off")).toBe(true);
- expect(groups.flatMap((g) => g.rows).every((r) => !r.item.policy.unattended)).toBe(true);
- expect(groups.find((g) => g.title === "accounts.example-idp.test")!.locked).toBe(true);
- });
-
- it("derives each item's consent state from pending requests, grants, rules and copies", () => {
- const o = fixtureOverview({
- rules: [
- {
- id: "rule-1",
- items: ["gh-bob"],
- targets: ["*"],
- callers: [{ fp: "fp", display: 'x (team X, signed id "com.example.ci")' }],
- created_ms: NOW - 1,
- not_after_ms: NOW + 86_400_000,
- enabled: true,
- note: "",
- },
- ],
- deliveries: [
- {
- import_id: "imp-1",
- target: "dev-2",
- provider_id: "slack",
- items: ["slack"],
- caller_fp: "fp-koala",
- delivered_ms: NOW - 1,
- expires_ms: NOW + 3_600_000,
- wiped: false,
- },
- ],
- });
- const rows = new Map(groupItems(o, NOW).flatMap((g) => g.rows.map((r) => [r.item.id, r.consent])));
- expect(rows.get("gh-ada")![0]).toEqual({ kind: "pending", text: "Waiting: com.example.koalabot" });
- expect(rows.get("gh-bob")![0]).toEqual({ kind: "rule", text: "Rule: com.example.ci → any Space" });
- expect(rows.get("slack")!.map((c) => c.kind)).toEqual(["delivered", "granted"]);
- expect(rows.get("idp")).toEqual([{ kind: "asks", text: "Asks every time" }]);
- });
-
- it("ignores expired, revoked and used-up grants", () => {
- const o = fixtureOverview();
- o.grants = [
- { ...o.grants[0]!, id: "a", not_after_ms: NOW - 1 },
- { ...o.grants[0]!, id: "b", revoked: true },
- { ...o.grants[0]!, id: "c", uses_left: 0 },
- ];
- const slack = groupItems(o, NOW).find((g) => g.title === "Slack")!.rows[0]!;
- expect(slack.consent).toEqual([{ kind: "asks", text: "Asks every time" }]);
- });
-
- it("reports a site as mixed when only some accounts are allowed", () => {
- const o = fixtureOverview();
- o.items[0]!.policy.unattended = true;
- expect(groupItems(o, NOW).find((g) => g.title === "github.example.test")!.unattended).toBe("mixed");
- });
-
- it("filters by site, account or app", () => {
- expect(groupItems(fixtureOverview(), NOW, "bob").flatMap((g) => g.rows.map((r) => r.item.id))).toEqual(["gh-bob"]);
- expect(groupItems(fixtureOverview(), NOW, "slack").map((g) => g.title)).toEqual(["Slack"]);
- });
-
- it("lists recent decisions from the audit log, newest first, labelled", () => {
- const d = recentDecisions(fixtureOverview());
- expect(d.map((x) => x.entry.seq)).toEqual([5, 4, 3]);
- expect(d[0]).toMatchObject({ verb: "Refused", tone: "deny" });
- expect(d[0]!.what).toBe("github.example.test (Chrome, Default) → dev-9");
- expect(d[1]).toMatchObject({ verb: "Approved", tone: "ok", what: "Slack (whole app session) → dev-2" });
- });
-
- it("names callers by their signing identifier", () => {
- expect(shortCaller('team X (team X, signed id "com.example.koalabot")')).toBe("com.example.koalabot");
- expect(shortCaller("com.example.adhoc (ad hoc signature, UNVERIFIED)")).toBe("com.example.adhoc");
- expect(shortCaller("/tmp/evil (UNSIGNED, UNTRUSTED)")).toBe("/tmp/evil");
- });
-
- it("summarises what a pending request would move and where", () => {
- const p = fixtureOverview().pending[0]!;
- expect(pendingSummary(p)).toBe("github.example.test → dev-1");
- expect(pendingSummary({ ...p, items: [p.items[0]!, p.items[0]!] })).toBe("github.example.test (2 accounts) → dev-1");
- expect(
- pendingSummary({ ...p, items: [], needs_import: [{ kind: "site", app: "firefox", site: "example.test" }] }),
- ).toBe("example.test (not imported) → dev-1");
- expect(kvItem("x").policy.unattended).toBe(false);
- });
-});
diff --git a/apps/cua-spaces/src/test/fakeKeyvault.ts b/apps/cua-spaces/src/test/fakeKeyvault.ts
deleted file mode 100644
index b3075dee06..0000000000
--- a/apps/cua-spaces/src/test/fakeKeyvault.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-// SPDX-License-Identifier: FSL-1.1-MIT
-// Copyright (c) 2026 Cua AI, Inc.
-
-import type {
- KeyvaultBridge,
- KeyvaultOverview,
- KvAuditEntry,
- KvCaller,
- KvGrant,
- KvItem,
- KvPending,
-} from "../native/keyvault";
-
-/** Fixture data only: made-up sites, accounts and callers. No values. */
-
-export const NOW = 1_800_000_000_000;
-
-export function kvItem(id: string, over: Partial<KvItem> = {}): KvItem {
- return {
- id,
- kind: "browser_site",
- label: `${over.site ?? id} (Chrome, Default)`,
- provider_id: "chrome",
- app_display: "Chrome",
- site: over.site,
- account: over.account,
- source: "Default",
- summary: { cookies: [], storage_origins: [], passwords: 0, files: [], keychain_services: [], bytes: 0 },
- warnings: [],
- identity_provider: false,
- policy: { allowed_targets: [], ttl_secs: 3600, unattended: false },
- created_ms: NOW - 86_400_000,
- updated_ms: NOW - 86_400_000,
- rev: 1,
- record_digest: "00",
- ...over,
- };
-}
-
-export const KOALA: KvCaller = {
- pid: 4242,
- uid: 501,
- path: "/Applications/OpenKoalaBots.app/Contents/MacOS/OpenKoalaBots",
- signing: { kind: "signed", team_id: "ABCDE12345", identifier: "com.example.koalabot", cdhash: "ab" },
- first_party: false,
- os_verified: true,
-};
-export const KOALA_DISPLAY = 'team ABCDE12345 (team ABCDE12345, signed id "com.example.koalabot")';
-
-export function fixtureOverview(over: Partial<KeyvaultOverview> = {}): KeyvaultOverview {
- const items = [
- kvItem("gh-ada", { site: "github.example.test", account: "[email protected]" }),
- kvItem("gh-bob", { site: "github.example.test", account: "[email protected]" }),
- kvItem("idp", { site: "accounts.example-idp.test", account: "[email protected]", identity_provider: true }),
- kvItem("slack", {
- kind: "app_session",
- label: "Slack (whole app session)",
- provider_id: "slack",
- app_display: "Slack",
- account: "Example Workspace",
- }),
- ];
- const pending: KvPending[] = [
- {
- id: "req-1",
- caller: KOALA,
- caller_fp: "fp-koala",
- caller_display: KOALA_DISPLAY,
- request: {
- selectors: [{ kind: "item", id: "gh-ada" }],
- targets: ["dev-1"],
- actions: ["teleport"],
- duration_secs: 900,
- reason: "open the pull request",
- claimed_name: "OpenKoalaBots",
- },
- items: [items[0]!],
- needs_import: [],
- created_ms: NOW - 30_000,
- },
- ];
- const grants: KvGrant[] = [
- {
- id: "grant-1",
- request_id: "req-0",
- caller_fp: "fp-koala",
- caller_display: KOALA_DISPLAY,
- items: ["slack"],
- targets: ["dev-2"],
- actions: ["teleport"],
- created_ms: NOW - 60_000,
- not_after_ms: NOW + 600_000,
- uses_left: 1,
- revoked: false,
- },
- ];
- const audit: KvAuditEntry[] = [
- { seq: 1, ts_ms: NOW - 86_400_000, kind: "vault.create", actor: "Cua", caller_fp: "cua", decision: "ok" },
- { seq: 2, ts_ms: NOW - 3_600_000, kind: "item.import", actor: "Cua", caller_fp: "cua", item: "gh-ada", decision: "ok" },
- { seq: 3, ts_ms: NOW - 120_000, kind: "consent.request", actor: KOALA_DISPLAY, caller_fp: "fp-koala", item: "slack", decision: "ok" },
- { seq: 4, ts_ms: NOW - 60_000, kind: "consent.allow", actor: "Cua", caller_fp: "cua", item: "slack", target: "dev-2", decision: "allow" },
- { seq: 5, ts_ms: NOW - 45_000, kind: "teleport.deny", actor: KOALA_DISPLAY, caller_fp: "fp-koala", item: "gh-bob", target: "dev-9", decision: "deny" },
- ];
- return {
- availability: "ready",
- serverVerified: true,
- status: {
- version: "0.1.0",
- initialized: true,
- unlocked: true,
- disabled: false,
- caller_first_party: true,
- caller_display: 'Cua: Cua (team YCK386LBJ7, signed id "com.trycua.spaces.prototype")',
- items: items.length,
- pending: pending.length,
- unlock_policy: "auto",
- },
- items,
- pending,
- grants,
- rules: [],
- deliveries: [],
- audit,
- auditVerification: { ok: true, entries: audit.length, unauthenticated: 0 },
- partialErrors: [],
- ...over,
- };
-}
-
-/**
- * An in-memory broker with the real one's rules for the page's actions: the
- * kill switch refuses approvals, identity providers never go unattended,
- * and `presence` decides the actions that widen access.
- */
-export function createFakeKeyvaultBridge(initial: KeyvaultOverview = fixtureOverview()) {
- const state = { overview: structuredClone(initial), presence: true };
- const calls: string[] = [];
- /** Passphrases the page sent (fixtures only). */
- const passphrases: string[] = [];
- const requirePresence = () => {
- if (!state.presence) throw new Error("user presence was not confirmed: declined");
- };
- const bridge: KeyvaultBridge & { calls: string[]; passphrases: string[]; state: typeof state } = {
- isNative: true,
- calls,
- passphrases,
- state,
- overview: async () => structuredClone(state.overview),
- setup: async () => {
- calls.push("setup");
- requirePresence();
- state.overview = fixtureOverview({ items: [], pending: [], grants: [], audit: [] });
- return "ABCDE-FGHIJ-KLMNO-PQRST-UVWXY-Z2345-67ABC-DEFGH";
- },
- setupWithPassphrase: async (passphrase) => {
- calls.push("setupWithPassphrase");
- passphrases.push(passphrase);
- requirePresence();
- state.overview = fixtureOverview({ items: [], pending: [], grants: [], audit: [] });
- return "ABCDE-FGHIJ-KLMNO-PQRST-UVWXY-Z2345-67ABC-DEFGH";
- },
- unlock: async () => {
- calls.push("unlock");
- state.overview = { ...fixtureOverview(), status: { ...fixtureOverview().status!, unlocked: true } };
- },
- unlockWithPassphrase: async (passphrase) => {
- calls.push("unlockWithPassphrase");
- passphrases.push(passphrase);
- state.overview = { ...fixtureOverview(), status: { ...fixtureOverview().status!, unlocked: true } };
- },
- setDisabled: async (disabled) => {
- calls.push(`setDisabled:${disabled}`);
- if (!disabled) requirePresence();
- state.overview.status = { ...state.overview.status!, disabled };
- if (disabled) state.overview.pending = [];
- },
- setUnattended: async (ids, on) => {
- calls.push(`setUnattended:${ids.join(",")}:${on}`);
- if (state.overview.status?.disabled) throw new Error("the Keyvault is disabled (global kill switch)");
- if (on) requirePresence();
- const out: KvItem[] = [];
- for (const id of ids) {
- const item = state.overview.items.find((i) => i.id === id)!;
- if (on && item.identity_provider) throw new Error(`forbidden: ${item.label} is an identity provider`);
- item.policy = { ...item.policy, unattended: on };
- out.push(item);
- }
- return out;
- },
- revokeGrant: async (id) => {
- calls.push(`revokeGrant:${id}`);
- let n = 0;
- for (const g of state.overview.grants)
- if ((id === "*" || g.id === id) && !g.revoked) {
- g.revoked = true;
- n++;
- }
- return n;
- },
- removeRule: async (id) => {
- calls.push(`removeRule:${id}`);
- state.overview.rules = state.overview.rules.filter((r) => r.id !== id);
- },
- release: async (target) => {
- calls.push(`release:${target}`);
- const wiped = state.overview.deliveries.filter((d) => d.target === target && !d.wiped);
- for (const d of wiped) d.wiped = true;
- return wiped.map((d) => d.import_id);
- },
- approve: async (requestId, items) => {
- calls.push(`approve:${requestId}`);
- calls.push(`approve-items:${items === null ? "*" : items.join(",")}`);
- if (state.overview.status?.disabled) throw new Error("the Keyvault is disabled (global kill switch)");
- requirePresence();
- const p = state.overview.pending.find((x) => x.id === requestId)!;
- state.overview.pending = state.overview.pending.filter((x) => x.id !== requestId);
- const grant: KvGrant = {
- id: `grant-for-${requestId}`,
- request_id: requestId,
- caller_fp: p.caller_fp,
- caller_display: p.caller_display,
- items: items ?? p.items.map((i) => i.id),
- targets: p.request.targets,
- actions: ["teleport"],
- created_ms: NOW,
- not_after_ms: NOW + 900_000,
- uses_left: 1,
- revoked: false,
- };
- state.overview.grants.push(grant);
- return grant;
- },
- deny: async (requestId) => {
- calls.push(`deny:${requestId}`);
- state.overview.pending = state.overview.pending.filter((x) => x.id !== requestId);
- },
- };
- return bridge;
-}
diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdx
index 2007e3dc7b..63c0fd0f78 100644
--- a/docs/content/docs/cua-sdk/reference/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/index.mdx
@@ -82,8 +82,10 @@ Pages marked *Cua Spaces app export* document the APIs the Cua Spaces apps are b
| [Stream section and facts](/cua-sdk/reference/spaces/app-core/stream) | A Space detail's Stream rows (desktop and windows with their icons and picture in picture) and its facts with live memory and storage use. *Cua Spaces app export.* |
| [New Space wizard](/cua-sdk/reference/spaces/app-core/new-space) | The New Space wizard: where it runs, image, engine, address and the create call. *Cua Spaces app export.* |
| [Image catalog](/cua-sdk/reference/spaces/app-core/images) | The images the New Space wizard offers: groups, sizes, the image field and its suggestions. *Cua Spaces app export.* |
-| [Teleport picker](/cua-sdk/reference/spaces/app-core/teleport) | The teleport picker and review, and consent. *Cua Spaces app export.* |
+| [Teleport picker](/cua-sdk/reference/spaces/app-core/teleport) | The teleport picker and its catalog. *Cua Spaces app export.* |
| [Teleport transfer and drag](/cua-sdk/reference/spaces/app-core/teleport-transfer) | The overlays that show a teleport in progress: the transfer overlay and drag-and-drop onto a Space. *Cua Spaces app export.* |
+| [Teleport plan and run](/cua-sdk/reference/spaces/app-core/teleport-run) | The teleport plan, its consent and capabilities, and the run's steps. *Cua Spaces app export.* |
+| [Teleport review](/cua-sdk/reference/spaces/app-core/teleport-review) | The review and consent before a teleport: what to send per site, from the app or from the Keyvault, and the choice remembered for next time. *Cua Spaces app export.* |
| [Teleport picker grid](/cua-sdk/reference/spaces/app-core/teleport-grid) | The teleport picker's tiles in both apps: tabs, app and window tiles with their icon and preview sources, and the arrow keys. *Cua Spaces app export.* |
| [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core) | Settings, Storage (this machine or an S3-compatible bucket, the Finder volume, the cache), the first run's Cua Volume page and the Drive page's devices and conflicts. *Cua Spaces app export.* |
| [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core) | The Agents page (persistent agents, memory, routines, computer access), the Drive page and the notifications the apps post. *Cua Spaces app export.* |
@@ -94,7 +96,7 @@ Pages marked *Cua Spaces app export* document the APIs the Cua Spaces apps are b
| [Power button](/cua-sdk/reference/spaces/app-core/power) | The power button on a Space: suspend and resume, or turn off and on. *Cua Spaces app export.* |
| [Notch](/cua-sdk/reference/spaces/app-core/notch) | The notch switcher: state, events, layout on the screen and motion. *Cua Spaces app export.* |
| [Keyvault](/cua-sdk/reference/spaces/app-core/keyvault) | The Keyvault broker client and its overview: items, pending requests, grants, rules and audit. *Cua Spaces app export.* |
-| [Keyvault screens](/cua-sdk/reference/spaces/app-core/keyvault-screens) | The Keyvault page, sidebar, list, site detail and the approval prompt. *Cua Spaces app export.* |
+| [Keyvault screens](/cua-sdk/reference/spaces/app-core/keyvault-screens) | The Keyvault page, sidebar, the vault list (apps, sites and items with their locks), the unlock prompt and the approval prompt. *Cua Spaces app export.* |
| [Onboarding and settings](/cua-sdk/reference/spaces/app-core/onboarding-settings) | First-run onboarding, its card miniatures, the settings file and the hotkey label. *Cua Spaces app export.* |
| [About, updates and launch](/cua-sdk/reference/spaces/app-core/about) | The About window and its update channel, what the apps do once they launch (the bundled cua install), and the daemon and refresh reports they read. *Cua Spaces app export.* |
| [Cua Cloud billing](/cua-sdk/reference/spaces/app-core/billing) | The Billing row in Settings and the out-of-credit notice on a refused cloud Space. *Cua Spaces app export.* |
@@ -137,4 +139,4 @@ Pages marked *Cua Spaces app export* document the APIs the Cua Spaces apps are b
290 items, 379 methods. The [Types](/cua-sdk/reference/types) page lists them.
-The Cua Spaces app export adds 685 items and 36 methods.
+The Cua Spaces app export adds 712 items and 38 methods.
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx
index 6320ac3855..f7392d03dd 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/index.mdx
@@ -72,7 +72,7 @@ pub fn app_menu_input_from_json(json: String) -> Result<AppMenuInput, CuaError>
## All items
-568 items, across this page and its subpages, grouped by page. Methods are listed on their object.
+595 items, across this page and its subpages, grouped by page. Methods are listed on their object.
**About, updates and launch**: [`app_about_after_launch`](/cua-sdk/reference/spaces/app-core/about#app_about_after_launch), [`app_about_allowed_channels`](/cua-sdk/reference/spaces/app-core/about#app_about_allowed_channels), [`app_about_input_from_json`](/cua-sdk/reference/spaces/app-core/about#app_about_input_from_json), [`app_about_refresh_notice`](/cua-sdk/reference/spaces/app-core/about#app_about_refresh_notice), [`app_about_restart_daemon`](/cua-sdk/reference/spaces/app-core/about#app_about_restart_daemon), [`app_about_view`](/cua-sdk/reference/spaces/app-core/about#app_about_view), [`app_daemon_check_from_json`](/cua-sdk/reference/spaces/app-core/about#app_daemon_check_from_json), [`app_launch_input_from_json`](/cua-sdk/reference/spaces/app-core/about#app_launch_input_from_json), [`app_refresh_report_from_json`](/cua-sdk/reference/spaces/app-core/about#app_refresh_report_from_json), [`AppAboutInput`](/cua-sdk/reference/spaces/app-core/about#appaboutinput-record), [`AppAboutLink`](/cua-sdk/reference/spaces/app-core/about#appaboutlink-record), [`AppAboutLinkId`](/cua-sdk/reference/spaces/app-core/about#appaboutlinkid-enum), [`AppAboutUpdates`](/cua-sdk/reference/spaces/app-core/about#appaboutupdates-record), [`AppAboutView`](/cua-sdk/reference/spaces/app-core/about#appaboutview-record), [`AppCliInstaller`](/cua-sdk/reference/spaces/app-core/about#appcliinstaller), [`AppCliInstallPlan`](/cua-sdk/reference/spaces/app-core/about#appcliinstallplan-record), [`AppCliInstallRequest`](/cua-sdk/reference/spaces/app-core/about#appcliinstallrequest-record), [`AppDaemonCheck`](/cua-sdk/reference/spaces/app-core/about#appdaemoncheck-record), [`AppInstallMethod`](/cua-sdk/reference/spaces/app-core/about#appinstallmethod-enum), [`AppLaunchInput`](/cua-sdk/reference/spaces/app-core/about#applaunchinput-record), [`AppLaunchPlan`](/cua-sdk/reference/spaces/app-core/about#applaunchplan-record), [`AppRefreshReport`](/cua-sdk/reference/spaces/app-core/about#apprefreshreport-record), [`AppUpdateChannel`](/cua-sdk/reference/spaces/app-core/about#appupdatechannel-enum)
@@ -84,7 +84,7 @@ pub fn app_menu_input_from_json(json: String) -> Result<AppMenuInput, CuaError>
**Cua Cloud billing**: [`app_billing_status`](/cua-sdk/reference/spaces/app-core/billing#app_billing_status), [`AppBillingCard`](/cua-sdk/reference/spaces/app-core/billing#appbillingcard-record), [`AppBillingCredit`](/cua-sdk/reference/spaces/app-core/billing#appbillingcredit-record), [`AppBillingStatus`](/cua-sdk/reference/spaces/app-core/billing#appbillingstatus-record), [`AppCreditNotice`](/cua-sdk/reference/spaces/app-core/billing#appcreditnotice-record)
-**Teleport picker**: [`app_catalog_entries_from_json`](/cua-sdk/reference/spaces/app-core/teleport#app_catalog_entries_from_json), [`app_catalog_entry`](/cua-sdk/reference/spaces/app-core/teleport#app_catalog_entry), [`app_picker_can_plan`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_can_plan), [`app_picker_consent`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_consent), [`app_picker_initial`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_initial), [`app_picker_plan_sensitive`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_plan_sensitive), [`app_picker_primary`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_primary), [`app_picker_progress`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_progress), [`app_picker_reduce`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_reduce), [`app_picker_review`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_review), [`app_picker_sections`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_sections), [`app_picker_sensitive_options`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_sensitive_options), [`app_picker_status`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_status), [`app_teleport_plan`](/cua-sdk/reference/spaces/app-core/teleport#app_teleport_plan), [`app_teleport_plan_from_json`](/cua-sdk/reference/spaces/app-core/teleport#app_teleport_plan_from_json), [`app_teleport_run_event`](/cua-sdk/reference/spaces/app-core/teleport#app_teleport_run_event), [`app_teleport_run_status`](/cua-sdk/reference/spaces/app-core/teleport#app_teleport_run_status), [`AppCatalogEntry`](/cua-sdk/reference/spaces/app-core/teleport#appcatalogentry-record), [`AppConsentItem`](/cua-sdk/reference/spaces/app-core/teleport#appconsentitem-record), [`AppConsentKind`](/cua-sdk/reference/spaces/app-core/teleport#appconsentkind-enum), [`AppEntrySection`](/cua-sdk/reference/spaces/app-core/teleport#appentrysection-record), [`AppInstallCuaPrompt`](/cua-sdk/reference/spaces/app-core/teleport#appinstallcuaprompt-record), [`AppPickerAction`](/cua-sdk/reference/spaces/app-core/teleport#apppickeraction-enum), [`AppPickerEvent`](/cua-sdk/reference/spaces/app-core/teleport#apppickerevent-enum), [`AppPickerPrimary`](/cua-sdk/reference/spaces/app-core/teleport#apppickerprimary-record), [`AppPickerState`](/cua-sdk/reference/spaces/app-core/teleport#apppickerstate-record), [`AppPickerStep`](/cua-sdk/reference/spaces/app-core/teleport#apppickerstep-enum), [`AppPickerTab`](/cua-sdk/reference/spaces/app-core/teleport#apppickertab-enum), [`AppPlanStepView`](/cua-sdk/reference/spaces/app-core/teleport#appplanstepview-record), [`AppReviewView`](/cua-sdk/reference/spaces/app-core/teleport#appreviewview-record), [`AppTeleportCapability`](/cua-sdk/reference/spaces/app-core/teleport#appteleportcapability-enum), [`AppTeleportConsent`](/cua-sdk/reference/spaces/app-core/teleport#appteleportconsent-record), [`AppTeleportMove`](/cua-sdk/reference/spaces/app-core/teleport#appteleportmove-enum), [`AppTeleportPlan`](/cua-sdk/reference/spaces/app-core/teleport#appteleportplan-record), [`AppTeleportRunEvent`](/cua-sdk/reference/spaces/app-core/teleport#appteleportrunevent-record), [`AppTeleportRunPhase`](/cua-sdk/reference/spaces/app-core/teleport#appteleportrunphase-enum), [`AppTeleportRunReport`](/cua-sdk/reference/spaces/app-core/teleport#appteleportrunreport-record)
+**Teleport picker**: [`app_catalog_entries_from_json`](/cua-sdk/reference/spaces/app-core/teleport#app_catalog_entries_from_json), [`app_catalog_entry`](/cua-sdk/reference/spaces/app-core/teleport#app_catalog_entry), [`app_picker_can_plan`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_can_plan), [`app_picker_consent`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_consent), [`app_picker_initial`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_initial), [`app_picker_plan_sensitive`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_plan_sensitive), [`app_picker_primary`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_primary), [`app_picker_progress`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_progress), [`app_picker_reduce`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_reduce), [`app_picker_review`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_review), [`app_picker_sections`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_sections), [`app_picker_sensitive_options`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_sensitive_options), [`app_picker_status`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_status), [`AppCatalogEntry`](/cua-sdk/reference/spaces/app-core/teleport#appcatalogentry-record), [`AppEntrySection`](/cua-sdk/reference/spaces/app-core/teleport#appentrysection-record), [`AppPickerAction`](/cua-sdk/reference/spaces/app-core/teleport#apppickeraction-enum), [`AppPickerEvent`](/cua-sdk/reference/spaces/app-core/teleport#apppickerevent-enum), [`AppPickerPrimary`](/cua-sdk/reference/spaces/app-core/teleport#apppickerprimary-record), [`AppPickerState`](/cua-sdk/reference/spaces/app-core/teleport#apppickerstate-record), [`AppPickerStep`](/cua-sdk/reference/spaces/app-core/teleport#apppickerstep-enum), [`AppPickerTab`](/cua-sdk/reference/spaces/app-core/teleport#apppickertab-enum)
**Your cloud**: [`app_cloud_connect_action_from_json`](/cua-sdk/reference/spaces/app-core/cloud#app_cloud_connect_action_from_json), [`app_cloud_connect_initial`](/cua-sdk/reference/spaces/app-core/cloud#app_cloud_connect_initial), [`app_cloud_connect_input_from_json`](/cua-sdk/reference/spaces/app-core/cloud#app_cloud_connect_input_from_json), [`app_cloud_connect_input_from_status_json`](/cua-sdk/reference/spaces/app-core/cloud#app_cloud_connect_input_from_status_json), [`app_cloud_connect_reduce`](/cua-sdk/reference/spaces/app-core/cloud#app_cloud_connect_reduce), [`app_cloud_connect_view`](/cua-sdk/reference/spaces/app-core/cloud#app_cloud_connect_view), [`app_connected_cloud_from_json`](/cua-sdk/reference/spaces/app-core/cloud#app_connected_cloud_from_json), [`app_connected_clouds_from_status_json`](/cua-sdk/reference/spaces/app-core/cloud#app_connected_clouds_from_status_json), [`app_is_cloud_word`](/cua-sdk/reference/spaces/app-core/cloud#app_is_cloud_word), [`AppCloudCheckInput`](/cua-sdk/reference/spaces/app-core/cloud#appcloudcheckinput-record), [`AppCloudCheckRow`](/cua-sdk/reference/spaces/app-core/cloud#appcloudcheckrow-record), [`AppCloudConnectAction`](/cua-sdk/reference/spaces/app-core/cloud#appcloudconnectaction-enum), [`AppCloudConnectInput`](/cua-sdk/reference/spaces/app-core/cloud#appcloudconnectinput-record), [`AppCloudConnectPhase`](/cua-sdk/reference/spaces/app-core/cloud#appcloudconnectphase-enum), [`AppCloudConnectRequest`](/cua-sdk/reference/spaces/app-core/cloud#appcloudconnectrequest-enum), [`AppCloudConnectState`](/cua-sdk/reference/spaces/app-core/cloud#appcloudconnectstate-record), [`AppCloudConnectView`](/cua-sdk/reference/spaces/app-core/cloud#appcloudconnectview-record), [`AppCloudField`](/cua-sdk/reference/spaces/app-core/cloud#appcloudfield-record), [`AppCloudOffer`](/cua-sdk/reference/spaces/app-core/cloud#appcloudoffer-record), [`AppCloudProviderInput`](/cua-sdk/reference/spaces/app-core/cloud#appcloudproviderinput-record), [`AppCloudProviderRow`](/cua-sdk/reference/spaces/app-core/cloud#appcloudproviderrow-record), [`AppCloudTargetArgs`](/cua-sdk/reference/spaces/app-core/cloud#appcloudtargetargs-record), [`AppConnectedCloud`](/cua-sdk/reference/spaces/app-core/cloud#appconnectedcloud-record)
@@ -108,7 +108,9 @@ pub fn app_menu_input_from_json(json: String) -> Result<AppMenuInput, CuaError>
**Teleport picker grid**: [`app_picker_app_grid`](/cua-sdk/reference/spaces/app-core/teleport-grid#app_picker_app_grid), [`app_picker_grid_primary`](/cua-sdk/reference/spaces/app-core/teleport-grid#app_picker_grid_primary), [`app_picker_grid_step`](/cua-sdk/reference/spaces/app-core/teleport-grid#app_picker_grid_step), [`app_picker_grid_tabs`](/cua-sdk/reference/spaces/app-core/teleport-grid#app_picker_grid_tabs), [`app_picker_remote_grid`](/cua-sdk/reference/spaces/app-core/teleport-grid#app_picker_remote_grid), [`app_picker_window_grid`](/cua-sdk/reference/spaces/app-core/teleport-grid#app_picker_window_grid), [`AppPickerGrid`](/cua-sdk/reference/spaces/app-core/teleport-grid#apppickergrid-record), [`AppPickerGridPrimary`](/cua-sdk/reference/spaces/app-core/teleport-grid#apppickergridprimary-record), [`AppPickerGridTab`](/cua-sdk/reference/spaces/app-core/teleport-grid#apppickergridtab-enum), [`AppPickerGridTabItem`](/cua-sdk/reference/spaces/app-core/teleport-grid#apppickergridtabitem-record), [`AppPickerTile`](/cua-sdk/reference/spaces/app-core/teleport-grid#apppickertile-record), [`AppPickerTileIcon`](/cua-sdk/reference/spaces/app-core/teleport-grid#apppickertileicon-enum), [`AppPickerTileSection`](/cua-sdk/reference/spaces/app-core/teleport-grid#apppickertilesection-record), [`AppPickerTileThumbnail`](/cua-sdk/reference/spaces/app-core/teleport-grid#apppickertilethumbnail-enum)
-**Keyvault**: [`app_sensitive_group_sdk`](/cua-sdk/reference/spaces/app-core/keyvault#app_sensitive_group_sdk), [`AppSensitiveGroup`](/cua-sdk/reference/spaces/app-core/keyvault#appsensitivegroup-enum), [`AppSensitiveOption`](/cua-sdk/reference/spaces/app-core/keyvault#appsensitiveoption-record), [`KeyvaultClient`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultclient), [`KeyvaultOverview`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultoverview-record), [`kv_credential_form`](/cua-sdk/reference/spaces/app-core/keyvault#kv_credential_form), [`kv_duration`](/cua-sdk/reference/spaces/app-core/keyvault#kv_duration), [`kv_labels`](/cua-sdk/reference/spaces/app-core/keyvault#kv_labels), [`kv_overview_from_json`](/cua-sdk/reference/spaces/app-core/keyvault#kv_overview_from_json), [`kv_passphrase_check`](/cua-sdk/reference/spaces/app-core/keyvault#kv_passphrase_check), [`kv_prune_dismissed`](/cua-sdk/reference/spaces/app-core/keyvault#kv_prune_dismissed), [`kv_recovery_key_text`](/cua-sdk/reference/spaces/app-core/keyvault#kv_recovery_key_text), [`kv_sharing_label`](/cua-sdk/reference/spaces/app-core/keyvault#kv_sharing_label), [`kv_signed_in_spaces`](/cua-sdk/reference/spaces/app-core/keyvault#kv_signed_in_spaces), [`kv_space_access_key`](/cua-sdk/reference/spaces/app-core/keyvault#kv_space_access_key), [`kv_visible_sharing_label`](/cua-sdk/reference/spaces/app-core/keyvault#kv_visible_sharing_label), [`KvAccessRequest`](/cua-sdk/reference/spaces/app-core/keyvault#kvaccessrequest-record), [`KvAuditEntry`](/cua-sdk/reference/spaces/app-core/keyvault#kvauditentry-record), [`KvCaller`](/cua-sdk/reference/spaces/app-core/keyvault#kvcaller-record), [`KvCommand`](/cua-sdk/reference/spaces/app-core/keyvault#kvcommand-enum), [`KvCookieInfo`](/cua-sdk/reference/spaces/app-core/keyvault#kvcookieinfo-record), [`KvCredentialForm`](/cua-sdk/reference/spaces/app-core/keyvault#kvcredentialform-record), [`KvDelivery`](/cua-sdk/reference/spaces/app-core/keyvault#kvdelivery-record), [`KvFormMode`](/cua-sdk/reference/spaces/app-core/keyvault#kvformmode-enum), [`KvGrant`](/cua-sdk/reference/spaces/app-core/keyvault#kvgrant-record), [`KvItem`](/cua-sdk/reference/spaces/app-core/keyvault#kvitem-record), [`KvItemPolicy`](/cua-sdk/reference/spaces/app-core/keyvault#kvitempolicy-record), [`KvItemSummary`](/cua-sdk/reference/spaces/app-core/keyvault#kvitemsummary-record), [`KvLabels`](/cua-sdk/reference/spaces/app-core/keyvault#kvlabels-record), [`KvMethod`](/cua-sdk/reference/spaces/app-core/keyvault#kvmethod-enum), [`KvOutcome`](/cua-sdk/reference/spaces/app-core/keyvault#kvoutcome-enum), [`KvPassphraseCheck`](/cua-sdk/reference/spaces/app-core/keyvault#kvpassphrasecheck-record), [`KvPending`](/cua-sdk/reference/spaces/app-core/keyvault#kvpending-record), [`KvRule`](/cua-sdk/reference/spaces/app-core/keyvault#kvrule-record), [`KvRuleCaller`](/cua-sdk/reference/spaces/app-core/keyvault#kvrulecaller-record), [`KvSelector`](/cua-sdk/reference/spaces/app-core/keyvault#kvselector-enum), [`KvSigning`](/cua-sdk/reference/spaces/app-core/keyvault#kvsigning-enum), [`KvStatus`](/cua-sdk/reference/spaces/app-core/keyvault#kvstatus-record), [`KvStrength`](/cua-sdk/reference/spaces/app-core/keyvault#kvstrength-enum), [`KvVerification`](/cua-sdk/reference/spaces/app-core/keyvault#kvverification-record)
+**Teleport review**: [`app_review_remember`](/cua-sdk/reference/spaces/app-core/teleport-review#app_review_remember), [`app_review_remember_key`](/cua-sdk/reference/spaces/app-core/teleport-review#app_review_remember_key), [`app_review_remembered`](/cua-sdk/reference/spaces/app-core/teleport-review#app_review_remembered), [`AppConsentItem`](/cua-sdk/reference/spaces/app-core/teleport-review#appconsentitem-record), [`AppConsentKind`](/cua-sdk/reference/spaces/app-core/teleport-review#appconsentkind-enum), [`AppInstallCuaPrompt`](/cua-sdk/reference/spaces/app-core/teleport-review#appinstallcuaprompt-record), [`AppPlanStepView`](/cua-sdk/reference/spaces/app-core/teleport-review#appplanstepview-record), [`AppRememberedChoice`](/cua-sdk/reference/spaces/app-core/teleport-review#apprememberedchoice-record), [`AppReviewChoice`](/cua-sdk/reference/spaces/app-core/teleport-review#appreviewchoice-record), [`AppReviewDomain`](/cua-sdk/reference/spaces/app-core/teleport-review#appreviewdomain-record), [`AppReviewToggle`](/cua-sdk/reference/spaces/app-core/teleport-review#appreviewtoggle-record), [`AppReviewView`](/cua-sdk/reference/spaces/app-core/teleport-review#appreviewview-record), [`AppSendSource`](/cua-sdk/reference/spaces/app-core/teleport-review#appsendsource-enum), [`AppVaultSource`](/cua-sdk/reference/spaces/app-core/teleport-review#appvaultsource-record)
+
+**Keyvault**: [`app_sensitive_group_sdk`](/cua-sdk/reference/spaces/app-core/keyvault#app_sensitive_group_sdk), [`AppSensitiveGroup`](/cua-sdk/reference/spaces/app-core/keyvault#appsensitivegroup-enum), [`AppSensitiveOption`](/cua-sdk/reference/spaces/app-core/keyvault#appsensitiveoption-record), [`KeyvaultClient`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultclient), [`KeyvaultOverview`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultoverview-record), [`kv_credential_form`](/cua-sdk/reference/spaces/app-core/keyvault#kv_credential_form), [`kv_duration`](/cua-sdk/reference/spaces/app-core/keyvault#kv_duration), [`kv_labels`](/cua-sdk/reference/spaces/app-core/keyvault#kv_labels), [`kv_overview_from_json`](/cua-sdk/reference/spaces/app-core/keyvault#kv_overview_from_json), [`kv_passphrase_check`](/cua-sdk/reference/spaces/app-core/keyvault#kv_passphrase_check), [`kv_prune_dismissed`](/cua-sdk/reference/spaces/app-core/keyvault#kv_prune_dismissed), [`kv_recovery_key_text`](/cua-sdk/reference/spaces/app-core/keyvault#kv_recovery_key_text), [`kv_sharing_label`](/cua-sdk/reference/spaces/app-core/keyvault#kv_sharing_label), [`kv_signed_in_spaces`](/cua-sdk/reference/spaces/app-core/keyvault#kv_signed_in_spaces), [`kv_space_access_key`](/cua-sdk/reference/spaces/app-core/keyvault#kv_space_access_key), [`kv_visible_sharing_label`](/cua-sdk/reference/spaces/app-core/keyvault#kv_visible_sharing_label), [`KvAccessRequest`](/cua-sdk/reference/spaces/app-core/keyvault#kvaccessrequest-record), [`KvAuditEntry`](/cua-sdk/reference/spaces/app-core/keyvault#kvauditentry-record), [`KvCaller`](/cua-sdk/reference/spaces/app-core/keyvault#kvcaller-record), [`KvCommand`](/cua-sdk/reference/spaces/app-core/keyvault#kvcommand-enum), [`KvCredentialForm`](/cua-sdk/reference/spaces/app-core/keyvault#kvcredentialform-record), [`KvDelivery`](/cua-sdk/reference/spaces/app-core/keyvault#kvdelivery-record), [`KvDomainCount`](/cua-sdk/reference/spaces/app-core/keyvault#kvdomaincount-record), [`KvFavicon`](/cua-sdk/reference/spaces/app-core/keyvault#kvfavicon-record), [`KvFormMode`](/cua-sdk/reference/spaces/app-core/keyvault#kvformmode-enum), [`KvGrant`](/cua-sdk/reference/spaces/app-core/keyvault#kvgrant-record), [`KvInventory`](/cua-sdk/reference/spaces/app-core/keyvault#kvinventory-record), [`KvItem`](/cua-sdk/reference/spaces/app-core/keyvault#kvitem-record), [`KvItemPolicy`](/cua-sdk/reference/spaces/app-core/keyvault#kvitempolicy-record), [`KvLabels`](/cua-sdk/reference/spaces/app-core/keyvault#kvlabels-record), [`KvMethod`](/cua-sdk/reference/spaces/app-core/keyvault#kvmethod-enum), [`KvOutcome`](/cua-sdk/reference/spaces/app-core/keyvault#kvoutcome-enum), [`KvPassphraseCheck`](/cua-sdk/reference/spaces/app-core/keyvault#kvpassphrasecheck-record), [`KvPending`](/cua-sdk/reference/spaces/app-core/keyvault#kvpending-record), [`KvRule`](/cua-sdk/reference/spaces/app-core/keyvault#kvrule-record), [`KvRuleCaller`](/cua-sdk/reference/spaces/app-core/keyvault#kvrulecaller-record), [`KvSelector`](/cua-sdk/reference/spaces/app-core/keyvault#kvselector-enum), [`KvSigning`](/cua-sdk/reference/spaces/app-core/keyvault#kvsigning-enum), [`KvStatus`](/cua-sdk/reference/spaces/app-core/keyvault#kvstatus-record), [`KvStrength`](/cua-sdk/reference/spaces/app-core/keyvault#kvstrength-enum), [`KvVerification`](/cua-sdk/reference/spaces/app-core/keyvault#kvverification-record)
**Share sheet**: [`app_share_action_from_json`](/cua-sdk/reference/spaces/app-core/share#app_share_action_from_json), [`app_share_initial`](/cua-sdk/reference/spaces/app-core/share#app_share_initial), [`app_share_input_from_json`](/cua-sdk/reference/spaces/app-core/share#app_share_input_from_json), [`app_share_reduce`](/cua-sdk/reference/spaces/app-core/share#app_share_reduce), [`app_share_state_from_json`](/cua-sdk/reference/spaces/app-core/share#app_share_state_from_json), [`app_share_view`](/cua-sdk/reference/spaces/app-core/share#app_share_view), [`AppRoleOption`](/cua-sdk/reference/spaces/app-core/share#approleoption-record), [`AppShareEntryInput`](/cua-sdk/reference/spaces/app-core/share#appshareentryinput-record), [`AppShareInput`](/cua-sdk/reference/spaces/app-core/share#appshareinput-record), [`AppShareRequest`](/cua-sdk/reference/spaces/app-core/share#appsharerequest-enum), [`AppShareRowView`](/cua-sdk/reference/spaces/app-core/share#appsharerowview-record), [`AppShareSheetAction`](/cua-sdk/reference/spaces/app-core/share#appsharesheetaction-enum), [`AppShareSheetState`](/cua-sdk/reference/spaces/app-core/share#appsharesheetstate-record), [`AppShareSheetView`](/cua-sdk/reference/spaces/app-core/share#appsharesheetview-record)
@@ -116,10 +118,12 @@ pub fn app_menu_input_from_json(json: String) -> Result<AppMenuInput, CuaError>
**Usage telemetry**: [`app_telemetry_creates`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_creates), [`app_telemetry_enroll`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_enroll), [`app_telemetry_feature`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_feature), [`app_telemetry_launched`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_launched), [`app_telemetry_onboarding`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_onboarding), [`app_telemetry_onboarding_finished`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_onboarding_finished), [`app_telemetry_record`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_record), [`app_telemetry_share`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_share), [`app_telemetry_start`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_start), [`app_telemetry_storage`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_storage), [`app_telemetry_welcome_left`](/cua-sdk/reference/spaces/app-core/telemetry#app_telemetry_welcome_left), [`AppTelemetrySignal`](/cua-sdk/reference/spaces/app-core/telemetry#apptelemetrysignal-enum)
+**Teleport plan and run**: [`app_teleport_plan`](/cua-sdk/reference/spaces/app-core/teleport-run#app_teleport_plan), [`app_teleport_plan_from_json`](/cua-sdk/reference/spaces/app-core/teleport-run#app_teleport_plan_from_json), [`app_teleport_run_event`](/cua-sdk/reference/spaces/app-core/teleport-run#app_teleport_run_event), [`app_teleport_run_status`](/cua-sdk/reference/spaces/app-core/teleport-run#app_teleport_run_status), [`AppTeleportCapability`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportcapability-enum), [`AppTeleportConsent`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportconsent-record), [`AppTeleportMove`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportmove-enum), [`AppTeleportPlan`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportplan-record), [`AppTeleportRunEvent`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportrunevent-record), [`AppTeleportRunPhase`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportrunphase-enum), [`AppTeleportRunReport`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportrunreport-record)
+
**Teleport transfer and drag**: [`app_transfer_reduce`](/cua-sdk/reference/spaces/app-core/teleport-transfer#app_transfer_reduce), [`app_transfer_title`](/cua-sdk/reference/spaces/app-core/teleport-transfer#app_transfer_title), [`AppDragOverlayEffect`](/cua-sdk/reference/spaces/app-core/teleport-transfer#appdragoverlayeffect-enum), [`AppDragOverlayEvent`](/cua-sdk/reference/spaces/app-core/teleport-transfer#appdragoverlayevent-enum), [`AppDragOverlayPhase`](/cua-sdk/reference/spaces/app-core/teleport-transfer#appdragoverlayphase-enum), [`AppDragOverlayState`](/cua-sdk/reference/spaces/app-core/teleport-transfer#appdragoverlaystate-record), [`AppDragOverlayTransition`](/cua-sdk/reference/spaces/app-core/teleport-transfer#appdragoverlaytransition-record), [`AppTransferOverlayState`](/cua-sdk/reference/spaces/app-core/teleport-transfer#apptransferoverlaystate-record), [`AppTransferPhase`](/cua-sdk/reference/spaces/app-core/teleport-transfer#apptransferphase-enum), [`AppTransferSignal`](/cua-sdk/reference/spaces/app-core/teleport-transfer#apptransfersignal-record), [`AppTransferStatus`](/cua-sdk/reference/spaces/app-core/teleport-transfer#apptransferstatus-enum)
**New Space wizard**: [`app_wizard_action_from_json`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_action_from_json), [`app_wizard_create_args`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_create_args), [`app_wizard_create_failed_text`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_create_failed_text), [`app_wizard_creating_text`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_creating_text), [`app_wizard_env_from_json`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_env_from_json), [`app_wizard_image_suggestions`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_image_suggestions), [`app_wizard_initial`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_initial), [`app_wizard_reduce`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_reduce), [`app_wizard_validate_image_ref`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_validate_image_ref), [`app_wizard_view`](/cua-sdk/reference/spaces/app-core/new-space#app_wizard_view), [`AppAddressForm`](/cua-sdk/reference/spaces/app-core/new-space#appaddressform-record), [`AppAddressSubmit`](/cua-sdk/reference/spaces/app-core/new-space#appaddresssubmit-record), [`AppAddressView`](/cua-sdk/reference/spaces/app-core/new-space#appaddressview-record), [`AppCloudEngine`](/cua-sdk/reference/spaces/app-core/new-space#appcloudengine-enum), [`AppCloudPricing`](/cua-sdk/reference/spaces/app-core/new-space#appcloudpricing-record), [`AppCreatePlan`](/cua-sdk/reference/spaces/app-core/new-space#appcreateplan-record), [`AppCreateSpaceArgs`](/cua-sdk/reference/spaces/app-core/new-space#appcreatespaceargs-record), [`AppGpuChoice`](/cua-sdk/reference/spaces/app-core/new-space#appgpuchoice-record), [`AppGpuRow`](/cua-sdk/reference/spaces/app-core/new-space#appgpurow-record), [`AppKindOption`](/cua-sdk/reference/spaces/app-core/new-space#appkindoption-record), [`AppLocalEngine`](/cua-sdk/reference/spaces/app-core/new-space#applocalengine-enum), [`AppLocalStorage`](/cua-sdk/reference/spaces/app-core/new-space#applocalstorage-record), [`AppLocation`](/cua-sdk/reference/spaces/app-core/new-space#applocation-enum), [`AppMenuOption`](/cua-sdk/reference/spaces/app-core/new-space#appmenuoption-record), [`AppRuntime`](/cua-sdk/reference/spaces/app-core/new-space#appruntime-enum), [`AppStepDot`](/cua-sdk/reference/spaces/app-core/new-space#appstepdot-record), [`AppStepState`](/cua-sdk/reference/spaces/app-core/new-space#appstepstate-enum), [`AppStepView`](/cua-sdk/reference/spaces/app-core/new-space#appstepview-record), [`AppStorageVolume`](/cua-sdk/reference/spaces/app-core/new-space#appstoragevolume-record), [`AppTile`](/cua-sdk/reference/spaces/app-core/new-space#apptile-record), [`AppWizardAction`](/cua-sdk/reference/spaces/app-core/new-space#appwizardaction-enum), [`AppWizardEnv`](/cua-sdk/reference/spaces/app-core/new-space#appwizardenv-record), [`AppWizardFact`](/cua-sdk/reference/spaces/app-core/new-space#appwizardfact-record), [`AppWizardField`](/cua-sdk/reference/spaces/app-core/new-space#appwizardfield-record), [`AppWizardLabels`](/cua-sdk/reference/spaces/app-core/new-space#appwizardlabels-record), [`AppWizardMode`](/cua-sdk/reference/spaces/app-core/new-space#appwizardmode-enum), [`AppWizardState`](/cua-sdk/reference/spaces/app-core/new-space#appwizardstate-record), [`AppWizardView`](/cua-sdk/reference/spaces/app-core/new-space#appwizardview-record)
**Image catalog**: [`AppImageDistro`](/cua-sdk/reference/spaces/app-core/images#appimagedistro-record), [`AppImageFieldView`](/cua-sdk/reference/spaces/app-core/images#appimagefieldview-record), [`AppImageGroup`](/cua-sdk/reference/spaces/app-core/images#appimagegroup-record), [`AppImageSizes`](/cua-sdk/reference/spaces/app-core/images#appimagesizes-record), [`AppImageSuggestion`](/cua-sdk/reference/spaces/app-core/images#appimagesuggestion-record), [`AppImageTier`](/cua-sdk/reference/spaces/app-core/images#appimagetier-enum), [`AppPlatformSize`](/cua-sdk/reference/spaces/app-core/images#appplatformsize-record), [`AppSandboxImage`](/cua-sdk/reference/spaces/app-core/images#appsandboximage-record), [`AppSuggestionGroup`](/cua-sdk/reference/spaces/app-core/images#appsuggestiongroup-record)
-**Keyvault screens**: [`kv_approval_approve_command`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_approve_command), [`kv_approval_deny_command`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_deny_command), [`kv_approval_open`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_open), [`kv_approval_reduce`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_reduce), [`kv_approval_view`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_view), [`kv_list`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_list), [`kv_page`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_page), [`kv_sidebar`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_sidebar), [`kv_site_detail`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_site_detail), [`kv_site_toggle`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_site_toggle), [`KvAccessKind`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvaccesskind-enum), [`KvAccessRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvaccessrow-record), [`KvApprovalAction`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvapprovalaction-enum), [`KvApprovalRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvapprovalrow-record), [`KvApprovalState`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvapprovalstate-record), [`KvApprovalView`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvapprovalview-record), [`KvCategory`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvcategory-enum), [`KvCategoryRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvcategoryrow-record), [`KvConsentChip`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvconsentchip-record), [`KvConsentChipKind`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvconsentchipkind-enum), [`KvDecision`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvdecision-record), [`KvDecisionTone`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvdecisiontone-enum), [`KvItemRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvitemrow-record), [`KvListView`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvlistview-record), [`KvPage`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvpage-record), [`KvPendingRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvpendingrow-record), [`KvRecentRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvrecentrow-record), [`KvSelection`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvselection-enum), [`KvSidebar`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvsidebar-record), [`KvSigningBadge`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvsigningbadge-record), [`KvSiteDetail`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvsitedetail-record), [`KvSiteGroup`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvsitegroup-record), [`KvSiteRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvsiterow-record), [`KvTone`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvtone-enum), [`KvTri`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvtri-enum)
+**Keyvault screens**: [`kv_approval_approve_command`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_approve_command), [`kv_approval_deny_command`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_deny_command), [`kv_approval_open`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_open), [`kv_approval_reduce`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_reduce), [`kv_approval_view`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_approval_view), [`kv_delete_command`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_delete_command), [`kv_delete_confirm`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_delete_confirm), [`kv_list`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_list), [`kv_live_copy_spaces`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_live_copy_spaces), [`kv_lock_command`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_lock_command), [`kv_page`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_page), [`kv_sidebar`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_sidebar), [`kv_unlock_command`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_unlock_command), [`kv_unlock_prompt`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_unlock_prompt), [`kv_unlock_prompt_always`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_unlock_prompt_always), [`kv_vault_prune`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_vault_prune), [`kv_vault_reduce`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_vault_reduce), [`kv_vault_source`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_vault_source), [`kv_vault_view`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kv_vault_view), [`KvAccessKind`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvaccesskind-enum), [`KvAccessRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvaccessrow-record), [`KvApprovalAction`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvapprovalaction-enum), [`KvApprovalRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvapprovalrow-record), [`KvApprovalState`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvapprovalstate-record), [`KvApprovalView`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvapprovalview-record), [`KvAppRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvapprow-record), [`KvCategory`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvcategory-enum), [`KvCategoryRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvcategoryrow-record), [`KvDecision`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvdecision-record), [`KvDecisionTone`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvdecisiontone-enum), [`KvDeleteConfirm`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvdeleteconfirm-record), [`KvKind`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvkind-enum), [`KvListView`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvlistview-record), [`KvLock`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvlock-enum), [`KvPage`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvpage-record), [`KvPendingRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvpendingrow-record), [`KvRecentRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvrecentrow-record), [`KvSelection`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvselection-enum), [`KvSidebar`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvsidebar-record), [`KvSigningBadge`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvsigningbadge-record), [`KvTone`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvtone-enum), [`KvTri`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvtri-enum), [`KvUnlockPrompt`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvunlockprompt-record), [`KvVaultAction`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvvaultaction-enum), [`KvVaultApp`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvvaultapp-record), [`KvVaultFiles`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvvaultfiles-record), [`KvVaultRow`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvvaultrow-record), [`KvVaultSelection`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvvaultselection-record), [`KvVaultSite`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvvaultsite-record), [`KvVaultSource`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvvaultsource-record), [`KvVaultState`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvvaultstate-record), [`KvVaultView`](/cua-sdk/reference/spaces/app-core/keyvault-screens#kvvaultview-record)
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/keyvault-screens.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/keyvault-screens.mdx
index b9480d35a0..78d5a047c9 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/keyvault-screens.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/keyvault-screens.mdx
@@ -1,6 +1,6 @@
---
title: "Keyvault screens"
-description: "The Keyvault page, sidebar, list, site detail and the approval prompt."
+description: "The Keyvault page, sidebar, the vault list (apps, sites and items with their locks), the unlock prompt and the approval prompt."
---
{/*
@@ -17,7 +17,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
These APIs are part of the Cua Spaces app export for building Spaces UIs. They are source-available under FSL-1.1-MIT and ship for Swift only (`import CuaSpacesFFI`); the Rust tab shows the `cua-spaces-ffi` crate they come from. The open source SDK packages for Python, TypeScript and Kotlin do not include them.
</Callout>
-The `kv_*` functions derive each Keyvault screen from a `KeyvaultOverview`. `kv_approval_open`, `kv_approval_reduce` and `kv_approval_view` drive the approval prompt; the `*_command` functions return the `KvCommand` to send.
+The `kv_*` functions derive each Keyvault screen from a `KeyvaultOverview`. `kv_vault_view` groups the vault by source app and site, with a lock on each row; `kv_vault_reduce` applies search, selection and open groups; `kv_unlock_prompt` is the "Allow unattended access?" prompt. `kv_approval_open`, `kv_approval_reduce` and `kv_approval_view` drive the approval prompt; the `*_command` functions return the `KvCommand` to send.
## `KvAccessRow` record
@@ -141,7 +141,7 @@ KvTri::Mixed
```swift
.category(category: KvCategory)
-.site(key: String)
+.app(key: String)
```
</Tab>
@@ -149,7 +149,7 @@ KvTri::Mixed
```rust
KvSelection::Category { category: KvCategory }
-KvSelection::Site { key: String }
+KvSelection::App { key: String }
```
</Tab>
@@ -158,7 +158,7 @@ KvSelection::Site { key: String }
| Variant | Description |
| --- | --- |
| `Category` | A category. Fields: `category: KvCategory` |
-| `Site` | A site. Fields: `key: String` |
+| `App` | One app's items. Fields: `key: String` |
## `KvSigningBadge` record
@@ -196,13 +196,25 @@ KvTone::Danger
| `Warn` | Caution. |
| `Danger` | Untrusted. |
+## `KvAppRow` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `key` | `String` | | The provider id (`chrome`): the key, and what the icon is looked up by. |
+| `title` | `String` | | "Google Chrome". |
+| `items` | `u32` | | Items. |
+| `waiting` | `bool` | | Something waits for this app. |
+
## `KvApprovalRow` record
| Field | Type | Default | Description |
| --- | --- | --- | --- |
-| `key` | `String` | | Row key. |
-| `title` | `String` | | Site or app. |
-| `account` | `String` | | Account, or "Not imported yet". |
+| `key` | `String` | | Row key: `<app>\|<site>`, `<app>\|files`, or `import:<n>`. |
+| `title` | `String` | | The site, or the app for files and imports. |
+| `account` | `String` | | "3 cookies, 1 password", or "Not saved yet". |
+| `provider_id` / `providerId` | `String` | | The app's provider id (its icon), when known. |
+| `items` | `u32` | | Items the row stands for. |
+| `item_ids` / `itemIds` | `Vec<String>` | | The items' ids. |
| `selected` | `bool` | | Ticked. |
| `is_import` / `isImport` | `bool` | | A new item the approval imports. |
@@ -213,7 +225,7 @@ Returned by [`kv_approval_open`](#kv_approval_open), [`kv_approval_reduce`](#kv_
| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `request_id` / `requestId` | `String` | | The request. |
-| `selected` | `Vec<String>` | | Ticked row keys (item ids, or `import:<n>` for new items). |
+| `selected` | `Vec<String>` | | Ticked row keys (`<app>\|<site>`, or `import:<n>` for new items). |
## `KvApprovalView` record
@@ -245,22 +257,16 @@ Returned by [`kv_approval_view`](#kv_approval_view).
| `count` | `Option<u32>` | | Count (none for Recent). |
| `badge` | `Option<u32>` | | The sidebar badge: Waiting's count while something waits. |
-## `KvConsentChip` record
+## `KvDeleteConfirm` record
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `kind` | [`KvConsentChipKind`](#kvconsentchipkind-enum) | | Kind. |
-| `text` | `String` | | Text. |
-
-## `KvItemRow` record
+Returned by [`kv_delete_confirm`](#kv_delete_confirm).
| Field | Type | Default | Description |
| --- | --- | --- | --- |
-| `item` | [`KvItem`](/cua-sdk/reference/spaces/app-core/keyvault#kvitem-record) | | The item. |
-| `account` | `String` | | "[email protected]", "Whole app session", or the profile. |
-| `consent` | [`Vec<KvConsentChip>`](#kvconsentchip-record) | | Strongest first; `asks` when nothing else applies. |
-| `toggle_enabled` / `toggleEnabled` | `bool` | | The unattended switch can be changed (not an identity provider). |
-| `toggle_help` / `toggleHelp` | `String` | | The switch's tooltip. |
+| `title` | `String` | | "Delete 3 items?" |
+| `message` | `String` | | What deleting does. |
+| `confirm` | `String` | | "Delete". |
+| `cancel` | `String` | | "Cancel". |
## `KvListView` record
@@ -269,11 +275,11 @@ Returned by [`kv_list`](#kv_list).
| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `title` | `String` | | Title. |
-| `sites` | [`Vec<KvSiteGroup>`](#kvsitegroup-record) | | Sites (All, or the one site). |
+| `vault` | `bool` | | The vault list shows (All Items, or one app). |
| `pending` | [`Vec<KvPendingRow>`](#kvpendingrow-record) | | Waiting. |
| `access` | [`Vec<KvAccessRow>`](#kvaccessrow-record) | | Access. |
| `recent` | [`Vec<KvRecentRow>`](#kvrecentrow-record) | | Recent. |
-| `empty_text` / `emptyText` | `Option<String>` | | "No items yet." and friends. |
+| `empty_text` / `emptyText` | `Option<String>` | | "Nothing is waiting." and friends. |
## `KvPage` record
@@ -296,7 +302,9 @@ Returned by [`kv_page`](#kv_page).
| `protection` | [`Vec<AppFact>`](/cua-sdk/reference/spaces/app-core/window#appfact-record) | | Protection facts. |
| `revoke_all` / `revokeAll` | `bool` | | "Revoke all" shows (more than one live grant). |
| `has_items` / `hasItems` | `bool` | | Items exist. |
-| `search_visible` / `searchVisible` | `bool` | | Search shows (more than six items). |
+| `search_visible` / `searchVisible` | `bool` | | Search shows (any item exists). |
+| `skip_unlock_prompt` / `skipUnlockPrompt` | `bool` | | "Never ask again" on the unlock prompt is on (Settings turns it off). |
+| `reset_notice` / `resetNotice` | `Option<String>` | | An earlier preview's vault was set aside: one line to show. |
| `pending_count` / `pendingCount` | `u32` | | Pending requests (the sidebar badge). |
| `kill_switch_help` / `killSwitchHelp` | `String` | | The switch's tooltip (it reads "on" while the Keyvault works). |
| `labels` | [`KvLabels`](/cua-sdk/reference/spaces/app-core/keyvault#kvlabels-record) | | The page's fixed words. |
@@ -319,40 +327,137 @@ Returned by [`kv_sidebar`](#kv_sidebar).
| Field | Type | Default | Description |
| --- | --- | --- | --- |
-| `categories` | [`Vec<KvCategoryRow>`](#kvcategoryrow-record) | | All, Waiting, Access, Recent. |
-| `sites` | [`Vec<KvSiteRow>`](#kvsiterow-record) | | One row per site or app. |
+| `categories` | [`Vec<KvCategoryRow>`](#kvcategoryrow-record) | | All Items, Waiting, Access, Recent. |
+| `apps` | [`Vec<KvAppRow>`](#kvapprow-record) | | One row per app, by name. |
-## `KvSiteDetail` record
+## `KvUnlockPrompt` record
-Returned by [`kv_site_detail`](#kv_site_detail).
+Returned by [`kv_unlock_prompt`](#kv_unlock_prompt), [`kv_unlock_prompt_always`](#kv_unlock_prompt_always).
| Field | Type | Default | Description |
| --- | --- | --- | --- |
-| `group` | [`KvSiteGroup`](#kvsitegroup-record) | | The group. |
-| `site_switch` / `siteSwitch` | `bool` | | The site switch shows (more than one account). |
-| `site_state` / `siteState` | [`KvTri`](#kvtri-enum) | | The site switch's state. |
-| `site_switch_enabled` / `siteSwitchEnabled` | `bool` | | The site switch can be flipped. |
-| `site_switch_help` / `siteSwitchHelp` | `String` | | Its tooltip. |
+| `title` | `String` | | "Allow unattended access?" |
+| `message` | `String` | | What it allows. |
+| `subject` | `String` | | "3 items" (a batch), or the one item's name. |
+| `deny` | `String` | | "Deny". |
+| `allow` | `String` | | "Allow". |
+| `never_ask` / `neverAsk` | `String` | | "Never ask again". |
-## `KvSiteGroup` record
+## `KvVaultApp` record
| Field | Type | Default | Description |
| --- | --- | --- | --- |
-| `key` | `String` | | Stable key. |
-| `title` | `String` | | "github.com" or "Slack". |
-| `app` | `String` | | "Chrome", "Slack". |
-| `rows` | [`Vec<KvItemRow>`](#kvitemrow-record) | | Accounts. |
-| `unattended` | [`KvTri`](#kvtri-enum) | | Unattended across rows. |
-| `locked` | `bool` | | Every row is an identity provider. |
+| `key` | `String` | | Group key: the provider id (`chrome`). |
+| `provider_id` / `providerId` | `String` | | The provider id, for the app's icon. |
+| `name` | `String` | | "Google Chrome". |
+| `count` | `u32` | | Items. |
+| `summary` | `String` | | "212 items, 14 unlocked". |
+| `updated` | `String` | | Grey time of the newest save. |
+| `selected` | [`KvTri`](#kvtri-enum) | | Selection of its items. |
+| `lock` | [`KvLock`](#kvlock-enum) | | Lock of its items. |
+| `unlock_ids` / `unlockIds` | `Vec<String>` | | Items a click on the lock unlocks (locked, not identity providers). |
+| `lock_ids` / `lockIds` | `Vec<String>` | | Items a click on the lock locks (unlocked). |
+| `open` | `bool` | | Open. |
+| `sites` | [`Vec<KvVaultSite>`](#kvvaultsite-record) | | Sites with their items, by name. |
+| `files` | [`Option<KvVaultFiles>`](#kvvaultfiles-record) | | Files, when it has any. |
+
+## `KvVaultFiles` record
-## `KvSiteRow` record
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `key` | `String` | | Group key. |
+| `count` | `u32` | | Files. |
+| `selected` | [`KvTri`](#kvtri-enum) | | Selection of its items. |
+| `lock` | [`KvLock`](#kvlock-enum) | | Lock of its items. |
+| `unlock_ids` / `unlockIds` | `Vec<String>` | | Items a click on the lock unlocks (locked, not identity providers). |
+| `lock_ids` / `lockIds` | `Vec<String>` | | Items a click on the lock locks (unlocked). |
+| `open` | `bool` | | Open. |
+| `rows` | [`Vec<KvVaultRow>`](#kvvaultrow-record) | | Its rows (empty while closed, unless searching). |
+
+## `KvVaultRow` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `id` | `String` | | Item id. |
+| `kind` | [`KvKind`](#kvkind-enum) | | Type. |
+| `kind_label` / `kindLabel` | `String` | | "Cookie". |
+| `symbol` | `String` | | The type's SF Symbol. |
+| `title` | `String` | | The key: a cookie name, storage key, username or file name. |
+| `subtitle` | `String` | | Grey line: the domain, or the file's folder. |
+| `updated` | `String` | | Grey time: "2 min ago". |
+| `locked` | `bool` | | Locked (needs approval for every use). |
+| `lock_symbol` / `lockSymbol` | `String` | | The lock icon: `lock.fill` or `lock.open`. |
+| `lock_help` / `lockHelp` | `String` | | The lock's tooltip and accessibility label. |
+| `identity_provider` / `identityProvider` | `bool` | | Identity provider: always asks, cannot be unlocked. |
+| `selected` | `bool` | | Selected. |
+
+## `KvVaultSelection` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `count` | `u32` | | Selected items. |
+| `ids` | `Vec<String>` | | Their ids, in list order. |
+| `title` | `String` | | "3 selected". |
+| `can_unlock` / `canUnlock` | `bool` | | Some selected item is locked and may be unlocked. |
+| `can_lock` / `canLock` | `bool` | | Some selected item is unlocked. |
+| `always_ask` / `alwaysAsk` | `u32` | | Selected items that always ask (identity providers). |
+| `unlock_ids` / `unlockIds` | `Vec<String>` | | The ids to send when unlocking (locked, not identity providers). |
+| `lock_ids` / `lockIds` | `Vec<String>` | | The ids to send when locking (unlocked). |
+
+## `KvVaultSite` record
| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `key` | `String` | | Group key. |
-| `title` | `String` | | "github.com" or "Slack". |
-| `accounts` | `u32` | | Accounts. |
-| `waiting` | `bool` | | Something waits for this site. |
+| `site` | `String` | | "github.com". |
+| `count` | `u32` | | Items (all of them, even while closed). |
+| `counts` | `String` | | "12 cookies, 2 storage values". |
+| `updated` | `String` | | Grey time of the newest save. |
+| `selected` | [`KvTri`](#kvtri-enum) | | Selection of its items. |
+| `lock` | [`KvLock`](#kvlock-enum) | | Lock of its items. |
+| `unlock_ids` / `unlockIds` | `Vec<String>` | | Items a click on the lock unlocks (locked, not identity providers). |
+| `lock_ids` / `lockIds` | `Vec<String>` | | Items a click on the lock locks (unlocked). |
+| `open` | `bool` | | Open. |
+| `rows` | [`Vec<KvVaultRow>`](#kvvaultrow-record) | | Its rows (empty while closed, unless searching). |
+
+## `KvVaultSource` record
+
+Returned by [`kv_vault_source`](#kv_vault_source).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `count` | `u32` | | Items that can be sent. |
+| `newest_ms` / `newestMs` | `i64` | | When the newest was saved, Unix ms (0: none). |
+| `ids` | `Vec<String>` | | Their ids, in list order. |
+| `password_ids` / `passwordIds` | `Vec<String>` | | The app's saved passwords (ids), never part of `ids`: they are sent only when ticked in the review. |
+
+## `KvVaultState` record
+
+Returned by [`kv_vault_prune`](#kv_vault_prune), [`kv_vault_reduce`](#kv_vault_reduce).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `query` | `String` | | The search text. |
+| `selected` | `Vec<String>` | | Selected item ids. |
+| `expanded` | `Vec<String>` | | Open groups (their keys); the rest are closed. |
+| `app` | `Option<String>` | | Narrowed to one app (its provider id), as the sidebar picks it. |
+
+## `KvVaultView` record
+
+Returned by [`kv_vault_view`](#kv_vault_view).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `apps` | [`Vec<KvVaultApp>`](#kvvaultapp-record) | | Apps, by name. |
+| `shown` | `u32` | | Items shown (after search). |
+| `total` | `u32` | | Items in the vault. |
+| `empty_text` / `emptyText` | `Option<String>` | | "No items yet." and friends. |
+| `names_hidden` / `namesHidden` | `bool` | | Domains and keys are hidden until the user confirms with Touch ID. |
+| `hidden_note` / `hiddenNote` | `Option<String>` | | What to say about it. |
+| `show_names_label` / `showNamesLabel` | `String` | | The button that opens the names. |
+| `search_prompt` / `searchPrompt` | `String` | | The search field's prompt. |
+| `selection` | [`KvVaultSelection`](#kvvaultselection-record) | | The selection. |
+| `can_select_all` / `canSelectAll` | `bool` | | Select all is offered. |
## `KvApprovalAction` enum
@@ -410,33 +515,31 @@ KvCategory::Recent
| Variant | Description |
| --- | --- |
-| `All` | Every site. |
+| `All` | Every item, grouped by app. |
| `Waiting` | Requests waiting for approval. |
| `Access` | Live grants, rules and copies. |
| `Recent` | Recent decisions. |
-## `KvConsentChipKind` enum
+## `KvKind` enum
<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
<Tab value="Swift">
```swift
-.pending
-.delivered
-.granted
-.rule
-.asks
+.cookie
+.localStorage
+.password
+.file
```
</Tab>
<Tab value="Rust">
```rust
-KvConsentChipKind::Pending
-KvConsentChipKind::Delivered
-KvConsentChipKind::Granted
-KvConsentChipKind::Rule
-KvConsentChipKind::Asks
+KvKind::Cookie
+KvKind::LocalStorage
+KvKind::Password
+KvKind::File
```
</Tab>
@@ -444,11 +547,77 @@ KvConsentChipKind::Asks
| Variant | Description |
| --- | --- |
-| `Pending` | A request waits. |
-| `Delivered` | A copy is in a Space. |
-| `Granted` | A live grant. |
-| `Rule` | An unattended rule. |
-| `Asks` | Nothing: asks every time. |
+| `Cookie` | A cookie. |
+| `LocalStorage` | A localStorage value. |
+| `Password` | A saved password. |
+| `File` | A file. |
+
+## `KvLock` enum
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+.locked
+.unlocked
+.mixed
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+KvLock::Locked
+KvLock::Unlocked
+KvLock::Mixed
+```
+
+</Tab>
+</Tabs>
+
+| Variant | Description |
+| --- | --- |
+| `Locked` | Every item needs approval for each use. |
+| `Unlocked` | Every item allows unattended access. |
+| `Mixed` | Some of each. |
+
+## `KvVaultAction` enum
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+.query(text: String)
+.toggle(id: String)
+.toggleGroup(key: String)
+.selectAll
+.clear
+.toggleOpen(key: String)
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+KvVaultAction::Query { text: String }
+KvVaultAction::Toggle { id: String }
+KvVaultAction::ToggleGroup { key: String }
+KvVaultAction::SelectAll
+KvVaultAction::Clear
+KvVaultAction::ToggleOpen { key: String }
+```
+
+</Tab>
+</Tabs>
+
+| Variant | Description |
+| --- | --- |
+| `Query` | The search text changed. Fields: `text: String` |
+| `Toggle` | Select or deselect one item. Fields: `id: String` |
+| `ToggleGroup` | Select or deselect every shown item of an app, a site or the files of an app (all of them when any is unselected, none when all are). Fields: `key: String` |
+| `SelectAll` | Select every shown item. |
+| `Clear` | Deselect everything. |
+| `ToggleOpen` | Open or close a group. Fields: `key: String` |
## `kv_approval_approve_command`
@@ -589,22 +758,77 @@ pub fn kv_approval_view(overview: KeyvaultOverview, state: KvApprovalState) -> K
**Returns** [`KvApprovalView`](#kvapprovalview-record)
+## `kv_delete_command`
+
+The command that deletes items and wipes their copies in Spaces.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func kvDeleteCommand(ids: [String]) -> KvCommand
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn kv_delete_command(ids: Vec<String>) -> KvCommand
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `ids` | `Vec<String>` | required |
+
+**Returns** [`KvCommand`](/cua-sdk/reference/spaces/app-core/keyvault#kvcommand-enum)
+
+## `kv_delete_confirm`
+
+The delete confirmation.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func kvDeleteConfirm(count: UInt32, liveCopies: UInt32) -> KvDeleteConfirm
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn kv_delete_confirm(count: u32, live_copies: u32) -> KvDeleteConfirm
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `count` | `u32` | required |
+| `live_copies` | `u32` | required |
+
+**Returns** [`KvDeleteConfirm`](#kvdeleteconfirm-record)
+
## `kv_list`
-The list for a sidebar selection.
+The pane for a sidebar selection (the vault list is `kv_vault_view`).
<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
<Tab value="Swift">
```swift
-func kvList(overview: KeyvaultOverview, selection: KvSelection, nowMs: Int64, query: String) -> KvListView
+func kvList(overview: KeyvaultOverview, selection: KvSelection, nowMs: Int64) -> KvListView
```
</Tab>
<Tab value="Rust">
```rust
-pub fn kv_list(overview: KeyvaultOverview, selection: KvSelection, now_ms: i64, query: String) -> KvListView
+pub fn kv_list(overview: KeyvaultOverview, selection: KvSelection, now_ms: i64) -> KvListView
```
</Tab>
@@ -615,10 +839,65 @@ pub fn kv_list(overview: KeyvaultOverview, selection: KvSelection, now_ms: i64,
| `overview` | [`KeyvaultOverview`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultoverview-record) | required |
| `selection` | [`KvSelection`](#kvselection-enum) | required |
| `now_ms` | `i64` | required |
-| `query` | `String` | required |
**Returns** [`KvListView`](#kvlistview-record)
+## `kv_live_copy_spaces`
+
+How many Spaces hold a live copy of any of `ids`.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func kvLiveCopySpaces(overview: KeyvaultOverview, ids: [String], nowMs: Int64) -> UInt32
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn kv_live_copy_spaces(overview: KeyvaultOverview, ids: Vec<String>, now_ms: i64) -> u32
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `overview` | [`KeyvaultOverview`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultoverview-record) | required |
+| `ids` | `Vec<String>` | required |
+| `now_ms` | `i64` | required |
+
+**Returns** `u32`
+
+## `kv_lock_command`
+
+The command that locks items.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func kvLockCommand(ids: [String]) -> KvCommand
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn kv_lock_command(ids: Vec<String>) -> KvCommand
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `ids` | `Vec<String>` | required |
+
+**Returns** [`KvCommand`](/cua-sdk/reference/spaces/app-core/keyvault#kvcommand-enum)
+
## `kv_page`
The page chrome.
@@ -649,7 +928,7 @@ pub fn kv_page(overview: KeyvaultOverview, now_ms: i64) -> KvPage
## `kv_sidebar`
-The Passwords-style sidebar.
+The sidebar: All Items, Waiting, Access, Recent, and one row per app.
<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
<Tab value="Swift">
@@ -675,22 +954,50 @@ pub fn kv_sidebar(overview: KeyvaultOverview, now_ms: i64) -> KvSidebar
**Returns** [`KvSidebar`](#kvsidebar-record)
-## `kv_site_detail`
+## `kv_unlock_command`
+
+The command that unlocks items (the daemon asks for Touch ID once).
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func kvUnlockCommand(ids: [String]) -> KvCommand
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn kv_unlock_command(ids: Vec<String>) -> KvCommand
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `ids` | `Vec<String>` | required |
+
+**Returns** [`KvCommand`](/cua-sdk/reference/spaces/app-core/keyvault#kvcommand-enum)
+
+## `kv_unlock_prompt`
-One site's detail.
+The unlock prompt for `count` items (`name`: the one item's name). None
+when the user chose "Never ask again".
<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
<Tab value="Swift">
```swift
-func kvSiteDetail(overview: KeyvaultOverview, key: String, nowMs: Int64) -> KvSiteDetail?
+func kvUnlockPrompt(overview: KeyvaultOverview, count: UInt32, name: String?) -> KvUnlockPrompt?
```
</Tab>
<Tab value="Rust">
```rust
-pub fn kv_site_detail(overview: KeyvaultOverview, key: String, now_ms: i64) -> Option<KvSiteDetail>
+pub fn kv_unlock_prompt(overview: KeyvaultOverview, count: u32, name: Option<String>) -> Option<KvUnlockPrompt>
```
</Tab>
@@ -699,27 +1006,27 @@ pub fn kv_site_detail(overview: KeyvaultOverview, key: String, now_ms: i64) -> O
| Parameter | Type | Default |
| --- | --- | --- |
| `overview` | [`KeyvaultOverview`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultoverview-record) | required |
-| `key` | `String` | required |
-| `now_ms` | `i64` | required |
+| `count` | `u32` | required |
+| `name` | `Option<String>` | required |
-**Returns** [`Option<KvSiteDetail>`](#kvsitedetail-record)
+**Returns** [`Option<KvUnlockPrompt>`](#kvunlockprompt-record)
-## `kv_site_toggle`
+## `kv_unlock_prompt_always`
-The site switch's command.
+The unlock prompt whatever the setting says.
<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
<Tab value="Swift">
```swift
-func kvSiteToggle(group: KvSiteGroup, on: Bool) -> KvCommand
+func kvUnlockPromptAlways(count: UInt32, name: String?) -> KvUnlockPrompt
```
</Tab>
<Tab value="Rust">
```rust
-pub fn kv_site_toggle(group: KvSiteGroup, on: bool) -> KvCommand
+pub fn kv_unlock_prompt_always(count: u32, name: Option<String>) -> KvUnlockPrompt
```
</Tab>
@@ -727,7 +1034,122 @@ pub fn kv_site_toggle(group: KvSiteGroup, on: bool) -> KvCommand
| Parameter | Type | Default |
| --- | --- | --- |
-| `group` | [`KvSiteGroup`](#kvsitegroup-record) | required |
-| `on` | `bool` | required |
+| `count` | `u32` | required |
+| `name` | `Option<String>` | required |
-**Returns** [`KvCommand`](/cua-sdk/reference/spaces/app-core/keyvault#kvcommand-enum)
+**Returns** [`KvUnlockPrompt`](#kvunlockprompt-record)
+
+## `kv_vault_prune`
+
+The selection without what the vault no longer holds.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func kvVaultPrune(overview: KeyvaultOverview, state: KvVaultState) -> KvVaultState
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn kv_vault_prune(overview: KeyvaultOverview, state: KvVaultState) -> KvVaultState
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `overview` | [`KeyvaultOverview`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultoverview-record) | required |
+| `state` | [`KvVaultState`](#kvvaultstate-record) | required |
+
+**Returns** [`KvVaultState`](#kvvaultstate-record)
+
+## `kv_vault_reduce`
+
+The vault list's next state (search, selection, open groups).
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func kvVaultReduce(overview: KeyvaultOverview, state: KvVaultState, action: KvVaultAction) -> KvVaultState
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn kv_vault_reduce(overview: KeyvaultOverview, state: KvVaultState, action: KvVaultAction) -> KvVaultState
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `overview` | [`KeyvaultOverview`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultoverview-record) | required |
+| `state` | [`KvVaultState`](#kvvaultstate-record) | required |
+| `action` | [`KvVaultAction`](#kvvaultaction-enum) | required |
+
+**Returns** [`KvVaultState`](#kvvaultstate-record)
+
+## `kv_vault_source`
+
+What the Keyvault holds for `provider_id` that a teleport can send.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func kvVaultSource(overview: KeyvaultOverview, providerId: String) -> KvVaultSource
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn kv_vault_source(overview: KeyvaultOverview, provider_id: String) -> KvVaultSource
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `overview` | [`KeyvaultOverview`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultoverview-record) | required |
+| `provider_id` | `String` | required |
+
+**Returns** [`KvVaultSource`](#kvvaultsource-record)
+
+## `kv_vault_view`
+
+The vault list: apps, sites and items with their locks, the selection and
+the batch bar.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func kvVaultView(overview: KeyvaultOverview, state: KvVaultState, nowMs: Int64) -> KvVaultView
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn kv_vault_view(overview: KeyvaultOverview, state: KvVaultState, now_ms: i64) -> KvVaultView
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `overview` | [`KeyvaultOverview`](/cua-sdk/reference/spaces/app-core/keyvault#keyvaultoverview-record) | required |
+| `state` | [`KvVaultState`](#kvvaultstate-record) | required |
+| `now_ms` | `i64` | required |
+
+**Returns** [`KvVaultView`](#kvvaultview-record)
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/keyvault.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/keyvault.mdx
index 71ac43a4c1..2035ee0a6a 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/keyvault.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/keyvault.mdx
@@ -97,6 +97,8 @@ the daemon ask for Touch ID. No call returns a secret value.
| --- | --- |
| [`new`](#keyvaultclientnew) | The broker in `cua_home` (`None`: `$CUA_HOME`, else `~/.cua`). |
| [`execute`](#keyvaultclientexecute) | Runs one page action (a broker request). |
+| [`favicons`](#keyvaultclientfavicons) | Site icons the vault holds (not secret; empty while names are hidden). |
+| [`inventory`](#keyvaultclientinventory) | What `app` holds, per domain with counts (the daemon asks for Touch ID when the browse window is closed). |
| [`lock`](#keyvaultclientlock) | Locks the vault. |
| [`overview`](#keyvaultclientoverview) | Everything the page shows. |
| [`setup_with_passphrase`](#keyvaultclientsetup_with_passphrase) | Creates the vault with a passphrase (and a recovery key, returned once). |
@@ -156,6 +158,58 @@ pub async fn execute(&self, command: KvCommand) -> Result<KvOutcome, CuaError>
**Returns** [`KvOutcome`](#kvoutcome-enum) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+### `KeyvaultClient.favicons`
+
+Site icons the vault holds (not secret; empty while names are hidden).
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func favicons() async -> [KvFavicon]
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn favicons(&self) -> Vec<KvFavicon>
+```
+
+</Tab>
+</Tabs>
+
+**Returns** [`Vec<KvFavicon>`](#kvfavicon-record) · **Async**
+
+### `KeyvaultClient.inventory`
+
+What `app` holds, per domain with counts (the daemon asks for Touch ID
+when the browse window is closed). Never a value.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func inventory(app: String, profile: String?) async throws -> KvInventory
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub async fn inventory(&self, app: String, profile: Option<String>) -> Result<KvInventory, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `app` | `String` | required |
+| `profile` | `Option<String>` | required |
+
+**Returns** [`KvInventory`](#kvinventory-record) · **Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
### `KeyvaultClient.lock`
Locks the vault.
@@ -269,7 +323,9 @@ Returned by [`KeyvaultClient.overview`](#keyvaultclientoverview), [`kv_overview_
| `message` | `Option<String>` | | A sentence when not ready. |
| `status` | [`Option<KvStatus>`](#kvstatus-record) | | The broker's status. |
| `server_verified` / `serverVerified` | `bool` | | The daemon was checked against Cua's signature. |
-| `items` | [`Vec<KvItem>`](#kvitem-record) | | Items. |
+| `items` | [`Vec<KvItem>`](#kvitem-record) | | The vault's secret items, in order (app, domain, key). |
+| `names_visible` / `namesVisible` | `bool` | | Domains and keys are present in `items` (the browse window is open). |
+| `items_total` / `itemsTotal` | `u32` | | Items in the vault. |
| `pending` | [`Vec<KvPending>`](#kvpending-record) | | Pending requests. |
| `grants` | [`Vec<KvGrant>`](#kvgrant-record) | | Grants. |
| `rules` | [`Vec<KvRule>`](#kvrule-record) | | Rules. |
@@ -319,15 +375,6 @@ Returned by [`KeyvaultClient.overview`](#keyvaultclientoverview), [`kv_overview_
| `launched_by` / `launchedBy` | `Option<String>` | | Launched by. |
| `verified_name` / `verifiedName` | `Option<String>` | | OS-verified leaf name. |
-## `KvCookieInfo` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `name` | `String` | | Name. |
-| `domain` | `String` | | Domain. |
-| `session` | `bool` | | Session cookie. |
-| `expires_ms` / `expiresMs` | `Option<i64>` | | Expiry. |
-
## `KvCredentialForm` record
Returned by [`kv_credential_form`](#kv_credential_form).
@@ -354,6 +401,29 @@ Returned by [`kv_credential_form`](#kv_credential_form).
| `expires_ms` / `expiresMs` | `u64` | | Wiped at (`KV_NO_EXPIRY`: only when wiped). |
| `wiped` | `bool` | | Already wiped. |
+## `KvDomainCount` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `domain` | `String` | | Registrable domain. |
+| `cookies` | `u32` | | Cookies. |
+| `session_cookies` / `sessionCookies` | `u32` | | Cookies without an expiry. |
+| `local_storage` / `localStorage` | `u32` | | localStorage values. |
+| `passwords` | `u32` | | Saved passwords. |
+| `signin` | `bool` | | Looks like it keeps a sign-in. |
+| `identity_provider` / `identityProvider` | `bool` | | An identity provider. |
+| `unavailable` | `u32` | | Cookies that cannot be read (Chrome's app-bound encryption). |
+| `unavailable_reason` / `unavailableReason` | `String` | | Why they cannot be read. |
+
+## `KvFavicon` record
+
+Returned by [`KeyvaultClient.favicons`](#keyvaultclientfavicons).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `site` | `String` | | The site (registrable domain). |
+| `png` | `String` | | PNG, base64. |
+
## `KvGrant` record
| Field | Type | Default | Description |
@@ -371,24 +441,37 @@ Returned by [`kv_credential_form`](#kv_credential_form).
| `revoked` | `bool` | | Revoked. |
| `agent` | `Option<String>` | | The named agent it was approved for. |
+## `KvInventory` record
+
+Returned by [`KeyvaultClient.inventory`](#keyvaultclientinventory).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `provider_id` / `providerId` | `String` | | Provider id. |
+| `app_display` / `appDisplay` | `String` | | App name. |
+| `domains` | [`Vec<KvDomainCount>`](#kvdomaincount-record) | | Domains with counts. |
+| `notes` | `Vec<String>` | | Notes. |
+
## `KvItem` record
| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `String` | | Id. |
-| `kind` | `String` | | `browser_site`, `site_passwords`, `app_session`. |
-| `label` | `String` | | Label. |
-| `provider_id` / `providerId` | `String` | | Provider. |
-| `app_display` / `appDisplay` | `String` | | App. |
-| `site` | `Option<String>` | | Site. |
-| `account` | `Option<String>` | | Account. |
+| `kind` | `String` | | `cookie`, `local_storage`, `password` or `file`. |
+| `provider_id` / `providerId` | `String` | | The source app (`chrome`, `slack`). |
+| `app_display` / `appDisplay` | `String` | | The app's name. |
+| `domain` | `Option<String>` | | A cookie's host, a storage value's or password's origin; none for a file or when the names are hidden. |
+| `key` | `String` | | A cookie name, storage key, username or file path; empty when the names are hidden. |
+| `path` | `Option<String>` | | A cookie's path. |
| `source` | `String` | | Profile. |
-| `summary` | [`KvItemSummary`](#kvitemsummary-record) | | Summary. |
-| `warnings` | `Vec<String>` | | Warnings. |
-| `identity_provider` / `identityProvider` | `bool` | | Identity providers always ask. |
-| `policy` | [`KvItemPolicy`](#kvitempolicy-record) | | Policy. |
+| `session` | `bool` | | A cookie without an expiry. |
+| `expires_ms` / `expiresMs` | `Option<i64>` | | A cookie's expiry, Unix ms. |
+| `bytes` | `u64` | | Bytes. |
+| `blob` | `Option<String>` | | The blob a big file's bytes live in. |
+| `identity_provider` / `identityProvider` | `bool` | | Identity providers always ask: they cannot be unlocked. |
+| `policy` | [`KvItemPolicy`](#kvitempolicy-record) | | Policy: `unattended` is the unlock. |
| `created_ms` / `createdMs` | `u64` | | Created. |
-| `updated_ms` / `updatedMs` | `u64` | | Updated. |
+| `updated_ms` / `updatedMs` | `u64` | | Last saved. |
| `rev` | `u64` | | Revision. |
| `record_digest` / `recordDigest` | `String` | | Digest. |
@@ -400,17 +483,6 @@ Returned by [`kv_credential_form`](#kv_credential_form).
| `ttl_secs` / `ttlSecs` | `u64` | | Delivery lifetime. |
| `unattended` | `bool` | | Unattended rules may use it. |
-## `KvItemSummary` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `cookies` | [`Vec<KvCookieInfo>`](#kvcookieinfo-record) | | Cookies. |
-| `storage_origins` / `storageOrigins` | `Vec<String>` | | Storage origins. |
-| `passwords` | `u32` | | Saved passwords. |
-| `files` | `Vec<String>` | | Files. |
-| `keychain_services` / `keychainServices` | `Vec<String>` | | Keychain services. |
-| `bytes` | `u64` | | Bytes. |
-
## `KvLabels` record
Returned by [`kv_labels`](#kv_labels).
@@ -425,9 +497,6 @@ Returned by [`kv_labels`](#kv_labels).
| `revoke_all` / `revokeAll` | `String` | | "Revoke all". |
| `confirm_note` / `confirmNote` | `String` | | Under the approval sheet. |
| `protection_title` / `protectionTitle` | `String` | | "Protection". |
-| `accounts_title` / `accountsTitle` | `String` | | A site's accounts section. |
-| `app_label` / `appLabel` | `String` | | A site's app fact. |
-| `every_account` / `everyAccount` | `String` | | A site's switch. |
## `KvPassphraseCheck` record
@@ -489,6 +558,9 @@ Returned by [`kv_passphrase_check`](#kv_passphrase_check).
| `os_protector_available` / `osProtectorAvailable` | `bool` | | The daemon can create the OS key store protector (setup offers Touch ID); false for a development daemon, which is passphrase-only. |
| `passphrase_available` / `passphraseAvailable` | `bool` | | A passphrase can always be chosen. |
| `unlock_protectors` / `unlockProtectors` | `Vec<String>` | | Protector kinds that can unlock this vault now (`macos-keychain`, `windows-credential`, `passphrase`, `recovery`). |
+| `browse_until_ms` / `browseUntilMs` | `Option<u64>` | | The browse window is open until this time, Unix ms: item names are visible until then. |
+| `skip_unlock_prompt` / `skipUnlockPrompt` | `Option<bool>` | | "Never ask again" on the unlock prompt is on. |
+| `reset_notice` / `resetNotice` | `Option<String>` | | An earlier preview's vault was found and set aside. |
## `KvVerification` record
@@ -510,6 +582,11 @@ Returned by [`kv_passphrase_check`](#kv_passphrase_check).
.unlock
.setDisabled(disabled: Bool)
.setUnattended(itemIds: [String], unattended: Bool)
+.setLocked(itemIds: [String], locked: Bool)
+.deleteItems(itemIds: [String])
+.setSkipUnlockPrompt(on: Bool)
+.browse
+.endBrowse
.revokeGrant(id: String)
.removeRule(id: String)
.setAutoWipe(on: Bool)
@@ -526,6 +603,11 @@ KvCommand::Setup
KvCommand::Unlock
KvCommand::SetDisabled { disabled: bool }
KvCommand::SetUnattended { item_ids: Vec<String>, unattended: bool }
+KvCommand::SetLocked { item_ids: Vec<String>, locked: bool }
+KvCommand::DeleteItems { item_ids: Vec<String> }
+KvCommand::SetSkipUnlockPrompt { on: bool }
+KvCommand::Browse
+KvCommand::EndBrowse
KvCommand::RevokeGrant { id: String }
KvCommand::RemoveRule { id: String }
KvCommand::SetAutoWipe { on: bool }
@@ -542,7 +624,12 @@ KvCommand::Deny { request_id: String }
| `Setup` | Create the vault with the OS key store (the daemon asks for presence). A passphrase never travels in a command: the shells pass it to `KeyvaultCommands::setup_with_passphrase` directly. |
| `Unlock` | Unlock with the OS key store (a passphrase goes to `KeyvaultCommands::unlock_with_passphrase`). |
| `SetDisabled` | The kill switch (turning it off asks for Touch ID). Fields: `disabled: bool` |
-| `SetUnattended` | Per-item unattended (turning on asks for Touch ID). Fields: `item_ids: Vec<String>`, `unattended: bool` |
+| `SetUnattended` | Per-item unattended (turning on asks for Touch ID): the same as `KvCommand.SetLocked` with `locked` the other way round. Fields: `item_ids: Vec<String>`, `unattended: bool` |
+| `SetLocked` | Lock or unlock items together. Unlocking allows unattended access and asks for Touch ID once for the whole batch; locking does not. Fields: `item_ids: Vec<String>`, `locked: bool` |
+| `DeleteItems` | Delete items, wiping every live copy of them in Spaces. Fields: `item_ids: Vec<String>` |
+| `SetSkipUnlockPrompt` | "Never ask again" on the unlock prompt (Settings turns it back on). Fields: `on: bool` |
+| `Browse` | Show item names for a few minutes (the daemon asks for Touch ID). |
+| `EndBrowse` | Hide item names again. |
| `RevokeGrant` | Revoke a grant (`*`: all). Fields: `id: String` |
| `RemoveRule` | Remove a rule. Fields: `id: String` |
| `SetAutoWipe` | Auto-wipe of delivered copies (turning it off asks for Touch ID). Fields: `on: bool` |
@@ -610,7 +697,9 @@ KvMethod::Passphrase
```swift
.done
.recoveryKey(key: String?)
-.items(items: [KvItem])
+.locked(changed: [String], skipped: [String])
+.deleted(count: UInt32, wiped: [String])
+.browsing(untilMs: UInt64)
.revoked(count: UInt32)
.wiped(imports: [String])
.granted(grant: KvGrant)
@@ -622,7 +711,9 @@ KvMethod::Passphrase
```rust
KvOutcome::Done
KvOutcome::RecoveryKey { key: Option<String> }
-KvOutcome::Items { items: Vec<KvItem> }
+KvOutcome::Locked { changed: Vec<String>, skipped: Vec<String> }
+KvOutcome::Deleted { count: u32, wiped: Vec<String> }
+KvOutcome::Browsing { until_ms: u64 }
KvOutcome::Revoked { count: u32 }
KvOutcome::Wiped { imports: Vec<String> }
KvOutcome::Granted { grant: KvGrant }
@@ -635,7 +726,9 @@ KvOutcome::Granted { grant: KvGrant }
| --- | --- |
| `Done` | Nothing to show. |
| `RecoveryKey` | The recovery key, shown once and never stored. Fields: `key: Option<String>` |
-| `Items` | Items after a policy change. Fields: `items: Vec<KvItem>` |
+| `Locked` | Items locked or unlocked. Identity providers always ask: they are in `skipped`, never changed. Fields: `changed: Vec<String>`, `skipped: Vec<String>` |
+| `Deleted` | Items deleted. Fields: `count: u32`, `wiped: Vec<String>` |
+| `Browsing` | The browse window is open until then, Unix ms. Fields: `until_ms: u64` |
| `Revoked` | Grants revoked. Fields: `count: u32` |
| `Wiped` | Imports wiped. Fields: `imports: Vec<String>` |
| `Granted` | The grant an approval minted. Fields: `grant: KvGrant` |
@@ -647,7 +740,7 @@ KvOutcome::Granted { grant: KvGrant }
```swift
.item(id: String)
-.site(app: String, site: String, account: String?)
+.site(app: String, site: String)
.app(app: String)
.login(site: String)
```
@@ -657,7 +750,7 @@ KvOutcome::Granted { grant: KvGrant }
```rust
KvSelector::Item { id: String }
-KvSelector::Site { app: String, site: String, account: Option<String> }
+KvSelector::Site { app: String, site: String }
KvSelector::App { app: String }
KvSelector::Login { site: String }
```
@@ -668,7 +761,7 @@ KvSelector::Login { site: String }
| Variant | Description |
| --- | --- |
| `Item` | An existing item. Fields: `id: String` |
-| `Site` | A site of an app. Fields: `app: String`, `site: String`, `account: Option<String>` |
+| `Site` | A site of an app. Fields: `app: String`, `site: String` |
| `App` | A whole app. Fields: `app: String` |
| `Login` | A site's saved password, used to sign in (never delivered). Fields: `site: String` |
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/meta.json b/docs/content/docs/cua-sdk/reference/spaces/app-core/meta.json
index 0168e2d182..82cfcddebe 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/meta.json
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/meta.json
@@ -8,6 +8,8 @@
"images",
"teleport",
"teleport-transfer",
+ "teleport-run",
+ "teleport-review",
"teleport-grid",
"cloud",
"drag-trigger",
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/onboarding-settings.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/onboarding-settings.mdx
index ee5a887fa4..88220f6005 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/onboarding-settings.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/onboarding-settings.mdx
@@ -329,6 +329,8 @@ Returned by [`app_settings_load`](#app_settings_load).
| `launch_at_login` / `launchAtLogin` | `Option<bool>` | | Launch at login, as the user chose it (the first run's Done page or Settings); `None`: never chosen (`crate.login_item.launch_plan`). |
| `experiments` | [`AppExperiments`](/cua-sdk/reference/spaces/app-core/experiments#appexperiments-record) | | Settings, Experiments: every switch off unless turned on (`crate.experiments`). |
| `dismissed_access` / `dismissedAccess` | `Vec<String>` | | Keyvault copies (import ids) the user dismissed from the notch: it no longer shows them, nothing is revoked or wiped (`crate.keyvault.view.prune_dismissed` forgets the gone ones). |
+| `keyvault_site_icons` / `keyvaultSiteIcons` | `bool` | | Keyvault rows may load a site's icon from Google's favicon service when the source browser had none (Settings, Keyvault; on by default). Off, only icons read locally are shown. |
+| `teleport_choices` / `teleportChoices` | [`Vec<AppRememberedChoice>`](/cua-sdk/reference/spaces/app-core/teleport-review#apprememberedchoice-record) | | The sites the user sent to each Space last time, per app (`crate.teleport.review.remember`): the review starts from them. |
| `auto_connect` / `autoConnect` | `bool` | | Settings, General: a running Space's desktop streams as soon as it is opened (on by default); off, it waits for Connect (`crate.spaces.cover`). |
## `AppOnboardingAction` enum
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport-review.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport-review.mdx
new file mode 100644
index 0000000000..b384bd8f8b
--- /dev/null
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport-review.mdx
@@ -0,0 +1,286 @@
+---
+title: "Teleport review"
+description: "The review and consent before a teleport: what to send per site, from the app or from the Keyvault, and the choice remembered for next time."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-sdk
+ Source: cua-bindgen docs --namespace cua_spaces_ffi (UniFFI metadata of libcua_spaces_ffi)
+ Version: 0.2.0
+*/}
+
+import { Callout } from 'fumadocs-ui/components/callout';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<Callout title="Cua Spaces app export">
+These APIs are part of the Cua Spaces app export for building Spaces UIs. They are source-available under FSL-1.1-MIT and ship for Swift only (`import CuaSpacesFFI`); the Rust tab shows the `cua-spaces-ffi` crate they come from. The open source SDK packages for Python, TypeScript and Kotlin do not include them.
+</Callout>
+
+`AppReviewView` is the review sheet. `AppReviewToggle` and `AppReviewChoice` change what is sent, per site or per part; `app_review_remember` keeps the choice for the next teleport of the same app to the same Space, and `AppVaultSource` offers the items the Keyvault already holds, which need no Keychain prompt.
+
+## `AppReviewView` record
+
+Returned by [`app_picker_review`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_review).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `title` | `String` | | "Teleport Slack to Aurora". |
+| `items` | [`Vec<AppConsentItem>`](#appconsentitem-record) | | The consent lines. |
+| `steps` | [`Vec<AppPlanStepView>`](#appplanstepview-record) | | Plan steps. |
+| `needs_acknowledgement` / `needsAcknowledgement` | `bool` | | The secrets checkbox shows. |
+| `acknowledged` | `bool` | | Checked. |
+| `offers_save_to_keyvault` / `offersSaveToKeyvault` | `bool` | | The "Save to Keyvault" checkbox shows (a sensitive plan only: there is nothing to keep sealed otherwise). |
+| `save_to_keyvault` / `saveToKeyvault` | `bool` | | Checked. |
+| `needs_relay_plaintext_acknowledgement` / `needsRelayPlaintextAcknowledgement` | `bool` | | The relay-plaintext warning's checkbox shows (S1): this Space predates end-to-end sealing, and the Cua relay could read this secret in transit. |
+| `acknowledged_relay_plaintext` / `acknowledgedRelayPlaintext` | `bool` | | Checked. |
+| `can_confirm` / `canConfirm` | `bool` | | "Teleport" is enabled. |
+| `leaves_text` / `leavesText` | `Option<String>` | | "12 MB leaves this Mac" (none when nothing leaves). |
+| `warnings` | `Vec<String>` | | Caveats. |
+| `toggles` | [`Vec<AppReviewToggle>`](#appreviewtoggle-record) | | Lines the user can turn off (files, folders, state, secrets), each with whether it is sent. The cookie store is the site list below. |
+| `offers_domains` / `offersDomains` | `bool` | | The plan sends a browser's cookies, so the sites can be chosen. |
+| `needs_domains` / `needsDomains` | `bool` | | The sites have not been read yet (the shell asks the Keyvault for them, which may ask for Touch ID). |
+| `domains` | [`Vec<AppReviewDomain>`](#appreviewdomain-record) | | The sites with counts, filtered by the search. |
+| `domain_summary` / `domainSummary` | `String` | | "3 of 12 sites". |
+| `domain_query` / `domainQuery` | `String` | | The sites search text. |
+| `selected_domains` / `selectedDomains` | `Vec<String>` | | The sites chosen (what is remembered for next time). |
+| `source` | [`AppSendSource`](#appsendsource-enum) | | Where it sends from. |
+| `offers_vault` / `offersVault` | `bool` | | The app has saved Keyvault items to send instead of reading the live app. |
+| `vault` | [`AppVaultSource`](#appvaultsource-record) | | The saved items. |
+| `vault_label` / `vaultLabel` | `String` | | "Send from the Keyvault (212 items, saved 2 days ago)". |
+| `live_label` / `liveLabel` | `String` | | "Read Chrome now (macOS asks for Keychain access)". |
+| `offers_passwords` / `offersPasswords` | `bool` | | "Also send saved passwords" shows (there are some to send). |
+| `include_passwords` / `includePasswords` | `bool` | | Ticked. |
+| `passwords_label` / `passwordsLabel` | `String` | | "Also send 14 saved passwords". |
+| `source_note` / `sourceNote` | `String` | | What the Keychain will do for this source, in a line. |
+
+## `AppSendSource` enum
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+.live
+.vault
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+AppSendSource::Live
+AppSendSource::Vault
+```
+
+</Tab>
+</Tabs>
+
+| Variant | Description |
+| --- | --- |
+| `Live` | Read the live app now (a browser's cookies are decrypted, so macOS asks for Keychain access). |
+| `Vault` | Send the items saved in the Keyvault for this app. Nothing is read from the host. |
+
+## `AppVaultSource` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `available` | `bool` | | The app has saved items that can be sent (passwords never are). |
+| `items` | `u32` | | How many. |
+| `saved` | `String` | | "saved 2 days ago". |
+| `selected` | `Vec<String>` | | The items chosen to send (ids). |
+| `password_ids` / `passwordIds` | `Vec<String>` | | The app's saved passwords (ids), sent only when ticked. |
+
+## `AppRememberedChoice` record
+
+Returned by [`app_review_remember`](#app_review_remember).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `key` | `String` | | `<app>\|<space>`. |
+| `domains` | `Vec<String>` | | The sites (registrable domains) that were sent. |
+
+## `AppPlanStepView` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `kind` | `String` | | `install`, `files`, `state`, `launch`. |
+| `summary` | `String` | | One line. |
+
+## `AppInstallCuaPrompt` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `installed` | `bool` | | Cua is installed but not running. |
+| `title` | `String` | | Title. |
+| `message` | `String` | | One line. |
+| `action_label` / `actionLabel` | `String` | | Button. |
+| `url` | `String` | | Button target: always one of the constants, never from the error. |
+
+## `AppConsentItem` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `kind` | [`AppConsentKind`](#appconsentkind-enum) | | Kind. |
+| `key` | `String` | | Stable key. |
+| `label` | `String` | | Label. |
+| `detail` | `String` | | Detail. |
+| `bytes` | `u64` | | Bytes that leave. |
+| `sensitive` | `bool` | | Credentials, cookies, tokens. |
+
+## `AppReviewChoice` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `source` | [`AppSendSource`](#appsendsource-enum) | | Where to send from. |
+| `domains` | [`Vec<KvDomainCount>`](/cua-sdk/reference/spaces/app-core/keyvault#kvdomaincount-record) | | The browser's sites with counts (none until read, or for an app that is not a browser). |
+| `selected_domains` / `selectedDomains` | `Vec<String>` | | The sites chosen. |
+| `query` | `String` | | The sites list's search text. |
+| `excluded` | `Vec<String>` | | Consent items (keys) turned off. |
+| `vault` | [`AppVaultSource`](#appvaultsource-record) | | The saved items. |
+| `loaded` | `bool` | | The sites were asked for (a failure counts: the review then sends what the plan lists). |
+| `include_passwords` / `includePasswords` | `bool` | | The saved passwords are ticked to send (off unless the user ticks them; never remembered). |
+
+## `AppReviewDomain` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `domain` | `String` | | The site (`github.com`). |
+| `counts` | `String` | | "12 cookies, 2 storage values". |
+| `count` | `u32` | | Items the site holds. |
+| `signin` | `bool` | | It looks like it keeps a sign-in. |
+| `identity_provider` / `identityProvider` | `bool` | | An identity provider: its session unlocks other apps. |
+| `selected` | `bool` | | Chosen to send. |
+| `selectable` | `bool` | | Can be chosen: it holds something that can be sent. A site whose cookies are all unreadable is greyed out. |
+| `unavailable` | `u32` | | Cookies that cannot be read, shown greyed with `unavailable_note`. |
+| `unavailable_note` / `unavailableNote` | `String` | | "3 cookies cannot be sent: Chrome protects them with ...", or empty. |
+
+## `AppReviewToggle` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `key` | `String` | | The consent item's key. |
+| `label` | `String` | | Label. |
+| `detail` | `String` | | Detail. |
+| `bytes` | `u64` | | Bytes that leave. |
+| `sensitive` | `bool` | | A secret. |
+| `selected` | `bool` | | Sent (not turned off). |
+
+## `AppConsentKind` enum
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+.install
+.file
+.folder
+.state
+.secret
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+AppConsentKind::Install
+AppConsentKind::File
+AppConsentKind::Folder
+AppConsentKind::State
+AppConsentKind::Secret
+```
+
+</Tab>
+</Tabs>
+
+| Variant | Description |
+| --- | --- |
+| `Install` | An install into the Space. |
+| `File` | A file that leaves this machine. |
+| `Folder` | A folder that leaves this machine. |
+| `State` | App state that leaves this machine. |
+| `Secret` | A secret that leaves this machine. |
+
+## `app_review_remember`
+
+`choices` with the sites just sent remembered for `key`.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appReviewRemember(choices: [AppRememberedChoice], key: String, domains: [String]) -> [AppRememberedChoice]
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_review_remember(choices: Vec<AppRememberedChoice>, key: String, domains: Vec<String>) -> Vec<AppRememberedChoice>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `choices` | [`Vec<AppRememberedChoice>`](#apprememberedchoice-record) | required |
+| `key` | `String` | required |
+| `domains` | `Vec<String>` | required |
+
+**Returns** [`Vec<AppRememberedChoice>`](#apprememberedchoice-record)
+
+## `app_review_remember_key`
+
+The key a review's site choice is remembered under (`<app>|<space>`).
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appReviewRememberKey(app: String, space: String) -> String
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_review_remember_key(app: String, space: String) -> String
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `app` | `String` | required |
+| `space` | `String` | required |
+
+**Returns** `String`
+
+## `app_review_remembered`
+
+What was picked last time for `key` (an app and a Space), if anything.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appReviewRemembered(choices: [AppRememberedChoice], key: String) -> [String]?
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_review_remembered(choices: Vec<AppRememberedChoice>, key: String) -> Option<Vec<String>>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `choices` | [`Vec<AppRememberedChoice>`](#apprememberedchoice-record) | required |
+| `key` | `String` | required |
+
+**Returns** `Option<Vec<String>>`
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport-run.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport-run.mdx
new file mode 100644
index 0000000000..d83ae347ca
--- /dev/null
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport-run.mdx
@@ -0,0 +1,278 @@
+---
+title: "Teleport plan and run"
+description: "The teleport plan, its consent and capabilities, and the run's steps."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-sdk
+ Source: cua-bindgen docs --namespace cua_spaces_ffi (UniFFI metadata of libcua_spaces_ffi)
+ Version: 0.2.0
+*/}
+
+import { Callout } from 'fumadocs-ui/components/callout';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<Callout title="Cua Spaces app export">
+These APIs are part of the Cua Spaces app export for building Spaces UIs. They are source-available under FSL-1.1-MIT and ship for Swift only (`import CuaSpacesFFI`); the Rust tab shows the `cua-spaces-ffi` crate they come from. The open source SDK packages for Python, TypeScript and Kotlin do not include them.
+</Callout>
+
+`app_teleport_plan` turns a `Teleport.plan` into the consent the user sees; `AppTeleportRunEvent` and `AppTeleportRunReport` follow the run.
+
+## `AppTeleportConsent` record
+
+Returned by [`app_picker_consent`](/cua-sdk/reference/spaces/app-core/teleport#app_picker_consent).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `approved` | `bool` | | Confirmed. |
+| `acknowledge_sensitive` / `acknowledgeSensitive` | `bool` | | Secrets acknowledged. |
+| `save_to_keyvault` / `saveToKeyvault` | `bool` | | "Save to Keyvault" checked. |
+| `acknowledge_relay_plaintext` / `acknowledgeRelayPlaintext` | `bool` | | `Plan.relay_unsealed`'s warning acknowledged (S1). |
+| `cookie_domains` / `cookieDomains` | `Option<Vec<String>>` | | The sites whose cookies to send (the review's per-site choice); `None` when the review did not list sites. |
+| `exclude` | `Vec<String>` | | Consent items (keys) the user turned off. |
+| `from_vault` / `fromVault` | `Option<Vec<String>>` | | Send these saved Keyvault items instead of reading the live app. |
+| `include_passwords` / `includePasswords` | `bool` | | Also send the saved passwords (ticked in the review). |
+
+## `AppTeleportPlan` record
+
+Returned by [`app_teleport_plan`](#app_teleport_plan), [`app_teleport_plan_from_json`](#app_teleport_plan_from_json).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `app` | [`AppCatalogEntry`](/cua-sdk/reference/spaces/app-core/teleport#appcatalogentry-record) | | The app. |
+| `space_id` / `spaceId` | `String` | | Target Space. |
+| `moves` | [`AppTeleportMove`](#appteleportmove-enum) | | What moves. |
+| `steps` | [`Vec<AppPlanStepView>`](/cua-sdk/reference/spaces/app-core/teleport-review#appplanstepview-record) | | Steps. |
+| `consent` | [`Vec<AppConsentItem>`](/cua-sdk/reference/spaces/app-core/teleport-review#appconsentitem-record) | | Consent lines. |
+| `sensitive` | `bool` | | Any line is a secret. |
+| `total_bytes` / `totalBytes` | `u64` | | Bytes that leave this machine. |
+| `warnings` | `Vec<String>` | | Caveats. |
+| `relay_unsealed` / `relayUnsealed` | `bool` | | This Space is reached through a relay connection that predates end-to-end sealing: a secret this plan sends would cross it in the clear (S1). Needs `acknowledgeRelayPlaintext` the same way a secret needs `acknowledgeSensitive`. Defaults to `false`: older fixtures and a plan from a relay that predates the capability both read as sealed (never retroactively flagged). |
+| `json` | `String` | | The SDK's JSON for this plan. |
+
+## `AppTeleportRunEvent` record
+
+Returned by [`app_teleport_run_event`](#app_teleport_run_event).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `step` | `u32` | | Step index. |
+| `steps` | `u32` | | Steps. |
+| `kind` | `String` | | Step kind. |
+| `phase` | [`AppTeleportRunPhase`](#appteleportrunphase-enum) | | Phase. |
+| `detail` | `String` | | Detail. |
+| `done_bytes` / `doneBytes` | `u64` | | Bytes done. |
+| `total_bytes` / `totalBytes` | `u64` | | Bytes total. |
+
+## `AppTeleportRunReport` record
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `app_id` / `appId` | `String` | | App id. |
+| `installed` | `Vec<String>` | | Installed. |
+| `sent` | `Vec<String>` | | Sent. |
+| `imported` | `Vec<String>` | | Imported. |
+| `skipped` | `Vec<String>` | | Skipped. |
+| `launched` | `bool` | | Launched. |
+
+## `AppTeleportCapability` enum
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+.full
+.installOnly
+.unsupported
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+AppTeleportCapability::Full
+AppTeleportCapability::InstallOnly
+AppTeleportCapability::Unsupported
+```
+
+</Tab>
+</Tabs>
+
+| Variant | Description |
+| --- | --- |
+| `Full` | App and signed-in state. |
+| `InstallOnly` | App, empty or with files. |
+| `Unsupported` | Not available. |
+
+## `AppTeleportMove` enum
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+.appOnly
+.appWithFiles
+.appWithState
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+AppTeleportMove::AppOnly
+AppTeleportMove::AppWithFiles
+AppTeleportMove::AppWithState
+```
+
+</Tab>
+</Tabs>
+
+| Variant | Description |
+| --- | --- |
+| `AppOnly` | Just the app. |
+| `AppWithFiles` | The app with files or folders. |
+| `AppWithState` | The app with its signed-in state. |
+
+## `AppTeleportRunPhase` enum
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+.started
+.progress
+.finished
+.failed
+.done
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+AppTeleportRunPhase::Started
+AppTeleportRunPhase::Progress
+AppTeleportRunPhase::Finished
+AppTeleportRunPhase::Failed
+AppTeleportRunPhase::Done
+```
+
+</Tab>
+</Tabs>
+
+| Variant | Description |
+| --- | --- |
+| `Started` | A step started. |
+| `Progress` | Bytes moved. |
+| `Finished` | A step finished. |
+| `Failed` | A step failed. |
+| `Done` | All done. |
+
+## `app_teleport_plan`
+
+A plan from `Teleport.plan`, as the review's plan.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appTeleportPlan(plan: TeleportPlan) -> AppTeleportPlan
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_teleport_plan(plan: TeleportPlan) -> AppTeleportPlan
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `plan` | [`TeleportPlan`](/cua-sdk/reference/spaces/teleport-apps#teleportplan-record) | required |
+
+**Returns** [`AppTeleportPlan`](#appteleportplan-record)
+
+## `app_teleport_plan_from_json`
+
+A teleport plan from JSON (fixtures, parity flows).
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appTeleportPlanFromJson(json: String) throws -> AppTeleportPlan
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_teleport_plan_from_json(json: String) -> Result<AppTeleportPlan, CuaError>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `json` | `String` | required |
+
+**Returns** [`AppTeleportPlan`](#appteleportplan-record) · **Raises** [`CuaError`](/cua-sdk/reference/errors)
+
+## `app_teleport_run_event`
+
+An SDK run event as the picker's (`AppPickerEvent.progress`).
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appTeleportRunEvent(event: TeleportRunEvent) -> AppTeleportRunEvent
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_teleport_run_event(event: TeleportRunEvent) -> AppTeleportRunEvent
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `event` | [`TeleportRunEvent`](/cua-sdk/reference/spaces/teleport-apps#teleportrunevent-record) | required |
+
+**Returns** [`AppTeleportRunEvent`](#appteleportrunevent-record)
+
+## `app_teleport_run_status`
+
+`app_picker_status` for a run's events as the SDK delivered them.
+
+<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
+<Tab value="Swift">
+
+```swift
+func appTeleportRunStatus(events: [TeleportRunEvent]) -> String?
+```
+
+</Tab>
+<Tab value="Rust">
+
+```rust
+pub fn app_teleport_run_status(events: Vec<TeleportRunEvent>) -> Option<String>
+```
+
+</Tab>
+</Tabs>
+
+| Parameter | Type | Default |
+| --- | --- | --- |
+| `events` | [`Vec<TeleportRunEvent>`](/cua-sdk/reference/spaces/teleport-apps#teleportrunevent-record) | required |
+
+**Returns** `Option<String>`
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport.mdx
index 3daed168bb..1c474bbb53 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/teleport.mdx
@@ -1,6 +1,6 @@
---
title: "Teleport picker"
-description: "The teleport picker and review, and consent."
+description: "The teleport picker and its catalog."
---
{/*
@@ -17,7 +17,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
These APIs are part of the Cua Spaces app export for building Spaces UIs. They are source-available under FSL-1.1-MIT and ship for Swift only (`import CuaSpacesFFI`); the Rust tab shows the `cua-spaces-ffi` crate they come from. The open source SDK packages for Python, TypeScript and Kotlin do not include them.
</Callout>
-The picker lists `Teleport.catalog` entries, reviews a `Teleport.plan` with its consent items, and follows the run. The overlays that show a teleport in progress are on [Teleport transfer and drag](/cua-sdk/reference/spaces/app-core/teleport-transfer).
+The picker lists `Teleport.catalog` entries and drives the steps up to the review. The overlays that show a teleport in progress are on [Teleport transfer and drag](/cua-sdk/reference/spaces/app-core/teleport-transfer).
## `AppEntrySection` record
@@ -28,42 +28,6 @@ Returned by [`app_picker_sections`](#app_picker_sections).
| `title` | `String` | | "Recent", "Apps", "Not available". |
| `entries` | [`Vec<AppCatalogEntry>`](#appcatalogentry-record) | | Entries. |
-## `AppReviewView` record
-
-Returned by [`app_picker_review`](#app_picker_review).
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `title` | `String` | | "Teleport Slack to Aurora". |
-| `items` | [`Vec<AppConsentItem>`](#appconsentitem-record) | | The consent lines. |
-| `steps` | [`Vec<AppPlanStepView>`](#appplanstepview-record) | | Plan steps. |
-| `needs_acknowledgement` / `needsAcknowledgement` | `bool` | | The secrets checkbox shows. |
-| `acknowledged` | `bool` | | Checked. |
-| `offers_save_to_keyvault` / `offersSaveToKeyvault` | `bool` | | The "Save to Keyvault" checkbox shows (a sensitive plan only: there is nothing to keep sealed otherwise). |
-| `save_to_keyvault` / `saveToKeyvault` | `bool` | | Checked. |
-| `needs_relay_plaintext_acknowledgement` / `needsRelayPlaintextAcknowledgement` | `bool` | | The relay-plaintext warning's checkbox shows (S1): this Space predates end-to-end sealing, and the Cua relay could read this secret in transit. |
-| `acknowledged_relay_plaintext` / `acknowledgedRelayPlaintext` | `bool` | | Checked. |
-| `can_confirm` / `canConfirm` | `bool` | | "Teleport" is enabled. |
-| `leaves_text` / `leavesText` | `Option<String>` | | "12 MB leaves this Mac" (none when nothing leaves). |
-| `warnings` | `Vec<String>` | | Caveats. |
-
-## `AppPlanStepView` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `kind` | `String` | | `install`, `files`, `state`, `launch`. |
-| `summary` | `String` | | One line. |
-
-## `AppInstallCuaPrompt` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `installed` | `bool` | | Cua is installed but not running. |
-| `title` | `String` | | Title. |
-| `message` | `String` | | One line. |
-| `action_label` / `actionLabel` | `String` | | Button. |
-| `url` | `String` | | Button target: always one of the constants, never from the error. |
-
## `AppCatalogEntry` record
Returned by [`app_catalog_entries_from_json`](#app_catalog_entries_from_json), [`app_catalog_entry`](#app_catalog_entry).
@@ -75,9 +39,9 @@ Returned by [`app_catalog_entries_from_json`](#app_catalog_entries_from_json), [
| `host_path` / `hostPath` | `Option<String>` | | Bundle path. |
| `host_app_id` / `hostAppId` | `Option<String>` | | Bundle id. |
| `version` | `Option<String>` | | Version. |
-| `capability` | [`AppTeleportCapability`](#appteleportcapability-enum) | | Capability. |
+| `capability` | [`AppTeleportCapability`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportcapability-enum) | | Capability. |
| `reason` | `Option<String>` | | Why unsupported, or a caveat. |
-| `moves` | [`Vec<AppTeleportMove>`](#appteleportmove-enum) | | Offered moves, UI order. |
+| `moves` | [`Vec<AppTeleportMove>`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportmove-enum) | | Offered moves, UI order. |
| `provider_id` / `providerId` | `Option<String>` | | Provider id. |
| `sensitive_groups` / `sensitiveGroups` | [`Vec<AppSensitiveGroup>`](/cua-sdk/reference/spaces/app-core/keyvault#appsensitivegroup-enum) | | The opt-in groups the signed-in state move offers, UI order. |
| `install_source` / `installSource` | `Option<String>` | | `manifest`, `image`, `space`. |
@@ -87,17 +51,6 @@ Returned by [`app_catalog_entries_from_json`](#app_catalog_entries_from_json), [
| `last_used_ms` / `lastUsedMs` | `Option<i64>` | | Last used (recents). |
| `json` | `String` | | The SDK's JSON for this entry. |
-## `AppConsentItem` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `kind` | [`AppConsentKind`](#appconsentkind-enum) | | Kind. |
-| `key` | `String` | | Stable key. |
-| `label` | `String` | | Label. |
-| `detail` | `String` | | Detail. |
-| `bytes` | `u64` | | Bytes that leave. |
-| `sensitive` | `bool` | | Credentials, cookies, tokens. |
-
## `AppPickerPrimary` record
Returned by [`app_picker_primary`](#app_picker_primary).
@@ -120,107 +73,20 @@ Returned by [`app_picker_initial`](#app_picker_initial), [`app_picker_reduce`](#
| `query` | `String` | | Search. |
| `selected_id` / `selectedId` | `Option<String>` | | Highlighted app. |
| `entry` | [`Option<AppCatalogEntry>`](#appcatalogentry-record) | | The chosen app. |
-| `moves` | [`Option<AppTeleportMove>`](#appteleportmove-enum) | | What moves. |
+| `moves` | [`Option<AppTeleportMove>`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportmove-enum) | | What moves. |
| `files` | `Vec<String>` | | Chosen files. |
| `sensitive` | [`Vec<AppSensitiveGroup>`](/cua-sdk/reference/spaces/app-core/keyvault#appsensitivegroup-enum) | | The opt-in groups checked on the options step (only planned with the signed-in state move). Each group's items are secrets the review lists and asks to acknowledge. |
-| `plan` | [`Option<AppTeleportPlan>`](#appteleportplan-record) | | The plan under review. |
+| `plan` | [`Option<AppTeleportPlan>`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportplan-record) | | The plan under review. |
| `acknowledged` | `bool` | | Secrets acknowledged. |
| `save_to_keyvault` / `saveToKeyvault` | `bool` | | "Save to Keyvault" checked: keep the captured session sealed in the Cua Keyvault after delivery, for reuse without asking again (shown alongside the acknowledgement, only when the plan is sensitive). |
| `acknowledged_relay_plaintext` / `acknowledgedRelayPlaintext` | `bool` | | `Plan.relay_unsealed`'s warning acknowledged (S1). |
-| `events` | [`Vec<AppTeleportRunEvent>`](#appteleportrunevent-record) | | Run events (last `MAX_EVENTS`). |
-| `report` | [`Option<AppTeleportRunReport>`](#appteleportrunreport-record) | | The run's report. |
+| `choice` | [`AppReviewChoice`](/cua-sdk/reference/spaces/app-core/teleport-review#appreviewchoice-record) | | What the review sends: which sites, which items, from where. |
+| `events` | [`Vec<AppTeleportRunEvent>`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportrunevent-record) | | Run events (last `MAX_EVENTS`). |
+| `report` | [`Option<AppTeleportRunReport>`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportrunreport-record) | | The run's report. |
| `error` | `Option<String>` | | Error text. |
-| `install_prompt` / `installPrompt` | [`Option<AppInstallCuaPrompt>`](#appinstallcuaprompt-record) | | The "needs the Cua app" prompt. |
+| `install_prompt` / `installPrompt` | [`Option<AppInstallCuaPrompt>`](/cua-sdk/reference/spaces/app-core/teleport-review#appinstallcuaprompt-record) | | The "needs the Cua app" prompt. |
| `error_back` / `errorBack` | [`AppPickerStep`](#apppickerstep-enum) | | Where Back from an error goes. |
-## `AppTeleportConsent` record
-
-Returned by [`app_picker_consent`](#app_picker_consent).
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `approved` | `bool` | | Confirmed. |
-| `acknowledge_sensitive` / `acknowledgeSensitive` | `bool` | | Secrets acknowledged. |
-| `save_to_keyvault` / `saveToKeyvault` | `bool` | | "Save to Keyvault" checked. |
-| `acknowledge_relay_plaintext` / `acknowledgeRelayPlaintext` | `bool` | | `Plan.relay_unsealed`'s warning acknowledged (S1). |
-
-## `AppTeleportPlan` record
-
-Returned by [`app_teleport_plan`](#app_teleport_plan), [`app_teleport_plan_from_json`](#app_teleport_plan_from_json).
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `app` | [`AppCatalogEntry`](#appcatalogentry-record) | | The app. |
-| `space_id` / `spaceId` | `String` | | Target Space. |
-| `moves` | [`AppTeleportMove`](#appteleportmove-enum) | | What moves. |
-| `steps` | [`Vec<AppPlanStepView>`](#appplanstepview-record) | | Steps. |
-| `consent` | [`Vec<AppConsentItem>`](#appconsentitem-record) | | Consent lines. |
-| `sensitive` | `bool` | | Any line is a secret. |
-| `total_bytes` / `totalBytes` | `u64` | | Bytes that leave this machine. |
-| `warnings` | `Vec<String>` | | Caveats. |
-| `relay_unsealed` / `relayUnsealed` | `bool` | | This Space is reached through a relay connection that predates end-to-end sealing: a secret this plan sends would cross it in the clear (S1). Needs `acknowledgeRelayPlaintext` the same way a secret needs `acknowledgeSensitive`. Defaults to `false`: older fixtures and a plan from a relay that predates the capability both read as sealed (never retroactively flagged). |
-| `json` | `String` | | The SDK's JSON for this plan. |
-
-## `AppTeleportRunEvent` record
-
-Returned by [`app_teleport_run_event`](#app_teleport_run_event).
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `step` | `u32` | | Step index. |
-| `steps` | `u32` | | Steps. |
-| `kind` | `String` | | Step kind. |
-| `phase` | [`AppTeleportRunPhase`](#appteleportrunphase-enum) | | Phase. |
-| `detail` | `String` | | Detail. |
-| `done_bytes` / `doneBytes` | `u64` | | Bytes done. |
-| `total_bytes` / `totalBytes` | `u64` | | Bytes total. |
-
-## `AppTeleportRunReport` record
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `app_id` / `appId` | `String` | | App id. |
-| `installed` | `Vec<String>` | | Installed. |
-| `sent` | `Vec<String>` | | Sent. |
-| `imported` | `Vec<String>` | | Imported. |
-| `skipped` | `Vec<String>` | | Skipped. |
-| `launched` | `bool` | | Launched. |
-
-## `AppConsentKind` enum
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-.install
-.file
-.folder
-.state
-.secret
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-AppConsentKind::Install
-AppConsentKind::File
-AppConsentKind::Folder
-AppConsentKind::State
-AppConsentKind::Secret
-```
-
-</Tab>
-</Tabs>
-
-| Variant | Description |
-| --- | --- |
-| `Install` | An install into the Space. |
-| `File` | A file that leaves this machine. |
-| `Folder` | A folder that leaves this machine. |
-| `State` | App state that leaves this machine. |
-| `Secret` | A secret that leaves this machine. |
-
## `AppPickerAction` enum
<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
@@ -271,6 +137,16 @@ AppPickerAction::StreamLocalSoon
.acknowledge(value: Bool)
.saveToKeyvault(value: Bool)
.acknowledgeRelayPlaintext(value: Bool)
+.domainsLoaded(inventory: KvInventory, remembered: [String]?)
+.domainsFailed
+.toggleDomain(domain: String)
+.selectShownDomains(value: Bool)
+.domainQuery(text: String)
+.toggleItem(key: String)
+.sendFrom(source: AppSendSource)
+.vaultItems(count: UInt32, newestMs: Int64, nowMs: Int64, selected: [String], passwordIds: [String])
+.togglePasswords(value: Bool)
+.vaultSelection(selected: [String])
.confirm
.progress(event: AppTeleportRunEvent)
.finished(report: AppTeleportRunReport)
@@ -296,6 +172,16 @@ AppPickerEvent::Planned { plan: AppTeleportPlan }
AppPickerEvent::Acknowledge { value: bool }
AppPickerEvent::SaveToKeyvault { value: bool }
AppPickerEvent::AcknowledgeRelayPlaintext { value: bool }
+AppPickerEvent::DomainsLoaded { inventory: KvInventory, remembered: Option<Vec<String>> }
+AppPickerEvent::DomainsFailed
+AppPickerEvent::ToggleDomain { domain: String }
+AppPickerEvent::SelectShownDomains { value: bool }
+AppPickerEvent::DomainQuery { text: String }
+AppPickerEvent::ToggleItem { key: String }
+AppPickerEvent::SendFrom { source: AppSendSource }
+AppPickerEvent::VaultItems { count: u32, newest_ms: i64, now_ms: i64, selected: Vec<String>, password_ids: Vec<String> }
+AppPickerEvent::TogglePasswords { value: bool }
+AppPickerEvent::VaultSelection { selected: Vec<String> }
AppPickerEvent::Confirm
AppPickerEvent::Progress { event: AppTeleportRunEvent }
AppPickerEvent::Finished { report: AppTeleportRunReport }
@@ -322,6 +208,16 @@ AppPickerEvent::Back
| `Acknowledge` | The secrets checkbox. Fields: `value: bool` |
| `SaveToKeyvault` | The "Save to Keyvault" checkbox. Fields: `value: bool` |
| `AcknowledgeRelayPlaintext` | The relay-plaintext warning's checkbox (S1). Fields: `value: bool` |
+| `DomainsLoaded` | The browser's sites with counts arrived (and what was picked last time for this app and Space, if anything). Fields: `inventory: KvInventory`, `remembered: Option<Vec<String>>` |
+| `DomainsFailed` | The inventory could not be read (the review then sends what the plan lists, as before). |
+| `ToggleDomain` | Pick or drop one site. Fields: `domain: String` |
+| `SelectShownDomains` | Pick or drop every site the search shows. Fields: `value: bool` |
+| `DomainQuery` | The sites list's search text. Fields: `text: String` |
+| `ToggleItem` | Turn a consent line on or off. Fields: `key: String` |
+| `SendFrom` | Where to send from. Fields: `source: AppSendSource` |
+| `VaultItems` | The app's saved Keyvault items (what the Keyvault holds for it). Fields: `count: u32`, `newest_ms: i64`, `now_ms: i64`, `selected: Vec<String>`, `password_ids: Vec<String>` |
+| `TogglePasswords` | Tick or untick "Also send saved passwords". Fields: `value: bool` |
+| `VaultSelection` | The chosen saved items changed. Fields: `selected: Vec<String>` |
| `Confirm` | Confirm the review. |
| `Progress` | A run event. Fields: `event: AppTeleportRunEvent` |
| `Finished` | The run finished. Fields: `report: AppTeleportRunReport` |
@@ -397,99 +293,6 @@ AppPickerTab::ThisMac
| `Space` | This machine's windows, teleported into the Space. |
| `ThisMac` | The Space's windows, streamed here. |
-## `AppTeleportCapability` enum
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-.full
-.installOnly
-.unsupported
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-AppTeleportCapability::Full
-AppTeleportCapability::InstallOnly
-AppTeleportCapability::Unsupported
-```
-
-</Tab>
-</Tabs>
-
-| Variant | Description |
-| --- | --- |
-| `Full` | App and signed-in state. |
-| `InstallOnly` | App, empty or with files. |
-| `Unsupported` | Not available. |
-
-## `AppTeleportMove` enum
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-.appOnly
-.appWithFiles
-.appWithState
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-AppTeleportMove::AppOnly
-AppTeleportMove::AppWithFiles
-AppTeleportMove::AppWithState
-```
-
-</Tab>
-</Tabs>
-
-| Variant | Description |
-| --- | --- |
-| `AppOnly` | Just the app. |
-| `AppWithFiles` | The app with files or folders. |
-| `AppWithState` | The app with its signed-in state. |
-
-## `AppTeleportRunPhase` enum
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-.started
-.progress
-.finished
-.failed
-.done
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-AppTeleportRunPhase::Started
-AppTeleportRunPhase::Progress
-AppTeleportRunPhase::Finished
-AppTeleportRunPhase::Failed
-AppTeleportRunPhase::Done
-```
-
-</Tab>
-</Tabs>
-
-| Variant | Description |
-| --- | --- |
-| `Started` | A step started. |
-| `Progress` | Bytes moved. |
-| `Finished` | A step finished. |
-| `Failed` | A step failed. |
-| `Done` | All done. |
-
## `app_catalog_entries_from_json`
Picker catalog entries from JSON (fixtures, parity flows).
@@ -596,7 +399,7 @@ pub fn app_picker_consent(state: AppPickerState) -> AppTeleportConsent
| --- | --- | --- |
| `state` | [`AppPickerState`](#apppickerstate-record) | required |
-**Returns** [`AppTeleportConsent`](#appteleportconsent-record)
+**Returns** [`AppTeleportConsent`](/cua-sdk/reference/spaces/app-core/teleport-run#appteleportconsent-record)
## `app_picker_initial`
@@ -760,7 +563,7 @@ pub fn app_picker_review(state: AppPickerState) -> Option<AppReviewView>
| --- | --- | --- |
| `state` | [`AppPickerState`](#apppickerstate-record) | required |
-**Returns** [`Option<AppReviewView>`](#appreviewview-record)
+**Returns** [`Option<AppReviewView>`](/cua-sdk/reference/spaces/app-core/teleport-review#appreviewview-record)
## `app_picker_sections`
@@ -844,111 +647,3 @@ pub fn app_picker_status(state: AppPickerState) -> Option<String>
| `state` | [`AppPickerState`](#apppickerstate-record) | required |
**Returns** `Option<String>`
-
-## `app_teleport_plan`
-
-A plan from `Teleport.plan`, as the review's plan.
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-func appTeleportPlan(plan: TeleportPlan) -> AppTeleportPlan
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-pub fn app_teleport_plan(plan: TeleportPlan) -> AppTeleportPlan
-```
-
-</Tab>
-</Tabs>
-
-| Parameter | Type | Default |
-| --- | --- | --- |
-| `plan` | [`TeleportPlan`](/cua-sdk/reference/spaces/teleport-apps#teleportplan-record) | required |
-
-**Returns** [`AppTeleportPlan`](#appteleportplan-record)
-
-## `app_teleport_plan_from_json`
-
-A teleport plan from JSON (fixtures, parity flows).
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-func appTeleportPlanFromJson(json: String) throws -> AppTeleportPlan
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-pub fn app_teleport_plan_from_json(json: String) -> Result<AppTeleportPlan, CuaError>
-```
-
-</Tab>
-</Tabs>
-
-| Parameter | Type | Default |
-| --- | --- | --- |
-| `json` | `String` | required |
-
-**Returns** [`AppTeleportPlan`](#appteleportplan-record) · **Raises** [`CuaError`](/cua-sdk/reference/errors)
-
-## `app_teleport_run_event`
-
-An SDK run event as the picker's (`AppPickerEvent.progress`).
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-func appTeleportRunEvent(event: TeleportRunEvent) -> AppTeleportRunEvent
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-pub fn app_teleport_run_event(event: TeleportRunEvent) -> AppTeleportRunEvent
-```
-
-</Tab>
-</Tabs>
-
-| Parameter | Type | Default |
-| --- | --- | --- |
-| `event` | [`TeleportRunEvent`](/cua-sdk/reference/spaces/teleport-apps#teleportrunevent-record) | required |
-
-**Returns** [`AppTeleportRunEvent`](#appteleportrunevent-record)
-
-## `app_teleport_run_status`
-
-`app_picker_status` for a run's events as the SDK delivered them.
-
-<Tabs items={['Swift', 'Rust']} groupId="sdk-lang" persist>
-<Tab value="Swift">
-
-```swift
-func appTeleportRunStatus(events: [TeleportRunEvent]) -> String?
-```
-
-</Tab>
-<Tab value="Rust">
-
-```rust
-pub fn app_teleport_run_status(events: Vec<TeleportRunEvent>) -> Option<String>
-```
-
-</Tab>
-</Tabs>
-
-| Parameter | Type | Default |
-| --- | --- | --- |
-| `events` | [`Vec<TeleportRunEvent>`](/cua-sdk/reference/spaces/teleport-apps#teleportrunevent-record) | required |
-
-**Returns** `Option<String>`
diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx
index 646a2a721d..ca00acbe7e 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx
@@ -620,6 +620,9 @@ Returned by [`app_settings_input_from_json`](#app_settings_input_from_json).
| `login_item` / `loginItem` | [`Option<AppLoginItemInput>`](#apploginiteminput-record) | | Launch at login, once the system was asked (none: no rows). |
| `experiments` | [`AppExperiments`](/cua-sdk/reference/spaces/app-core/experiments#appexperiments-record) | | Settings, Experiments (what the page mentions follows them). |
| `keyvault_auto_wipe` / `keyvaultAutoWipe` | `Option<bool>` | | The Keyvault's auto-wipe, once the broker told it (none: no Keyvault section). |
+| `keyvault_unlock_prompt` / `keyvaultUnlockPrompt` | `Option<bool>` | | The unlock prompt shows (false once the user chose "Never ask again"); none until the broker told it. |
+| `keyvault_site_icons` / `keyvaultSiteIcons` | `bool` | | Load site icons from Google when the browser had none (`AppSettings.keyvault_site_icons`). |
+| `keyvault_protection` / `keyvaultProtection` | [`Vec<AppFact>`](#appfact-record) | | The Keyvault's protection facts (Touch ID, the daemon's signature), shown in the section. |
| `auto_connect` / `autoConnect` | `Option<bool>` | | "Connect to the desktop automatically" (none: no row; a shell without the preview cover leaves it out). |
## `AppSettingsOption` record
diff --git a/docs/content/docs/cua-sdk/reference/spaces/teleport-apps.mdx b/docs/content/docs/cua-sdk/reference/spaces/teleport-apps.mdx
index 5c58782638..d68a7d89b9 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/teleport-apps.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/teleport-apps.mdx
@@ -175,6 +175,10 @@ The user's answer to the consent screen.
| `acknowledge_sensitive` / `acknowledgeSensitive` | `bool` | `false` | Saw and accepted the secrets. |
| `save_to_keyvault` / `saveToKeyvault` | `bool` | `false` | "Save to Keyvault": keep the captured session sealed in the user's own Cua Keyvault after this delivery. |
| `acknowledge_relay_plaintext` / `acknowledgeRelayPlaintext` | `bool` | `false` | Saw and accepted `TeleportPlan.relay_unsealed`'s warning (S1). |
+| `cookie_domains` / `cookieDomains` | `Option<Vec<String>>` | `None` | The review's per-site choice: the sites whose cookies to send (`None`: every cookie in the selection). |
+| `exclude` | `Vec<String>` | `[]` | Consent items (their keys) the user turned off. |
+| `from_vault` / `fromVault` | `Option<Vec<String>>` | `None` | Send these saved Keyvault items (ids) instead of reading the live app: nothing is captured from the host. |
+| `include_passwords` / `includePasswords` | `bool` | `false` | Also send the saved passwords: only when ticked in the review. |
## `TeleportConsentItem` record
diff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdx
index b7dbc7e77d..97c5fd321c 100644
--- a/docs/content/docs/cua-sdk/reference/types.mdx
+++ b/docs/content/docs/cua-sdk/reference/types.mdx
@@ -50,7 +50,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f
291 items. Methods are listed on their object.
-The 685 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift only) are listed on their pages: [Decoded media](/cua-sdk/reference/spaces/decoded-media), [Host teleport](/cua-sdk/reference/spaces/teleport-host), [Teleport an app](/cua-sdk/reference/spaces/teleport-apps), [Spaces app core](/cua-sdk/reference/spaces/app-core#all-items), [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core#all-items), [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core#all-items).
+The 712 items of the Cua Spaces app export (source-available, FSL-1.1-MIT, Swift only) are listed on their pages: [Decoded media](/cua-sdk/reference/spaces/decoded-media), [Host teleport](/cua-sdk/reference/spaces/teleport-host), [Teleport an app](/cua-sdk/reference/spaces/teleport-apps), [Spaces app core](/cua-sdk/reference/spaces/app-core#all-items), [App core: Cua Volume storage, mount and sync](/cua-sdk/reference/spaces/volume-app-core#all-items), [App core: agents, drive, notifications](/cua-sdk/reference/spaces/agents-app-core#all-items).
| Item | Kind | Summary |
| --- | --- | --- |
diff --git a/docs/content/docs/spaces/guides/keyvault.mdx b/docs/content/docs/spaces/guides/keyvault.mdx
index 6a3b0c9197..ec69b76a38 100644
--- a/docs/content/docs/spaces/guides/keyvault.mdx
+++ b/docs/content/docs/spaces/guides/keyvault.mdx
@@ -1,13 +1,17 @@
---
title: Keyvault
-description: 'The Cua Keyvault holds the sessions teleport moves and the passwords agents sign in with, per site and per account. Every use asks you first. Review items, approve requests, revoke access and turn it off from the Keyvault page.'
+description: 'The Cua Keyvault is a password manager for what teleport moves: cookies, localStorage values, passwords and files, grouped by the app they came from. Every item is locked until you allow unattended access. Search, select several, lock, unlock or delete them, approve requests and turn it off from the Keyvault page.'
---
import { Callout } from 'fumadocs-ui/components/callout';
-The Keyvault is where Cua keeps the signed-in sessions that teleport moves into
-Spaces, and the saved passwords agents sign in with. It lives in the Cua daemon, encrypted on disk. Apps and agents never
-read it: they ask, you approve, and the daemon delivers into the Space.
+The Keyvault is where Cua keeps what teleport moves into Spaces and the saved
+passwords agents sign in with. It works like a password manager, grouped by the
+app each secret came from (Chrome, Slack, Arc). Inside an app, every secret is
+its own item: a cookie, a localStorage value, a password, or a file for
+everything else (bookmarks, session files, app state). It lives in the Cua
+daemon, encrypted on disk. Apps and agents never read it: they ask, you
+approve, and the daemon delivers into the Space.
Open **Keyvault** in the Cua Spaces sidebar.
@@ -16,10 +20,10 @@ Open **Keyvault** in the Cua Spaces sidebar.
| Section | What it shows |
|---------|---------------|
| Waiting for approval | Requests from apps and agents: the verified caller, what moves, where and for how long. **Approve** asks for Touch ID or your password. |
-| Items | Saved sessions per site and per account. **Unattended** lets unattended rules use an item; it is off for every item until you turn it on. Identity providers always ask. |
+| All Items | Items grouped by app, then by site, with the files of an app together. Each item shows its type, its key, its domain and when it was last saved in grey, and a **lock**. Select items, a site or a whole app to lock, unlock or delete them together. Search matches a domain, a key, an app or a type. Names stay hidden until you confirm with Touch ID (**Show Items**). |
| Live access | Grants, unattended rules and copies delivered to Spaces, with **Revoke**, **Remove** and **Wipe**. |
| Recent | Decisions from the audit log, and whether its hash chain verifies. |
-| Protection | Who confirms (the Cua daemon, with Touch ID), how the vault unlocks, and whether this app and the daemon are verified as Cua. |
+| Settings, Keyvault | Who confirms (the Cua daemon, with Touch ID), how the vault unlocks, whether this app and the daemon are verified as Cua, the prompt you can turn back on after **Never ask again**, and whether site icons may load from Google. |
## Every use asks
@@ -29,14 +33,61 @@ By default, every use of a saved session or password asks you first:
is used until you approve it with Touch ID or your password.
- One approval covers one use. Teleporting again, or signing in again, asks
again unless you widen the approval.
-- No item is **Unattended** until you turn it on, and no unattended rule
- exists until you write one. Both ask for Touch ID.
+- Every item is **locked** until you unlock it, and no unattended rule exists
+ until you write one. Unlocking asks for Touch ID.
- The Cua app and CLI themselves also ask for Touch ID before each teleport
or sign-in.
+## Items, keys and saving again
+
+An item is keyed within its app: a file by its path, a cookie by its host,
+name and path, a localStorage value by its origin and key, a password by its
+origin and username. Saving the same app again (teleporting Chrome twice with
+**Save to Keyvault**) updates the items it already holds by that key and never
+duplicates them. A saved item keeps its lock and its place; only its value and
+its last-saved time change. A big file is kept as an encrypted blob rather than
+inside the item.
+
+## Icons
+
+Apps show their own icon, looked up once per app version and kept in a cache. A
+site shows the icon your browser already had for it: Cua reads it from the
+browser's local favicon store when it saves the site's items (the file is
+copied first, so the browser is never touched) and keeps it in the vault as
+non-secret metadata, visible only while the list is open. When the browser had
+none, Cua can ask Google's favicon service for it, sending only the site's
+registrable domain (never a path, an item or a name), a few at a time as rows
+appear. Answers, including "none", are cached on disk so a domain is asked at
+most once a week. Turn this off with **Load site icons from Google** in
+Settings, Keyvault; the globe stands in for any site without a local icon.
+
+## Locks
+
+A **locked** item needs your approval for every use. Clicking the lock
+**unlocks** it, which allows unattended access: any agent with access to the
+Cua Spaces MCP can have that key written into your connected Spaces without
+asking each time. The secrets are not sent to the agent; they are delivered
+into the Space. Before Touch ID, a prompt explains this with **Deny**,
+**Allow** and **Never ask again**. **Never ask again** skips the explanation
+from then on (Touch ID is still asked) and can be turned back on in Settings,
+Keyvault.
+
+Select several items, a site or a whole app and unlock them with one prompt and
+one Touch ID. Locking an item again, or deleting it, ends the access it gave.
+Deleting items also wipes any copy delivered to a Space. Identity providers
+(Google, Microsoft, Apple, Okta) always ask and cannot be unlocked.
+
+## Choosing what to send
+
+The teleport review is the same list. For a browser you choose which sites to
+send, with counts per site, instead of the whole profile; it starts from what
+you sent last time to that Space, or from the sites that look like they keep a
+sign-in. When the app has saved items, the review can send those instead of
+reading the app again, so macOS does not ask for Keychain access.
+
## Saved passwords
-Import your browser's saved passwords, one item per site:
+Import your browser's saved passwords, one item per login:
```bash test="cli-shape" id="kv-import-passwords"
cua keyvault import-passwords --browser chrome
@@ -47,11 +98,40 @@ An agent uses one only through [site login](/spaces/guides/site-login): you
approve the sign-in, and the Keyvault types it into the page on the saved
login's own origin. Chrome on macOS and Linux is supported.
+Passwords go into a Space's browser only when you tick **Also send saved
+passwords** in the teleport review (it is off unless you do, and never
+remembered). Each one is re-encrypted for the browser in the Space with that
+browser's own key and written beside the logins it already has, so the browser
+must have been opened once there. An agent can never have a password delivered,
+only used through site login.
+
+## What is an item and what stays a file
+
+For Chrome and the other Chromium browsers each of these is its own item:
+
+- every cookie, with every attribute the browser keeps (creation and update
+ times, priority, source scheme and port, same-site, a partitioned cookie's
+ top-level site). A partitioned cookie stays partitioned and is a different
+ item from the same name without a partition;
+- every localStorage value, read from the browser's own store and written back
+ into the Space's while its browser is not running;
+- saved passwords, as above.
+
+On Windows, Chrome's app-bound encryption keeps a cookie or password readable
+only by Chrome itself. Those are listed in the review, greyed, with that reason,
+and are never sent; the rest of the site still is.
+
+Everything else is saved as a file, by its path: preferences, bookmarks, the
+open tabs and session state, session storage, extensions and, for Electron
+apps such as Slack, their own cookie and localStorage files. A cookie or value
+that cannot be read as an item is not silently dropped: it stays a file or is
+listed as unavailable.
+
## Saved sessions (cookies)
-The Keyvault can also hold a site's cookies, decrypted from Chrome's Safe
-Storage-encrypted store and kept sealed like any other item, per site rather
-than the whole profile. Unlike a saved password, a delivered session's
+The Keyvault holds a browser's cookies one item each, decrypted from Chrome's
+Safe Storage-encrypted store and kept sealed like any other item. Unlike a
+saved password, a delivered session's
cookies are meant to be used: when an agent's grant or unattended rule
delivers one into a Space, the Space's own Chrome gets its own freshly
created (or existing) Safe Storage key, and the cookies are re-encrypted
diff --git a/docs/content/docs/spaces/guides/teleport-an-app.mdx b/docs/content/docs/spaces/guides/teleport-an-app.mdx
index fd4178156a..79c797cf29 100644
--- a/docs/content/docs/spaces/guides/teleport-an-app.mdx
+++ b/docs/content/docs/spaces/guides/teleport-an-app.mdx
@@ -50,6 +50,22 @@ login](/spaces/guides/site-login), without ever exposing the password to an
agent. **Keep me signed in** (cookies) does not have this limitation.
</Callout>
+### Choosing sites and sending from the Keyvault
+
+In Cua Spaces, **Keep me signed in** lists the browser's sites with counts
+(for example `github.com, 12 cookies, 3 storage values`) so you send the
+sites you mean to, not the whole profile. It starts from what you sent to that
+Space last time, or from the sites that look like they keep a sign-in; an
+identity provider (Google, Microsoft, Apple, Okta) is never picked for you.
+Other lines of the consent screen can be turned off one by one. Cookies are
+read once to build the list's counts from the plaintext columns of Chrome's
+store; nothing is decrypted until you teleport.
+
+If the Keyvault already holds items for the app (from **Save to Keyvault**),
+the review can **send from the Keyvault** instead: you pick from the saved
+items, nothing is read from this Mac, and macOS does not ask for Keychain
+access. See [Keyvault](/spaces/guides/keyvault).
+
## In Cua Spaces
- **Teleport an app…** in a Space's window or viewer opens the picker: search,
diff --git a/libs/cua-spacesd/Cargo.lock b/libs/cua-spacesd/Cargo.lock
index e7199951d9..80af5188c3 100644
--- a/libs/cua-spacesd/Cargo.lock
+++ b/libs/cua-spacesd/Cargo.lock
@@ -1200,6 +1200,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crc32c"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
+dependencies = [
+ "rustc_version",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.1"
@@ -1294,6 +1303,18 @@ dependencies = [
"cmov",
]
+[[package]]
+name = "cua-chromium-storage"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "cua-teleport-bundle",
+ "rusty-leveldb",
+ "tempfile",
+ "thiserror 2.0.20",
+ "tracing",
+]
+
[[package]]
name = "cua-driver-contract"
version = "0.32.0"
@@ -1753,6 +1774,7 @@ dependencies = [
name = "cua-spacesd-teleport"
version = "0.1.4"
dependencies = [
+ "cua-chromium-storage",
"cua-teleport-bundle",
"hex",
"ignore",
@@ -2050,6 +2072,17 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+[[package]]
+name = "errno"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1"
+dependencies = [
+ "errno-dragonfly",
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -2060,6 +2093,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "errno-dragonfly"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
+dependencies = [
+ "cc",
+ "libc",
+]
+
[[package]]
name = "error-code"
version = "3.4.0"
@@ -3012,6 +3055,12 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "integer-encoding"
+version = "3.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -5010,7 +5059,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags 2.13.1",
- "errno",
+ "errno 0.3.14",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
@@ -5058,6 +5107,21 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+[[package]]
+name = "rusty-leveldb"
+version = "4.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43ddda8f34100fca4bf1b0bbf743d12d27b5d84c35c74a52f392aac26f54e82d"
+dependencies = [
+ "bytes",
+ "crc32c",
+ "errno 0.2.8",
+ "fs2",
+ "integer-encoding",
+ "rand 0.8.8",
+ "snap",
+]
+
[[package]]
name = "ryu"
version = "1.0.23"
@@ -5408,7 +5472,7 @@ version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
- "errno",
+ "errno 0.3.14",
"libc",
]
@@ -5454,6 +5518,12 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100"
+[[package]]
+name = "snap"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886"
+
[[package]]
name = "socket2"
version = "0.6.5"
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/Cargo.toml b/libs/cua-spacesd/crates/cua-spacesd-teleport/Cargo.toml
index bca6bb95c9..057ec03a0e 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/Cargo.toml
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/Cargo.toml
@@ -12,6 +12,9 @@ publish = false
# The effect-free contract shared with the sender (cua-teleport in the cua
# SDK). The driver never depends on the sender.
cua-teleport-bundle = { path = "../../../cua/crates/cua-teleport-bundle" }
+# Writing the destination browser's localStorage (a LevelDB) back, while it is
+# not running (`importers/chrome.rs`).
+cua-chromium-storage = { path = "../../../cua/crates/cua-chromium-storage" }
hex.workspace = true
ignore = "0.4"
serde.workspace = true
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
index c255d01ff1..f892a46828 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
@@ -131,13 +131,24 @@ const KNOWN_COLUMNS: &[&str] = &[
"creation_utc",
"has_expires",
"is_persistent",
+ // The rest of Chrome's current schema: written from the source's row when
+ // it had them, else at Chrome's own defaults, so the destination's row
+ // is the source's row (a partitioned cookie stays partitioned).
+ "last_access_utc",
+ "last_update_utc",
+ "priority",
+ "source_scheme",
+ "source_port",
+ "source_type",
+ "has_cross_site_ancestor",
+ "top_frame_site_key",
];
/// Microseconds since the Windows/Chrome epoch (1601-01-01 UTC) for the
/// current time -- the unit every Chrome `*_utc` cookie column uses,
/// including `creation_utc`, which is `NOT NULL` with no default in Chrome's
/// real schema and therefore always needs an explicit value.
-fn chrome_now_utc() -> i64 {
+pub(crate) fn chrome_now_utc() -> i64 {
const UNIX_TO_CHROME_EPOCH_MICROS: i64 = 11_644_473_600_000_000;
let unix_micros = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -280,10 +291,17 @@ fn install_into_db(
// Chrome's own invariant: a persistent cookie has an expiry,
// a session cookie (`expires_utc == 0`) does not.
"has_expires" | "is_persistent" => ((item.expires_utc != 0) as i64).into(),
- // Chrome stamps this at insert time; this import IS the
- // creation event on this machine, so "now" is correct, not a
- // placeholder.
- "creation_utc" => now.into(),
+ // The source's creation time when it had one; else this
+ // import is the creation event on this machine.
+ "creation_utc" => item.extra.creation_utc.unwrap_or(now).into(),
+ "last_access_utc" => item.extra.last_access_utc.unwrap_or(0).into(),
+ "last_update_utc" => item.extra.last_update_utc.unwrap_or(now).into(),
+ "priority" => item.extra.priority.unwrap_or(1).into(),
+ "source_scheme" => item.extra.source_scheme.unwrap_or(0).into(),
+ "source_port" => item.extra.source_port.unwrap_or(-1).into(),
+ "source_type" => item.extra.source_type.unwrap_or(0).into(),
+ "has_cross_site_ancestor" => item.extra.has_cross_site_ancestor.unwrap_or(0).into(),
+ "top_frame_site_key" => item.extra.partition_key.clone().unwrap_or_default().into(),
other => unreachable!("column {other} was filtered out of KNOWN_COLUMNS above"),
});
}
@@ -468,6 +486,7 @@ mod tests {
is_secure: true,
is_httponly: true,
samesite: 1,
+ extra: Default::default(),
}
}
@@ -685,6 +704,93 @@ mod tests {
assert!(host.calls().is_empty());
}
+ /// Every attribute the source row had lands in the destination row, and a
+ /// partitioned cookie stays partitioned next to the same name unpartitioned.
+ #[test]
+ fn every_attribute_is_written_and_a_partitioned_cookie_stays_partitioned() {
+ use cua_teleport_bundle::cookies::CookieExtra;
+ let dir = tempfile::tempdir().unwrap();
+ let profile = dir.path().join("Default");
+ let host = Arc::new(FakeHost::new());
+ let mut record = ImportRecord::default();
+ let mut full = item(".example.com", "__Host-sid", "partitioned-value");
+ full.expires_utc = 13_400_000_000_000_000;
+ full.extra = CookieExtra {
+ creation_utc: Some(13_300_000_000_000_001),
+ last_access_utc: Some(13_300_000_000_000_002),
+ last_update_utc: Some(13_300_000_000_000_003),
+ priority: Some(2),
+ source_scheme: Some(2),
+ source_port: Some(443),
+ source_type: Some(1),
+ has_cross_site_ancestor: Some(1),
+ partition_key: Some("https://top.example".into()),
+ };
+ let plain = item(".example.com", "__Host-sid", "plain-value");
+ install_cookies(
+ host.as_ref(),
+ &profile,
+ "Chrome Safe Storage",
+ Platform::Linux,
+ &[full, plain],
+ &mut record,
+ )
+ .unwrap();
+ let conn = rusqlite::Connection::open(profile.join("Network/Cookies")).unwrap();
+ let rows: i64 = conn
+ .query_row("SELECT count(*) FROM cookies", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(rows, 2, "partitioned and unpartitioned are two cookies");
+ #[allow(clippy::type_complexity)]
+ let got: (i64, i64, i64, i64, i64, i64, i64, i64, i64, String) = conn
+ .query_row(
+ "SELECT creation_utc, last_access_utc, last_update_utc, priority, source_scheme, \
+ source_port, source_type, has_cross_site_ancestor, expires_utc, top_frame_site_key \
+ FROM cookies WHERE top_frame_site_key != ''",
+ [],
+ |r| {
+ Ok((
+ r.get(0)?,
+ r.get(1)?,
+ r.get(2)?,
+ r.get(3)?,
+ r.get(4)?,
+ r.get(5)?,
+ r.get(6)?,
+ r.get(7)?,
+ r.get(8)?,
+ r.get(9)?,
+ ))
+ },
+ )
+ .unwrap();
+ assert_eq!(
+ got,
+ (
+ 13_300_000_000_000_001,
+ 13_300_000_000_000_002,
+ 13_300_000_000_000_003,
+ 2,
+ 2,
+ 443,
+ 1,
+ 1,
+ 13_400_000_000_000_000,
+ "https://top.example".to_string()
+ )
+ );
+ // The unpartitioned one got Chrome's defaults, with no partition.
+ let (prio, scheme, port, key): (i64, i64, i64, String) = conn
+ .query_row(
+ "SELECT priority, source_scheme, source_port, top_frame_site_key FROM cookies \
+ WHERE top_frame_site_key = ''",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
+ )
+ .unwrap();
+ assert_eq!((prio, scheme, port, key.as_str()), (1, 0, -1, ""));
+ }
+
#[test]
fn never_launched_profile_creates_the_keychain_key_on_macos() {
let dir = tempfile::tempdir().unwrap();
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs
index 1f98f71503..b667e28c5c 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs
@@ -16,6 +16,8 @@ use cua_teleport_bundle::cookies::COOKIES_ENTRY;
use cua_teleport_bundle::layout::chrome::{
launch_program_for, remap_to_platform, user_data_dir_for, DISPLAY, ID, TABS_JSON,
};
+use cua_teleport_bundle::local_storage::LOCAL_STORAGE_ENTRY;
+use cua_teleport_bundle::logins::LOGINS_ENTRY;
use cua_teleport_bundle::{LaunchSpec, Platform, WindowRestore};
use super::write_entry;
@@ -76,6 +78,8 @@ impl ImportProvider for ChromeImporter {
let mut reader = BundleReader::open_with_limit(bundle, self.max_total_bytes)?;
let mut tab_urls: Vec<String> = Vec::new();
let mut cookies_entry: Option<Vec<u8>> = None;
+ let mut local_storage_entry: Option<Vec<u8>> = None;
+ let mut logins_entry: Option<Vec<u8>> = None;
while let Some(entry) = reader.next_entry()? {
if entry.rel_path == TABS_JSON {
@@ -91,6 +95,19 @@ impl ImportProvider for ChromeImporter {
cookies_entry = Some(entry.bytes);
continue;
}
+ // localStorage values: written into the destination's own
+ // `Local Storage` LevelDB below (a raw copy of the sender's
+ // LevelDB files would replace whatever the destination has).
+ // Saved passwords the user ticked: re-encrypted under this
+ // destination's own key below, like the cookies.
+ if entry.rel_path == LOGINS_ENTRY {
+ logins_entry = Some(entry.bytes);
+ continue;
+ }
+ if entry.rel_path == LOCAL_STORAGE_ENTRY {
+ local_storage_entry = Some(entry.bytes);
+ continue;
+ }
let dest = dest_home.join(remap_to_platform(&entry.rel_path, platform));
write_entry(&dest, &entry, false, record)?;
}
@@ -117,6 +134,47 @@ impl ImportProvider for ChromeImporter {
)?;
}
}
+ if let Some(bytes) = logins_entry {
+ let items = cua_teleport_bundle::logins::parse(&bytes);
+ if !items.is_empty() {
+ let service = chromium_crypto::macos_safe_storage_service(ID)
+ .unwrap_or("Chrome Safe Storage");
+ crate::logins::install_logins(
+ &*self.host,
+ &user_data_dir.join("Default"),
+ service,
+ platform,
+ &items,
+ record,
+ )?;
+ }
+ }
+ if let Some(bytes) = local_storage_entry {
+ let items = cua_teleport_bundle::local_storage::parse(&bytes);
+ if !items.is_empty() {
+ // Same single-profile scope as the cookies above. The
+ // destination Chrome is not running yet (this import
+ // launches it afterwards), so LevelDB's lock is free.
+ let store = cua_chromium_storage::store_dir(&user_data_dir.join("Default"));
+ let existed = store.is_dir();
+ if !existed {
+ record.create_dir_all(&store)?;
+ }
+ let written =
+ cua_chromium_storage::write(&store, &items, crate::cookies::chrome_now_utc())
+ .map_err(|e| crate::TeleportError::Provider(e.to_string()))?;
+ record.local_storage_written(&store, &written);
+ // The database files themselves are new when it did not
+ // exist: ledger them so a wipe removes them with the keys.
+ if !existed {
+ if let Ok(entries) = std::fs::read_dir(&store) {
+ for e in entries.flatten() {
+ record.file_written(&e.path());
+ }
+ }
+ }
+ }
+ }
// Suppress the first-run/onboarding flow: on a freshly-imported profile it
// starts its own new-tab session and discards the transferred session that
// `--restore-last-session` would otherwise reopen.
@@ -322,6 +380,7 @@ mod tests {
is_secure: true,
is_httponly: true,
samesite: 1,
+ extra: Default::default(),
}]);
let bundle_bytes = bundle(
"chrome",
@@ -356,4 +415,121 @@ mod tests {
.1;
assert_eq!(&*plain, b"gh-session-value");
}
+
+ /// localStorage from the Keyvault lands in the destination's own
+ /// `Local Storage` LevelDB, beside what that browser already held, and a
+ /// wipe takes out exactly the keys the import wrote.
+ #[test]
+ fn local_storage_is_written_into_the_destinations_leveldb_and_wiped_by_key() {
+ use cua_teleport_bundle::local_storage::{serialize, LocalStorageItem};
+ let dest = tempfile::tempdir().unwrap();
+ let store = dest
+ .path()
+ .join("Library/Application Support/Google/Chrome/Default/Local Storage/leveldb");
+ // The destination already has a value of its own.
+ let own = LocalStorageItem {
+ origin: "https://mine.example".into(),
+ key: "keep".into(),
+ value: "me".into(),
+ key_raw: None,
+ value_raw: None,
+ };
+ cua_chromium_storage::write(&store, &[own], 1).unwrap();
+ let item = |origin: &str, key: &str, value: &str| LocalStorageItem {
+ origin: origin.into(),
+ key: key.into(),
+ value: value.into(),
+ key_raw: None,
+ value_raw: None,
+ };
+ let json = serialize(&[
+ item("https://github.com", "color_mode", "dark"),
+ item("https://github.com", "名前", "値"),
+ ]);
+ let bundle_bytes = bundle(
+ "chrome",
+ &[
+ ("tabs.json", 0o644, b"[]"),
+ (LOCAL_STORAGE_ENTRY, 0o600, &json),
+ ],
+ );
+ let mut record = ImportRecord::default();
+ ChromeImporter::new()
+ .import_recorded(
+ &mut Cursor::new(bundle_bytes),
+ dest.path(),
+ Platform::MacOS,
+ &mut record,
+ )
+ .unwrap();
+ // Not written as a file, and the sender's names are the destination's.
+ assert!(!dest.path().join(LOCAL_STORAGE_ENTRY).exists());
+ let mut got = cua_chromium_storage::read(&store).unwrap();
+ got.sort_by(|a, b| (&a.origin, &a.key).cmp(&(&b.origin, &b.key)));
+ let names: Vec<(&str, &str, &str)> = got
+ .iter()
+ .map(|i| (i.origin.as_str(), i.key.as_str(), i.value.as_str()))
+ .collect();
+ assert_eq!(
+ names,
+ [
+ ("https://github.com", "color_mode", "dark"),
+ ("https://github.com", "名前", "値"),
+ ("https://mine.example", "keep", "me"),
+ ]
+ );
+ // Wipe removes the import's keys and leaves the browser's own.
+ let ledger = crate::ledger::Ledger::new("i1", "chrome", &record, 0, 1);
+ let report = crate::ledger::wipe(&ledger, dest.path(), &crate::host::FakeHost::new());
+ assert!(report.complete(), "{:?}", report.errors);
+ assert_eq!(
+ report.local_storage_keys_removed, 3,
+ "two values and the new origin META"
+ );
+ let left = cua_chromium_storage::read(&store).unwrap();
+ assert_eq!(left.len(), 1);
+ assert_eq!(left[0].origin, "https://mine.example");
+ // A second wipe finds nothing to remove.
+ let again = crate::ledger::wipe(&ledger, dest.path(), &crate::host::FakeHost::new());
+ assert_eq!(again.local_storage_keys_removed, 0);
+ }
+
+ /// A fresh destination (Chrome never launched) gets a new store, and a
+ /// wipe removes the files the import created with it.
+ #[test]
+ fn local_storage_creates_the_store_for_a_never_launched_browser() {
+ use cua_teleport_bundle::local_storage::{serialize, LocalStorageItem};
+ let dest = tempfile::tempdir().unwrap();
+ let json = serialize(&[LocalStorageItem {
+ origin: "https://github.com".into(),
+ key: "k".into(),
+ value: "v".into(),
+ key_raw: None,
+ value_raw: None,
+ }]);
+ let bundle_bytes = bundle(
+ "chrome",
+ &[
+ ("tabs.json", 0o644, b"[]"),
+ (LOCAL_STORAGE_ENTRY, 0o600, &json),
+ ],
+ );
+ let mut record = ImportRecord::default();
+ ChromeImporter::new()
+ .import_recorded(
+ &mut Cursor::new(bundle_bytes),
+ dest.path(),
+ Platform::Linux,
+ &mut record,
+ )
+ .unwrap();
+ let store = dest
+ .path()
+ .join(".config/google-chrome/Default/Local Storage/leveldb");
+ assert_eq!(cua_chromium_storage::read(&store).unwrap().len(), 1);
+ let ledger = crate::ledger::Ledger::new("i2", "chrome", &record, 0, 1);
+ let report = crate::ledger::wipe(&ledger, dest.path(), &crate::host::FakeHost::new());
+ assert!(report.complete(), "{:?}", report.errors);
+ assert!(!store.exists(), "the store the import created is gone");
+ }
}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs
index 47bbfc0e4d..81cc364bbe 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs
@@ -59,6 +59,32 @@ pub struct CookieRowRef {
pub path: String,
}
+/// One saved login an import wrote into an existing `Login Data` database,
+/// identified by what Chromium matches a login on, so `wipe` deletes exactly
+/// this row and nothing the browser already held.
+#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct LoginRowRef {
+ /// Absolute path of the `Login Data` database.
+ pub db: PathBuf,
+ /// `logins.origin_url`.
+ pub origin_url: String,
+ /// `logins.username_value`.
+ pub username_value: String,
+ /// `logins.signon_realm`.
+ pub signon_realm: String,
+}
+
+/// The localStorage keys an import wrote into a Chromium `Local Storage`
+/// LevelDB, so `wipe` can delete exactly those (hex, as LevelDB keys are
+/// arbitrary bytes) and leave the browser's own values alone.
+#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct StorageKeysRef {
+ /// Absolute path of the `Local Storage/leveldb` directory.
+ pub db: PathBuf,
+ /// Data keys and created `META:` keys, hex.
+ pub keys: Vec<String>,
+}
+
/// What one import wrote, as reported by the importer while it wrote it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ImportRecord {
@@ -73,6 +99,10 @@ pub struct ImportRecord {
/// have already called [`Self::file_written`] for it, so this is only
/// the merge case, into a database the import did not create).
pub cookie_rows: Vec<CookieRowRef>,
+ /// localStorage keys written into a `Local Storage` LevelDB.
+ pub local_storage: Vec<StorageKeysRef>,
+ /// Saved logins written into an existing `Login Data` database.
+ pub login_rows: Vec<LoginRowRef>,
/// Things the user should be told about that did not fail the import
/// (e.g. the app will ask once for a password). Reported back to the
/// client, never ledgered.
@@ -133,6 +163,51 @@ impl ImportRecord {
}
}
+ /// Records a saved login written into an existing `Login Data` database.
+ pub fn login_row_written(
+ &mut self,
+ db: &Path,
+ origin_url: &str,
+ username_value: &str,
+ signon_realm: &str,
+ ) {
+ let row = LoginRowRef {
+ db: db.to_path_buf(),
+ origin_url: origin_url.to_owned(),
+ username_value: username_value.to_owned(),
+ signon_realm: signon_realm.to_owned(),
+ };
+ if !self.login_rows.contains(&row) {
+ self.login_rows.push(row);
+ }
+ }
+
+ /// Records localStorage keys written into the LevelDB at `db`.
+ pub fn local_storage_written(&mut self, db: &Path, written: &cua_chromium_storage::Written) {
+ let keys: Vec<String> = written
+ .keys
+ .iter()
+ .chain(&written.meta_keys)
+ .map(hex::encode)
+ .collect();
+ if keys.is_empty() {
+ return;
+ }
+ match self.local_storage.iter_mut().find(|r| r.db == db) {
+ Some(r) => {
+ for k in keys {
+ if !r.keys.contains(&k) {
+ r.keys.push(k);
+ }
+ }
+ }
+ None => self.local_storage.push(StorageKeysRef {
+ db: db.to_path_buf(),
+ keys,
+ }),
+ }
+ }
+
/// Adds everything in `other` that is not already here.
pub fn merge(&mut self, other: &ImportRecord) {
for f in &other.files {
@@ -143,6 +218,23 @@ impl ImportRecord {
self.cookie_rows.push(r.clone());
}
}
+ for r in &other.login_rows {
+ if !self.login_rows.contains(r) {
+ self.login_rows.push(r.clone());
+ }
+ }
+ for r in &other.local_storage {
+ for k in &r.keys {
+ match self.local_storage.iter_mut().find(|x| x.db == r.db) {
+ Some(x) if !x.keys.contains(k) => x.keys.push(k.clone()),
+ Some(_) => {}
+ None => self.local_storage.push(StorageKeysRef {
+ db: r.db.clone(),
+ keys: vec![k.clone()],
+ }),
+ }
+ }
+ }
for d in &other.created_dirs {
if !self.created_dirs.contains(d) {
self.created_dirs.push(d.clone());
@@ -159,6 +251,8 @@ impl ImportRecord {
&& self.created_dirs.is_empty()
&& self.keychain_items.is_empty()
&& self.cookie_rows.is_empty()
+ && self.local_storage.is_empty()
+ && self.login_rows.is_empty()
}
}
@@ -182,6 +276,12 @@ pub struct Ledger {
/// predates row-level cookie tracking, not a ledger that lost rows).
#[serde(default)]
pub cookie_rows: Vec<CookieRowRef>,
+ /// localStorage keys written into a `Local Storage` LevelDB.
+ #[serde(default)]
+ pub local_storage: Vec<StorageKeysRef>,
+ /// Saved logins written into an existing `Login Data` database.
+ #[serde(default)]
+ pub login_rows: Vec<LoginRowRef>,
/// Unix ms after which the import is wiped; 0 = never.
pub expires_at_ms: u64,
/// Unix ms of the import.
@@ -205,6 +305,8 @@ impl Ledger {
directories: record.created_dirs.clone(),
keychain_items: record.keychain_items.clone(),
cookie_rows: record.cookie_rows.clone(),
+ local_storage: record.local_storage.clone(),
+ login_rows: record.login_rows.clone(),
expires_at_ms,
imported_at_ms,
}
@@ -217,6 +319,8 @@ impl Ledger {
created_dirs: self.directories.clone(),
keychain_items: self.keychain_items.clone(),
cookie_rows: self.cookie_rows.clone(),
+ local_storage: self.local_storage.clone(),
+ login_rows: self.login_rows.clone(),
notices: Vec::new(),
}
}
@@ -406,6 +510,11 @@ pub struct WipeReport {
/// database itself is never in `removed_paths`: it was not this
/// import's file to remove).
pub cookie_rows_removed: u32,
+ /// localStorage keys deleted from a `Local Storage` LevelDB (the
+ /// database itself is never removed).
+ pub local_storage_keys_removed: u32,
+ /// Saved logins deleted from an existing `Login Data` database.
+ pub login_rows_removed: u32,
/// Ledgered paths refused (outside the home, `..`, symlinks), with why.
/// Never retried: a refused entry is not trusted.
pub refused: Vec<(PathBuf, String)>,
@@ -483,6 +592,16 @@ fn delete_cookie_row(db: &Path, host_key: &str, name: &str, path: &str) -> rusql
)
}
+/// Deletes exactly one saved login from a `Login Data` database. A row that
+/// is not there is not an error.
+fn delete_login_row(row: &LoginRowRef) -> rusqlite::Result<usize> {
+ let conn = rusqlite::Connection::open(&row.db)?;
+ conn.execute(
+ "DELETE FROM logins WHERE origin_url = ?1 AND username_value = ?2 AND signon_realm = ?3",
+ rusqlite::params![row.origin_url, row.username_value, row.signon_realm],
+ )
+}
+
/// Undoes `ledger` under `dest_home`: removes its files, the directories it
/// created (see below), its Keychain items and its cookie rows (through
/// `host` for the Keychain; everything else directly).
@@ -552,6 +671,58 @@ pub fn wipe(ledger: &Ledger, dest_home: &Path, host: &dyn HostEffects) -> WipeRe
Err(why) => report.refused.push((row.db.clone(), why)),
}
}
+ for row in &ledger.login_rows {
+ let rel = match confine(&row.db, dest_home) {
+ Ok(rel) => rel,
+ Err(why) => {
+ report.refused.push((row.db.clone(), why));
+ continue;
+ }
+ };
+ match probe(dest_home, &rel) {
+ Ok(Probe::Missing) => {}
+ Ok(Probe::Present(meta)) if meta.is_dir() => report.refused.push((
+ row.db.clone(),
+ "ledgered as a Login Data database but is a directory".into(),
+ )),
+ Ok(Probe::Present(_)) => match delete_login_row(row) {
+ Ok(n) => report.login_rows_removed += n as u32,
+ Err(e) => {
+ report.errors.push(format!("{}: {e}", row.db.display()));
+ report.failed.login_rows.push(row.clone());
+ }
+ },
+ Err(why) => report.refused.push((row.db.clone(), why)),
+ }
+ }
+ for r in &ledger.local_storage {
+ let rel = match confine(&r.db, dest_home) {
+ Ok(rel) => rel,
+ Err(why) => {
+ report.refused.push((r.db.clone(), why));
+ continue;
+ }
+ };
+ match probe(dest_home, &rel) {
+ Ok(Probe::Missing) => {}
+ Ok(Probe::Present(meta)) if !meta.is_dir() => report.refused.push((
+ r.db.clone(),
+ "ledgered as a LevelDB directory but is a file".into(),
+ )),
+ Ok(Probe::Present(_)) => {
+ let keys: Vec<Vec<u8>> =
+ r.keys.iter().filter_map(|k| hex::decode(k).ok()).collect();
+ match cua_chromium_storage::delete(&r.db, &keys) {
+ Ok(n) => report.local_storage_keys_removed += n as u32,
+ Err(e) => {
+ report.errors.push(format!("{}: {e}", r.db.display()));
+ report.failed.local_storage.push(r.clone());
+ }
+ }
+ }
+ Err(why) => report.refused.push((r.db.clone(), why)),
+ }
+ }
let mut dirs: Vec<(PathBuf, PathBuf)> = Vec::new();
for path in &ledger.directories {
match confine(path, dest_home) {
@@ -749,6 +920,8 @@ mod tests {
directories: dirs.to_vec(),
keychain_items: vec![],
cookie_rows: vec![],
+ local_storage: vec![],
+ login_rows: vec![],
expires_at_ms: expires,
imported_at_ms: 1,
}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/lib.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/lib.rs
index de36a550df..f36ac98011 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/lib.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/lib.rs
@@ -30,6 +30,7 @@ pub mod host;
pub mod importers;
pub mod keychain;
pub mod ledger;
+pub mod logins;
mod receiver;
pub use cua_teleport_bundle::{
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/logins.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/logins.rs
new file mode 100644
index 0000000000..676d115171
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/logins.rs
@@ -0,0 +1,296 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Installing saved logins into the destination's OWN Chromium-family
+//! browser, re-encrypted under the destination's OWN Safe Storage key.
+//!
+//! The sender decrypts the logins the user ticked in the review on the
+//! source and hands them across already plaintext inside the reserved
+//! [`cua_teleport_bundle::logins::LOGINS_ENTRY`]. Like
+//! [`crate::cookies::install_cookies`], this module never receives the
+//! source's key: it derives this machine's own key, encrypts each password
+//! under it and writes the row into the browser's real `Login Data`
+//! database, discovering the live columns with `PRAGMA table_info` and only
+//! setting the ones it knows the meaning of.
+//!
+//! Unlike cookies, there is no schema this module can safely create from
+//! nothing: Chrome migrates `Login Data` from a version number, and a
+//! hand-made table at the wrong version would be razed on first launch. So
+//! when the browser has never been launched here (no `Login Data` yet) the
+//! passwords are skipped with a notice back to the sender instead of
+//! guessing.
+
+use std::path::Path;
+
+use cua_teleport_bundle::chromium_crypto;
+use cua_teleport_bundle::logins::LoginItem;
+use cua_teleport_bundle::Platform;
+
+use crate::cookies::{chrome_now_utc, ensure_safe_storage_secret};
+use crate::host::HostEffects;
+use crate::ledger::ImportRecord;
+use crate::{Result, TeleportError};
+
+/// The columns this module fills when the table has them.
+const KNOWN_COLUMNS: &[&str] = &[
+ "origin_url",
+ "action_url",
+ "username_element",
+ "username_value",
+ "password_element",
+ "password_value",
+ "signon_realm",
+ "date_created",
+ "date_last_used",
+ "date_password_modified",
+ "blacklisted_by_user",
+ "scheme",
+ "preferred",
+ "times_used",
+];
+
+/// Installs `items` into `profile_dir`'s `Login Data`. Returns how many rows
+/// were written.
+pub fn install_logins(
+ host: &dyn HostEffects,
+ profile_dir: &Path,
+ service: &'static str,
+ platform: Platform,
+ items: &[LoginItem],
+ record: &mut ImportRecord,
+) -> Result<usize> {
+ if items.is_empty() {
+ return Ok(0);
+ }
+ if platform == Platform::Windows {
+ return Err(TeleportError::Provider(
+ "re-encrypting saved passwords for a Windows destination (DPAPI) is not supported yet"
+ .into(),
+ ));
+ }
+ let db = profile_dir.join("Login Data");
+ if !db.is_file() {
+ // Not a failure of the whole import (the cookies and files still
+ // land): the passwords wait for a browser that has run once.
+ record.notices.push(
+ "Saved passwords were not sent: the browser here has no password store yet. Open it \
+ once in this Space, then send the passwords again."
+ .into(),
+ );
+ return Ok(0);
+ }
+ let secret = ensure_safe_storage_secret(host, platform, service, record)
+ .map_err(|e| TeleportError::Provider(format!("Safe Storage key for {service}: {e}")))?;
+ let rounds = match platform {
+ Platform::Linux => chromium_crypto::LINUX_V10_PBKDF2_ROUNDS,
+ Platform::MacOS | Platform::Windows => chromium_crypto::MACOS_PBKDF2_ROUNDS,
+ };
+ let key = chromium_crypto::derive_key(&secret, rounds);
+ let conn = rusqlite::Connection::open(&db)
+ .map_err(|e| TeleportError::Provider(format!("opening Login Data failed: {e}")))?;
+ let present = columns(&conn)
+ .map_err(|e| TeleportError::Provider(format!("reading Login Data schema failed: {e}")))?;
+ for required in [
+ "origin_url",
+ "username_value",
+ "password_value",
+ "signon_realm",
+ ] {
+ if !present.contains(required) {
+ return Err(TeleportError::Provider(format!(
+ "the destination's Login Data table has no {required:?} column; this Chrome \
+ version's schema is not one this build can write passwords into"
+ )));
+ }
+ }
+ let cols: Vec<&str> = KNOWN_COLUMNS
+ .iter()
+ .copied()
+ .filter(|c| present.contains(*c))
+ .collect();
+ let placeholders: Vec<String> = (1..=cols.len()).map(|i| format!("?{i}")).collect();
+ let sql = format!(
+ "INSERT OR REPLACE INTO logins ({}) VALUES ({})",
+ cols.join(", "),
+ placeholders.join(", ")
+ );
+ let mut stmt = conn
+ .prepare(&sql)
+ .map_err(|e| TeleportError::Provider(format!("preparing login insert failed: {e}")))?;
+ let now = chrome_now_utc();
+ let mut written = 0;
+ for item in items {
+ let encrypted = chromium_crypto::encrypt_v10(&key, &item.password);
+ let args: Vec<rusqlite::types::Value> = cols
+ .iter()
+ .map(|c| match *c {
+ "origin_url" => item.origin.clone().into(),
+ "action_url" => item.signon_realm.clone().into(),
+ "username_element" | "password_element" => String::new().into(),
+ "username_value" => item.username.clone().into(),
+ "password_value" => encrypted.clone().into(),
+ "signon_realm" => item.signon_realm.clone().into(),
+ "date_created" | "date_password_modified" => now.into(),
+ "date_last_used"
+ | "scheme"
+ | "blacklisted_by_user"
+ | "preferred"
+ | "times_used" => 0i64.into(),
+ other => unreachable!("column {other} was filtered out of KNOWN_COLUMNS above"),
+ })
+ .collect();
+ stmt.execute(rusqlite::params_from_iter(args))
+ .map_err(|e| TeleportError::Provider(format!("writing a saved login failed: {e}")))?;
+ record.login_row_written(&db, &item.origin, &item.username, &item.signon_realm);
+ written += 1;
+ }
+ Ok(written)
+}
+
+fn columns(conn: &rusqlite::Connection) -> rusqlite::Result<std::collections::HashSet<String>> {
+ let mut stmt = conn.prepare("PRAGMA table_info(\"logins\")")?;
+ let names = stmt
+ .query_map([], |r| r.get::<_, String>(1))?
+ .collect::<rusqlite::Result<Vec<_>>>()?;
+ Ok(names.into_iter().map(|n| n.to_ascii_lowercase()).collect())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::host::FakeHost;
+
+ fn login(origin: &str, user: &str, pw: &[u8]) -> LoginItem {
+ LoginItem {
+ origin: origin.into(),
+ username: user.into(),
+ password: pw.to_vec(),
+ signon_realm: cua_teleport_bundle::logins::signon_realm(origin),
+ }
+ }
+
+ /// A `Login Data` the way a Chrome that already ran has it (trimmed to the
+ /// columns that matter plus ones this module must tolerate).
+ fn existing(dir: &Path) -> std::path::PathBuf {
+ let db = dir.join("Login Data");
+ let conn = rusqlite::Connection::open(&db).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE logins (origin_url VARCHAR NOT NULL, action_url VARCHAR,
+ username_element VARCHAR, username_value VARCHAR, password_element VARCHAR,
+ password_value BLOB, submit_element VARCHAR, signon_realm VARCHAR NOT NULL,
+ date_created INTEGER NOT NULL, blacklisted_by_user INTEGER NOT NULL,
+ scheme INTEGER NOT NULL, password_type INTEGER, times_used INTEGER,
+ date_last_used INTEGER NOT NULL DEFAULT 0, date_password_modified INTEGER NOT NULL DEFAULT 0,
+ UNIQUE (origin_url, username_element, username_value, password_element, signon_realm));
+ INSERT INTO logins (origin_url, action_url, username_element, username_value,
+ password_element, password_value, signon_realm, date_created, blacklisted_by_user, scheme)
+ VALUES ('https://mine.example', 'https://mine.example/', '', 'me', '', x'7631300102',
+ 'https://mine.example/', 1, 0, 0);",
+ )
+ .unwrap();
+ db
+ }
+
+ #[test]
+ fn logins_are_reencrypted_under_the_destinations_key_beside_the_browsers_own() {
+ let home = tempfile::tempdir().unwrap();
+ let dir = home.path().join("Default");
+ std::fs::create_dir(&dir).unwrap();
+ let db = existing(&dir);
+ let host = FakeHost::new();
+ let mut record = ImportRecord::default();
+ let n = install_logins(
+ &host,
+ &dir,
+ "Chrome Safe Storage",
+ Platform::Linux,
+ &[login("https://github.com", "octo", b"gh-pw-1234")],
+ &mut record,
+ )
+ .unwrap();
+ assert_eq!(n, 1);
+ let conn = rusqlite::Connection::open(&db).unwrap();
+ let count: i64 = conn
+ .query_row("SELECT count(*) FROM logins", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(count, 2, "the browser's own login is still there");
+ let (enc, realm): (Vec<u8>, String) = conn
+ .query_row(
+ "SELECT password_value, signon_realm FROM logins WHERE username_value = 'octo'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(realm, "https://github.com/");
+ assert!(enc.starts_with(b"v10"));
+ assert!(
+ !enc.windows(10).any(|w| w == b"gh-pw-1234"),
+ "never plaintext"
+ );
+ let key = chromium_crypto::derive_key(
+ chromium_crypto::LINUX_V10_PASSWORD,
+ chromium_crypto::LINUX_V10_PBKDF2_ROUNDS,
+ );
+ let plain = chromium_crypto::decrypt_prefixed(&key, &enc).unwrap().1;
+ assert_eq!(&*plain, b"gh-pw-1234");
+ assert_eq!(record.login_rows.len(), 1);
+
+ // Wipe removes exactly this login.
+ let ledger = crate::ledger::Ledger::new("i", "chrome", &record, 0, 1);
+ let removed = crate::ledger::wipe(&ledger, home.path(), &host);
+ assert_eq!(removed.login_rows_removed, 1, "{:?}", removed.refused);
+ let left: i64 = conn
+ .query_row("SELECT count(*) FROM logins", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(left, 1);
+ }
+
+ #[test]
+ fn a_browser_never_launched_gets_a_notice_and_nothing_is_guessed() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut record = ImportRecord::default();
+ let n = install_logins(
+ &FakeHost::new(),
+ dir.path(),
+ "Chrome Safe Storage",
+ Platform::Linux,
+ &[login("https://github.com", "octo", b"pw")],
+ &mut record,
+ )
+ .unwrap();
+ assert_eq!(n, 0);
+ assert!(
+ record.notices[0].contains("Open it once"),
+ "{:?}",
+ record.notices
+ );
+ assert!(!dir.path().join("Login Data").exists());
+ }
+
+ #[test]
+ fn empty_input_and_windows_are_refused_without_touching_anything() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut rec = ImportRecord::default();
+ assert_eq!(
+ install_logins(
+ &FakeHost::new(),
+ dir.path(),
+ "x",
+ Platform::Linux,
+ &[],
+ &mut rec
+ )
+ .unwrap(),
+ 0
+ );
+ assert!(install_logins(
+ &FakeHost::new(),
+ dir.path(),
+ "x",
+ Platform::Windows,
+ &[login("https://a.test", "u", b"p")],
+ &mut rec
+ )
+ .is_err());
+ }
+}
diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
index 19a7da6b52..5d5f68066a 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
@@ -1756,6 +1756,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crc32c"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
+dependencies = [
+ "rustc_version",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -1939,6 +1948,18 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "cua-chromium-storage"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "cua-teleport-bundle",
+ "rusty-leveldb",
+ "tempfile",
+ "thiserror 2.0.20",
+ "tracing",
+]
+
[[package]]
name = "cua-contrib"
version = "0.1.0"
@@ -2464,6 +2485,7 @@ dependencies = [
"chrono",
"cua-agents",
"cua-auth",
+ "cua-chromium-storage",
"cua-daemon",
"cua-fleet",
"cua-home",
@@ -2605,6 +2627,7 @@ dependencies = [
name = "cua-spacesd-teleport"
version = "0.1.4"
dependencies = [
+ "cua-chromium-storage",
"cua-teleport-bundle",
"hex",
"ignore",
@@ -2638,6 +2661,7 @@ dependencies = [
"core-foundation 0.10.1",
"core-graphics 0.25.0",
"cua-agents",
+ "cua-chromium-storage",
"cua-home",
"cua-icon-cache",
"cua-machine-seal",
@@ -3195,6 +3219,17 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+[[package]]
+name = "errno"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1"
+dependencies = [
+ "errno-dragonfly",
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -3205,6 +3240,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "errno-dragonfly"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
+dependencies = [
+ "cc",
+ "libc",
+]
+
[[package]]
name = "error-code"
version = "3.4.0"
@@ -4264,6 +4309,12 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "integer-encoding"
+version = "3.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -6614,7 +6665,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
dependencies = [
"bitflags 2.13.2",
- "errno",
+ "errno 0.3.14",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
@@ -6703,6 +6754,21 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+[[package]]
+name = "rusty-leveldb"
+version = "4.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43ddda8f34100fca4bf1b0bbf743d12d27b5d84c35c74a52f392aac26f54e82d"
+dependencies = [
+ "bytes",
+ "crc32c",
+ "errno 0.2.8",
+ "fs2",
+ "integer-encoding",
+ "rand 0.8.8",
+ "snap",
+]
+
[[package]]
name = "ryu"
version = "1.0.23"
@@ -7081,7 +7147,7 @@ version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
- "errno",
+ "errno 0.3.14",
"libc",
]
@@ -7153,6 +7219,12 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100"
+[[package]]
+name = "snap"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886"
+
[[package]]
name = "socket2"
version = "0.6.5"
diff --git a/libs/cua-spacesd/tests/spaces-e2e/src/bin/cua-test-fixtures.rs b/libs/cua-spacesd/tests/spaces-e2e/src/bin/cua-test-fixtures.rs
index 9a5b249573..f5da5a0a38 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/src/bin/cua-test-fixtures.rs
+++ b/libs/cua-spacesd/tests/spaces-e2e/src/bin/cua-test-fixtures.rs
@@ -209,7 +209,7 @@ mod test_daemon {
.expect("create the test Keyvault");
// The user imports the fixture profile's session into the vault, as
// they would on the Keyvault page; teleport moves only what is here.
- let items = broker
+ let report = broker
.import(
&user,
ImportSpec {
@@ -220,7 +220,7 @@ mod test_daemon {
)
.await
.expect("import the fixture Firefox session");
- assert!(!items.is_empty(), "the fixture profile yields a vault item");
+ assert!(report.saved > 0, "the fixture profile yields a vault item");
let socket = home.path().join("cua.sock");
let handle = server::start(
runtime.clone(),
diff --git a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
index 38ab3c4024..9dea4bd07a 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
@@ -1087,6 +1087,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crc32c"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
+dependencies = [
+ "rustc_version",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.1"
@@ -1213,6 +1222,18 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "cua-chromium-storage"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "cua-teleport-bundle",
+ "rusty-leveldb",
+ "tempfile",
+ "thiserror 2.0.20",
+ "tracing",
+]
+
[[package]]
name = "cua-driver-contract"
version = "0.32.0"
@@ -1479,6 +1500,7 @@ dependencies = [
name = "cua-spacesd-teleport"
version = "0.1.4"
dependencies = [
+ "cua-chromium-storage",
"cua-teleport-bundle",
"hex",
"ignore",
@@ -1512,6 +1534,7 @@ dependencies = [
"core-foundation",
"core-graphics 0.25.0",
"cua-agents",
+ "cua-chromium-storage",
"cua-home",
"cua-icon-cache",
"cua-machine-seal",
@@ -1556,6 +1579,7 @@ dependencies = [
name = "cua-teleport-e2e"
version = "0.0.0"
dependencies = [
+ "cua-chromium-storage",
"cua-spacesd-client",
"cua-spacesd-server",
"cua-spacesd-teleport",
@@ -1779,6 +1803,17 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+[[package]]
+name = "errno"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1"
+dependencies = [
+ "errno-dragonfly",
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -1789,6 +1824,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "errno-dragonfly"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
+dependencies = [
+ "cc",
+ "libc",
+]
+
[[package]]
name = "error-code"
version = "3.4.0"
@@ -2740,6 +2785,12 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "integer-encoding"
+version = "3.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -4620,7 +4671,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags 2.13.1",
- "errno",
+ "errno 0.3.14",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
@@ -4668,6 +4719,21 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+[[package]]
+name = "rusty-leveldb"
+version = "4.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43ddda8f34100fca4bf1b0bbf743d12d27b5d84c35c74a52f392aac26f54e82d"
+dependencies = [
+ "bytes",
+ "crc32c",
+ "errno 0.2.8",
+ "fs2",
+ "integer-encoding",
+ "rand 0.8.8",
+ "snap",
+]
+
[[package]]
name = "ryu"
version = "1.0.23"
@@ -5009,7 +5075,7 @@ version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
- "errno",
+ "errno 0.3.14",
"libc",
]
@@ -5055,6 +5121,12 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100"
+[[package]]
+name = "snap"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886"
+
[[package]]
name = "socket2"
version = "0.6.5"
diff --git a/libs/cua-spacesd/tests/teleport-e2e/Cargo.toml b/libs/cua-spacesd/tests/teleport-e2e/Cargo.toml
index 60fd8df9b8..092e7989ac 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/Cargo.toml
+++ b/libs/cua-spacesd/tests/teleport-e2e/Cargo.toml
@@ -23,6 +23,7 @@ cua-spacesd-client = { path = "../../../cua/crates/cua-spacesd-client" }
cua-spacesd-server = { path = "../../crates/cua-spacesd-server" }
cua-spacesd-teleport = { path = "../../crates/cua-spacesd-teleport" }
cua-teleport-bundle = { path = "../../../cua/crates/cua-teleport-bundle" }
+cua-chromium-storage = { path = "../../../cua/crates/cua-chromium-storage" }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
tempfile = "3"
rusqlite = { version = "0.40.1", default-features = false, features = ["bundled"] }
diff --git a/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs b/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs
index a700e6f75f..4f0d503a8b 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs
+++ b/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs
@@ -302,6 +302,165 @@ async fn cookies_land_in_a_chrome_that_was_never_launched() {
}
}
+/// The modern layout end to end: a source Chrome with `Network/Cookies` in its
+/// current schema (every attribute, a partitioned cookie, a Windows
+/// app-bound value) and a `Local Storage` LevelDB goes through the real sender,
+/// an in-process spacesd and the receiver. Every cookie attribute lands in the
+/// guest's own database, the partitioned cookie stays partitioned, the
+/// app-bound one is not sent, and the localStorage values land in the guest's
+/// LevelDB.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn modern_layout_cookie_attributes_and_local_storage_arrive_whole() {
+ use cua_chromium_storage as ls;
+ use cua_teleport::browser_cookies::{
+ write_modern_cookies_db_for_tests, CookieExtras, ModernTestRow, TestCookieRow,
+ };
+ use cua_teleport_bundle::chromium_crypto as crypto;
+
+ let g = guest().await;
+ let src = tempfile::tempdir().unwrap();
+ fake_chrome(src.path());
+ let profile = src.path().join(".config/google-chrome/Default");
+ std::fs::remove_file(profile.join("Network/Cookies")).unwrap();
+ let key = crypto::derive_key(crypto::LINUX_V10_PASSWORD, crypto::LINUX_V10_PBKDF2_ROUNDS);
+ let enc = |v: &[u8]| crypto::encrypt_v10(&key, v);
+ let core = |host: &'static str, name: &'static str, value: Vec<u8>| TestCookieRow {
+ host_key: host,
+ name,
+ encrypted_value: value,
+ path: "/",
+ expires_utc: 13_400_000_000_000_000,
+ is_secure: true,
+ is_httponly: true,
+ samesite: 1,
+ };
+ let full = CookieExtras {
+ creation_utc: Some(13_300_000_000_000_001),
+ last_access_utc: Some(13_300_000_000_000_002),
+ last_update_utc: Some(13_300_000_000_000_003),
+ priority: Some(2),
+ source_scheme: Some(2),
+ source_port: Some(443),
+ source_type: Some(1),
+ has_cross_site_ancestor: Some(1),
+ top_frame_site_key: Some("https://top.example".into()),
+ };
+ let mut app_bound = b"v20".to_vec();
+ app_bound.extend_from_slice(&[9u8; 40]);
+ write_modern_cookies_db_for_tests(
+ &profile,
+ &[
+ ModernTestRow {
+ core: core(".example.com", "sid", enc(b"partitioned")),
+ extra: full,
+ },
+ ModernTestRow {
+ core: core(".example.com", "sid", enc(b"plain")),
+ extra: CookieExtras::default(),
+ },
+ ModernTestRow {
+ core: core(".bank.test", "app_bound", app_bound),
+ extra: CookieExtras::default(),
+ },
+ ],
+ )
+ .unwrap();
+ let item = |origin: &str, key: &str, value: &str| ls::LocalStorageItem {
+ origin: origin.into(),
+ key: key.into(),
+ value: value.into(),
+ key_raw: None,
+ value_raw: None,
+ };
+ let source_items = vec![
+ item("https://github.com", "color_mode", "dark"),
+ item("https://a.example", "日本", "こんにちは"),
+ ];
+ ls::write(
+ &ls::store_dir(&profile),
+ &source_items,
+ 13_300_000_000_000_000,
+ )
+ .unwrap();
+
+ let (_, teleporter) = sender(src.path());
+ let env = client(&g.url, TransportPreference::Native).await;
+ teleporter
+ .send(
+ &env,
+ &chrome(),
+ TransferScope::FullProfile,
+ Selection::All,
+ Arc::new(AutoApprove),
+ )
+ .await
+ .unwrap();
+
+ let user_data = if cfg!(target_os = "macos") {
+ "Library/Application Support/Google/Chrome"
+ } else {
+ ".config/google-chrome"
+ };
+ let dest = g.dest_home.path().join(user_data).join("Default");
+ let conn = rusqlite::Connection::open(dest.join("Network/Cookies")).unwrap();
+ let rows: i64 = conn
+ .query_row("SELECT count(*) FROM cookies", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(rows, 2, "the app-bound cookie is not sent");
+ #[allow(clippy::type_complexity)]
+ let got: (i64, i64, i64, i64, i64, i64, i64, i64, String) = conn
+ .query_row(
+ "SELECT creation_utc, last_access_utc, last_update_utc, priority, source_scheme,
+ source_port, source_type, has_cross_site_ancestor, top_frame_site_key
+ FROM cookies WHERE top_frame_site_key != ''",
+ [],
+ |r| {
+ Ok((
+ r.get(0)?,
+ r.get(1)?,
+ r.get(2)?,
+ r.get(3)?,
+ r.get(4)?,
+ r.get(5)?,
+ r.get(6)?,
+ r.get(7)?,
+ r.get(8)?,
+ ))
+ },
+ )
+ .unwrap();
+ assert_eq!(
+ got,
+ (
+ 13_300_000_000_000_001,
+ 13_300_000_000_000_002,
+ 13_300_000_000_000_003,
+ 2,
+ 2,
+ 443,
+ 1,
+ 1,
+ "https://top.example".to_string()
+ )
+ );
+ let unpartitioned: i64 = conn
+ .query_row(
+ "SELECT count(*) FROM cookies WHERE top_frame_site_key = '' AND name = 'sid'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(unpartitioned, 1);
+ // The guest's own LevelDB holds the same values.
+ let mut got = ls::read(&ls::store_dir(&dest)).unwrap();
+ got.sort_by(|a, b| a.origin.cmp(&b.origin));
+ let mut want = source_items.clone();
+ want.sort_by(|a, b| a.origin.cmp(&b.origin));
+ assert_eq!(got, want);
+ // And not as raw LevelDB files of the sender's.
+ assert!(!g.dest_home.path().join("localstorage.json").exists());
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn default_selection_withholds_credentials() {
let g = guest().await;
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index 75382348c6..4953b3ce74 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -1866,6 +1866,15 @@ dependencies = [
"spin",
]
+[[package]]
+name = "crc32c"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
+dependencies = [
+ "rustc_version",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -2099,6 +2108,18 @@ dependencies = [
"url",
]
+[[package]]
+name = "cua-chromium-storage"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "cua-teleport-bundle",
+ "rusty-leveldb",
+ "tempfile",
+ "thiserror 2.0.20",
+ "tracing",
+]
+
[[package]]
name = "cua-cli"
version = "0.1.0"
@@ -2664,6 +2685,7 @@ dependencies = [
"chrono",
"cua-agents",
"cua-auth",
+ "cua-chromium-storage",
"cua-daemon",
"cua-fleet",
"cua-home",
@@ -2822,6 +2844,7 @@ dependencies = [
"core-foundation 0.10.1",
"core-graphics 0.25.0",
"cua-agents",
+ "cua-chromium-storage",
"cua-home",
"cua-icon-cache",
"cua-machine-seal",
@@ -3413,6 +3436,17 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+[[package]]
+name = "errno"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1"
+dependencies = [
+ "errno-dragonfly",
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -3423,6 +3457,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "errno-dragonfly"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
+dependencies = [
+ "cc",
+ "libc",
+]
+
[[package]]
name = "fallible-iterator"
version = "0.3.0"
@@ -3620,6 +3664,16 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "fs2"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
+dependencies = [
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -4441,6 +4495,12 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "integer-encoding"
+version = "3.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+
[[package]]
name = "interpolate_name"
version = "0.2.4"
@@ -6860,7 +6920,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [
"bitflags 2.13.2",
- "errno",
+ "errno 0.3.14",
"libc",
"linux-raw-sys 0.4.15",
"windows-sys 0.52.0",
@@ -6873,7 +6933,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
dependencies = [
"bitflags 2.13.2",
- "errno",
+ "errno 0.3.14",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
@@ -6974,6 +7034,21 @@ dependencies = [
"wait-timeout",
]
+[[package]]
+name = "rusty-leveldb"
+version = "4.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43ddda8f34100fca4bf1b0bbf743d12d27b5d84c35c74a52f392aac26f54e82d"
+dependencies = [
+ "bytes",
+ "crc32c",
+ "errno 0.2.8",
+ "fs2",
+ "integer-encoding",
+ "rand 0.8.8",
+ "snap",
+]
+
[[package]]
name = "ryu"
version = "1.0.23"
@@ -7382,7 +7457,7 @@ version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
- "errno",
+ "errno 0.3.14",
"libc",
]
@@ -7494,6 +7569,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "snap"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886"
+
[[package]]
name = "socket2"
version = "0.6.5"
diff --git a/libs/cua/Cargo.toml b/libs/cua/Cargo.toml
index ca8e1b529d..bf428e22fd 100644
--- a/libs/cua/Cargo.toml
+++ b/libs/cua/Cargo.toml
@@ -16,6 +16,8 @@ members = [
"crates/cua-disk",
"crates/cua-daemon",
"crates/cua-teleport-bundle",
+ # Chromium localStorage (Local Storage LevelDB) as items.
+ "crates/cua-chromium-storage",
"crates/cua-teleport",
# The Keyvault: the local vault and broker that owns teleport.
"crates/cua-keyvault",
@@ -163,6 +165,7 @@ cua-agents = { path = "crates/cua-agents", version = "0.1.0" }
cua-volume = { path = "crates/cua-volume", version = "0.1.0" }
cua-sdk = { path = "crates/cua-sdk", version = "0.1.0", default-features = false }
cua-teleport-bundle = { path = "crates/cua-teleport-bundle", version = "0.1.0" }
+cua-chromium-storage = { path = "crates/cua-chromium-storage", version = "0.1.0" }
cua-teleport = { path = "crates/cua-teleport", version = "0.1.0" }
cua-keyvault = { path = "crates/cua-keyvault", version = "0.1.0" }
cua-spaces-app-core = { path = "crates/cua-spaces-app-core", version = "0.1.0" }
diff --git a/libs/cua/crates/cua-chromium-storage/Cargo.toml b/libs/cua/crates/cua-chromium-storage/Cargo.toml
new file mode 100644
index 0000000000..1aabaf82f8
--- /dev/null
+++ b/libs/cua/crates/cua-chromium-storage/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "cua-chromium-storage"
+description = "Chromium localStorage (the Local Storage LevelDB) read and written as items, for Keyvault and teleport."
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+authors.workspace = true
+license = "FSL-1.1-MIT"
+repository.workspace = true
+publish = false
+
+[dependencies]
+cua-teleport-bundle.workspace = true
+base64.workspace = true
+thiserror.workspace = true
+tempfile.workspace = true
+tracing.workspace = true
+# A maintained, pure-Rust LevelDB (reads Chromium's Snappy tables and log).
+rusty-leveldb = "4"
diff --git a/libs/cua/crates/cua-chromium-storage/LICENSE b/libs/cua/crates/cua-chromium-storage/LICENSE
new file mode 100644
index 0000000000..79293ae602
--- /dev/null
+++ b/libs/cua/crates/cua-chromium-storage/LICENSE
@@ -0,0 +1,110 @@
+# Functional Source License, Version 1.1, MIT Future License
+
+## Abbreviation
+
+FSL-1.1-MIT
+
+## Notice
+
+Copyright 2026 Cua AI, Inc.
+
+## Terms and Conditions
+
+### Licensor ("We")
+
+The party offering the Software under these Terms and Conditions.
+
+### The Software
+
+The "Software" is each version of the software that we make available under
+these Terms and Conditions, as indicated by our inclusion of these Terms and
+Conditions with the Software.
+
+### License Grant
+
+Subject to your compliance with this License Grant and the Patents,
+Redistribution and Trademark clauses below, we hereby grant you the right to
+use, copy, modify, create derivative works, publicly perform, publicly display
+and redistribute the Software for any Permitted Purpose identified below.
+
+### Permitted Purpose
+
+A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
+means making the Software available to others in a commercial product or
+service that:
+
+1. substitutes for the Software;
+
+2. substitutes for any other product or service we offer using the Software
+ that exists as of the date we make the Software available; or
+
+3. offers the same or substantially similar functionality as the Software.
+
+Permitted Purposes specifically include using the Software:
+
+1. for your internal use and access;
+
+2. for non-commercial education;
+
+3. for non-commercial research; and
+
+4. in connection with professional services that you provide to a licensee
+ using the Software in accordance with these Terms and Conditions.
+
+### Patents
+
+To the extent your use for a Permitted Purpose would necessarily infringe our
+patents, the license grant above includes a license under our patents. If you
+make a claim against any party that the Software infringes or contributes to
+the infringement of any patent, then your patent license to the Software ends
+immediately.
+
+### Redistribution
+
+The Terms and Conditions apply to all copies, modifications and derivatives of
+the Software.
+
+If you redistribute any copies, modifications or derivatives of the Software,
+you must include a copy of or a link to these Terms and Conditions and not
+remove any copyright notices provided in or with the Software.
+
+### Disclaimer
+
+THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
+PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
+
+IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
+SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
+EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
+
+### Trademarks
+
+Except for displaying the License Details and identifying us as the origin of
+the Software, you have no right under these Terms and Conditions to use our
+trademarks, trade names, service marks or product names.
+
+## Grant of Future License
+
+We hereby irrevocably grant you an additional license to use the Software under
+the MIT license that is effective on the second anniversary of the date we make
+the Software available. On or after that date, you may use the Software under
+the MIT license, in which case the following will apply:
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/libs/cua/crates/cua-chromium-storage/src/lib.rs b/libs/cua/crates/cua-chromium-storage/src/lib.rs
new file mode 100644
index 0000000000..e15a00476c
--- /dev/null
+++ b/libs/cua/crates/cua-chromium-storage/src/lib.rs
@@ -0,0 +1,518 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Chromium localStorage, read and written as items.
+//!
+//! A Chromium-family browser keeps `localStorage` in a LevelDB directory,
+//! `<profile>/Local Storage/leveldb`. Its keys are
+//!
+//! ```text
+//! VERSION "1"
+//! META:<origin> protobuf { last_modified, size_bytes }
+//! METAACCESS:<origin> protobuf { last_accessed }
+//! _<origin> 0x00 <fmt> <key> the value: <fmt> <bytes>
+//! ```
+//!
+//! where `<fmt>` is `0x01` for Latin-1 text and `0x00` for UTF-16LE, in keys
+//! and in values alike. [`read`] turns the data keys into
+//! [`LocalStorageItem`]s from a private copy of the directory (so a running
+//! browser's files and lock are never touched); [`write`] puts items back
+//! into a destination directory **while that browser is not running**
+//! (LevelDB takes an exclusive lock, and a running browser holds it), adding
+//! `META:` for an origin that has none and `VERSION` for a new database;
+//! [`delete`] takes written keys out again.
+//!
+//! Nothing here reads or writes anything outside the directory it is given.
+
+use std::path::{Path, PathBuf};
+
+use base64::Engine as _;
+use rusty_leveldb::{DB, LdbIterator, Options};
+
+pub use cua_teleport_bundle::local_storage::{LOCAL_STORAGE_ENTRY, LocalStorageItem};
+
+/// Why a read or write failed.
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ /// The directory is missing or unreadable.
+ #[error("localStorage store: {0}")]
+ Io(String),
+ /// LevelDB refused (damaged files, or a running browser holds the lock).
+ #[error("localStorage database: {0}")]
+ Db(String),
+ /// The store is bigger than this build reads into memory.
+ #[error("localStorage is {0} MiB, more than the {1} MiB this build reads")]
+ TooLarge(u64, u64),
+}
+
+/// A result.
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// The most a read copies and holds (the database's files, in MiB).
+pub const MAX_STORE_MIB: u64 = 256;
+
+/// `<profile>/Local Storage/leveldb`.
+pub fn store_dir(profile_dir: &Path) -> PathBuf {
+ profile_dir.join("Local Storage").join("leveldb")
+}
+
+const DATA_PREFIX: u8 = b'_';
+const META_PREFIX: &[u8] = b"META:";
+const VERSION_KEY: &[u8] = b"VERSION";
+
+fn db_err(e: rusty_leveldb::Status) -> Error {
+ Error::Db(e.to_string())
+}
+
+fn b64() -> base64::engine::general_purpose::GeneralPurpose {
+ base64::engine::general_purpose::STANDARD
+}
+
+/// Text stored the way Chromium stores it: a format byte (`0x01` Latin-1,
+/// `0x00` UTF-16LE) then the characters. Returns the text and whether it is
+/// the exact content (a lone surrogate, or an unknown format byte, is not).
+fn decode_text(stored: &[u8]) -> (String, bool) {
+ match stored.split_first() {
+ Some((1, rest)) => (rest.iter().map(|&b| b as char).collect(), true),
+ Some((0, rest)) if rest.len() % 2 == 0 => {
+ let units: Vec<u16> = rest
+ .chunks_exact(2)
+ .map(|c| u16::from_le_bytes([c[0], c[1]]))
+ .collect();
+ match String::from_utf16(&units) {
+ Ok(s) => (s, true),
+ Err(_) => (String::from_utf16_lossy(&units), false),
+ }
+ }
+ Some((_, rest)) => (String::from_utf8_lossy(rest).into_owned(), false),
+ None => (String::new(), true),
+ }
+}
+
+/// The inverse of [`decode_text`]: Latin-1 when every character fits (as
+/// Chromium writes it), else UTF-16LE.
+fn encode_text(text: &str) -> Vec<u8> {
+ if text.chars().all(|c| (c as u32) < 256) {
+ let mut out = Vec::with_capacity(1 + text.len());
+ out.push(1);
+ out.extend(text.chars().map(|c| c as u32 as u8));
+ out
+ } else {
+ let mut out = vec![0u8];
+ for u in text.encode_utf16() {
+ out.extend_from_slice(&u.to_le_bytes());
+ }
+ out
+ }
+}
+
+/// `_<origin>\0<fmt><key>` for an item (its exact stored key bytes when it
+/// carries them).
+fn data_key(item: &LocalStorageItem) -> Vec<u8> {
+ let mut k = Vec::with_capacity(item.origin.len() + item.key.len() + 4);
+ k.push(DATA_PREFIX);
+ k.extend_from_slice(item.origin.as_bytes());
+ k.push(0);
+ match item.key_raw.as_deref().and_then(|r| b64().decode(r).ok()) {
+ Some(raw) => k.extend_from_slice(&raw),
+ None => k.extend_from_slice(&encode_text(&item.key)),
+ }
+ k
+}
+
+fn value_bytes(item: &LocalStorageItem) -> Vec<u8> {
+ match item.value_raw.as_deref().and_then(|r| b64().decode(r).ok()) {
+ Some(raw) => raw,
+ None => encode_text(&item.value),
+ }
+}
+
+/// Parses a data key: the origin and the stored key bytes (format byte
+/// included). `None` for `VERSION`, `META:`, `METAACCESS:` and anything else.
+fn parse_data_key(k: &[u8]) -> Option<(String, &[u8])> {
+ let rest = k.strip_prefix(&[DATA_PREFIX])?;
+ let nul = rest.iter().position(|&b| b == 0)?;
+ let origin = std::str::from_utf8(&rest[..nul]).ok()?;
+ Some((origin.to_string(), &rest[nul + 1..]))
+}
+
+/// A private copy of `dir` (every file but `LOCK`), removed on drop.
+fn private_copy(dir: &Path) -> Result<tempfile::TempDir> {
+ let mut total = 0u64;
+ let mut files = Vec::new();
+ for e in std::fs::read_dir(dir).map_err(|e| Error::Io(format!("{}: {e}", dir.display())))? {
+ let e = e.map_err(|e| Error::Io(e.to_string()))?;
+ let meta = e.metadata().map_err(|e| Error::Io(e.to_string()))?;
+ if meta.is_file() && e.file_name() != "LOCK" {
+ total += meta.len();
+ files.push(e.path());
+ }
+ }
+ if total > MAX_STORE_MIB * 1024 * 1024 {
+ return Err(Error::TooLarge(total / (1024 * 1024), MAX_STORE_MIB));
+ }
+ let tmp = tempfile::Builder::new()
+ .prefix("cua-localstorage-")
+ .tempdir()
+ .map_err(|e| Error::Io(e.to_string()))?;
+ for f in files {
+ let name = f.file_name().unwrap_or_default();
+ std::fs::copy(&f, tmp.path().join(name)).map_err(|e| Error::Io(e.to_string()))?;
+ }
+ Ok(tmp)
+}
+
+/// Every localStorage value in `dir` (a `Local Storage/leveldb` directory),
+/// read from a private copy. A directory that is not there is no items.
+pub fn read(dir: &Path) -> Result<Vec<LocalStorageItem>> {
+ if !dir.is_dir() {
+ return Ok(Vec::new());
+ }
+ let copy = private_copy(dir)?;
+ let opts = Options {
+ create_if_missing: false,
+ ..Options::default()
+ };
+ let mut db = DB::open(copy.path(), opts).map_err(db_err)?;
+ let mut it = db.new_iter().map_err(db_err)?;
+ let mut out = Vec::new();
+ while let Some((k, v)) = it.next() {
+ let Some((origin, key_bytes)) = parse_data_key(&k) else {
+ continue;
+ };
+ let (key, key_exact) = decode_text(key_bytes);
+ let (value, value_exact) = decode_text(&v);
+ out.push(LocalStorageItem {
+ origin,
+ key,
+ value,
+ key_raw: (!key_exact).then(|| b64().encode(key_bytes)),
+ value_raw: (!value_exact).then(|| b64().encode(&v)),
+ });
+ }
+ drop(it);
+ let _ = db.close();
+ Ok(out)
+}
+
+/// How many values each origin holds, without decoding any (what a review
+/// shows before anything is saved). Read from a private copy.
+pub fn count_by_origin(dir: &Path) -> Result<std::collections::BTreeMap<String, u32>> {
+ let mut counts = std::collections::BTreeMap::new();
+ if !dir.is_dir() {
+ return Ok(counts);
+ }
+ let copy = private_copy(dir)?;
+ let opts = Options {
+ create_if_missing: false,
+ ..Options::default()
+ };
+ let mut db = DB::open(copy.path(), opts).map_err(db_err)?;
+ let mut it = db.new_iter().map_err(db_err)?;
+ while let Some((k, _)) = it.next() {
+ if let Some((origin, _)) = parse_data_key(&k) {
+ *counts.entry(origin).or_insert(0) += 1;
+ }
+ }
+ drop(it);
+ let _ = db.close();
+ Ok(counts)
+}
+
+fn varint(mut n: u64, out: &mut Vec<u8>) {
+ loop {
+ let b = (n & 0x7f) as u8;
+ n >>= 7;
+ if n == 0 {
+ out.push(b);
+ return;
+ }
+ out.push(b | 0x80);
+ }
+}
+
+/// `META:` value: `last_modified` (field 1, Chrome microseconds since 1601)
+/// and `size_bytes` (field 2).
+fn meta_value(last_modified: i64, size_bytes: u64) -> Vec<u8> {
+ let mut out = vec![0x08];
+ varint(last_modified.max(0) as u64, &mut out);
+ out.push(0x10);
+ varint(size_bytes, &mut out);
+ out
+}
+
+/// What [`write`] put in, so a wipe can take exactly it out again.
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct Written {
+ /// Data keys written.
+ pub keys: Vec<Vec<u8>>,
+ /// `META:` keys this write created (the origin had none).
+ pub meta_keys: Vec<Vec<u8>>,
+}
+
+/// Writes `items` into `dir`, creating the database when there is none. The
+/// destination browser must not be running: LevelDB's lock is exclusive, so
+/// a running browser makes this fail rather than corrupt anything.
+/// `now_chrome_micros` stamps a new origin's `META:`.
+pub fn write(dir: &Path, items: &[LocalStorageItem], now_chrome_micros: i64) -> Result<Written> {
+ if items.is_empty() {
+ return Ok(Written::default());
+ }
+ std::fs::create_dir_all(dir).map_err(|e| Error::Io(format!("{}: {e}", dir.display())))?;
+ let opts = Options {
+ create_if_missing: true,
+ ..Options::default()
+ };
+ let mut db = DB::open(dir, opts).map_err(|e| {
+ Error::Db(format!(
+ "{e}; close the browser in the destination and try again"
+ ))
+ })?;
+ let mut written = Written::default();
+ if db.get(VERSION_KEY).is_none() {
+ db.put(VERSION_KEY, b"1").map_err(db_err)?;
+ }
+ let mut sizes: std::collections::BTreeMap<&str, u64> = Default::default();
+ for item in items {
+ let key = data_key(item);
+ let value = value_bytes(item);
+ *sizes.entry(item.origin.as_str()).or_default() += (key.len() + value.len()) as u64;
+ db.put(&key, &value).map_err(db_err)?;
+ written.keys.push(key);
+ }
+ for (origin, size) in sizes {
+ let mut meta = META_PREFIX.to_vec();
+ meta.extend_from_slice(origin.as_bytes());
+ if db.get(&meta).is_none() {
+ db.put(&meta, &meta_value(now_chrome_micros, size))
+ .map_err(db_err)?;
+ written.meta_keys.push(meta);
+ }
+ }
+ db.flush().map_err(db_err)?;
+ db.close().map_err(db_err)?;
+ Ok(written)
+}
+
+/// Deletes `keys` (what [`write`] returned) from `dir`. Returns how many
+/// were present.
+pub fn delete(dir: &Path, keys: &[Vec<u8>]) -> Result<usize> {
+ // No database here (never created, or its files were removed): nothing
+ // to delete out of.
+ if keys.is_empty() || !dir.join("CURRENT").is_file() {
+ return Ok(0);
+ }
+ let opts = Options {
+ create_if_missing: false,
+ ..Options::default()
+ };
+ let mut db = DB::open(dir, opts).map_err(db_err)?;
+ let mut n = 0;
+ for k in keys {
+ if db.get(k).is_some() {
+ db.delete(k).map_err(db_err)?;
+ n += 1;
+ }
+ }
+ db.flush().map_err(db_err)?;
+ db.close().map_err(db_err)?;
+ Ok(n)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use rusty_leveldb::CompressorId;
+ use rusty_leveldb::compressor::SnappyCompressor;
+
+ fn item(origin: &str, key: &str, value: &str) -> LocalStorageItem {
+ LocalStorageItem {
+ origin: origin.into(),
+ key: key.into(),
+ value: value.into(),
+ key_raw: None,
+ value_raw: None,
+ }
+ }
+
+ /// Builds a store the way Chromium lays it out, key by key.
+ fn chromium_store(dir: &Path, compress: bool) {
+ let mut opts = Options::default();
+ if compress {
+ opts.compressor = SnappyCompressor::ID;
+ }
+ let mut db = DB::open(dir, opts).unwrap();
+ db.put(b"VERSION", b"1").unwrap();
+ db.put(
+ b"META:https://github.com",
+ &meta_value(13_300_000_000_000_000, 40),
+ )
+ .unwrap();
+ db.put(b"METAACCESS:https://github.com", &[0x08, 0x01])
+ .unwrap();
+ // `_https://github.com` NUL 0x01 `color_mode` -> 0x01 `dark`
+ db.put(b"_https://github.com\x00\x01color_mode", b"\x01dark")
+ .unwrap();
+ // A UTF-16 key and value ("naïve" fits Latin-1, "日本" does not).
+ let mut k = b"_https://a.example\x00\x00".to_vec();
+ for u in "日本".encode_utf16() {
+ k.extend_from_slice(&u.to_le_bytes());
+ }
+ let mut v = vec![0u8];
+ for u in "こんにちは".encode_utf16() {
+ v.extend_from_slice(&u.to_le_bytes());
+ }
+ db.put(&k, &v).unwrap();
+ db.put(b"_https://a.example\x00\x01na\xefve", b"\x01caf\xe9")
+ .unwrap();
+ // A lone surrogate cannot be text.
+ db.put(b"_https://a.example\x00\x01bad", &[0, 0x00, 0xd8])
+ .unwrap();
+ if compress {
+ db.compact_range(b"\x00", b"\xff").unwrap();
+ }
+ db.flush().unwrap();
+ db.close().unwrap();
+ }
+
+ fn sorted(mut v: Vec<LocalStorageItem>) -> Vec<LocalStorageItem> {
+ v.sort_by(|a, b| (&a.origin, &a.key).cmp(&(&b.origin, &b.key)));
+ v
+ }
+
+ #[test]
+ fn reads_chromiums_layout_skipping_meta_and_decoding_latin1_and_utf16() {
+ let dir = tempfile::tempdir().unwrap();
+ chromium_store(dir.path(), false);
+ let items = sorted(read(dir.path()).unwrap());
+ assert_eq!(items.len(), 4);
+ let counts = count_by_origin(dir.path()).unwrap();
+ assert_eq!(counts["https://github.com"], 1);
+ assert_eq!(counts["https://a.example"], 3);
+ let find = |o: &str, k: &str| items.iter().find(|i| i.origin == o && i.key == k).unwrap();
+ assert_eq!(find("https://github.com", "color_mode").value, "dark");
+ assert_eq!(find("https://a.example", "日本").value, "こんにちは");
+ assert_eq!(find("https://a.example", "na\u{ef}ve").value, "caf\u{e9}");
+ let bad = find("https://a.example", "bad");
+ assert!(bad.value_raw.is_some(), "kept exactly, not guessed");
+ assert!(find("https://a.example", "日本").value_raw.is_none());
+ // The source directory was only read from a copy: still opens, no LOCK left behind by us.
+ assert!(dir.path().join("CURRENT").exists());
+ }
+
+ #[test]
+ fn write_then_read_round_trips_and_adds_version_and_meta() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = dir.path().join("Local Storage/leveldb");
+ let items = vec![
+ item("https://github.com", "color_mode", "dark"),
+ item("https://github.com", "tz", "Europe/Zurich"),
+ item("https://a.example", "日本", "こんにちは 🙂"),
+ LocalStorageItem {
+ origin: "https://a.example".into(),
+ key: "bad".into(),
+ value: "\u{fffd}".into(),
+ key_raw: None,
+ value_raw: Some(b64().encode([0u8, 0x00, 0xd8])),
+ },
+ ];
+ let w = write(&store, &items, 13_300_000_000_000_000).unwrap();
+ assert_eq!(w.keys.len(), 4);
+ assert_eq!(w.meta_keys.len(), 2, "one META per new origin");
+ assert_eq!(sorted(read(&store).unwrap()), sorted(items.clone()));
+ // The database Chrome opens has VERSION and META for each origin.
+ let mut db = DB::open(
+ &store,
+ Options {
+ create_if_missing: false,
+ ..Options::default()
+ },
+ )
+ .unwrap();
+ assert_eq!(&*db.get(b"VERSION").unwrap(), b"1");
+ assert!(db.get(b"META:https://github.com").is_some());
+ // Latin-1 where it fits, UTF-16 where it does not, as Chromium writes.
+ assert_eq!(
+ &*db.get(b"_https://github.com\x00\x01color_mode").unwrap(),
+ b"\x01dark"
+ );
+ db.close().unwrap();
+ // Writing again updates in place and keeps the existing META.
+ let again = write(
+ &store,
+ &[item("https://github.com", "color_mode", "light")],
+ 1,
+ )
+ .unwrap();
+ assert!(again.meta_keys.is_empty());
+ let now = read(&store).unwrap();
+ assert_eq!(now.len(), 4);
+ assert_eq!(
+ now.iter().find(|i| i.key == "color_mode").unwrap().value,
+ "light"
+ );
+ }
+
+ #[test]
+ fn writing_into_an_existing_chromium_store_keeps_what_was_there_and_wipe_removes_only_ours() {
+ let dir = tempfile::tempdir().unwrap();
+ chromium_store(dir.path(), false);
+ let w = write(
+ dir.path(),
+ &[item("https://new.example", "k", "v")],
+ 13_300_000_000_000_001,
+ )
+ .unwrap();
+ assert_eq!(read(dir.path()).unwrap().len(), 5);
+ assert_eq!(delete(dir.path(), &w.keys).unwrap(), 1);
+ assert_eq!(delete(dir.path(), &w.meta_keys).unwrap(), 1);
+ let left = read(dir.path()).unwrap();
+ assert_eq!(left.len(), 4);
+ assert!(left.iter().all(|i| i.origin != "https://new.example"));
+ }
+
+ #[test]
+ fn a_snappy_compressed_table_reads_as_chromium_writes_them() {
+ let dir = tempfile::tempdir().unwrap();
+ chromium_store(dir.path(), true);
+ assert!(
+ std::fs::read_dir(dir.path()).unwrap().any(|e| e
+ .unwrap()
+ .path()
+ .extension()
+ .is_some_and(|x| x == "ldb")),
+ "compaction wrote a table"
+ );
+ assert_eq!(read(dir.path()).unwrap().len(), 4);
+ }
+
+ #[test]
+ fn a_missing_store_is_no_items_and_a_locked_one_fails_clearly() {
+ let dir = tempfile::tempdir().unwrap();
+ assert!(read(&dir.path().join("none")).unwrap().is_empty());
+ let store = dir.path().join("s");
+ chromium_store(
+ &{
+ std::fs::create_dir_all(&store).unwrap();
+ store.clone()
+ },
+ false,
+ );
+ // Hold the lock like a running browser does.
+ let held = DB::open(&store, Options::default()).unwrap();
+ let err = write(&store, &[item("https://x.example", "k", "v")], 1).unwrap_err();
+ assert!(err.to_string().contains("close the browser"), "{err}");
+ drop(held);
+ }
+
+ #[test]
+ fn text_codec_matches_chromiums_choice() {
+ assert_eq!(encode_text("caf\u{e9}"), b"\x01caf\xe9");
+ assert_eq!(encode_text("日"), vec![0, 0xe5, 0x65]);
+ assert_eq!(decode_text(b"\x01abc"), ("abc".to_string(), true));
+ assert_eq!(decode_text(&[0, b'a', 0]), ("a".to_string(), true));
+ assert!(!decode_text(&[9, 1, 2]).1);
+ assert_eq!(parse_data_key(b"META:https://x"), None);
+ assert_eq!(parse_data_key(b"VERSION"), None);
+ }
+}
diff --git a/libs/cua/crates/cua-keyvault/src/broker.rs b/libs/cua/crates/cua-keyvault/src/broker.rs
index 05f9d4d4f3..113a47abf2 100644
--- a/libs/cua/crates/cua-keyvault/src/broker.rs
+++ b/libs/cua/crates/cua-keyvault/src/broker.rs
@@ -32,13 +32,13 @@ use crate::capability::{Action, Capability, Caveat, VerifyContext};
use crate::crypto::{self, SecretKey};
use crate::model::{
DEFAULT_GRANT_SECS, DEFAULT_RULE_SECS, Delivery, Grant, ItemKind, ItemMeta, ItemPayload,
- ItemPolicy, ItemSummary, MAX_TTL_SECS, RuleCaller, Settings, UnattendedRule, UnlockPolicy,
+ ItemPolicy, MAX_TTL_SECS, PayloadEntry, RuleCaller, Settings, UnattendedRule, UnlockPolicy,
};
use crate::policy::{self, Authority};
use crate::protector::{
PassphraseProtector, Protector, ProtectorKind, RecoveryKey, RecoveryProtector,
};
-use crate::store::Vault;
+use crate::store::{UpsertOutcome, Vault};
use crate::{Error, Result};
/// Pending consent requests per caller (per budget bucket).
@@ -123,17 +123,16 @@ pub enum Selector {
/// Item id.
id: String,
},
- /// One site of a browser (`app`: `chrome`, `firefox`).
+ /// Every cookie, storage value and file one site of an app holds
+ /// (`app`: `chrome`, `firefox`).
Site {
/// Provider id.
app: String,
/// Registrable domain (`github.com`).
site: String,
- /// Account, when known.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- account: Option<String>,
},
- /// A whole app session (`slack`, `discord`, `claude-code`).
+ /// Everything an app holds that can be delivered (`slack`, `discord`,
+ /// `chrome`): its cookies, storage values and files, never passwords.
App {
/// Provider id.
app: String,
@@ -150,16 +149,21 @@ impl Selector {
fn matches(&self, item: &ItemMeta) -> bool {
match self {
Selector::Item { id } => &item.id == id,
- Selector::Site { app, site, account } => {
- item.kind == ItemKind::BrowserSite
+ Selector::Site { app, site } => {
+ item.kind.deliverable()
&& &item.provider_id == app
- && item.site.as_deref() == Some(site.as_str())
- && (account.is_none() || item.account == *account)
+ && item
+ .domain
+ .as_deref()
+ .is_some_and(|d| host_in_site(&crate::record::host_of(d), site))
}
- Selector::App { app } => item.kind == ItemKind::AppSession && &item.provider_id == app,
+ Selector::App { app } => item.kind.deliverable() && &item.provider_id == app,
Selector::Login { site } => {
- item.kind == ItemKind::SitePasswords
- && item.site.as_deref().is_some_and(|s| host_in_site(site, s))
+ item.kind == ItemKind::Password
+ && item.domain.as_deref().is_some_and(|d| {
+ let h = crate::record::host_of(d);
+ host_in_site(&h, site) || host_in_site(site, &h)
+ })
}
}
}
@@ -224,26 +228,52 @@ pub struct ImportSpec {
/// independent selection mechanism.
#[serde(default)]
pub paths: Option<Vec<String>>,
+ /// The registrable domains whose cookies, storage values and passwords
+ /// to keep, the review sheet's per-domain choice. `None` keeps
+ /// everything the capture read (or what `sites` names); `Some` keeps
+ /// only these, even if empty.
+ #[serde(default)]
+ pub domains: Option<Vec<String>>,
+ /// Also read the browser's saved passwords for `domains` (every site when
+ /// `None`) and deliver them. Only the review's explicit choice sets this;
+ /// it needs `confirm_passwords`, and the passwords are re-encrypted for
+ /// the destination browser's own key.
+ #[serde(default)]
+ pub passwords: bool,
}
-/// One importable thing, as the inventory shows it.
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
-pub struct Candidate {
- /// Kind.
- pub kind: ItemKind,
- /// Site (browsers) or `None` (whole app).
+/// One domain a browser holds secrets for, as the inventory shows it:
+/// counts only, never values.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DomainInventory {
+ /// Registrable domain (`github.com`).
+ pub domain: String,
+ /// Cookies.
+ #[serde(default)]
+ pub cookies: u32,
+ /// Cookies without an expiry (they die with the browser session).
+ #[serde(default)]
+ pub session_cookies: u32,
+ /// localStorage values.
+ #[serde(default)]
+ pub local_storage: u32,
+ /// Saved passwords.
#[serde(default)]
- pub site: Option<String>,
- /// Account or workspace names, when detectable.
+ pub passwords: u32,
+ /// Looks like it keeps a sign-in (a session or auth cookie): what a
+ /// minimal teleport carries.
#[serde(default)]
- pub accounts: Vec<String>,
- /// Label.
- pub label: String,
- /// Contents, without values.
- pub summary: ItemSummary,
- /// Warnings (device-bound sessions and so on).
+ pub signin: bool,
+ /// An identity provider (its session unlocks other apps).
#[serde(default)]
- pub warnings: Vec<String>,
+ pub identity_provider: bool,
+ /// Cookies this build cannot read (Chrome's app-bound encryption): listed
+ /// so a review can grey them out and say why, never sent.
+ #[serde(default)]
+ pub unavailable: u32,
+ /// Why they cannot be read (empty when none).
+ #[serde(default)]
+ pub unavailable_reason: String,
}
/// What a host app offers.
@@ -256,8 +286,10 @@ pub struct Inventory {
/// Profile read.
#[serde(default)]
pub profile: Option<String>,
- /// Candidates. Nothing is selected by default.
- pub candidates: Vec<Candidate>,
+ /// Domains with secrets, with counts. Empty for an app that is not a
+ /// browser. Nothing is selected by default.
+ #[serde(default)]
+ pub domains: Vec<DomainInventory>,
/// Notes.
#[serde(default)]
pub notes: Vec<String>,
@@ -338,13 +370,15 @@ pub trait Backend: Send + Sync {
fn inventory(&self, app: &str, profile: Option<&str>) -> Result<Inventory>;
/// Captures the chosen items. Blocking. Called only after user presence.
fn capture(&self, spec: &ImportSpec) -> Result<Vec<Captured>>;
- /// Builds one bundle from same-provider payloads and imports it into
- /// `target`; the receiver wipes it on its own at `expires_ms`.
+ /// Builds one bundle from the entries a codec made of same-provider
+ /// records and imports it into `target`; the receiver wipes it on its
+ /// own at `expires_ms`. `scope` is `tabs` or `full`.
async fn deliver(
&self,
target: &str,
provider_id: &str,
- payloads: Vec<ItemPayload>,
+ scope: &str,
+ entries: Vec<PayloadEntry>,
expires_ms: u64,
) -> Result<DeliveryOutcome>;
/// [`Self::deliver`], telling `stage` when it packs, uploads (with
@@ -353,35 +387,48 @@ pub trait Backend: Send + Sync {
&self,
target: &str,
provider_id: &str,
- payloads: Vec<ItemPayload>,
+ scope: &str,
+ entries: Vec<PayloadEntry>,
expires_ms: u64,
stage: StageSink,
) -> Result<DeliveryOutcome> {
let _ = stage;
- self.deliver(target, provider_id, payloads, expires_ms)
+ self.deliver(target, provider_id, scope, entries, expires_ms)
.await
}
/// [`Self::deliver_with_progress`], also asking the receiver to launch the
/// imported app in the Space's logged-in GUI session (`launch`). The
/// default ignores `launch` (a backend that cannot launch reports
/// `launched: false` in its [`DeliveryOutcome`]).
+ #[allow(clippy::too_many_arguments)]
async fn deliver_launching(
&self,
target: &str,
provider_id: &str,
- payloads: Vec<ItemPayload>,
+ scope: &str,
+ entries: Vec<PayloadEntry>,
expires_ms: u64,
stage: StageSink,
launch: bool,
) -> Result<DeliveryOutcome> {
let _ = launch;
- self.deliver_with_progress(target, provider_id, payloads, expires_ms, stage)
+ self.deliver_with_progress(target, provider_id, scope, entries, expires_ms, stage)
.await
}
/// Wipes an earlier import from `target`.
async fn wipe(&self, target: &str, import_id: &str) -> Result<Vec<String>>;
/// Tells the UI a consent request is waiting (open the Keyvault page).
fn notify_consent(&self, _pending: &PendingView) {}
+ /// The icons of `sites` from the source app's own local store, as
+ /// `(site, png)`. Never from the network. Blocking. The default has none.
+ fn favicons(
+ &self,
+ _app: &str,
+ _profile: Option<&str>,
+ _sites: &[String],
+ ) -> Result<Vec<(String, Vec<u8>)>> {
+ Ok(Vec::new())
+ }
/// Reads a browser profile's saved passwords, one
/// [`ItemKind::SitePasswords`] item per site whose payload holds only
/// [`crate::model::LOGINS_ENTRY`]. Blocking. Called only after user
@@ -689,6 +736,15 @@ pub struct TeleportRequest {
pub items: Vec<String>,
/// Target Space.
pub target: String,
+ /// Launch the delivered app in the Space once it is imported (the
+ /// teleport's `launch_after`); a backend that cannot launch ignores it.
+ #[serde(default)]
+ pub launch: bool,
+ /// Deliver the saved passwords among `items` too. Only the Cua app's own
+ /// interactive request may set this (the user ticked them in the review);
+ /// a token or a rule never delivers a password, whatever it names.
+ #[serde(default)]
+ pub include_passwords: bool,
}
/// What a teleport did.
@@ -745,6 +801,17 @@ pub struct Status {
/// it. Empty when there is no vault.
#[serde(default)]
pub unlock_protectors: Vec<ProtectorKind>,
+ /// The browse window is open until this time, Unix ms (first party
+ /// only): item names are visible until then.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub browse_until_ms: Option<u64>,
+ /// "Never ask again" on the unlock prompt is on (first party only).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub skip_unlock_prompt: Option<bool>,
+ /// Set when an earlier preview's vault was found and set aside, so a
+ /// new one is created (one line for the UI).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub reset_notice: Option<String>,
}
/// Creating a vault. Its `Debug` never prints the passphrase, and the
@@ -829,6 +896,63 @@ pub struct RuleSpec {
pub note: String,
}
+/// A site's icon (`png`: base64).
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SiteIcon {
+ /// The site.
+ pub site: String,
+ /// PNG, base64.
+ pub png: String,
+}
+
+/// The most items one save, delete or lock call takes.
+pub const MAX_ITEMS_PER_SAVE: usize = 100_000;
+
+/// What storing a capture did.
+struct Stored {
+ items: Vec<ItemMeta>,
+ /// Ids of the items that did not exist before.
+ created: Vec<String>,
+ report: ImportReport,
+}
+
+/// What saving into the vault did, in counts (the vault upserts by key:
+/// saving the same app again updates its items and never duplicates them).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ImportReport {
+ /// Items saved or refreshed.
+ pub saved: usize,
+ /// New items.
+ pub created: usize,
+ /// Existing items whose value changed.
+ pub updated: usize,
+ /// Existing items saved again with the same value.
+ pub unchanged: usize,
+}
+
+/// The most items one [`Broker::list_items`] page returns.
+pub const MAX_PAGE: usize = 1000;
+
+/// One page of items.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ItemPage {
+ /// The page.
+ pub items: Vec<ItemMeta>,
+ /// Items in the vault.
+ pub total: usize,
+ /// The browse window is open: domains and keys are present.
+ pub names_visible: bool,
+}
+
+/// What [`Broker::set_locked`] changed.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LockOutcome {
+ /// Items whose lock changed.
+ pub changed: Vec<String>,
+ /// Identity provider items asked to unlock: they always ask.
+ pub skipped: Vec<String>,
+}
+
/// Broker configuration.
#[derive(Clone, Debug)]
pub struct BrokerConfig {
@@ -856,6 +980,10 @@ struct State {
/// Consent-request timestamps across every caller (global rate limit).
global_requests: VecDeque<u64>,
presence_until_ms: u64,
+ /// The browse window: until this time the first-party list returns item
+ /// names (domains and keys), opened with user presence. Closed, it
+ /// returns the app, type and lock state only.
+ browse_until_ms: u64,
/// Callers verified during this run (rules may name them).
seen: HashMap<String, CallerIdentity>,
}
@@ -875,6 +1003,8 @@ pub struct Broker {
/// Why this daemon cannot create the OS key store protector (`None`: it
/// can). Computed once: the daemon's own signature does not change.
os_enroll_block: std::sync::OnceLock<Option<String>>,
+ /// See [`Status::reset_notice`].
+ reset_notice: Option<String>,
}
fn uid() -> Result<String> {
@@ -920,12 +1050,40 @@ impl Broker {
backend: Arc<dyn Backend>,
presence: Arc<dyn UserPresence>,
) -> Result<Self> {
+ let mut reset_notice = None;
let vault = if Vault::exists(&cfg.dir) {
- Some(Vault::open(&cfg.dir)?.with_anchor(generation_anchor(&cfg))?)
+ match Vault::open(&cfg.dir) {
+ Ok(v) => Some(v.with_anchor(generation_anchor(&cfg))?),
+ // A vault from an earlier preview (whole-app items) is not
+ // migrated. It is set aside, not deleted, and a new one is
+ // set up.
+ Err(Error::OldFormat(f)) => {
+ let name = cfg
+ .dir
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_else(|| "keyvault".into());
+ let aside = cfg.dir.with_file_name(format!("{name}.preview-v{f}"));
+ let aside = if aside.exists() {
+ cfg.dir
+ .with_file_name(format!("{name}.preview-v{f}-{}", crate::now_ms()))
+ } else {
+ aside
+ };
+ std::fs::rename(&cfg.dir, &aside).map_err(|_| Error::OldFormat(f))?;
+ reset_notice = Some(format!(
+ "An earlier preview's Keyvault was set aside at {}. Set up a new one.",
+ aside.display()
+ ));
+ None
+ }
+ Err(e) => return Err(e),
+ }
} else {
None
};
Ok(Self {
+ reset_notice,
cfg,
backend,
presence,
@@ -1129,6 +1287,17 @@ impl Broker {
},
os_protector_available: self.os_enroll_block().is_none(),
passphrase_available: true,
+ browse_until_ms: if fp && crate::now_ms() < st.browse_until_ms {
+ Some(st.browse_until_ms)
+ } else {
+ None
+ },
+ skip_unlock_prompt: if fp {
+ meta.map(|m| m.settings.skip_unlock_prompt)
+ } else {
+ None
+ },
+ reset_notice: self.reset_notice.clone(),
unlock_protectors: match (&st.vault, fp) {
(Some(v), true) => {
let os_ok = self.os_use_block().is_none();
@@ -1325,6 +1494,7 @@ impl Broker {
v.lock();
}
st.presence_until_ms = 0;
+ st.browse_until_ms = 0;
Ok(())
}
@@ -1434,55 +1604,95 @@ impl Broker {
// Items
// ------------------------------------------------------------------
- /// Every item's coarse metadata (first party). Never payloads, and never
- /// the cookie names, domains or storage origins: bulk enumeration returns
- /// only labels and counts, so an injected or confused-deputy first-party
- /// client cannot harvest the user's whole logged-in map without presence
- /// (red-team F17). Per-item detail comes from [`Broker::describe_item`],
- /// which requires presence.
- pub async fn list_items(&self, caller: &CallerIdentity) -> Result<Vec<ItemMeta>> {
- policy::require_first_party(caller, "listing Keyvault items")?;
+ /// How long a browse window stays open once the user confirmed presence.
+ pub const BROWSE_WINDOW_MS: u64 = 5 * 60_000;
+
+ /// Opens the browse window (first party + user presence): for a few
+ /// minutes [`Broker::list_items`] returns item names (domains and
+ /// keys) as well as apps, types and lock states. Returns when the
+ /// window closes, Unix ms. Names are a sensitive map of the user's
+ /// logged-in life, so the bulk list never has them without this
+ /// (red-team F17). Values are never returned, here or anywhere.
+ pub async fn browse(&self, caller: &CallerIdentity) -> Result<u64> {
+ policy::require_first_party(caller, "browsing the Keyvault")?;
self.ensure_session(caller).await?;
- let mut st = self.state.lock().await;
- Ok(Self::vault_mut(&mut st)?
- .meta()?
- .items
- .values()
- .map(|i| i.redacted())
- .collect())
- }
-
- /// One item's full metadata, including cookie names and domains and storage
- /// origins (first party + user presence). This detail set is a sensitive
- /// map of the user's logged-in life, so it is gated on presence even for a
- /// first party, whose address space may have been injected (red-team
- /// F17/F3). Never returns payload values.
- pub async fn describe_item(&self, caller: &CallerIdentity, id: &str) -> Result<ItemMeta> {
- policy::require_first_party(caller, "reading item detail")?;
- let label = {
+ {
let mut st = self.state.lock().await;
- Self::vault_mut(&mut st)?
- .meta()?
- .items
- .get(id)
- .map(|i| i.label.clone())
- .ok_or_else(|| Error::NotFound(format!("item {id}")))?
- };
+ Self::vault_mut(&mut st)?;
+ }
self.confirm(format!(
- "Show the saved cookie names and domains for {label} ({})",
+ "Show what the Cua Keyvault holds ({})",
caller.display()
))
.await?;
+ let until = crate::now_ms() + Self::BROWSE_WINDOW_MS;
let mut st = self.state.lock().await;
- Self::vault_mut(&mut st)?
- .meta()?
- .items
- .get(id)
- .cloned()
- .ok_or_else(|| Error::NotFound(format!("item {id}")))
+ Self::vault_mut(&mut st)?;
+ st.browse_until_ms = until;
+ Self::audit(&mut st, ev("vault.browse", caller, "ok"));
+ Ok(until)
+ }
+
+ /// Closes the browse window now.
+ pub async fn end_browse(&self, caller: &CallerIdentity) -> Result<()> {
+ policy::require_first_party(caller, "browsing the Keyvault")?;
+ self.state.lock().await.browse_until_ms = 0;
+ Ok(())
+ }
+
+ /// Opens the browse window unless it is already open.
+ async fn ensure_browsing(&self, caller: &CallerIdentity) -> Result<()> {
+ let open = crate::now_ms() < self.state.lock().await.browse_until_ms;
+ if open {
+ return Ok(());
+ }
+ self.browse(caller).await.map(|_| ())
+ }
+
+ /// One page of the vault's items (first party), ordered by app, domain
+ /// and key. Inside the browse window ([`Broker::browse`]) they carry
+ /// their domains and keys; outside it they carry only the app, type,
+ /// lock state and timestamps, so an injected or confused-deputy
+ /// first-party client cannot harvest the user's logged-in map without
+ /// presence (red-team F17). Never payloads.
+ pub async fn list_items(
+ &self,
+ caller: &CallerIdentity,
+ offset: usize,
+ limit: usize,
+ ) -> Result<ItemPage> {
+ policy::require_first_party(caller, "listing Keyvault items")?;
+ self.ensure_session(caller).await?;
+ let mut st = self.state.lock().await;
+ let names = crate::now_ms() < st.browse_until_ms;
+ let meta = Self::vault_mut(&mut st)?.meta()?;
+ let mut all: Vec<&ItemMeta> = meta.items.values().collect();
+ all.sort_by(|a, b| {
+ (&a.provider_id, &a.domain, a.kind, &a.key, &a.id).cmp(&(
+ &b.provider_id,
+ &b.domain,
+ b.kind,
+ &b.key,
+ &b.id,
+ ))
+ });
+ let total = all.len();
+ let items = all
+ .into_iter()
+ .skip(offset)
+ .take(limit.clamp(1, MAX_PAGE))
+ .map(|i| if names { i.clone() } else { i.redacted() })
+ .collect();
+ Ok(ItemPage {
+ items,
+ total,
+ names_visible: names,
+ })
}
- /// What a host app offers, per site (first party; reads metadata only).
+ /// What a host app offers, per domain, with counts (first party; needs
+ /// the browse window, so it asks for presence when that is closed).
+ /// Reads metadata only, never values.
pub async fn inventory(
&self,
caller: &CallerIdentity,
@@ -1490,6 +1700,7 @@ impl Broker {
profile: Option<&str>,
) -> Result<Inventory> {
policy::require_first_party(caller, "reading host apps")?;
+ self.ensure_browsing(caller).await?;
let b = self.backend.clone();
let (app, profile) = (app.to_string(), profile.map(str::to_string));
tokio::task::spawn_blocking(move || b.inventory(&app, profile.as_deref()))
@@ -1499,7 +1710,7 @@ impl Broker {
/// Imports sites or an app session into the vault (first party +
/// presence). Each site becomes its own item.
- pub async fn import(&self, caller: &CallerIdentity, spec: ImportSpec) -> Result<Vec<ItemMeta>> {
+ pub async fn import(&self, caller: &CallerIdentity, spec: ImportSpec) -> Result<ImportReport> {
let r = self.import_inner(caller, spec).await;
self.record_action(KeyvaultAction::Import, KeyvaultMethod::None, &r);
r
@@ -1509,7 +1720,7 @@ impl Broker {
&self,
caller: &CallerIdentity,
spec: ImportSpec,
- ) -> Result<Vec<ItemMeta>> {
+ ) -> Result<ImportReport> {
policy::require_first_party(caller, "importing into the Keyvault")?;
{
let st = self.state.lock().await;
@@ -1519,7 +1730,8 @@ impl Broker {
}
let reason = import_reason(&spec, caller);
self.confirm(reason).await?;
- self.import_confirmed(caller, spec).await
+ let captured = self.capture_confirmed(spec).await?;
+ Ok(self.store_captured(caller, captured).await?.report)
}
async fn import_confirmed(
@@ -1528,7 +1740,7 @@ impl Broker {
spec: ImportSpec,
) -> Result<Vec<ItemMeta>> {
let captured = self.capture_confirmed(spec).await?;
- self.store_captured(caller, captured).await
+ Ok(self.store_captured(caller, captured).await?.items)
}
/// The capture half of [`Self::import_confirmed`] (after presence):
@@ -1624,6 +1836,7 @@ impl Broker {
}
}
validate_target(&target)?;
+ let with_passwords = spec.passwords && spec.confirm_passwords;
let reason = format!(
"Teleport {} to {} ({})",
describe_spec(&spec),
@@ -1636,7 +1849,8 @@ impl Broker {
if save {
tell(TeleportStage::Saving);
}
- let items = self.store_captured(caller, captured).await?;
+ let stored = self.store_captured(caller, captured).await?;
+ let items = stored.items;
let item_ids: Vec<String> = items.iter().map(|m| m.id.clone()).collect();
if item_ids.is_empty() {
return Err(Error::Invalid(
@@ -1653,6 +1867,8 @@ impl Broker {
token: None,
items: item_ids.clone(),
target: target.clone(),
+ include_passwords: with_passwords,
+ launch: false,
};
let result = self
.teleport_inner(
@@ -1664,31 +1880,32 @@ impl Broker {
)
.await;
crate::telemetry::teleport(&self.telemetry, caller, &app, started, &result, n);
- if !save {
- for id in &item_ids {
- if let Err(e) = self.forget_item(caller, id).await {
- tracing::warn!(
- item = %id,
- error = %e,
- "keyvault: could not forget an unsaved item after teleport"
- );
- }
+ if !save && !stored.created.is_empty() {
+ // Only what this call added is forgotten; an item that was
+ // already saved stays (and holds the value just read).
+ if let Err(e) = self.forget_items(caller, &stored.created).await {
+ tracing::warn!(
+ error = %e,
+ "keyvault: could not forget unsaved items after teleport"
+ );
}
}
result
}
- /// Crypto-shreds `id`'s vault record (like [`Self::delete_item`]) but
- /// never wipes a delivery it already made: used only by
+ /// Crypto-shreds these vault records (like [`Self::delete_items`]) but
+ /// never wipes a delivery they already made: used only by
/// [`Self::import_and_teleport`]'s `save: false`, where the point is to
/// forget the vault copy while leaving what was just delivered in place.
- async fn forget_item(&self, caller: &CallerIdentity, id: &str) -> Result<()> {
- policy::require_first_party(caller, "forgetting an unsaved Keyvault item")?;
+ async fn forget_items(&self, caller: &CallerIdentity, ids: &[String]) -> Result<()> {
+ policy::require_first_party(caller, "forgetting unsaved Keyvault items")?;
let mut st = self.state.lock().await;
- Self::vault_mut(&mut st)?.delete_item(id)?;
+ Self::vault_mut(&mut st)?.delete_items(ids)?;
let mut e = ev("item.delete", caller, "ok");
- e.item = Some(id.into());
- e.detail = "not saved (import_and_teleport save=false)".into();
+ e.detail = format!(
+ "not saved (import_and_teleport save=false) count={}",
+ ids.len()
+ );
Self::audit(&mut st, e);
Ok(())
}
@@ -1701,7 +1918,7 @@ impl Broker {
&self,
caller: &CallerIdentity,
spec: PasswordImportSpec,
- ) -> Result<Vec<ItemMeta>> {
+ ) -> Result<ImportReport> {
let r = self.import_passwords_inner(caller, spec).await;
self.record_action(KeyvaultAction::Import, KeyvaultMethod::None, &r);
r
@@ -1711,7 +1928,7 @@ impl Broker {
&self,
caller: &CallerIdentity,
spec: PasswordImportSpec,
- ) -> Result<Vec<ItemMeta>> {
+ ) -> Result<ImportReport> {
policy::require_first_party(caller, "importing saved passwords")?;
if spec.app.trim().is_empty() {
return Err(Error::Invalid("name the browser to import from".into()));
@@ -1738,71 +1955,282 @@ impl Broker {
let captured = tokio::task::spawn_blocking(move || b.capture_passwords(&spec2))
.await
.map_err(|e| Error::Backend(e.to_string()))??;
- self.store_captured(caller, captured).await
+ Ok(self.store_captured(caller, captured).await?.report)
}
async fn store_captured(
&self,
caller: &CallerIdentity,
captured: Vec<Captured>,
- ) -> Result<Vec<ItemMeta>> {
+ ) -> Result<Stored> {
+ if captured.len() > MAX_ITEMS_PER_SAVE {
+ return Err(Error::Invalid(format!(
+ "{} items in one save; the limit is {MAX_ITEMS_PER_SAVE}",
+ captured.len()
+ )));
+ }
+ let mut batch = Vec::with_capacity(captured.len());
+ for c in captured {
+ let mut m = c.meta;
+ if m.key.is_empty() {
+ return Err(Error::Invalid("an item needs a key".into()));
+ }
+ if !m.kind.keyed_by_path() && m.domain.as_deref().is_none_or(str::is_empty) {
+ return Err(Error::Invalid(format!(
+ "a {} item needs a domain",
+ m.kind.label().to_lowercase()
+ )));
+ }
+ if m.kind.keyed_by_path() {
+ m.domain = None;
+ }
+ m.identity_provider = m
+ .domain
+ .as_deref()
+ .is_some_and(crate::model::is_identity_provider);
+ if m.identity_provider {
+ m.policy.ttl_secs = m.policy.ttl_secs.min(crate::model::IDP_TTL_SECS);
+ m.policy.unattended = false;
+ }
+ batch.push((m, c.payload));
+ }
+ // Site icons, from the browser's own local store (never the network).
+ let icons = self.capture_favicons(&batch).await;
let mut st = self.state.lock().await;
let v = Self::vault_mut(&mut st)?;
- let mut out = Vec::new();
- for c in captured {
- // Re-importing the same site replaces the old item's payload and
- // keeps its id, policy and grants.
- let existing = v
- .meta()?
- .items
- .values()
- .find(|i| {
- i.provider_id == c.meta.provider_id
- && i.kind == c.meta.kind
- && i.site == c.meta.site
- && i.account == c.meta.account
- && i.source == c.meta.source
- })
- .map(|i| i.id.clone());
- let id = match existing {
- Some(id) => {
- v.replace_payload(&id, &c.payload)?;
- let summary = c.meta.summary.clone();
- let warnings = c.meta.warnings.clone();
- v.update_meta(|m| {
- let it = m.items.get_mut(&id).expect("exists");
- it.summary = summary;
- it.warnings = warnings;
- Ok(())
- })?;
- id
- }
- None => v.put_item(c.meta, &c.payload)?,
- };
- out.push(v.meta()?.items[&id].clone());
+ // Saving the same app again upserts by key: same item, same lock.
+ let saved = v.upsert_items(batch)?;
+ if let Err(e) = v.set_favicons(icons) {
+ tracing::warn!(error = %e, "keyvault: could not keep site icons");
}
- for it in &out {
- let mut e = ev("item.import", caller, "ok");
- e.item = Some(it.id.clone());
- Self::audit(&mut st, e);
+ let meta = v.meta()?;
+ let items: Vec<ItemMeta> = saved.iter().map(|u| meta.items[&u.id].clone()).collect();
+ let count = |o: UpsertOutcome| saved.iter().filter(|u| u.outcome == o).count();
+ let created: Vec<String> = saved
+ .iter()
+ .filter(|u| u.outcome == UpsertOutcome::Created)
+ .map(|u| u.id.clone())
+ .collect();
+ let mut e = ev("item.import", caller, "ok");
+ e.detail = format!(
+ "items={} created={} updated={} unchanged={}",
+ saved.len(),
+ created.len(),
+ count(UpsertOutcome::Updated),
+ count(UpsertOutcome::Unchanged)
+ );
+ Self::audit(&mut st, e);
+ let report = ImportReport {
+ saved: saved.len(),
+ created: created.len(),
+ updated: count(UpsertOutcome::Updated),
+ unchanged: count(UpsertOutcome::Unchanged),
+ };
+ Ok(Stored {
+ items,
+ created,
+ report,
+ })
+ }
+
+ /// Icons for the sites of what is about to be saved. Best effort: a
+ /// missing or unreadable store means the globe stands in.
+ async fn capture_favicons(&self, batch: &[(ItemMeta, ItemPayload)]) -> Vec<(String, String)> {
+ use base64::Engine as _;
+ let Some((first, _)) = batch.first() else {
+ return Vec::new();
+ };
+ let (app, source) = (first.provider_id.clone(), first.source.clone());
+ let mut sites: Vec<String> = batch
+ .iter()
+ .filter(|(m, _)| m.provider_id == app)
+ .filter_map(|(m, _)| m.domain.as_deref().map(crate::record::site_of))
+ .filter(|s| !s.is_empty())
+ .collect();
+ sites.sort();
+ sites.dedup();
+ if sites.is_empty() {
+ return Vec::new();
}
- Ok(out)
+ let b = self.backend.clone();
+ let profile = (!source.is_empty() && source != "default").then_some(source);
+ let r =
+ tokio::task::spawn_blocking(move || b.favicons(&app, profile.as_deref(), &sites)).await;
+ match r {
+ Ok(Ok(v)) => v
+ .into_iter()
+ .map(|(s, png)| (s, base64::engine::general_purpose::STANDARD.encode(png)))
+ .collect(),
+ _ => Vec::new(),
+ }
+ }
+
+ /// Site icons for the list (first party; needs the browse window, since
+ /// the sites are names). `png` is base64.
+ pub async fn list_favicons(&self, caller: &CallerIdentity) -> Result<Vec<SiteIcon>> {
+ policy::require_first_party(caller, "listing site icons")?;
+ let mut st = self.state.lock().await;
+ let open = crate::now_ms() < st.browse_until_ms;
+ let meta = Self::vault_mut(&mut st)?.meta()?;
+ if !open {
+ return Ok(Vec::new());
+ }
+ Ok(meta
+ .favicons
+ .iter()
+ .map(|(site, png)| SiteIcon {
+ site: site.clone(),
+ png: png.clone(),
+ })
+ .collect())
}
- /// Deletes an item and wipes its live deliveries (first party).
- pub async fn delete_item(&self, caller: &CallerIdentity, id: &str) -> Result<Vec<String>> {
+ /// Deletes items (first party) and wipes every live copy of them in
+ /// every Space, then shreds the vault records. Nothing is deleted when
+ /// any id is unknown. Returns the wiped import ids.
+ pub async fn delete_items(
+ &self,
+ caller: &CallerIdentity,
+ ids: Vec<String>,
+ ) -> Result<Vec<String>> {
policy::require_first_party(caller, "deleting Keyvault items")?;
+ if ids.is_empty() || ids.len() > MAX_ITEMS_PER_SAVE {
+ return Err(Error::Invalid("name the items to delete".into()));
+ }
+ {
+ let mut st = self.state.lock().await;
+ let meta = Self::vault_mut(&mut st)?.meta()?;
+ if let Some(missing) = ids.iter().find(|i| !meta.items.contains_key(*i)) {
+ return Err(Error::NotFound(format!("item {missing}")));
+ }
+ }
let wiped = self
- .wipe_where(caller, |d| d.items.iter().any(|i| i == id))
+ .wipe_where(caller, |d| d.items.iter().any(|i| ids.contains(i)))
.await?;
let mut st = self.state.lock().await;
- Self::vault_mut(&mut st)?.delete_item(id)?;
+ let removed = Self::vault_mut(&mut st)?.delete_items(&ids)?;
let mut e = ev("item.delete", caller, "ok");
- e.item = Some(id.into());
+ if let [only] = removed.as_slice() {
+ e.item = Some(only.id.clone());
+ }
+ e.detail = format!("count={} wiped={}", removed.len(), wiped.len());
Self::audit(&mut st, e);
Ok(wiped)
}
+ /// Locks or unlocks items (first party). Locked is the default: every
+ /// use needs the user's approval. Unlocked allows unattended access:
+ /// any agent with access to the Cua Spaces MCP may have the item
+ /// written into the user's connected Spaces without asking each time.
+ /// The secrets are never sent to the agent, only delivered into Spaces.
+ ///
+ /// Unlocking widens access, so it asks for user presence ONCE for the
+ /// whole batch. Locking narrows it and does not; it also revokes the
+ /// unattended grants still alive for those items. An identity provider
+ /// item always asks and is reported in [`LockOutcome::skipped`].
+ pub async fn set_locked(
+ &self,
+ caller: &CallerIdentity,
+ ids: Vec<String>,
+ locked: bool,
+ ) -> Result<LockOutcome> {
+ policy::require_first_party(caller, "locking Keyvault items")?;
+ if ids.is_empty() || ids.len() > MAX_ITEMS_PER_SAVE {
+ return Err(Error::Invalid("name the items to lock or unlock".into()));
+ }
+ let mut seen = std::collections::HashSet::new();
+ let ids: Vec<String> = ids.into_iter().filter(|i| seen.insert(i.clone())).collect();
+ let (changed, skipped) = {
+ let mut st = self.state.lock().await;
+ if !locked && Self::settings(&st)?.disabled {
+ return Err(Error::Disabled);
+ }
+ let meta = Self::vault_mut(&mut st)?.meta()?;
+ let mut changed = Vec::new();
+ let mut skipped = Vec::new();
+ for id in &ids {
+ let it = meta
+ .items
+ .get(id)
+ .ok_or_else(|| Error::NotFound(format!("item {id}")))?;
+ if locked {
+ if !it.locked() {
+ changed.push(id.clone());
+ }
+ } else if it.identity_provider {
+ skipped.push(id.clone());
+ } else if it.locked() {
+ changed.push(id.clone());
+ }
+ }
+ (changed, skipped)
+ };
+ if changed.is_empty() {
+ return Ok(LockOutcome { changed, skipped });
+ }
+ if !locked {
+ self.confirm(format!(
+ "Allow unattended access to {} Keyvault item{}: any agent with the Cua Spaces MCP may write {} into your connected Spaces ({})",
+ changed.len(),
+ if changed.len() == 1 { "" } else { "s" },
+ if changed.len() == 1 { "it" } else { "them" },
+ caller.display()
+ ))
+ .await?;
+ }
+ let mut st = self.state.lock().await;
+ let v = Self::vault_mut(&mut st)?;
+ v.update_meta(|m| {
+ for id in &changed {
+ let it = m
+ .items
+ .get_mut(id)
+ .ok_or_else(|| Error::NotFound(format!("item {id}")))?;
+ it.policy.unattended = !locked;
+ }
+ if locked {
+ // Rules and unattended grants that relied on the unlock lose
+ // the item (and a grant left with nothing is revoked).
+ for r in &mut m.rules {
+ r.items.retain(|i| !changed.contains(i));
+ }
+ m.rules.retain(|r| !r.items.is_empty());
+ for g in m.grants.iter_mut().filter(|g| g.unattended) {
+ if g.items.iter().any(|i| changed.contains(i)) {
+ g.revoked = true;
+ }
+ }
+ }
+ Ok(())
+ })?;
+ let mut e = ev(
+ if locked { "item.lock" } else { "item.unlock" },
+ caller,
+ "ok",
+ );
+ e.detail = format!("count={}", changed.len());
+ Self::audit(&mut st, e);
+ Ok(LockOutcome { changed, skipped })
+ }
+
+ /// "Never ask again" on the unlock prompt (first party): the app skips
+ /// its explanation of what unlocking allows. It never skips the
+ /// presence check [`Broker::set_locked`] asks for, and turning it off
+ /// again (Settings) restores the prompt. Nothing is widened by it.
+ pub async fn set_skip_unlock_prompt(&self, caller: &CallerIdentity, on: bool) -> Result<()> {
+ policy::require_first_party(caller, "changing Keyvault settings")?;
+ let mut st = self.state.lock().await;
+ let v = Self::vault_mut(&mut st)?;
+ v.update_meta(|m| {
+ m.settings.skip_unlock_prompt = on;
+ Ok(())
+ })?;
+ let mut e = ev("settings.update", caller, "ok");
+ e.detail = format!("skip_unlock_prompt={on}");
+ Self::audit(&mut st, e);
+ Ok(())
+ }
+
/// Sets an item's policy (first party; widening needs presence).
pub async fn set_item_policy(
&self,
@@ -1812,7 +2240,7 @@ impl Broker {
) -> Result<ItemMeta> {
policy::require_first_party(caller, "changing item policies")?;
new.ttl_secs = new.ttl_secs.clamp(60, MAX_TTL_SECS);
- let (old, label) = {
+ let (old, label, idp) = {
let mut st = self.state.lock().await;
let it = Self::vault_mut(&mut st)?
.meta()?
@@ -1820,8 +2248,13 @@ impl Broker {
.get(id)
.cloned()
.ok_or_else(|| Error::NotFound(format!("item {id}")))?;
- (it.policy.clone(), it.label.clone())
+ (it.policy.clone(), it.label(), it.identity_provider)
};
+ if idp && new.unattended {
+ return Err(Error::Forbidden(
+ "identity provider sessions always ask; they cannot be unlocked".into(),
+ ));
+ }
if old.widened_by(&new) {
self.confirm(format!("Widen the Keyvault policy for {label}"))
.await?;
@@ -1978,6 +2411,19 @@ impl Broker {
needs_import,
created_ms: now,
};
+ // Every item is unlocked: the user already allowed unattended access
+ // (with presence) when they unlocked it, so this is answered
+ // without a prompt. The caller still never sees a value: it gets a
+ // capability token for a delivery INTO the Space.
+ if view.needs_import.is_empty()
+ && policy::unattended_eligible(
+ &view.items,
+ &view.request.targets,
+ &view.request.actions,
+ )
+ {
+ return self.auto_grant(st, view);
+ }
st.pending.insert(
view.id.clone(),
Pending {
@@ -2013,6 +2459,82 @@ impl Broker {
Ok(caller_view)
}
+ /// Answers an unattended-eligible request (see
+ /// [`policy::unattended_eligible`]): mints the grant the user would
+ /// have approved, short and single-use unless the request asked
+ /// otherwise, and audits it as unattended.
+ fn auto_grant(
+ &self,
+ mut st: tokio::sync::MutexGuard<'_, State>,
+ view: PendingView,
+ ) -> Result<PendingView> {
+ let targets = view.request.targets.clone();
+ let target_ids = self.resolve_target_ids(&targets)?;
+ let now = crate::now_ms();
+ let secs =
+ policy::clamp_grant_secs(view.request.duration_secs.unwrap_or(DEFAULT_GRANT_SECS));
+ let uses = match view.request.uses {
+ Some(0) => None,
+ Some(n) => Some(n.min(1000)),
+ None => Some(1),
+ };
+ let item_ids: Vec<String> = view.items.iter().map(|i| i.id.clone()).collect();
+ let grant = Grant {
+ id: uid()?,
+ request_id: view.id.clone(),
+ caller_fp: view.caller_fp.clone(),
+ caller_display: view.caller_display.clone(),
+ items: item_ids.clone(),
+ targets: targets.clone(),
+ target_ids,
+ actions: view.request.actions.clone(),
+ created_ms: now,
+ not_after_ms: now + secs * 1000,
+ uses_left: uses,
+ revoked: false,
+ agent: view.request.agent.clone(),
+ unattended: true,
+ };
+ let v = Self::vault_mut(&mut st)?;
+ let epoch = v.update_meta(|m| {
+ m.grants.push(grant.clone());
+ Ok(m.epoch)
+ })?;
+ let token = self.mint(&grant, epoch)?;
+ st.decided.insert(
+ view.id.clone(),
+ (
+ view.caller_fp.clone(),
+ Decision::Granted {
+ token: token.encode(),
+ grant_id: grant.id.clone(),
+ items: item_ids,
+ targets,
+ not_after_ms: grant.not_after_ms,
+ },
+ ),
+ );
+ let mut e = ev("consent.allow", &view.caller, "allow");
+ e.target = view.request.targets.first().cloned();
+ e.detail = format!(
+ "request={} grant={} requester={} secs={secs} unattended (items unlocked) items={}",
+ view.id,
+ grant.id,
+ view.caller_fp,
+ view.items.len()
+ );
+ Self::audit(&mut st, e);
+ drop(st);
+ self.decided.notify_waiters();
+ crate::telemetry::consent(
+ &self.telemetry,
+ cua_telemetry::events::ConsentDecision::Approved,
+ );
+ let mut caller_view = view;
+ caller_view.items = caller_view.items.iter().map(|i| i.redacted()).collect();
+ Ok(caller_view)
+ }
+
/// Waits up to `timeout` for the user's answer to the caller's own
/// request. A granted token is handed over once.
pub async fn await_decision(
@@ -2184,7 +2706,13 @@ impl Broker {
Some(a) => format!("agent {a} ({})", view.caller_display),
None => view.caller_display.clone(),
};
- let sites: Vec<String> = view.items.iter().filter_map(|i| i.site.clone()).collect();
+ let mut sites: Vec<String> = view
+ .items
+ .iter()
+ .filter_map(|i| i.domain.as_deref().map(crate::record::site_of))
+ .collect();
+ sites.sort();
+ sites.dedup();
format!(
"Allow {who} to sign in to {} in {} ({})",
if sites.is_empty() {
@@ -2244,7 +2772,7 @@ impl Broker {
if !it.policy.allows_target(t) {
return Err(Error::Forbidden(format!(
"item {} may not go to {t} (its policy)",
- it.label
+ it.label()
)));
}
}
@@ -2264,6 +2792,7 @@ impl Broker {
uses_left: uses,
revoked: false,
agent: view.request.agent.clone(),
+ unattended: false,
};
let epoch = v.update_meta(|m| {
m.grants.push(grant.clone());
@@ -2496,8 +3025,9 @@ impl Broker {
})
.unwrap_or_default()
};
+ let launch = req.launch;
let r = self
- .teleport_inner(caller, req, PresenceAlready::NotConfirmed, None, false)
+ .teleport_inner(caller, req, PresenceAlready::NotConfirmed, None, launch)
.await;
crate::telemetry::teleport(&self.telemetry, caller, &app, started, &r, items);
r
@@ -2671,19 +3201,28 @@ impl Broker {
.min()
.unwrap_or(crate::model::DEFAULT_TTL_SECS);
let auto_wipe = meta.settings.auto_wipe;
+ let passwords_ok =
+ req.include_passwords && authority == Authority::Interactive && caller.first_party;
let mut out = Vec::new();
for (provider, (ids, superseded)) in groups {
let mut payloads = Vec::new();
for i in &ids {
- // Saved logins stay sealed: only the site-login fill
- // reads them, never a delivery.
- let p = v.read_payload(i)?.deliverable();
- if !p.entries.is_empty() {
- payloads.push(p);
+ // Saved passwords stay sealed: the site-login fill reads
+ // them, and a delivery carries them only when the user
+ // ticked them in the review (interactive, first party).
+ if !meta.items[i].kind.deliverable() && !passwords_ok {
+ continue;
}
+ // A big file's bytes live in a blob; put them back.
+ payloads.push(v.inline_blobs(&v.read_payload(i)?)?);
}
if !payloads.is_empty() {
- out.push((provider, ids, payloads, superseded));
+ // Items are one secret apiece: the provider's codec
+ // reassembles them into the entries the receiver
+ // installs (and re-encrypts for its own machine).
+ let scope = payloads[0].scope.clone();
+ let entries = crate::record::codec_for(&provider).import(&payloads)?;
+ out.push((provider, ids, scope, entries, superseded));
}
}
if out.is_empty() {
@@ -2693,11 +3232,7 @@ impl Broker {
.into(),
));
}
- let labels: Vec<String> = req
- .items
- .iter()
- .map(|i| meta.items[i].label.clone())
- .collect();
+ let labels: Vec<String> = req.items.iter().map(|i| meta.items[i].label()).collect();
(authority, out, labels, ttl, auto_wipe)
};
if authority == Authority::Interactive && presence == PresenceAlready::NotConfirmed {
@@ -2718,6 +3253,9 @@ impl Broker {
let mut e = ev("teleport.authorize", caller, "allow");
e.target = Some(req.target.clone());
e.detail = format!("{} items={}", authority.describe(), req.items.len());
+ if req.include_passwords {
+ e.detail.push_str(" INCLUDING SAVED PASSWORDS");
+ }
Self::audit_required(&mut st, e)?;
}
// Phase 2 (unlocked): supersede, deliver.
@@ -2730,7 +3268,7 @@ impl Broker {
..Default::default()
};
let mut delivered = Vec::new();
- for (provider, ids, payloads, superseded) in groups {
+ for (provider, ids, scope, entries, superseded) in groups {
for d in &superseded {
// Best effort: a failed wipe of the superseded import still
// leaves its own TTL to clean up.
@@ -2742,7 +3280,8 @@ impl Broker {
.deliver_launching(
&req.target,
&provider,
- payloads,
+ &scope,
+ entries,
expires_ms,
sink.clone(),
true,
@@ -2754,7 +3293,8 @@ impl Broker {
.deliver_with_progress(
&req.target,
&provider,
- payloads,
+ &scope,
+ entries,
expires_ms,
sink.clone(),
)
@@ -2765,7 +3305,8 @@ impl Broker {
.deliver_launching(
&req.target,
&provider,
- payloads,
+ &scope,
+ entries,
expires_ms,
Arc::new(|_| {}),
true,
@@ -2774,7 +3315,7 @@ impl Broker {
}
None => {
self.backend
- .deliver(&req.target, &provider, payloads, expires_ms)
+ .deliver(&req.target, &provider, &scope, entries, expires_ms)
.await
}
};
@@ -2879,15 +3420,25 @@ impl Broker {
};
let v = Self::vault_mut(&mut st)?;
let meta = v.meta()?.clone();
- let candidates: Vec<&ItemMeta> = meta
+ // One password per item (keyed by origin + username): the ones
+ // saved for exactly this origin, for this user when asked, and
+ // allowed in this Space.
+ let mut candidates: Vec<&ItemMeta> = meta
.items
.values()
.filter(|i| {
- i.kind == ItemKind::SitePasswords
- && i.site.as_deref().is_some_and(|s| host_in_site(&host, s))
+ i.kind == ItemKind::Password
+ && i.domain
+ .as_deref()
+ .is_some_and(|d| d.eq_ignore_ascii_case(&origin))
&& i.policy.allows_target(&req.target)
+ && req
+ .username
+ .as_deref()
+ .is_none_or(|u| u.eq_ignore_ascii_case(&i.key))
})
.collect();
+ candidates.sort_by(|a, b| a.key.cmp(&b.key));
if candidates.is_empty() {
denied(&mut st, format!("origin={origin} no saved password"));
return Err(Error::NotFound(format!(
@@ -2955,8 +3506,8 @@ impl Broker {
return Err(err);
};
let v = Self::vault_mut(&mut st)?;
- let logins = v.read_payload(&item_id)?.logins()?;
- let pick = logins.iter().find(|l| {
+ let saved = v.read_payload(&item_id)?.login()?;
+ let pick = Some(&saved).filter(|l| {
l.origin == origin
&& req
.username
@@ -2964,7 +3515,7 @@ impl Broker {
.is_none_or(|u| u.eq_ignore_ascii_case(&l.username))
});
let Some(login) = pick.cloned() else {
- drop(logins);
+ drop(saved);
denied(
&mut st,
format!("origin={origin} no saved login for this origin"),
@@ -2977,7 +3528,7 @@ impl Broker {
.unwrap_or_default()
)));
};
- drop(logins);
+ drop(saved);
if let Authority::Grant(g) = &authority {
let v = Self::vault_mut(&mut st)?;
v.update_meta(|m| {
@@ -2989,7 +3540,11 @@ impl Broker {
Ok(())
})?;
}
- let site = meta.items[&item_id].site.clone().unwrap_or_default();
+ let site = meta.items[&item_id]
+ .domain
+ .as_deref()
+ .map(crate::record::site_of)
+ .unwrap_or_default();
// The agent the user approved (the grant's) names the use; a
// caller cannot relabel an approved sign-in as another agent's.
let approved_agent = match &authority {
@@ -3248,10 +3803,10 @@ fn human_secs(secs: u64) -> String {
}
fn describe_selection(view: &PendingView) -> String {
- let mut parts: Vec<String> = view.items.iter().map(|i| i.label.clone()).collect();
+ let mut parts: Vec<String> = view.items.iter().map(|i| i.label()).collect();
for s in &view.needs_import {
match s {
- Selector::Site { app, site, .. } => parts.push(format!("{site} ({app}, import)")),
+ Selector::Site { app, site } => parts.push(format!("{site} ({app}, import)")),
Selector::App { app } => parts.push(format!("the whole {app} session (import)")),
Selector::Item { id } => parts.push(id.clone()),
Selector::Login { site } => parts.push(format!("the saved password for {site}")),
@@ -3277,7 +3832,7 @@ fn describe_spec(spec: &ImportSpec) -> String {
let sites: Vec<&str> = spec.sites.iter().map(|s| s.site.as_str()).collect();
format!("{} from {}", sites.join(", "), spec.app)
};
- let pw = if spec.sites.iter().any(|s| s.include_passwords) {
+ let pw = if spec.passwords || spec.sites.iter().any(|s| s.include_passwords) {
" INCLUDING SAVED PASSWORDS"
} else {
""
@@ -3297,7 +3852,7 @@ fn imports_for(needs: &[Selector], opts: &ApproveOptions) -> Vec<ImportSpec> {
let mut by_app: BTreeMap<String, ImportSpec> = BTreeMap::new();
for s in needs {
match s {
- Selector::Site { app, site, .. } => {
+ Selector::Site { app, site } => {
let spec = by_app.entry(app.clone()).or_insert_with(|| ImportSpec {
app: app.clone(),
cookies: opts.cookies,
diff --git a/libs/cua/crates/cua-keyvault/src/ipc.rs b/libs/cua/crates/cua-keyvault/src/ipc.rs
index 33be325a75..bd28b84dcf 100644
--- a/libs/cua/crates/cua-keyvault/src/ipc.rs
+++ b/libs/cua/crates/cua-keyvault/src/ipc.rs
@@ -28,12 +28,12 @@ use crate::audit::{AuditEntry, Verification};
#[cfg(unix)]
use crate::broker::StageSink;
use crate::broker::{
- AccessRequest, ApproveOptions, Broker, Decision, ImportSpec, InitRequest, Inventory,
- LoginOutcome, LoginRequest, PasswordImportSpec, PendingView, RuleSpec, Status, TeleportOutcome,
- TeleportRequest, TeleportStage, UnlockRequest,
+ AccessRequest, ApproveOptions, Broker, Decision, ImportReport, ImportSpec, InitRequest,
+ Inventory, ItemPage, LockOutcome, LoginOutcome, LoginRequest, PasswordImportSpec, PendingView,
+ RuleSpec, SiteIcon, Status, TeleportOutcome, TeleportRequest, TeleportStage, UnlockRequest,
};
use crate::caller::{CallerIdentity, TrustPolicy};
-use crate::model::{Delivery, Grant, ItemMeta, ItemPolicy, UnattendedRule, UnlockPolicy};
+use crate::model::{Delivery, Grant, ItemPolicy, UnattendedRule, UnlockPolicy};
use crate::{Error, Result};
/// Largest frame accepted either way.
@@ -73,13 +73,23 @@ pub enum Request {
#[serde(default)]
auto_lock_minutes: Option<u32>,
},
- /// Items (coarse: labels and counts only).
- ListItems,
- /// One item's full detail (cookie names, domains, origins). Needs presence.
- DescribeItem {
- /// Item id.
- id: String,
+ /// One page of items. Names (domains and keys) only inside the browse
+ /// window; outside it: app, type, lock state and times.
+ ListItems {
+ /// Items to skip.
+ #[serde(default)]
+ offset: usize,
+ /// Page size (default and most: [`crate::broker::MAX_PAGE`]).
+ #[serde(default)]
+ limit: Option<usize>,
},
+ /// Site icons (empty while the browse window is closed).
+ ListFavicons,
+ /// Open the browse window (needs presence): item names become visible
+ /// for a few minutes.
+ Browse,
+ /// Close the browse window.
+ EndBrowse,
/// A host app's per-site inventory.
Inventory {
/// Provider id.
@@ -94,10 +104,23 @@ pub enum Request {
ImportPasswords(PasswordImportSpec),
/// Sign in to a site in a target Space with a saved password.
Login(LoginRequest),
- /// Delete an item.
- DeleteItem {
- /// Item id.
- id: String,
+ /// Delete items, wiping every live copy of them in Spaces.
+ DeleteItems {
+ /// Item ids.
+ ids: Vec<String>,
+ },
+ /// Lock or unlock items together. Unlocking allows unattended access
+ /// and asks for presence once for the batch.
+ SetLocked {
+ /// Item ids.
+ ids: Vec<String>,
+ /// Lock (true) or unlock.
+ locked: bool,
+ },
+ /// "Never ask again" on the unlock prompt.
+ SetSkipUnlockPrompt {
+ /// On (true) or off.
+ on: bool,
},
/// Set an item's policy.
SetItemPolicy {
@@ -337,15 +360,30 @@ pub async fn dispatch(broker: &Broker, caller: &CallerIdentity, req: Request) ->
.set_unlock_policy(caller, policy, auto_lock_minutes)
.await
),
- Request::ListItems => reply!(broker.list_items(caller).await),
- Request::DescribeItem { id } => reply!(broker.describe_item(caller, &id).await),
+ Request::ListItems { offset, limit } => reply!(
+ broker
+ .list_items(caller, offset, limit.unwrap_or(crate::broker::MAX_PAGE))
+ .await
+ ),
+ Request::ListFavicons => reply!(broker.list_favicons(caller).await),
+ Request::Browse => reply!(
+ broker
+ .browse(caller)
+ .await
+ .map(|until| serde_json::json!({ "browse_until_ms": until }))
+ ),
+ Request::EndBrowse => reply!(broker.end_browse(caller).await),
Request::Inventory { app, profile } => {
reply!(broker.inventory(caller, &app, profile.as_deref()).await)
}
Request::Import(spec) => reply!(broker.import(caller, spec).await),
Request::ImportPasswords(spec) => reply!(broker.import_passwords(caller, spec).await),
Request::Login(r) => reply!(broker.login(caller, r).await),
- Request::DeleteItem { id } => reply!(broker.delete_item(caller, &id).await),
+ Request::DeleteItems { ids } => reply!(broker.delete_items(caller, ids).await),
+ Request::SetLocked { ids, locked } => reply!(broker.set_locked(caller, ids, locked).await),
+ Request::SetSkipUnlockPrompt { on } => {
+ reply!(broker.set_skip_unlock_prompt(caller, on).await)
+ }
Request::SetItemPolicy { id, policy } => {
reply!(broker.set_item_policy(caller, &id, policy).await)
}
@@ -833,13 +871,56 @@ impl KeyvaultClient {
pub async fn lock(&mut self) -> Result<()> {
self.call(&Request::Lock).await.map(|_| ())
}
- /// Items (coarse metadata).
- pub async fn list_items(&mut self) -> Result<Vec<ItemMeta>> {
- self.typed(&Request::ListItems).await
+ /// Every item, page by page. Names are present only inside the browse
+ /// window ([`Self::browse`]).
+ pub async fn list_items(&mut self) -> Result<ItemPage> {
+ let mut all = ItemPage::default();
+ loop {
+ let page: ItemPage = self
+ .typed(&Request::ListItems {
+ offset: all.items.len(),
+ limit: None,
+ })
+ .await?;
+ let empty = page.items.is_empty();
+ all.total = page.total;
+ all.names_visible = page.names_visible;
+ all.items.extend(page.items);
+ if empty || all.items.len() >= all.total {
+ return Ok(all);
+ }
+ }
}
- /// One item's full detail (needs presence).
- pub async fn describe_item(&mut self, id: &str) -> Result<ItemMeta> {
- self.typed(&Request::DescribeItem { id: id.into() }).await
+ /// Site icons, empty while the browse window is closed.
+ pub async fn list_favicons(&mut self) -> Result<Vec<SiteIcon>> {
+ let v = self.call(&Request::ListFavicons).await?;
+ serde_json::from_value(v).map_err(|e| Error::Invalid(e.to_string()))
+ }
+ /// Opens the browse window (the daemon asks for presence). Returns when
+ /// it closes, Unix ms.
+ pub async fn browse(&mut self) -> Result<u64> {
+ let v = self.call(&Request::Browse).await?;
+ Ok(v.get("browse_until_ms")
+ .and_then(Value::as_u64)
+ .unwrap_or(0))
+ }
+ /// Closes the browse window.
+ pub async fn end_browse(&mut self) -> Result<()> {
+ self.call(&Request::EndBrowse).await.map(|_| ())
+ }
+ /// Deletes items and wipes their live copies. Returns the wiped imports.
+ pub async fn delete_items(&mut self, ids: Vec<String>) -> Result<Vec<String>> {
+ self.typed(&Request::DeleteItems { ids }).await
+ }
+ /// Locks or unlocks items together (unlocking asks for presence once).
+ pub async fn set_locked(&mut self, ids: Vec<String>, locked: bool) -> Result<LockOutcome> {
+ self.typed(&Request::SetLocked { ids, locked }).await
+ }
+ /// "Never ask again" on the unlock prompt.
+ pub async fn set_skip_unlock_prompt(&mut self, on: bool) -> Result<()> {
+ self.call(&Request::SetSkipUnlockPrompt { on })
+ .await
+ .map(|_| ())
}
/// Inventory.
pub async fn inventory(&mut self, app: &str, profile: Option<&str>) -> Result<Inventory> {
@@ -850,11 +931,11 @@ impl KeyvaultClient {
.await
}
/// Import.
- pub async fn import(&mut self, spec: ImportSpec) -> Result<Vec<ItemMeta>> {
+ pub async fn import(&mut self, spec: ImportSpec) -> Result<ImportReport> {
self.typed(&Request::Import(spec)).await
}
/// Import a browser's saved passwords (first party; presence).
- pub async fn import_passwords(&mut self, spec: PasswordImportSpec) -> Result<Vec<ItemMeta>> {
+ pub async fn import_passwords(&mut self, spec: PasswordImportSpec) -> Result<ImportReport> {
self.typed(&Request::ImportPasswords(spec)).await
}
/// Sign in to a site in a Space with a saved password.
diff --git a/libs/cua/crates/cua-keyvault/src/lib.rs b/libs/cua/crates/cua-keyvault/src/lib.rs
index 6b9d35ea21..c4bc4452b0 100644
--- a/libs/cua/crates/cua-keyvault/src/lib.rs
+++ b/libs/cua/crates/cua-keyvault/src/lib.rs
@@ -47,6 +47,7 @@ pub mod macos;
pub mod model;
pub mod policy;
pub mod protector;
+pub mod record;
pub mod rollback;
pub mod store;
/// Broker-side usage telemetry (counts and fixed vocabularies only).
@@ -79,6 +80,12 @@ pub enum Error {
/// The global kill switch is on.
#[error("the Keyvault is disabled (global kill switch); enable it in Cua to teleport")]
Disabled,
+ /// The vault was written by an earlier preview build (format 1, whole-app
+ /// items). It is not migrated.
+ #[error(
+ "the Keyvault was created by an earlier preview (format {0}) and cannot be read; it was set aside"
+ )]
+ OldFormat(u32),
/// A file failed an integrity check.
#[error("the Keyvault is damaged: {0}")]
Corrupt(String),
diff --git a/libs/cua/crates/cua-keyvault/src/model.rs b/libs/cua/crates/cua-keyvault/src/model.rs
index ee0ce3d715..16dde73a92 100644
--- a/libs/cua/crates/cua-keyvault/src/model.rs
+++ b/libs/cua/crates/cua-keyvault/src/model.rs
@@ -13,75 +13,106 @@ use zeroize::Zeroize;
use crate::audit::Head;
use crate::capability::Action;
-/// Item kinds.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+/// What a secret item is.
+///
+/// The vault is a list of items grouped by source app. Each item is one
+/// secret: a cookie, a localStorage value, a password, or a file (the
+/// catch-all for bookmarks, session files and non-browser app state).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ItemKind {
- /// One site (eTLD+1) of one browser profile: cookies, and optionally
- /// its storage.
- BrowserSite,
- /// Saved passwords for one site (never selected by default).
- SitePasswords,
- /// A whole app session (Electron apps, CLIs): every workspace or
- /// account the app holds.
- AppSession,
+ /// One cookie: key is the cookie name, domain its host.
+ Cookie,
+ /// One localStorage value: key is the storage key, domain its origin host.
+ LocalStorage,
+ /// One saved password: key is the username, domain its site. Passwords
+ /// stay sealed: they sign in through site login and are never delivered
+ /// as files.
+ Password,
+ /// A file: key is its path, relative to the app's data.
+ File,
}
impl ItemKind {
/// Label used in the UI.
pub fn label(self) -> &'static str {
match self {
- ItemKind::BrowserSite => "Site session",
- ItemKind::SitePasswords => "Saved passwords",
- ItemKind::AppSession => "Whole app session",
+ ItemKind::Cookie => "Cookie",
+ ItemKind::LocalStorage => "Local storage",
+ ItemKind::Password => "Password",
+ ItemKind::File => "File",
}
}
-}
-/// One cookie, described without its value.
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
-pub struct CookieInfo {
- /// Cookie name.
- pub name: String,
- /// Host or domain (`.github.com`).
- pub domain: String,
- /// Session cookie (no expiry).
- pub session: bool,
- /// Expiry, Unix ms (persistent cookies).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub expires_ms: Option<i64>,
-}
+ /// Stable tag used in unique keys and the wire.
+ pub fn tag(self) -> &'static str {
+ match self {
+ ItemKind::Cookie => "cookie",
+ ItemKind::LocalStorage => "local_storage",
+ ItemKind::Password => "password",
+ ItemKind::File => "file",
+ }
+ }
-/// What an item contains, for "view before sending". Never values.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct ItemSummary {
- /// Cookies (names and domains).
- #[serde(default)]
- pub cookies: Vec<CookieInfo>,
- /// Storage origins carried (`https://github.com`).
- #[serde(default)]
- pub storage_origins: Vec<String>,
- /// Saved passwords carried (count only).
- #[serde(default)]
- pub passwords: u32,
- /// Bundle paths carried.
- #[serde(default)]
- pub files: Vec<String>,
- /// Keychain services carried (for example `Chrome Safe Storage`).
- #[serde(default)]
- pub keychain_services: Vec<String>,
- /// Payload bytes.
- #[serde(default)]
- pub bytes: u64,
+ /// Whether items of this kind are keyed by path (files) rather than by
+ /// domain and key.
+ pub fn keyed_by_path(self) -> bool {
+ self == ItemKind::File
+ }
+
+ /// Whether an item of this kind can be delivered into a Space as app
+ /// state. Passwords never are.
+ pub fn deliverable(self) -> bool {
+ self != ItemKind::Password
+ }
}
-impl ItemSummary {
- /// Session cookies.
- pub fn session_cookies(&self) -> usize {
- self.cookies.iter().filter(|c| c.session).count()
+/// The identity of an item within its app: a file's relative path, a
+/// cookie's host plus name plus path, a localStorage value's origin plus
+/// key, or a password's origin plus username. The kind is part of it so a
+/// cookie and a storage value that share a domain and a name stay two
+/// items. Saving the same app again upserts by this key and never
+/// duplicates.
+pub fn unique_key(kind: ItemKind, domain: Option<&str>, key: &str, path: Option<&str>) -> String {
+ if kind.keyed_by_path() {
+ format!("{}\u{1f}{key}", kind.tag())
+ } else {
+ format!(
+ "{}\u{1f}{}\u{1f}{key}\u{1f}{}",
+ kind.tag(),
+ domain.unwrap_or("").trim().to_ascii_lowercase(),
+ if kind == ItemKind::Cookie {
+ path.unwrap_or("/")
+ } else {
+ ""
+ }
+ )
}
}
+/// Domains whose session unlocks other apps (red-team F7): such an item
+/// can never be unlocked for unattended use and gets a short delivery
+/// lifetime.
+pub fn is_identity_provider(domain: &str) -> bool {
+ const IDPS: [&str; 12] = [
+ "google.com",
+ "googleusercontent.com",
+ "microsoft.com",
+ "microsoftonline.com",
+ "live.com",
+ "office.com",
+ "apple.com",
+ "icloud.com",
+ "okta.com",
+ "auth0.com",
+ "onelogin.com",
+ "duosecurity.com",
+ ];
+ let d = domain.trim().trim_start_matches('.').to_ascii_lowercase();
+ IDPS.iter()
+ .any(|i| d == *i || d.ends_with(&format!(".{i}")))
+}
+
/// Per-item policy.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ItemPolicy {
@@ -135,43 +166,54 @@ impl ItemPolicy {
}
}
-/// A vault item's metadata.
+/// A vault item's metadata. It never holds the value: that is the sealed
+/// payload (`items/<id>.sealed`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ItemMeta {
/// Item id.
pub id: String,
- /// Kind.
+ /// Type.
pub kind: ItemKind,
- /// Label (`github.com (Chrome, Default)`).
- pub label: String,
- /// Teleport provider id (`chrome`, `firefox`, `slack`).
+ /// Source app: the teleport provider id (`chrome`, `slack`).
pub provider_id: String,
/// App display name.
pub app_display: String,
- /// Registrable domain, for site items.
+ /// Domain: a cookie's host, a storage value's origin host, a password's
+ /// site. `None` for files.
#[serde(default, skip_serializing_if = "Option::is_none")]
- pub site: Option<String>,
- /// Account or workspace, when detectable.
+ pub domain: Option<String>,
+ /// Key: a cookie name, a storage key, a username, or a file's path.
+ pub key: String,
+ /// A cookie's path (part of its key: the same name on the same host can
+ /// exist under several paths).
#[serde(default, skip_serializing_if = "Option::is_none")]
- pub account: Option<String>,
- /// Where it was imported from (profile name).
+ pub path: Option<String>,
+ /// Where it was read from (profile name).
#[serde(default)]
pub source: String,
- /// Contents, without values.
- pub summary: ItemSummary,
- /// Warnings shown with the item (device-bound sessions and so on).
+ /// A cookie without an expiry (dies with the browser session).
+ #[serde(default)]
+ pub session: bool,
+ /// A cookie's expiry, Unix ms.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub expires_ms: Option<i64>,
+ /// Payload bytes.
#[serde(default)]
- pub warnings: Vec<String>,
+ pub bytes: u64,
+ /// The content-addressed blob a big file's bytes live in (SHA-256, hex).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub blob: Option<String>,
/// An identity provider (Google, Microsoft, Apple, Okta, ...): its
- /// session unlocks every federated app, so it never goes into
- /// unattended rules and defaults to a short TTL (red-team F7).
+ /// session unlocks every federated app, so it can never be unlocked
+ /// for unattended use and defaults to a short TTL (red-team F7).
#[serde(default)]
pub identity_provider: bool,
- /// Policy.
+ /// Policy. `policy.unattended` is the unlock: the lock icon's open
+ /// state. A locked item needs the user's approval for every use.
pub policy: ItemPolicy,
/// Created, Unix ms.
pub created_ms: u64,
- /// Last updated, Unix ms.
+ /// Last saved (upserted), Unix ms.
pub updated_ms: u64,
/// Payload revision.
pub rev: u64,
@@ -180,24 +222,76 @@ pub struct ItemMeta {
}
impl ItemMeta {
- /// A coarse copy for bulk enumeration: labels, kind, site, account and
- /// counts are kept, but the identifying cookie names and domains, storage
- /// origins and keychain-service names are stripped. That detail set is
- /// itself sensitive (it maps the user's whole logged-in life: which banks,
- /// which employers' SSO, internal hostnames), so it is never returned by a
- /// no-presence bulk `ListItems`; `DescribeItem` returns it behind user
- /// presence (red-team F17).
+ /// This item's key within its app (see [`unique_key`]).
+ pub fn unique_key(&self) -> String {
+ unique_key(
+ self.kind,
+ self.domain.as_deref(),
+ &self.key,
+ self.path.as_deref(),
+ )
+ }
+
+ /// A one-line name: `domain / key`, or the file's path.
+ pub fn label(&self) -> String {
+ match (&self.domain, self.kind.keyed_by_path()) {
+ (Some(d), false) if !d.is_empty() => format!("{d} / {}", self.key),
+ _ => self.key.clone(),
+ }
+ }
+
+ /// Locked: every use needs the user's approval.
+ pub fn locked(&self) -> bool {
+ !self.policy.unattended
+ }
+
+ /// A copy for bulk enumeration without presence: app, type, lock state
+ /// and timestamps are kept, but the domain and key are stripped. Those
+ /// names are themselves sensitive (they map the user's whole logged-in
+ /// life: which banks, which employers' SSO, internal hostnames), so
+ /// they are only returned inside a browse window the user opened with
+ /// presence, never to a third party (red-team F17).
pub fn redacted(&self) -> ItemMeta {
let mut m = self.clone();
- for c in &mut m.summary.cookies {
- c.name = String::new();
- c.domain = String::new();
- }
- m.summary.storage_origins.clear();
- m.summary.keychain_services.clear();
- m.summary.files.clear();
+ m.domain = None;
+ m.key = String::new();
+ m.path = None;
+ m.source = String::new();
+ m.blob = None;
m
}
+
+ /// A new item to save: its type, app, domain (none for a file) and key,
+ /// with the default policy (locked). The vault fills in the id, times,
+ /// revision and digest.
+ pub fn draft(
+ kind: ItemKind,
+ provider_id: &str,
+ app_display: &str,
+ domain: Option<&str>,
+ key: &str,
+ ) -> ItemMeta {
+ ItemMeta {
+ id: String::new(),
+ kind,
+ provider_id: provider_id.into(),
+ app_display: app_display.into(),
+ domain: domain.map(str::to_string),
+ key: key.into(),
+ path: None,
+ source: String::new(),
+ session: false,
+ expires_ms: None,
+ bytes: 0,
+ blob: None,
+ identity_provider: false,
+ policy: ItemPolicy::default(),
+ created_ms: 0,
+ updated_ms: 0,
+ rev: 0,
+ record_digest: String::new(),
+ }
+ }
}
/// A bundle entry inside an item payload.
@@ -230,22 +324,42 @@ impl Drop for PayloadEntry {
}
}
-/// An item's secret payload: what gets delivered.
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+/// An item's secret payload: one canonical JSON record, stored decrypted
+/// inside the sealed item (the vault encrypts it at rest). The schema is
+/// versioned (`cookie@1`) so a format change is a new schema with a codec
+/// that reads the old one. Big file content is not inlined: the record
+/// names a content-addressed blob (see [`crate::record::FileRecord`]).
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ItemPayload {
/// Provider id (the receiver's importer).
pub provider_id: String,
/// `tabs` or `full`.
pub scope: String,
- /// Bundle entries.
- pub entries: Vec<PayloadEntry>,
+ /// The record's schema: `cookie@1`, `local_storage@1`, `password@1` or
+ /// `file@1`.
+ pub schema: String,
+ /// The record: canonical JSON text. Wiped on drop.
+ pub record: String,
}
-/// The reserved payload entry of a [`ItemKind::SitePasswords`] item that
-/// holds its decrypted saved logins (JSON [`LoginRecord`]s, base64 like every
-/// entry). It stays sealed in the vault: teleport never delivers it, and only
-/// the site-login fill reads it.
-pub const LOGINS_ENTRY: &str = ".cua-keyvault/logins.json";
+impl std::fmt::Debug for ItemPayload {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ItemPayload")
+ .field("provider_id", &self.provider_id)
+ .field("schema", &self.schema)
+ .field(
+ "record",
+ &format_args!("<{} bytes redacted>", self.record.len()),
+ )
+ .finish()
+ }
+}
+
+impl Drop for ItemPayload {
+ fn drop(&mut self) {
+ self.record.zeroize();
+ }
+}
/// One saved login inside the vault. `Debug` never prints the password, and
/// every field is wiped on drop.
@@ -283,38 +397,36 @@ pub fn mask_username(u: &str) -> String {
}
impl ItemPayload {
- /// The saved logins this payload holds (empty when it holds none).
- pub fn logins(&self) -> crate::Result<Vec<LoginRecord>> {
- use base64::Engine as _;
- let Some(e) = self.entries.iter().find(|e| e.rel_path == LOGINS_ENTRY) else {
- return Ok(Vec::new());
- };
- let mut bytes = zeroize::Zeroizing::new(
- base64::engine::general_purpose::STANDARD
- .decode(&e.data)
- .map_err(|_| crate::Error::Corrupt("saved logins entry is not base64".into()))?,
- );
- let out = serde_json::from_slice(&bytes)
- .map_err(|_| crate::Error::Corrupt("saved logins entry is not valid".into()));
- bytes.zeroize();
- out
- }
-
- /// A payload entry holding `logins` (for [`LOGINS_ENTRY`]).
- pub fn logins_entry(logins: &[LoginRecord]) -> crate::Result<PayloadEntry> {
- use base64::Engine as _;
- let json = zeroize::Zeroizing::new(serde_json::to_vec(logins)?);
- Ok(PayloadEntry {
- rel_path: LOGINS_ENTRY.into(),
- mode: 0o600,
- data: base64::engine::general_purpose::STANDARD.encode(json.as_slice()),
+ /// This payload with another record (same provider, scope and schema).
+ pub fn with_record(&self, record: String) -> ItemPayload {
+ ItemPayload {
+ provider_id: self.provider_id.clone(),
+ scope: self.scope.clone(),
+ schema: self.schema.clone(),
+ record,
+ }
+ }
+
+ /// A password item's payload: its one saved login.
+ pub fn password(provider_id: &str, login: &LoginRecord) -> crate::Result<ItemPayload> {
+ Ok(ItemPayload {
+ provider_id: provider_id.into(),
+ scope: "full".into(),
+ schema: crate::record::PASSWORD_V1.into(),
+ record: serde_json::to_string(login)?,
})
}
- /// This payload without its reserved entries: what teleport may deliver.
- pub fn deliverable(mut self) -> ItemPayload {
- self.entries.retain(|e| e.rel_path != LOGINS_ENTRY);
- self
+ /// The saved login a password item holds. Anything else is refused.
+ pub fn login(&self) -> crate::Result<LoginRecord> {
+ if self.schema != crate::record::PASSWORD_V1 {
+ return Err(crate::Error::Corrupt(format!(
+ "{} is not a saved login",
+ self.schema
+ )));
+ }
+ serde_json::from_str(&self.record)
+ .map_err(|_| crate::Error::Corrupt("the saved login is not valid".into()))
}
}
@@ -356,6 +468,10 @@ pub struct Grant {
/// every use is audited under it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent: Option<String>,
+ /// Minted without asking, because every item it covers was unlocked
+ /// (allowed unattended). Locking one of them revokes it.
+ #[serde(default)]
+ pub unattended: bool,
}
impl Grant {
@@ -486,6 +602,11 @@ pub struct Settings {
/// (the default) they stay until wiped ([`NO_EXPIRY`]).
#[serde(default)]
pub auto_wipe: bool,
+ /// The user chose "Never ask again" on the unlock prompt: unlocking an
+ /// item (allowing unattended access) skips the explanation prompt. It
+ /// never skips the presence check (Touch ID) the broker asks for.
+ #[serde(default)]
+ pub skip_unlock_prompt: bool,
}
impl Default for Settings {
@@ -495,6 +616,7 @@ impl Default for Settings {
unlock_policy: UnlockPolicy::Auto,
auto_lock_minutes: 15,
auto_wipe: false,
+ skip_unlock_prompt: false,
}
}
}
@@ -517,6 +639,11 @@ pub struct Meta {
pub rules: Vec<UnattendedRule>,
/// Deliveries (live and recently wiped).
pub deliveries: Vec<Delivery>,
+ /// Site icons (registrable domain to base64 PNG), read from the source
+ /// browser's own local favicon store when its items were saved. Not
+ /// secret, small and bounded; pruned with the last item of a site.
+ #[serde(default)]
+ pub favicons: BTreeMap<String, String>,
/// The audit chain head this metadata vouches for.
pub audit_head: Head,
}
@@ -590,6 +717,7 @@ mod tests {
uses_left: Some(1),
revoked: false,
agent: None,
+ unattended: false,
};
assert!(g.is_live(5));
assert!(!g.is_live(10));
@@ -613,4 +741,115 @@ mod tests {
let s = format!("{e:?}");
assert!(!s.contains("c2VjcmV0"), "{s}");
}
+
+ fn meta(kind: ItemKind, domain: Option<&str>, key: &str) -> ItemMeta {
+ ItemMeta {
+ id: "i".into(),
+ kind,
+ provider_id: "chrome".into(),
+ app_display: "Chrome".into(),
+ domain: domain.map(str::to_string),
+ key: key.into(),
+ path: None,
+ source: "Default".into(),
+ session: false,
+ expires_ms: None,
+ bytes: 0,
+ blob: None,
+ identity_provider: false,
+ policy: ItemPolicy::default(),
+ created_ms: 0,
+ updated_ms: 0,
+ rev: 1,
+ record_digest: String::new(),
+ }
+ }
+
+ #[test]
+ fn a_files_key_is_its_path_and_the_rest_are_domain_plus_key() {
+ let f = meta(ItemKind::File, Some("ignored.test"), "Default/Bookmarks");
+ assert_eq!(
+ f.unique_key(),
+ meta(ItemKind::File, None, "Default/Bookmarks").unique_key()
+ );
+ assert_ne!(
+ f.unique_key(),
+ meta(ItemKind::File, None, "Default/Preferences").unique_key()
+ );
+ let c = meta(ItemKind::Cookie, Some("GitHub.com"), "sid");
+ assert_eq!(
+ c.unique_key(),
+ meta(ItemKind::Cookie, Some("github.com"), "sid").unique_key()
+ );
+ assert_ne!(
+ c.unique_key(),
+ meta(ItemKind::Cookie, Some("github.com"), "other").unique_key()
+ );
+ assert_ne!(
+ c.unique_key(),
+ meta(ItemKind::Cookie, Some("gitlab.com"), "sid").unique_key()
+ );
+ assert_ne!(
+ c.unique_key(),
+ meta(ItemKind::LocalStorage, Some("github.com"), "sid").unique_key(),
+ "a cookie and a storage value stay two items"
+ );
+ assert_ne!(
+ c.unique_key(),
+ meta(ItemKind::Password, Some("github.com"), "sid").unique_key()
+ );
+ // A cookie is host + name + path; a leading dot is a different cookie.
+ let mut under_path = meta(ItemKind::Cookie, Some("GitHub.com"), "sid");
+ under_path.path = Some("/api".into());
+ assert_ne!(c.unique_key(), under_path.unique_key());
+ let mut root = meta(ItemKind::Cookie, Some("GitHub.com"), "sid");
+ root.path = Some("/".into());
+ assert_eq!(
+ c.unique_key(),
+ root.unique_key(),
+ "no path means the root path"
+ );
+ assert_ne!(
+ c.unique_key(),
+ meta(ItemKind::Cookie, Some(".github.com"), "sid").unique_key(),
+ "a domain cookie and a host-only cookie are two cookies"
+ );
+ // A password is origin + username; a storage value is origin + key.
+ assert_ne!(
+ meta(ItemKind::Password, Some("https://a.test"), "u").unique_key(),
+ meta(ItemKind::Password, Some("https://b.test"), "u").unique_key()
+ );
+ }
+
+ #[test]
+ fn labels_and_locks() {
+ assert_eq!(
+ meta(ItemKind::Cookie, Some("github.com"), "sid").label(),
+ "github.com / sid"
+ );
+ assert_eq!(meta(ItemKind::File, None, "a/b").label(), "a/b");
+ let mut m = meta(ItemKind::Cookie, Some("github.com"), "sid");
+ assert!(m.locked(), "items are locked until the user unlocks them");
+ m.policy.unattended = true;
+ assert!(!m.locked());
+ }
+
+ #[test]
+ fn redaction_keeps_the_app_and_drops_the_names() {
+ let r = meta(ItemKind::Cookie, Some("bank.example"), "sid").redacted();
+ assert_eq!(r.provider_id, "chrome");
+ assert_eq!(r.kind, ItemKind::Cookie);
+ assert!(r.domain.is_none() && r.key.is_empty() && r.source.is_empty());
+ let json = serde_json::to_string(&r).unwrap();
+ assert!(!json.contains("bank.example"), "{json}");
+ }
+
+ #[test]
+ fn identity_providers_are_recognised_with_subdomains() {
+ assert!(is_identity_provider("accounts.google.com"));
+ assert!(is_identity_provider(".login.microsoftonline.com"));
+ assert!(is_identity_provider("okta.com"));
+ assert!(!is_identity_provider("notgoogle.com"));
+ assert!(!is_identity_provider("github.com"));
+ }
}
diff --git a/libs/cua/crates/cua-keyvault/src/policy.rs b/libs/cua/crates/cua-keyvault/src/policy.rs
index dc4624c314..b64dd462b8 100644
--- a/libs/cua/crates/cua-keyvault/src/policy.rs
+++ b/libs/cua/crates/cua-keyvault/src/policy.rs
@@ -92,6 +92,29 @@ pub fn validate_rule(rule: &mut UnattendedRule, meta: &Meta, now_ms: u64) -> Res
Ok(())
}
+/// Whether a request can be answered without asking the user: it names
+/// items, every one of them is unlocked (the user allowed unattended access
+/// when they unlocked it) and is not an identity provider, every target is
+/// one each item may go to, and the actions are only the ones unlocking
+/// covers (writing the item into a Space, or signing in with it).
+pub fn unattended_eligible(
+ items: &[crate::model::ItemMeta],
+ targets: &[String],
+ actions: &[crate::capability::Action],
+) -> bool {
+ use crate::capability::Action;
+ !items.is_empty()
+ && !targets.is_empty()
+ && actions
+ .iter()
+ .all(|a| matches!(a, Action::Teleport | Action::Login))
+ && items.iter().all(|i| {
+ i.policy.unattended
+ && !i.identity_provider
+ && targets.iter().all(|t| i.policy.allows_target(t))
+ })
+}
+
/// Clamps a grant lifetime.
pub fn clamp_grant_secs(secs: u64) -> u64 {
secs.clamp(30, MAX_GRANT_SECS)
@@ -113,7 +136,7 @@ pub fn prune(meta: &mut Meta, now_ms: u64) -> usize {
#[cfg(test)]
mod tests {
use super::*;
- use crate::model::{ItemKind, ItemMeta, ItemPolicy, ItemSummary, RuleCaller};
+ use crate::model::{ItemKind, ItemMeta, ItemPolicy, RuleCaller};
fn meta_with_item(unattended: bool, targets: Vec<String>) -> Meta {
let mut m = Meta::default();
@@ -121,15 +144,17 @@ mod tests {
"i1".into(),
ItemMeta {
id: "i1".into(),
- kind: ItemKind::BrowserSite,
- label: "l".into(),
+ kind: ItemKind::Cookie,
provider_id: "chrome".into(),
app_display: "Chrome".into(),
- site: None,
- account: None,
+ domain: Some("example.test".into()),
+ key: "sid".into(),
+ path: None,
source: String::new(),
- summary: ItemSummary::default(),
- warnings: vec![],
+ session: false,
+ expires_ms: None,
+ bytes: 0,
+ blob: None,
identity_provider: false,
policy: ItemPolicy {
allowed_targets: targets,
diff --git a/libs/cua/crates/cua-keyvault/src/record.rs b/libs/cua/crates/cua-keyvault/src/record.rs
new file mode 100644
index 0000000000..4abb0d5705
--- /dev/null
+++ b/libs/cua/crates/cua-keyvault/src/record.rs
@@ -0,0 +1,1277 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The record layer: what the vault stores, and the codecs between it and an
+//! app's native state.
+//!
+//! The vault holds one **record** per secret. A record is canonical JSON
+//! with a versioned schema (`cookie@1`, `local_storage@1`, `password@1`,
+//! `file@1`), kept decrypted inside the sealed item. Nothing about how an
+//! app encrypts its own storage lives in a record: a cookie is its host,
+//! name, path, value and attributes, not a `v10` blob keyed to one machine.
+//!
+//! A [`RecordCodec`] is the only thing that knows an app's native format:
+//!
+//! - [`RecordCodec::export`] turns the entries a provider read from the app
+//! (decrypted cookie rows, files) into records, and reports what it could
+//! not or must not export ([`Unavailable`]);
+//! - [`RecordCodec::import`] turns records back into the entries the
+//! receiver installs. The receiver re-encrypts each cookie under the
+//! destination's own key (macOS `v10`, Linux `v10`/`v11`, Chrome 130's
+//! host-key digest), so a Chromium format change stays inside that code
+//! and never reaches the vault.
+//!
+//! Sending part of an app is filtering records. Everything above this
+//! module (search, multi-select, locks, the review) works on records
+//! without knowing which app they came from.
+
+use base64::Engine as _;
+use serde::{Deserialize, Serialize};
+use zeroize::Zeroize;
+
+use crate::model::{ItemKind, ItemMeta, ItemPayload, LoginRecord, PayloadEntry};
+use crate::{Error, Result};
+
+/// Cookie schema, version 1.
+pub const COOKIE_V1: &str = "cookie@1";
+/// localStorage value schema, version 1.
+pub const LOCAL_STORAGE_V1: &str = "local_storage@1";
+/// Saved password schema, version 1.
+pub const PASSWORD_V1: &str = "password@1";
+/// File schema, version 1.
+pub const FILE_V1: &str = "file@1";
+
+/// The native bundle entry that carries decrypted cookie rows (a JSON array;
+/// `cua_teleport_bundle::cookies::COOKIES_ENTRY`).
+pub const COOKIES_ENTRY: &str = "cookies.json";
+/// The native bundle entry that carries localStorage values, a JSON array of
+/// `{origin, key, value}`.
+pub const LOCAL_STORAGE_ENTRY: &str = "localstorage.json";
+
+/// The reserved bundle entry carrying saved passwords the user ticked, for
+/// the receiver to re-encrypt under its own browser key
+/// (`cua_teleport_bundle::logins::LOGINS_ENTRY`).
+pub const LOGINS_ENTRY: &str = "logins.json";
+
+/// Files larger than this are stored as content-addressed blobs and
+/// referenced by hash, never inlined in the record's JSON.
+pub const INLINE_FILE_LIMIT: usize = 64 * 1024;
+
+/// The schema an item kind's records use.
+pub fn schema_for(kind: ItemKind) -> &'static str {
+ match kind {
+ ItemKind::Cookie => COOKIE_V1,
+ ItemKind::LocalStorage => LOCAL_STORAGE_V1,
+ ItemKind::Password => PASSWORD_V1,
+ ItemKind::File => FILE_V1,
+ }
+}
+
+/// The kind a schema belongs to (`None` for an unknown or newer schema).
+pub fn kind_of_schema(schema: &str) -> Option<ItemKind> {
+ [
+ ItemKind::Cookie,
+ ItemKind::LocalStorage,
+ ItemKind::Password,
+ ItemKind::File,
+ ]
+ .into_iter()
+ .find(|k| schema_for(*k) == schema)
+}
+
+mod b64vec {
+ use base64::Engine as _;
+ use serde::{Deserialize, Deserializer, Serializer};
+
+ pub fn serialize<S: Serializer>(v: &[u8], s: S) -> Result<S::Ok, S::Error> {
+ s.serialize_str(&base64::engine::general_purpose::STANDARD.encode(v))
+ }
+
+ pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
+ let s = String::deserialize(d)?;
+ base64::engine::general_purpose::STANDARD
+ .decode(s)
+ .map_err(serde::de::Error::custom)
+ }
+}
+
+/// A cookie, `cookie@1`. Lossless over what a browser stores: every field
+/// beyond the first eight is optional because not every source reports it
+/// (a reader that does not fill them leaves them out; a codec that can
+/// write them back does). Keyed by `host_key` + `name` + `path`.
+///
+/// Fields are declared in alphabetical order: that is the canonical JSON
+/// order, so equal cookies serialize to equal text.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CookieRecord {
+ /// Creation time, Chrome microseconds since 1601 (kept when known).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub creation_utc: Option<i64>,
+ /// Expiry, Chrome microseconds since 1601; `0` is a session cookie.
+ pub expires_utc: i64,
+ /// Chrome's `has_cross_site_ancestor` (kept when known).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub has_cross_site_ancestor: Option<i64>,
+ /// Host key, exactly as the browser stores it (`.github.com`).
+ pub host_key: String,
+ /// `HttpOnly`.
+ pub http_only: bool,
+ /// Chrome's `last_access_utc` (kept when known).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_access_utc: Option<i64>,
+ /// Last update, Chrome microseconds since 1601 (kept when known).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_update_utc: Option<i64>,
+ /// Name.
+ pub name: String,
+ /// Partition key of a CHIPS (partitioned) cookie: the top-level site.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub partition_key: Option<String>,
+ /// Path.
+ pub path: String,
+ /// Chrome's cookie priority (0 low, 1 medium, 2 high).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub priority: Option<i64>,
+ /// Chrome's `samesite` (-1 unspecified, 0 none, 1 lax, 2 strict).
+ pub same_site: i64,
+ /// `Secure`.
+ pub secure: bool,
+ /// The port the cookie was set from (`-1`: unspecified).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source_port: Option<i64>,
+ /// Chrome's source scheme (0 unset, 1 non-secure, 2 secure).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source_scheme: Option<i64>,
+ /// Chrome's `source_type` (0 unknown, 1 http, 2 script, 3 other).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source_type: Option<i64>,
+ /// The value, decrypted.
+ #[serde(with = "b64vec")]
+ pub value: Vec<u8>,
+}
+
+impl CookieRecord {
+ /// The item key: the cookie's name, and for a partitioned (CHIPS) cookie
+ /// its partition too, so a partitioned cookie never collides with (and
+ /// is never merged into) the same name set without a partition.
+ pub fn key(&self) -> String {
+ match self.partition_key.as_deref().filter(|p| !p.is_empty()) {
+ Some(p) => format!("{} (partitioned: {p})", self.name),
+ None => self.name.clone(),
+ }
+ }
+}
+
+impl std::fmt::Debug for CookieRecord {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("CookieRecord")
+ .field("host_key", &self.host_key)
+ .field("name", &self.name)
+ .field("path", &self.path)
+ .field("value", &"<redacted>")
+ .finish_non_exhaustive()
+ }
+}
+
+impl Drop for CookieRecord {
+ fn drop(&mut self) {
+ self.value.zeroize();
+ }
+}
+
+impl CookieRecord {
+ /// Whether the cookie has no expiry.
+ pub fn session(&self) -> bool {
+ self.expires_utc == 0
+ }
+
+ /// The expiry in Unix ms (`None` for a session cookie).
+ pub fn expires_ms(&self) -> Option<i64> {
+ const CHROME_EPOCH_OFFSET_MS: i64 = 11_644_473_600_000;
+ (self.expires_utc != 0).then_some(self.expires_utc / 1000 - CHROME_EPOCH_OFFSET_MS)
+ }
+}
+
+/// A localStorage value, `local_storage@1`. Keyed by `origin` + `key`.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LocalStorageRecord {
+ /// The storage key.
+ pub key: String,
+ /// The origin (`https://github.com`).
+ pub origin: String,
+ /// The value.
+ pub value: String,
+ /// The exact stored key bytes (base64), only when `key` cannot hold them
+ /// losslessly (a lone UTF-16 surrogate).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub key_raw: Option<String>,
+ /// The exact stored value bytes (base64), only when `value` cannot hold
+ /// them losslessly.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub value_raw: Option<String>,
+}
+
+impl std::fmt::Debug for LocalStorageRecord {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("LocalStorageRecord")
+ .field("origin", &self.origin)
+ .field("key", &self.key)
+ .field("value", &"<redacted>")
+ .finish()
+ }
+}
+
+impl Drop for LocalStorageRecord {
+ fn drop(&mut self) {
+ self.value.zeroize();
+ if let Some(raw) = &mut self.value_raw {
+ raw.zeroize();
+ }
+ }
+}
+
+/// A file, `file@1`. Keyed by its path. The bytes are inline (`content`,
+/// base64) when small, or in a content-addressed encrypted blob (`blob`,
+/// the SHA-256) when not; the JSON never carries a big file's bytes.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct FileRecord {
+ /// SHA-256 of the blob holding the bytes (hex), for a big file.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub blob: Option<String>,
+ /// The bytes, base64, for a small file.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub content: Option<String>,
+ /// Unix mode.
+ pub mode: u32,
+ /// Path relative to the app's data.
+ pub path: String,
+ /// SHA-256 of the bytes (hex).
+ pub sha256: String,
+ /// Size in bytes.
+ pub size: u64,
+}
+
+impl std::fmt::Debug for FileRecord {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("FileRecord")
+ .field("path", &self.path)
+ .field("size", &self.size)
+ .finish_non_exhaustive()
+ }
+}
+
+impl Drop for FileRecord {
+ fn drop(&mut self) {
+ if let Some(c) = self.content.as_mut() {
+ c.zeroize();
+ }
+ }
+}
+
+fn sha256_hex(bytes: &[u8]) -> String {
+ hex::encode(crate::crypto::sha256(bytes))
+}
+
+/// A record a codec exported, with the facts the vault indexes it by.
+#[derive(Clone, Debug)]
+pub struct NewRecord {
+ /// Type.
+ pub kind: ItemKind,
+ /// Domain (none for a file).
+ pub domain: Option<String>,
+ /// Key (name, storage key, username or path).
+ pub key: String,
+ /// A cookie's path.
+ pub path: Option<String>,
+ /// A cookie without an expiry.
+ pub session: bool,
+ /// A cookie's expiry, Unix ms.
+ pub expires_ms: Option<i64>,
+ /// Payload bytes (for display).
+ pub bytes: u64,
+ /// The record: canonical JSON.
+ pub record: String,
+}
+
+impl NewRecord {
+ /// This record as an item to save.
+ pub fn into_item(
+ self,
+ provider_id: &str,
+ app_display: &str,
+ source: &str,
+ scope: &str,
+ ) -> (ItemMeta, ItemPayload) {
+ let mut meta = ItemMeta::draft(
+ self.kind,
+ provider_id,
+ app_display,
+ self.domain.as_deref(),
+ &self.key,
+ );
+ meta.path = self.path;
+ meta.session = self.session;
+ meta.expires_ms = self.expires_ms;
+ meta.bytes = self.bytes;
+ meta.source = source.into();
+ let payload = ItemPayload {
+ provider_id: provider_id.into(),
+ scope: scope.into(),
+ schema: schema_for(self.kind).into(),
+ record: self.record.clone(),
+ };
+ (meta, payload)
+ }
+}
+
+/// Something a codec did not export, and why. Never silent: the review and
+/// the vault list say so.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Unavailable {
+ /// What it is (a path, or "N cookies").
+ pub what: String,
+ /// Why it was not exported.
+ pub reason: String,
+ /// It can be exported, but only after the user explicitly opts in (a
+ /// consent-gated item), as opposed to not at all.
+ pub needs_opt_in: bool,
+}
+
+/// What a codec exported.
+#[derive(Debug, Default)]
+pub struct Exported {
+ /// The records.
+ pub records: Vec<NewRecord>,
+ /// What was left out.
+ pub unavailable: Vec<Unavailable>,
+}
+
+/// What the user explicitly chose, for consent-gated items.
+#[derive(Clone, Debug, Default)]
+pub struct ExportOptions {
+ /// Paths the user explicitly selected. A consent-gated path is exported
+ /// only when it is named here.
+ pub opted_in: Vec<String>,
+}
+
+/// An app's native format, behind one interface.
+pub trait RecordCodec: Send + Sync {
+ /// The codec's name.
+ fn id(&self) -> &'static str;
+
+ /// Native entries to records, reporting what was left out.
+ fn export(&self, entries: Vec<PayloadEntry>, opts: &ExportOptions) -> Result<Exported>;
+
+ /// Records back to the native entries the receiver installs. Passwords
+ /// are only the reserved logins entry, and only when the user ticked
+ /// them (the broker withholds them otherwise). Files that
+ /// were stored as blobs must already be inlined (see
+ /// [`crate::store::Vault::inline_blobs`]).
+ fn import(&self, payloads: &[ItemPayload]) -> Result<Vec<PayloadEntry>>;
+}
+
+/// Cookie rows as a bundle carries them
+/// (`cua_teleport_bundle::cookies::CookieItem`'s wire shape).
+#[derive(Serialize, Deserialize)]
+struct CookieRow {
+ host_key: String,
+ name: String,
+ #[serde(with = "b64vec")]
+ value: Vec<u8>,
+ path: String,
+ expires_utc: i64,
+ is_secure: bool,
+ is_httponly: bool,
+ #[serde(default)]
+ samesite: i64,
+ #[serde(flatten)]
+ extra: CookieExtra,
+}
+
+impl Drop for CookieRow {
+ fn drop(&mut self) {
+ self.value.zeroize();
+ }
+}
+
+/// The cookie columns beyond the core ones, as the bundle carries them
+/// (`cua_teleport_bundle::cookies::CookieExtra`, flattened).
+#[derive(Default, Serialize, Deserialize)]
+struct CookieExtra {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ creation_utc: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ last_access_utc: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ last_update_utc: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ priority: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ source_scheme: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ source_port: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ source_type: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ has_cross_site_ancestor: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ partition_key: Option<String>,
+}
+
+/// A saved login as a bundle carries it
+/// (`cua_teleport_bundle::logins::LoginItem`'s wire shape).
+#[derive(Serialize, Deserialize)]
+struct LoginRow {
+ origin: String,
+ username: String,
+ #[serde(with = "b64vec")]
+ password: Vec<u8>,
+ signon_realm: String,
+}
+
+impl Drop for LoginRow {
+ fn drop(&mut self) {
+ self.password.zeroize();
+ }
+}
+
+#[derive(Serialize, Deserialize)]
+struct StorageRow {
+ origin: String,
+ key: String,
+ value: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ key_raw: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ value_raw: Option<String>,
+}
+
+impl Drop for StorageRow {
+ fn drop(&mut self) {
+ self.value.zeroize();
+ }
+}
+
+fn b64() -> base64::engine::general_purpose::GeneralPurpose {
+ base64::engine::general_purpose::STANDARD
+}
+
+fn entry_bytes(e: &PayloadEntry) -> Result<zeroize::Zeroizing<Vec<u8>>> {
+ Ok(zeroize::Zeroizing::new(b64().decode(&e.data).map_err(
+ |_| Error::Corrupt(format!("{} is not base64", e.rel_path)),
+ )?))
+}
+
+/// A cookie record, ready to save.
+pub fn cookie_record(c: &CookieRecord) -> Result<NewRecord> {
+ Ok(NewRecord {
+ kind: ItemKind::Cookie,
+ domain: Some(c.host_key.clone()),
+ key: c.key(),
+ path: Some(c.path.clone()),
+ session: c.session(),
+ expires_ms: c.expires_ms(),
+ bytes: c.value.len() as u64,
+ record: serde_json::to_string(c)?,
+ })
+}
+
+/// A localStorage record, ready to save.
+pub fn local_storage_record(v: &LocalStorageRecord) -> Result<NewRecord> {
+ Ok(NewRecord {
+ kind: ItemKind::LocalStorage,
+ domain: Some(v.origin.clone()),
+ key: v.key.clone(),
+ path: None,
+ session: false,
+ expires_ms: None,
+ bytes: v.value.len() as u64,
+ record: serde_json::to_string(v)?,
+ })
+}
+
+/// A saved-password record, ready to save.
+pub fn password_record(l: &LoginRecord) -> Result<NewRecord> {
+ Ok(NewRecord {
+ kind: ItemKind::Password,
+ domain: Some(l.origin.clone()),
+ key: l.username.clone(),
+ path: None,
+ session: false,
+ expires_ms: None,
+ bytes: l.password.len() as u64,
+ record: serde_json::to_string(l)?,
+ })
+}
+
+/// A file record, ready to save (the bytes inline; the vault moves a big
+/// file's bytes into a blob when it stores it).
+pub fn file_record(path: &str, mode: u32, bytes: &[u8]) -> Result<NewRecord> {
+ let f = FileRecord {
+ blob: None,
+ content: Some(b64().encode(bytes)),
+ mode,
+ path: path.into(),
+ sha256: sha256_hex(bytes),
+ size: bytes.len() as u64,
+ };
+ Ok(NewRecord {
+ kind: ItemKind::File,
+ domain: None,
+ key: path.into(),
+ path: None,
+ session: false,
+ expires_ms: None,
+ bytes: bytes.len() as u64,
+ record: serde_json::to_string(&f)?,
+ })
+}
+
+/// The codec every app gets: cookie rows and localStorage rows become
+/// records, every other entry becomes a file record.
+pub struct GenericCodec;
+
+impl RecordCodec for GenericCodec {
+ fn id(&self) -> &'static str {
+ "generic"
+ }
+
+ fn export(&self, entries: Vec<PayloadEntry>, _opts: &ExportOptions) -> Result<Exported> {
+ let mut out = Exported::default();
+ for e in &entries {
+ match e.rel_path.as_str() {
+ COOKIES_ENTRY => {
+ let bytes = entry_bytes(e)?;
+ let rows: Vec<CookieRow> = serde_json::from_slice(&bytes)
+ .map_err(|_| Error::Corrupt("cookies.json is not valid".into()))?;
+ for r in &rows {
+ out.records.push(cookie_record(&CookieRecord {
+ creation_utc: r.extra.creation_utc,
+ expires_utc: r.expires_utc,
+ has_cross_site_ancestor: r.extra.has_cross_site_ancestor,
+ host_key: r.host_key.clone(),
+ http_only: r.is_httponly,
+ last_access_utc: r.extra.last_access_utc,
+ last_update_utc: r.extra.last_update_utc,
+ name: r.name.clone(),
+ partition_key: r.extra.partition_key.clone().filter(|k| !k.is_empty()),
+ path: r.path.clone(),
+ priority: r.extra.priority,
+ same_site: r.samesite,
+ secure: r.is_secure,
+ source_port: r.extra.source_port,
+ source_scheme: r.extra.source_scheme,
+ source_type: r.extra.source_type,
+ value: r.value.clone(),
+ })?);
+ }
+ }
+ LOCAL_STORAGE_ENTRY => {
+ let bytes = entry_bytes(e)?;
+ let rows: Vec<StorageRow> = serde_json::from_slice(&bytes)
+ .map_err(|_| Error::Corrupt("localstorage.json is not valid".into()))?;
+ for r in &rows {
+ out.records.push(local_storage_record(&LocalStorageRecord {
+ key: r.key.clone(),
+ origin: r.origin.clone(),
+ value: r.value.clone(),
+ key_raw: r.key_raw.clone(),
+ value_raw: r.value_raw.clone(),
+ })?);
+ }
+ }
+ path => {
+ let bytes = entry_bytes(e)?;
+ out.records.push(file_record(path, e.mode, &bytes)?);
+ }
+ }
+ }
+ Ok(out)
+ }
+
+ fn import(&self, payloads: &[ItemPayload]) -> Result<Vec<PayloadEntry>> {
+ let mut cookies: Vec<CookieRow> = Vec::new();
+ let mut storage: Vec<StorageRow> = Vec::new();
+ let mut logins: Vec<LoginRow> = Vec::new();
+ let mut files: Vec<PayloadEntry> = Vec::new();
+ for p in payloads {
+ match p.schema.as_str() {
+ COOKIE_V1 => {
+ let c: CookieRecord = serde_json::from_str(&p.record)
+ .map_err(|_| Error::Corrupt("a cookie record is not valid".into()))?;
+ cookies.push(CookieRow {
+ host_key: c.host_key.clone(),
+ name: c.name.clone(),
+ value: c.value.clone(),
+ path: c.path.clone(),
+ expires_utc: c.expires_utc,
+ is_secure: c.secure,
+ is_httponly: c.http_only,
+ samesite: c.same_site,
+ extra: CookieExtra {
+ creation_utc: c.creation_utc,
+ last_access_utc: c.last_access_utc,
+ last_update_utc: c.last_update_utc,
+ priority: c.priority,
+ source_scheme: c.source_scheme,
+ source_port: c.source_port,
+ source_type: c.source_type,
+ has_cross_site_ancestor: c.has_cross_site_ancestor,
+ partition_key: c.partition_key.clone(),
+ },
+ });
+ }
+ LOCAL_STORAGE_V1 => {
+ let v: LocalStorageRecord = serde_json::from_str(&p.record)
+ .map_err(|_| Error::Corrupt("a localStorage record is not valid".into()))?;
+ storage.push(StorageRow {
+ origin: v.origin.clone(),
+ key: v.key.clone(),
+ value: v.value.clone(),
+ key_raw: v.key_raw.clone(),
+ value_raw: v.value_raw.clone(),
+ });
+ }
+ FILE_V1 => {
+ let f: FileRecord = serde_json::from_str(&p.record)
+ .map_err(|_| Error::Corrupt("a file record is not valid".into()))?;
+ let content = f.content.clone().ok_or_else(|| {
+ Error::Corrupt(format!(
+ "{} has no bytes to deliver (blob not inlined)",
+ f.path
+ ))
+ })?;
+ let entry = PayloadEntry {
+ rel_path: f.path.clone(),
+ mode: f.mode,
+ data: content,
+ };
+ // A file named twice is written once; the later one wins.
+ match files.iter_mut().find(|x| x.rel_path == entry.rel_path) {
+ Some(slot) => *slot = entry,
+ None => files.push(entry),
+ }
+ }
+ // A saved login is here only because the user ticked it (the
+ // broker withholds passwords otherwise): it rides in its own
+ // reserved entry, re-encrypted by the receiver.
+ PASSWORD_V1 => {
+ let l: LoginRecord = serde_json::from_str(&p.record)
+ .map_err(|_| Error::Corrupt("a password record is not valid".into()))?;
+ logins.push(LoginRow {
+ origin: l.origin.clone(),
+ username: l.username.clone(),
+ password: l.password.as_bytes().to_vec(),
+ signon_realm: format!("{}/", l.origin.trim_end_matches('/')),
+ });
+ }
+ other => {
+ return Err(Error::Unsupported(format!(
+ "this build cannot deliver {other} records"
+ )));
+ }
+ }
+ }
+ // Rows already carry a `value` the receiver re-encrypts; join them.
+ if !cookies.is_empty() {
+ let json = zeroize::Zeroizing::new(serde_json::to_vec(&cookies)?);
+ files.push(PayloadEntry {
+ rel_path: COOKIES_ENTRY.into(),
+ mode: 0o600,
+ data: b64().encode(json.as_slice()),
+ });
+ }
+ if !logins.is_empty() {
+ let json = zeroize::Zeroizing::new(serde_json::to_vec(&logins)?);
+ files.push(PayloadEntry {
+ rel_path: LOGINS_ENTRY.into(),
+ mode: 0o600,
+ data: b64().encode(json.as_slice()),
+ });
+ }
+ if !storage.is_empty() {
+ let json = zeroize::Zeroizing::new(serde_json::to_vec(&storage)?);
+ files.push(PayloadEntry {
+ rel_path: LOCAL_STORAGE_ENTRY.into(),
+ mode: 0o600,
+ data: b64().encode(json.as_slice()),
+ });
+ }
+ Ok(files)
+ }
+}
+
+/// Chromium-family browsers (Chrome, Brave, Edge, Arc, Vivaldi): the generic
+/// codec, withholding what must not leave without the user's explicit say.
+pub struct ChromiumCodec;
+
+/// Chromium files that are never exported unless the user explicitly picked
+/// them, with why.
+const CHROMIUM_GATED: [(&str, &str); 2] = [
+ (
+ "Web Data",
+ "holds the browser's sign-in refresh tokens, which outlive cookies and grant account access",
+ ),
+ (
+ "Login Data",
+ "its passwords are encrypted for this Mac; saved passwords are kept as password items instead",
+ ),
+];
+
+fn gated_reason(path: &str) -> Option<&'static str> {
+ let name = path.rsplit('/').next().unwrap_or(path);
+ CHROMIUM_GATED
+ .iter()
+ .find(|(n, _)| *n == name)
+ .map(|(_, why)| *why)
+}
+
+impl RecordCodec for ChromiumCodec {
+ fn id(&self) -> &'static str {
+ "chromium"
+ }
+
+ fn export(&self, entries: Vec<PayloadEntry>, opts: &ExportOptions) -> Result<Exported> {
+ let mut unavailable = Vec::new();
+ let kept: Vec<PayloadEntry> = entries
+ .into_iter()
+ .filter(|e| match gated_reason(&e.rel_path) {
+ Some(why) if !opts.opted_in.iter().any(|p| p == &e.rel_path) => {
+ unavailable.push(Unavailable {
+ what: e.rel_path.clone(),
+ reason: why.into(),
+ needs_opt_in: true,
+ });
+ false
+ }
+ _ => true,
+ })
+ .collect();
+ let mut out = GenericCodec.export(kept, opts)?;
+ out.unavailable.extend(unavailable);
+ Ok(out)
+ }
+
+ fn import(&self, payloads: &[ItemPayload]) -> Result<Vec<PayloadEntry>> {
+ GenericCodec.import(payloads)
+ }
+}
+
+/// The codec for a provider id.
+pub fn codec_for(provider_id: &str) -> Box<dyn RecordCodec> {
+ match provider_id {
+ "chrome" | "chromium" | "brave" | "edge" | "arc" | "vivaldi" | "opera" => {
+ Box::new(ChromiumCodec)
+ }
+ _ => Box::new(GenericCodec),
+ }
+}
+
+/// Whether a cookie name looks like it keeps a sign-in (a session, an
+/// authentication token), as opposed to analytics or preferences. It picks
+/// the default for a minimal teleport: the sites that need to stay signed
+/// in. A heuristic; the user reviews and changes the selection.
+pub fn looks_like_signin(name: &str) -> bool {
+ let n = name.to_ascii_lowercase();
+ const NOT: [&str; 8] = [
+ "_ga",
+ "_gid",
+ "_gat",
+ "_fbp",
+ "__utm",
+ "_hj",
+ "optimizely",
+ "ajs_",
+ ];
+ if NOT.iter().any(|p| n.starts_with(p)) {
+ return false;
+ }
+ const YES: [&str; 11] = [
+ "session",
+ "sess",
+ "sid",
+ "auth",
+ "token",
+ "login",
+ "logged_in",
+ "jwt",
+ "csrf",
+ "user",
+ "secure",
+ ];
+ YES.iter()
+ .any(|y| n == *y || n.contains(y) && !n.contains("pref") && !n.contains("theme"))
+}
+
+/// The host of a cookie domain, an origin or a host: scheme, credentials,
+/// port and path are dropped, a leading dot too, and it is lower-cased
+/// (`https://App.GitHub.com:8443/x` and `.app.github.com` are
+/// `app.github.com`).
+pub fn host_of(domain: &str) -> String {
+ let d = domain.trim();
+ let d = d.split_once("://").map_or(d, |(_, r)| r);
+ let d = d.split(['/', '?', '#']).next().unwrap_or(d);
+ let d = d.rsplit_once('@').map_or(d, |(_, r)| r);
+ let d = match d.rsplit_once(':') {
+ Some((h, port)) if port.chars().all(|c| c.is_ascii_digit()) && !h.contains(':') => h,
+ _ => d,
+ };
+ d.trim_start_matches('.').to_ascii_lowercase()
+}
+
+/// A conservative registrable domain for a cookie host, an origin or a host:
+/// the last two labels of [`host_of`] (three under a few known two-label
+/// suffixes). Used to group items by site; the grouping never decides
+/// access.
+pub fn site_of(domain: &str) -> String {
+ const MULTI: [&str; 10] = [
+ "co.uk", "org.uk", "gov.uk", "ac.uk", "co.jp", "com.au", "com.br", "co.nz", "co.in",
+ "com.cn",
+ ];
+ let host = host_of(domain);
+ let labels: Vec<&str> = host.split('.').filter(|l| !l.is_empty()).collect();
+ if labels.len() <= 2 || host.chars().all(|c| c.is_ascii_digit() || c == '.') {
+ return host;
+ }
+ let last_two = format!("{}.{}", labels[labels.len() - 2], labels[labels.len() - 1]);
+ if MULTI.contains(&last_two.as_str()) {
+ return format!("{}.{last_two}", labels[labels.len() - 3]);
+ }
+ last_two
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn cookie(host: &str, name: &str, path: &str, value: &[u8]) -> CookieRecord {
+ CookieRecord {
+ creation_utc: None,
+ expires_utc: 13_397_000_000_000_000,
+ host_key: host.into(),
+ http_only: true,
+ last_update_utc: None,
+ name: name.into(),
+ partition_key: None,
+ last_access_utc: None,
+ source_type: None,
+ has_cross_site_ancestor: None,
+ path: path.into(),
+ priority: None,
+ same_site: 1,
+ secure: true,
+ source_port: None,
+ source_scheme: None,
+ value: value.to_vec(),
+ }
+ }
+
+ fn entry(path: &str, data: &[u8]) -> PayloadEntry {
+ PayloadEntry {
+ rel_path: path.into(),
+ mode: 0o600,
+ data: b64().encode(data),
+ }
+ }
+
+ // ---- golden JSON: the schemas are a stored format ----
+
+ #[test]
+ fn cookie_v1_golden() {
+ let c = cookie(".github.com", "user_session", "/", b"s3cret");
+ assert_eq!(
+ serde_json::to_string(&c).unwrap(),
+ r#"{"expires_utc":13397000000000000,"host_key":".github.com","http_only":true,"name":"user_session","path":"/","same_site":1,"secure":true,"value":"czNjcmV0"}"#
+ );
+ let mut full = c.clone();
+ full.creation_utc = Some(1);
+ full.last_update_utc = Some(2);
+ full.partition_key = Some("https://top.example".into());
+ full.priority = Some(2);
+ full.source_port = Some(443);
+ full.source_scheme = Some(2);
+ full.source_type = Some(1);
+ full.last_access_utc = Some(3);
+ full.has_cross_site_ancestor = Some(1);
+ assert_eq!(
+ serde_json::to_string(&full).unwrap(),
+ r#"{"creation_utc":1,"expires_utc":13397000000000000,"has_cross_site_ancestor":1,"host_key":".github.com","http_only":true,"last_access_utc":3,"last_update_utc":2,"name":"user_session","partition_key":"https://top.example","path":"/","priority":2,"same_site":1,"secure":true,"source_port":443,"source_scheme":2,"source_type":1,"value":"czNjcmV0"}"#
+ );
+ // A partitioned cookie is its own item, never merged into the same
+ // name without a partition.
+ assert_eq!(c.key(), "user_session");
+ assert_eq!(
+ full.key(),
+ "user_session (partitioned: https://top.example)"
+ );
+ let back: CookieRecord =
+ serde_json::from_str(&serde_json::to_string(&full).unwrap()).unwrap();
+ assert_eq!(back, full);
+ }
+
+ #[test]
+ fn local_storage_v1_golden() {
+ let v = LocalStorageRecord {
+ key: "token".into(),
+ origin: "https://app.example".into(),
+ value: "abc".into(),
+ key_raw: None,
+ value_raw: None,
+ };
+ assert_eq!(
+ serde_json::to_string(&v).unwrap(),
+ r#"{"key":"token","origin":"https://app.example","value":"abc"}"#
+ );
+ // A value that is not valid text keeps its exact stored bytes.
+ let raw = LocalStorageRecord {
+ key: "bad".into(),
+ origin: "https://app.example".into(),
+ value: "\u{fffd}".into(),
+ key_raw: None,
+ value_raw: Some("AAA=".into()),
+ };
+ assert_eq!(
+ serde_json::to_string(&raw).unwrap(),
+ "{\"key\":\"bad\",\"origin\":\"https://app.example\",\"value\":\"\u{fffd}\",\"value_raw\":\"AAA=\"}"
+ );
+ }
+
+ #[test]
+ fn password_v1_golden() {
+ let l = LoginRecord {
+ origin: "https://github.com".into(),
+ username: "octo".into(),
+ password: "pw".into(),
+ };
+ assert_eq!(
+ serde_json::to_string(&l).unwrap(),
+ r#"{"origin":"https://github.com","username":"octo","password":"pw"}"#
+ );
+ }
+
+ #[test]
+ fn file_v1_golden_inline_and_blob() {
+ let n = file_record("Default/Bookmarks", 0o600, b"{}").unwrap();
+ assert_eq!(
+ n.record,
+ r#"{"content":"e30=","mode":384,"path":"Default/Bookmarks","sha256":"44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a","size":2}"#
+ );
+ let blob = FileRecord {
+ blob: Some("ab".repeat(32)),
+ content: None,
+ mode: 0o600,
+ path: "Default/History".into(),
+ sha256: "ab".repeat(32),
+ size: 9_999_999,
+ };
+ assert_eq!(
+ serde_json::to_string(&blob).unwrap(),
+ format!(
+ r#"{{"blob":"{h}","mode":384,"path":"Default/History","sha256":"{h}","size":9999999}}"#,
+ h = "ab".repeat(32)
+ )
+ );
+ }
+
+ #[test]
+ fn schemas_and_kinds_agree() {
+ for k in [
+ ItemKind::Cookie,
+ ItemKind::LocalStorage,
+ ItemKind::Password,
+ ItemKind::File,
+ ] {
+ assert_eq!(kind_of_schema(schema_for(k)), Some(k));
+ }
+ assert_eq!(
+ kind_of_schema("cookie@2"),
+ None,
+ "a newer schema is not guessed at"
+ );
+ }
+
+ // ---- codec round trips ----
+
+ fn payload_of(n: NewRecord) -> ItemPayload {
+ let (_, p) = n.into_item("chrome", "Chrome", "Default", "full");
+ p
+ }
+
+ #[test]
+ fn export_then_import_round_trips_cookies_and_files() {
+ let rows = serde_json::json!([
+ {"host_key": ".github.com", "name": "a", "value": "djE=", "path": "/", "expires_utc": 0,
+ "is_secure": true, "is_httponly": false, "samesite": -1},
+ {"host_key": "api.github.com", "name": "b", "value": "djI=", "path": "/v3", "expires_utc": 5,
+ "is_secure": false, "is_httponly": true, "samesite": 2}
+ ]);
+ let exported = ChromiumCodec
+ .export(
+ vec![
+ entry(COOKIES_ENTRY, rows.to_string().as_bytes()),
+ entry("Default/Bookmarks", b"{}"),
+ entry("Local State", b"ls"),
+ ],
+ &ExportOptions::default(),
+ )
+ .unwrap();
+ assert!(exported.unavailable.is_empty());
+ let kinds: Vec<_> = exported.records.iter().map(|r| r.kind).collect();
+ assert_eq!(
+ kinds,
+ vec![
+ ItemKind::Cookie,
+ ItemKind::Cookie,
+ ItemKind::File,
+ ItemKind::File
+ ]
+ );
+ assert_eq!(exported.records[0].domain.as_deref(), Some(".github.com"));
+ assert_eq!(exported.records[1].path.as_deref(), Some("/v3"));
+ assert!(exported.records[0].session && !exported.records[1].session);
+
+ let payloads: Vec<ItemPayload> = exported.records.into_iter().map(payload_of).collect();
+ let entries = ChromiumCodec.import(&payloads).unwrap();
+ let by = |p: &str| {
+ entries
+ .iter()
+ .find(|e| e.rel_path == p)
+ .map(|e| b64().decode(&e.data).unwrap())
+ };
+ let back: serde_json::Value = serde_json::from_slice(&by(COOKIES_ENTRY).unwrap()).unwrap();
+ assert_eq!(back, rows, "the receiver gets the rows the provider read");
+ assert_eq!(by("Default/Bookmarks").unwrap(), b"{}");
+ assert_eq!(by("Local State").unwrap(), b"ls");
+ }
+
+ /// Native entries (the bundle's JSON rows) to records and back: every
+ /// cookie attribute and every localStorage value, including one whose
+ /// bytes are not valid text, comes back as it went in.
+ #[test]
+ fn every_cookie_attribute_and_localstorage_value_round_trips_native_to_record_and_back() {
+ let cookies = serde_json::json!([
+ {"host_key": ".example.com", "name": "sid", "value": "djE=", "path": "/",
+ "expires_utc": 13_400_000_000_000_000i64, "is_secure": true, "is_httponly": true,
+ "samesite": 1, "creation_utc": 11, "last_access_utc": 12, "last_update_utc": 13,
+ "priority": 2, "source_scheme": 2, "source_port": 443, "source_type": 1,
+ "has_cross_site_ancestor": 1, "partition_key": "https://top.example"},
+ {"host_key": ".example.com", "name": "sid", "value": "djI=", "path": "/",
+ "expires_utc": 0, "is_secure": false, "is_httponly": false, "samesite": -1}
+ ]);
+ let storage = serde_json::json!([
+ {"origin": "https://github.com", "key": "color_mode", "value": "dark"},
+ {"origin": "https://a.example", "key": "日本", "value": "こんにちは \u{1F642}"},
+ {"origin": "https://a.example", "key": "bad", "value": "\u{fffd}", "value_raw": "AAAA2A=="}
+ ]);
+ let exported = ChromiumCodec
+ .export(
+ vec![
+ entry(COOKIES_ENTRY, cookies.to_string().as_bytes()),
+ entry(LOCAL_STORAGE_ENTRY, storage.to_string().as_bytes()),
+ ],
+ &ExportOptions::default(),
+ )
+ .unwrap();
+ // The two cookies are two items: one partitioned, one not.
+ let keys: Vec<(ItemKind, String)> = exported
+ .records
+ .iter()
+ .map(|r| (r.kind, r.key.clone()))
+ .collect();
+ assert!(keys.contains(&(ItemKind::Cookie, "sid".into())));
+ assert!(keys.contains(&(
+ ItemKind::Cookie,
+ "sid (partitioned: https://top.example)".into()
+ )));
+ assert_eq!(
+ exported
+ .records
+ .iter()
+ .filter(|r| r.kind == ItemKind::LocalStorage)
+ .count(),
+ 3
+ );
+ let payloads: Vec<ItemPayload> = exported.records.into_iter().map(payload_of).collect();
+ let entries = ChromiumCodec.import(&payloads).unwrap();
+ let by = |p: &str| -> serde_json::Value {
+ let e = entries.iter().find(|e| e.rel_path == p).unwrap();
+ serde_json::from_slice(&b64().decode(&e.data).unwrap()).unwrap()
+ };
+ let sorted = |mut v: serde_json::Value, k: &[&str]| {
+ v.as_array_mut().unwrap().sort_by_key(|x| {
+ k.iter()
+ .map(|f| x[*f].as_str().unwrap_or_default().to_string())
+ .collect::<Vec<_>>()
+ });
+ v
+ };
+ assert_eq!(
+ sorted(by(COOKIES_ENTRY), &["host_key", "name", "partition_key"]),
+ sorted(cookies, &["host_key", "name", "partition_key"]),
+ "the receiver gets every attribute the source had"
+ );
+ assert_eq!(
+ sorted(by(LOCAL_STORAGE_ENTRY), &["origin", "key"]),
+ sorted(storage, &["origin", "key"])
+ );
+ }
+
+ #[test]
+ fn selective_send_is_filtering_records_and_files_dedupe() {
+ let mk = |h: &str| payload_of(cookie_record(&cookie(h, "sid", "/", b"v")).unwrap());
+ let all = [mk(".a.test"), mk(".b.test"), mk(".c.test")];
+ let chosen: Vec<ItemPayload> = all
+ .iter()
+ .filter(|p| p.record.contains(".a.test") || p.record.contains(".c.test"))
+ .cloned()
+ .collect();
+ let entries = GenericCodec.import(&chosen).unwrap();
+ let json: Vec<serde_json::Value> =
+ serde_json::from_slice(&b64().decode(&entries[0].data).unwrap()).unwrap();
+ assert_eq!(json.len(), 2);
+ assert!(json.iter().all(|r| r["host_key"] != ".b.test"));
+
+ let twice = [
+ payload_of(file_record("x", 0o600, b"old").unwrap()),
+ payload_of(file_record("x", 0o600, b"new").unwrap()),
+ ];
+ let entries = GenericCodec.import(&twice).unwrap();
+ assert_eq!(entries.len(), 1);
+ assert_eq!(b64().decode(&entries[0].data).unwrap(), b"new");
+ }
+
+ #[test]
+ fn a_password_is_only_the_reserved_logins_entry_and_unknown_schemas_are_refused() {
+ let pw = ItemPayload::password(
+ "chrome",
+ &LoginRecord {
+ origin: "https://github.com".into(),
+ username: "octo".into(),
+ password: "pw".into(),
+ },
+ )
+ .unwrap();
+ // Never a file of app state: only the reserved entry the receiver
+ // re-encrypts (the broker passes a password here only when the user
+ // ticked it).
+ let entries = GenericCodec.import(&[pw]).unwrap();
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0].rel_path, LOGINS_ENTRY);
+ let rows: serde_json::Value =
+ serde_json::from_slice(&b64().decode(&entries[0].data).unwrap()).unwrap();
+ assert_eq!(rows[0]["username"], "octo");
+ assert_eq!(rows[0]["signon_realm"], "https://github.com/");
+ assert_eq!(rows[0]["password"], b64().encode(b"pw"));
+ let newer = ItemPayload {
+ provider_id: "chrome".into(),
+ scope: "full".into(),
+ schema: "cookie@2".into(),
+ record: "{}".into(),
+ };
+ assert!(matches!(
+ GenericCodec.import(&[newer]),
+ Err(Error::Unsupported(_))
+ ));
+ }
+
+ #[test]
+ fn consent_gated_files_are_withheld_unless_explicitly_chosen() {
+ let entries = || {
+ vec![
+ entry("Default/Web Data", b"tokens"),
+ entry("Default/Login Data", b"pw"),
+ entry("Default/Bookmarks", b"{}"),
+ ]
+ };
+ let out = ChromiumCodec
+ .export(entries(), &ExportOptions::default())
+ .unwrap();
+ assert_eq!(out.records.len(), 1, "only the bookmarks");
+ assert_eq!(out.unavailable.len(), 2);
+ assert!(out.unavailable.iter().all(|u| u.needs_opt_in));
+ assert!(out.unavailable[0].reason.contains("refresh tokens"));
+ // The user picked Web Data themselves: it is exported.
+ let out = ChromiumCodec
+ .export(
+ entries(),
+ &ExportOptions {
+ opted_in: vec!["Default/Web Data".into()],
+ },
+ )
+ .unwrap();
+ assert_eq!(out.records.len(), 2);
+ assert_eq!(out.unavailable.len(), 1);
+ // The generic codec has no gates.
+ assert_eq!(
+ GenericCodec
+ .export(entries(), &ExportOptions::default())
+ .unwrap()
+ .records
+ .len(),
+ 3
+ );
+ assert_eq!(codec_for("brave").id(), "chromium");
+ assert_eq!(codec_for("slack").id(), "generic");
+ }
+
+ #[test]
+ fn garbled_cookie_rows_are_an_error_not_a_silent_drop() {
+ assert!(
+ GenericCodec
+ .export(
+ vec![entry(COOKIES_ENTRY, b"not json")],
+ &ExportOptions::default()
+ )
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn debug_never_prints_a_value() {
+ let c = cookie(".a.test", "sid", "/", b"VERY-SECRET");
+ assert!(!format!("{c:?}").contains("VERY-SECRET"));
+ let p = payload_of(cookie_record(&c).unwrap());
+ assert!(
+ !format!("{p:?}").contains("czNjcmV0") && !format!("{p:?}").contains("VkVSWS1TRUNSRVQ")
+ );
+ }
+
+ #[test]
+ fn signin_cookies_are_told_from_analytics() {
+ for yes in [
+ "user_session",
+ "_gh_sess",
+ "SID",
+ "auth_token",
+ "logged_in",
+ "__Secure-1PSID",
+ "JSESSIONID",
+ "token_v2",
+ ] {
+ assert!(looks_like_signin(yes), "{yes}");
+ }
+ for no in [
+ "_ga",
+ "_gid",
+ "_fbp",
+ "__utma",
+ "ajs_anonymous_id",
+ "theme",
+ "NID_pref",
+ "lang",
+ ] {
+ assert!(!looks_like_signin(no), "{no}");
+ }
+ }
+
+ #[test]
+ fn site_of_groups_hosts_origins_and_cookie_domains() {
+ assert_eq!(site_of(".github.com"), "github.com");
+ assert_eq!(site_of("api.github.com"), "github.com");
+ assert_eq!(site_of("https://gist.github.com:8443/x"), "github.com");
+ assert_eq!(site_of("www.bbc.co.uk"), "bbc.co.uk");
+ assert_eq!(site_of("localhost"), "localhost");
+ assert_eq!(site_of("127.0.0.1"), "127.0.0.1");
+ assert_eq!(site_of("http://127.0.0.1:8000"), "127.0.0.1");
+ }
+}
diff --git a/libs/cua/crates/cua-keyvault/src/store.rs b/libs/cua/crates/cua-keyvault/src/store.rs
index 23143d0a34..b0141383c9 100644
--- a/libs/cua/crates/cua-keyvault/src/store.rs
+++ b/libs/cua/crates/cua-keyvault/src/store.rs
@@ -8,6 +8,7 @@
//! vault.json header: format, vault id, protector records (wrapped VMK only)
//! meta.sealed Meta, AEAD under HKDF(VMK, "meta"), AAD = vault id
//! items/<id>.sealed {rev, wrapped item key, payload}; AAD = vault | id | rev
+//! blobs/<sha256>.sealed a big file's bytes, content-addressed; AAD = vault | hash
//! audit.log hash-chained JSONL (see `audit`)
//! ```
//!
@@ -26,7 +27,12 @@ use crate::protector::{Protector, ProtectorRecord};
use crate::{Error, Result};
/// Header format version this build reads and writes.
-pub const FORMAT: u32 = 1;
+///
+/// Format 2 stores one sealed item per secret (cookie, localStorage value,
+/// password or file) grouped by app. Format 1 held whole-app sessions; it
+/// was only ever shipped in previews and is not migrated (see
+/// [`Error::OldFormat`]).
+pub const FORMAT: u32 = 2;
/// Largest item payload accepted (bundles above this are refused).
pub const MAX_ITEM_BYTES: usize = 256 * 1024 * 1024;
@@ -43,6 +49,27 @@ pub struct Header {
pub protectors: Vec<ProtectorRecord>,
}
+/// What [`Vault::upsert_items`] did with one item.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum UpsertOutcome {
+ /// A new item.
+ Created,
+ /// An existing item whose value changed.
+ Updated,
+ /// An existing item saved again with the same value (only its
+ /// timestamp moved).
+ Unchanged,
+}
+
+/// One saved item.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Upsert {
+ /// The item id (existing items keep theirs).
+ pub id: String,
+ /// What happened.
+ pub outcome: UpsertOutcome,
+}
+
#[derive(Serialize, Deserialize)]
struct ItemRecord {
id: String,
@@ -56,6 +83,7 @@ struct Keys {
meta: SecretKey,
wrap: SecretKey,
audit: SecretKey,
+ blob: SecretKey,
}
impl Keys {
@@ -64,6 +92,7 @@ impl Keys {
meta: vmk.derive(b"cua-keyvault/v1/meta"),
wrap: vmk.derive(b"cua-keyvault/v1/item-wrap"),
audit: vmk.derive(b"cua-keyvault/v1/audit"),
+ blob: vmk.derive(b"cua-keyvault/v2/blob"),
vmk,
}
}
@@ -139,6 +168,14 @@ fn item_aad(vault_id: &str, id: &str, rev: u64, part: &str) -> Vec<u8> {
format!("cua-keyvault/v1/item-{part}|{vault_id}|{id}|{rev}").into_bytes()
}
+fn blob_aad(vault_id: &str, hash: &str) -> Vec<u8> {
+ format!("cua-keyvault/v2/blob|{vault_id}|{hash}").into_bytes()
+}
+
+fn valid_hash(h: &str) -> bool {
+ h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
+}
+
fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-')
}
@@ -205,6 +242,9 @@ impl Vault {
})?;
let header: Header =
serde_json::from_slice(&raw).map_err(|e| Error::Corrupt(format!("vault.json: {e}")))?;
+ if header.format < FORMAT {
+ return Err(Error::OldFormat(header.format));
+ }
if header.format != FORMAT {
return Err(Error::Corrupt(format!(
"vault format {} is not supported by this build (expects {FORMAT})",
@@ -378,6 +418,123 @@ impl Vault {
Ok(self.dir.join("items").join(format!("{id}.sealed")))
}
+ fn blob_path(&self, hash: &str) -> Result<PathBuf> {
+ if !valid_hash(hash) {
+ return Err(Error::Invalid(format!("bad blob hash {hash:?}")));
+ }
+ Ok(self.dir.join("blobs").join(format!("{hash}.sealed")))
+ }
+
+ /// Seals `bytes` as a content-addressed blob and returns its SHA-256
+ /// (hex). The same bytes are stored once, however many items name them.
+ pub fn put_blob(&self, bytes: &[u8]) -> Result<String> {
+ let keys = self.keys()?;
+ if bytes.len() > MAX_ITEM_BYTES {
+ return Err(Error::Invalid(format!(
+ "a file of {} bytes is over the {MAX_ITEM_BYTES} byte limit",
+ bytes.len()
+ )));
+ }
+ let hash = hex::encode(crypto::sha256(bytes));
+ let path = self.blob_path(&hash)?;
+ if path.exists() {
+ return Ok(hash);
+ }
+ private_dir(&self.dir.join("blobs"))?;
+ let sealed = crypto::seal(&keys.blob, &blob_aad(&self.header.vault_id, &hash), bytes)?;
+ write_private(&path, &serde_json::to_vec(&sealed)?)?;
+ Ok(hash)
+ }
+
+ /// Reads a blob, checking it against its own name.
+ pub fn read_blob(&self, hash: &str) -> Result<Zeroizing<Vec<u8>>> {
+ let keys = self.keys()?;
+ let raw = std::fs::read(self.blob_path(hash)?)?;
+ let sealed: Sealed = serde_json::from_slice(&raw)
+ .map_err(|e| Error::Corrupt(format!("blob {hash}: {e}")))?;
+ let plain = crypto::open(&keys.blob, &blob_aad(&self.header.vault_id, hash), &sealed)
+ .map_err(|_| Error::Corrupt(format!("blob {hash} does not authenticate")))?;
+ if !crypto::ct_eq(
+ hex::encode(crypto::sha256(&plain)).as_bytes(),
+ hash.as_bytes(),
+ ) {
+ return Err(Error::Corrupt(format!(
+ "blob {hash} does not match its name (swapped)"
+ )));
+ }
+ Ok(plain)
+ }
+
+ /// A payload with a big file's bytes put back inline, for delivery.
+ pub fn inline_blobs(&self, payload: &ItemPayload) -> Result<ItemPayload> {
+ use base64::Engine as _;
+ if payload.schema != crate::record::FILE_V1 {
+ return Ok(payload.clone());
+ }
+ let mut f: crate::record::FileRecord = serde_json::from_str(&payload.record)
+ .map_err(|_| Error::Corrupt("a file record is not valid".into()))?;
+ if let Some(hash) = f.blob.take() {
+ let bytes = self.read_blob(&hash)?;
+ f.content = Some(base64::engine::general_purpose::STANDARD.encode(bytes.as_slice()));
+ }
+ Ok(payload.with_record(serde_json::to_string(&f)?))
+ }
+
+ /// Moves a big file's bytes out of its record into a blob (the record
+ /// then names the hash); anything else is stored as it is.
+ fn externalize(&self, meta: &mut ItemMeta, payload: ItemPayload) -> Result<ItemPayload> {
+ use base64::Engine as _;
+ meta.blob = None;
+ if payload.schema != crate::record::FILE_V1 {
+ return Ok(payload);
+ }
+ let mut f: crate::record::FileRecord = serde_json::from_str(&payload.record)
+ .map_err(|_| Error::Invalid("a file record is not valid".into()))?;
+ let Some(content) = f.content.clone() else {
+ meta.blob = f.blob.clone();
+ return Ok(payload);
+ };
+ let bytes = Zeroizing::new(
+ base64::engine::general_purpose::STANDARD
+ .decode(content)
+ .map_err(|_| Error::Invalid("a file record is not base64".into()))?,
+ );
+ if bytes.len() <= crate::record::INLINE_FILE_LIMIT {
+ return Ok(payload);
+ }
+ let hash = self.put_blob(&bytes)?;
+ f.content = None;
+ f.blob = Some(hash.clone());
+ meta.blob = Some(hash);
+ Ok(payload.with_record(serde_json::to_string(&f)?))
+ }
+
+ /// Deletes blobs no item names any more.
+ fn gc_blobs(&self) -> Result<()> {
+ let dir = self.dir.join("blobs");
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ return Ok(());
+ };
+ let live: std::collections::HashSet<&str> = self
+ .meta()?
+ .items
+ .values()
+ .filter_map(|i| i.blob.as_deref())
+ .collect();
+ for e in rd.flatten() {
+ let name = e.file_name().to_string_lossy().into_owned();
+ let Some(hash) = name.strip_suffix(".sealed") else {
+ continue;
+ };
+ if !live.contains(hash) {
+ let len = e.metadata().map(|m| m.len()).unwrap_or(0) as usize;
+ let _ = std::fs::write(e.path(), vec![0u8; len]);
+ let _ = std::fs::remove_file(e.path());
+ }
+ }
+ Ok(())
+ }
+
fn write_item(&self, id: &str, rev: u64, payload: &ItemPayload) -> Result<String> {
let keys = self.keys()?;
let vid = &self.header.vault_id;
@@ -405,44 +562,151 @@ impl Vault {
Ok(digest)
}
- /// Stores a new item. `meta.id`, `rev`, `record_digest` and timestamps
- /// are assigned here.
- pub fn put_item(&mut self, mut meta: ItemMeta, payload: &ItemPayload) -> Result<String> {
- let id = crypto::random_id()?;
- let digest = self.write_item(&id, 1, payload)?;
- let now = crate::now_ms();
- meta.id = id.clone();
- meta.rev = 1;
- meta.record_digest = digest;
- meta.created_ms = now;
- meta.updated_ms = now;
- let res = self.update_meta(|m| {
- m.items.insert(meta.id.clone(), meta);
- Ok(())
- });
- if res.is_err() {
- let _ = std::fs::remove_file(self.item_path(&id)?);
- }
- res.map(|_| id)
+ /// Saves one item (see [`Vault::upsert_items`]) and returns its id.
+ pub fn put_item(&mut self, meta: ItemMeta, payload: &ItemPayload) -> Result<String> {
+ let mut out = self.upsert_items(vec![(meta, payload.clone())])?;
+ Ok(out.remove(0).id)
}
- /// Replaces an item's payload (new revision, new item key).
- pub fn replace_payload(&mut self, id: &str, payload: &ItemPayload) -> Result<()> {
- let rev = self
+ /// Saves a batch of items, upserting by key: an item whose app and
+ /// [`ItemMeta::unique_key`] already exist is updated in place (same id,
+ /// same lock state and policy, same creation time), never duplicated.
+ /// Later duplicates inside the batch win. The whole batch is one
+ /// metadata write. `updated_ms` is bumped for every item saved again;
+ /// the sealed record is rewritten only when its value changed.
+ pub fn upsert_items(&mut self, items: Vec<(ItemMeta, ItemPayload)>) -> Result<Vec<Upsert>> {
+ let now = crate::now_ms();
+ // (provider, unique key) -> id, for what the vault already holds.
+ let mut index: std::collections::HashMap<(String, String), String> = self
.meta()?
.items
- .get(id)
- .ok_or_else(|| Error::NotFound(format!("item {id}")))?
- .rev
- + 1;
- let digest = self.write_item(id, rev, payload)?;
- self.update_meta(|m| {
- let it = m.items.get_mut(id).expect("checked above");
- it.rev = rev;
- it.record_digest = digest;
- it.updated_ms = crate::now_ms();
+ .values()
+ .map(|i| ((i.provider_id.clone(), i.unique_key()), i.id.clone()))
+ .collect();
+ // Later duplicates win: keep the last of each key, in first-seen order.
+ let mut order: Vec<(String, String)> = Vec::new();
+ let mut last: std::collections::HashMap<(String, String), (ItemMeta, ItemPayload)> =
+ std::collections::HashMap::new();
+ for (m, p) in items {
+ let k = (m.provider_id.clone(), m.unique_key());
+ if !last.contains_key(&k) {
+ order.push(k.clone());
+ }
+ last.insert(k, (m, p));
+ }
+ enum Change {
+ New(Box<ItemMeta>),
+ Saved {
+ id: String,
+ meta: Box<ItemMeta>,
+ written: Option<(u64, String)>,
+ },
+ }
+ let mut changes = Vec::new();
+ let mut created_files: Vec<String> = Vec::new();
+ let mut out = Vec::new();
+ let fail = |this: &Self, files: &[String], e: Error| -> Error {
+ for id in files {
+ if let Ok(p) = this.item_path(id) {
+ let _ = std::fs::remove_file(p);
+ }
+ }
+ e
+ };
+ for k in order {
+ let (mut meta, payload) = last.remove(&k).expect("keyed above");
+ meta.updated_ms = now;
+ let payload = match self.externalize(&mut meta, payload) {
+ Ok(p) => p,
+ Err(e) => return Err(fail(self, &created_files, e)),
+ };
+ match index.get(&k).cloned() {
+ Some(id) => {
+ let cur = self.meta()?.items[&id].clone();
+ let same = self
+ .read_payload(&id)
+ .map(|p| p == payload)
+ .unwrap_or(false);
+ let written = if same {
+ None
+ } else {
+ let rev = cur.rev + 1;
+ match self.write_item(&id, rev, &payload) {
+ Ok(d) => Some((rev, d)),
+ Err(e) => return Err(fail(self, &created_files, e)),
+ }
+ };
+ out.push(Upsert {
+ id: id.clone(),
+ outcome: if same {
+ UpsertOutcome::Unchanged
+ } else {
+ UpsertOutcome::Updated
+ },
+ });
+ changes.push(Change::Saved {
+ id,
+ meta: Box::new(meta),
+ written,
+ });
+ }
+ None => {
+ let id = crypto::random_id()?;
+ let digest = match self.write_item(&id, 1, &payload) {
+ Ok(d) => d,
+ Err(e) => return Err(fail(self, &created_files, e)),
+ };
+ created_files.push(id.clone());
+ meta.id = id.clone();
+ meta.rev = 1;
+ meta.record_digest = digest;
+ meta.created_ms = now;
+ index.insert(k, id.clone());
+ out.push(Upsert {
+ id,
+ outcome: UpsertOutcome::Created,
+ });
+ changes.push(Change::New(Box::new(meta)));
+ }
+ }
+ }
+ let res = self.update_meta(|m| {
+ for c in changes {
+ match c {
+ Change::New(meta) => {
+ m.items.insert(meta.id.clone(), *meta);
+ }
+ Change::Saved { id, meta, written } => {
+ let it = m
+ .items
+ .get_mut(&id)
+ .ok_or_else(|| Error::NotFound(format!("item {id}")))?;
+ // Facts about the secret refresh; the user's choices
+ // (the lock, targets, lifetime) and identity stay.
+ it.updated_ms = meta.updated_ms;
+ it.session = meta.session;
+ it.expires_ms = meta.expires_ms;
+ it.bytes = meta.bytes;
+ it.blob = meta.blob.clone();
+ it.path = meta.path.clone();
+ it.app_display = meta.app_display;
+ it.source = meta.source;
+ if let Some((rev, digest)) = written {
+ it.rev = rev;
+ it.record_digest = digest;
+ }
+ }
+ }
+ }
Ok(())
- })
+ });
+ match res {
+ Ok(()) => {
+ self.gc_blobs()?;
+ Ok(out)
+ }
+ Err(e) => Err(fail(self, &created_files, e)),
+ }
}
/// Decrypts an item's payload after checking its record against the
@@ -486,34 +750,82 @@ impl Vault {
.map_err(|e| Error::Corrupt(format!("item {id} payload: {e}")))
}
+ /// Remembers site icons (site to base64 PNG), one metadata write. The
+ /// map stays bounded.
+ pub fn set_favicons(&mut self, icons: Vec<(String, String)>) -> Result<()> {
+ const MAX: usize = 1024;
+ if icons.is_empty() {
+ return Ok(());
+ }
+ self.update_meta(|m| {
+ for (site, png) in icons {
+ if m.favicons.len() < MAX || m.favicons.contains_key(&site) {
+ m.favicons.insert(site, png);
+ }
+ }
+ Ok(())
+ })
+ }
+
/// Deletes an item (crypto-shredded: the record, with its wrapped key,
/// is removed) and drops it from grants and rules.
pub fn delete_item(&mut self, id: &str) -> Result<ItemMeta> {
- let path = self.item_path(id)?;
+ self.delete_items(&[id.to_string()])
+ .map(|mut v| v.remove(0))
+ }
+
+ /// Deletes several items with one metadata write. Fails, deleting
+ /// nothing, when any id is unknown.
+ pub fn delete_items(&mut self, ids: &[String]) -> Result<Vec<ItemMeta>> {
+ let mut seen = std::collections::HashSet::new();
+ let ids: Vec<String> = ids
+ .iter()
+ .filter(|i| seen.insert(i.as_str()))
+ .cloned()
+ .collect();
+ let ids = ids.as_slice();
+ let paths = ids
+ .iter()
+ .map(|i| self.item_path(i))
+ .collect::<Result<Vec<_>>>()?;
let removed = self.update_meta(|m| {
- let it = m
- .items
- .remove(id)
- .ok_or_else(|| Error::NotFound(format!("item {id}")))?;
+ let mut removed = Vec::new();
+ for id in ids {
+ let it = m
+ .items
+ .remove(id)
+ .ok_or_else(|| Error::NotFound(format!("item {id}")))?;
+ removed.push(it);
+ }
for g in &mut m.grants {
- g.items.retain(|i| i != id);
+ g.items.retain(|i| !ids.contains(i));
if g.items.is_empty() {
g.revoked = true;
}
}
for r in &mut m.rules {
- r.items.retain(|i| i != id);
+ r.items.retain(|i| !ids.contains(i));
}
m.rules.retain(|r| !r.items.is_empty());
- Ok(it)
+ // An icon goes with the last item of its site.
+ let live: std::collections::HashSet<String> = m
+ .items
+ .values()
+ .filter_map(|i| i.domain.as_deref().map(crate::record::site_of))
+ .collect();
+ m.favicons.retain(|site, _| live.contains(site));
+ Ok(removed)
})?;
- if path.exists() {
- // Overwrite before unlinking (best effort on copy-on-write file
- // systems; the wrapped key is what makes this a shred).
- let len = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) as usize;
- let _ = std::fs::write(&path, vec![0u8; len]);
- std::fs::remove_file(&path)?;
+ for path in paths {
+ if path.exists() {
+ // Overwrite before unlinking (best effort on copy-on-write
+ // file systems; the wrapped key is what makes this a shred).
+ let len = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) as usize;
+ let _ = std::fs::write(&path, vec![0u8; len]);
+ std::fs::remove_file(&path)?;
+ }
}
+ self.gc_blobs()?;
Ok(removed)
}
@@ -545,7 +857,7 @@ impl Vault {
mod tests {
use super::*;
use crate::crypto::KdfParams;
- use crate::model::{ItemKind, ItemPolicy, ItemSummary, PayloadEntry};
+ use crate::model::{ItemKind, ItemPolicy};
use crate::protector::{PassphraseProtector, RecoveryKey, RecoveryProtector};
pub(crate) fn pp() -> PassphraseProtector {
@@ -553,35 +865,25 @@ mod tests {
}
pub(crate) fn sample_meta() -> ItemMeta {
- ItemMeta {
- id: String::new(),
- kind: ItemKind::BrowserSite,
- label: "github.com (Chrome)".into(),
- provider_id: "chrome".into(),
- app_display: "Google Chrome".into(),
- site: Some("github.com".into()),
- account: None,
- source: "Default".into(),
- summary: ItemSummary::default(),
- warnings: vec![],
- identity_provider: false,
- policy: ItemPolicy::default(),
- created_ms: 0,
- updated_ms: 0,
- rev: 0,
- record_digest: String::new(),
- }
+ let mut m = ItemMeta::draft(
+ ItemKind::Cookie,
+ "chrome",
+ "Google Chrome",
+ Some("github.com"),
+ "user_session",
+ );
+ m.source = "Default".into();
+ m.policy = ItemPolicy::default();
+ m
}
+ /// A cookie payload whose value is `fixture-<tag>`.
pub(crate) fn sample_payload(tag: &str) -> ItemPayload {
ItemPayload {
provider_id: "chrome".into(),
scope: "full".into(),
- entries: vec![PayloadEntry {
- rel_path: "Cookies".into(),
- mode: 0o600,
- data: crypto::b64_encode(format!("fixture-{tag}").as_bytes()),
- }],
+ schema: crate::record::COOKIE_V1.into(),
+ record: format!(r#"{{"fixture":"{tag}"}}"#),
}
}
@@ -593,7 +895,7 @@ mod tests {
let mut v = Vault::create(&dir, &[&pp(), &RecoveryProtector(rk.clone())]).unwrap();
let id = v.put_item(sample_meta(), &sample_payload("a")).unwrap();
assert_eq!(v.read_payload(&id).unwrap(), sample_payload("a"));
- v.replace_payload(&id, &sample_payload("b")).unwrap();
+ v.put_item(sample_meta(), &sample_payload("b")).unwrap();
assert_eq!(v.meta().unwrap().items[&id].rev, 2);
drop(v);
@@ -610,7 +912,7 @@ mod tests {
v.lock();
v.unlock(&pp()).unwrap();
let removed = v.delete_item(&id).unwrap();
- assert_eq!(removed.site.as_deref(), Some("github.com"));
+ assert_eq!(removed.domain.as_deref(), Some("github.com"));
assert!(!dir.join("items").join(format!("{id}.sealed")).exists());
#[cfg(unix)]
@@ -669,11 +971,13 @@ mod tests {
let dir = d.path().join("kv");
let mut v = Vault::create(&dir, &[&pp()]).unwrap();
let a = v.put_item(sample_meta(), &sample_payload("a")).unwrap();
- let b = v.put_item(sample_meta(), &sample_payload("b")).unwrap();
+ let mut other = sample_meta();
+ other.key = "other".into();
+ let b = v.put_item(other, &sample_payload("b")).unwrap();
let pa = dir.join("items").join(format!("{a}.sealed"));
let pb = dir.join("items").join(format!("{b}.sealed"));
let old_a = std::fs::read(&pa).unwrap();
- v.replace_payload(&a, &sample_payload("a2")).unwrap();
+ v.put_item(sample_meta(), &sample_payload("a2")).unwrap();
// Rollback of one item to its previous revision.
std::fs::write(&pa, &old_a).unwrap();
assert!(matches!(v.read_payload(&a), Err(Error::Corrupt(_))));
@@ -740,7 +1044,7 @@ mod tests {
let item_path = dir.join("items").join(format!("{id}.sealed"));
let item_snap = std::fs::read(&item_path).unwrap();
// Move the vault forward: trip the kill switch and rotate the payload.
- v.replace_payload(&id, &sample_payload("b")).unwrap();
+ v.put_item(sample_meta(), &sample_payload("b")).unwrap();
v.update_meta(|m| {
m.settings.disabled = true;
Ok(())
@@ -787,4 +1091,226 @@ mod tests {
v.unlock(&RecoveryProtector(rk)).unwrap();
assert_eq!(v.header().protectors[0].id, rec.id);
}
+
+ fn item(kind: ItemKind, domain: Option<&str>, key: &str) -> ItemMeta {
+ ItemMeta {
+ kind,
+ domain: domain.map(str::to_string),
+ key: key.into(),
+ ..sample_meta()
+ }
+ }
+
+ fn vault(d: &tempfile::TempDir) -> Vault {
+ Vault::create(&d.path().join("kv"), &[&pp()]).unwrap()
+ }
+
+ #[test]
+ fn saving_an_app_twice_upserts_by_key_and_never_duplicates() {
+ let d = tempfile::tempdir().unwrap();
+ let mut v = vault(&d);
+ let batch = |tag: &str| {
+ vec![
+ (
+ item(ItemKind::Cookie, Some("github.com"), "user_session"),
+ sample_payload(tag),
+ ),
+ (
+ item(ItemKind::Cookie, Some("github.com"), "_gh_sess"),
+ sample_payload(tag),
+ ),
+ (
+ item(ItemKind::File, None, "Default/Bookmarks"),
+ sample_payload(tag),
+ ),
+ ]
+ };
+ let first = v.upsert_items(batch("a")).unwrap();
+ assert!(first.iter().all(|u| u.outcome == UpsertOutcome::Created));
+ let created = v.meta().unwrap().items.clone();
+ assert_eq!(created.len(), 3);
+
+ // The user unlocks one item between the two saves.
+ let id0 = first[0].id.clone();
+ v.update_meta(|m| {
+ m.items.get_mut(&id0).unwrap().policy.unattended = true;
+ Ok(())
+ })
+ .unwrap();
+ std::thread::sleep(std::time::Duration::from_millis(3));
+
+ // Same value: unchanged, timestamps move, nothing duplicates.
+ let again = v.upsert_items(batch("a")).unwrap();
+ assert_eq!(v.meta().unwrap().items.len(), 3);
+ assert!(again.iter().all(|u| u.outcome == UpsertOutcome::Unchanged));
+ assert_eq!(
+ again.iter().map(|u| &u.id).collect::<Vec<_>>(),
+ first.iter().map(|u| &u.id).collect::<Vec<_>>()
+ );
+ let it = &v.meta().unwrap().items[&id0];
+ assert_eq!(it.created_ms, created[&id0].created_ms);
+ assert!(it.updated_ms > created[&id0].updated_ms, "updated-at moves");
+ assert_eq!(it.rev, 1, "an unchanged value is not rewritten");
+ assert!(it.policy.unattended, "saving again keeps the lock state");
+
+ // A changed value: updated in place with a new revision.
+ let changed = v.upsert_items(batch("b")).unwrap();
+ assert!(changed.iter().all(|u| u.outcome == UpsertOutcome::Updated));
+ assert_eq!(v.meta().unwrap().items.len(), 3);
+ assert_eq!(v.meta().unwrap().items[&id0].rev, 2);
+ assert_eq!(v.read_payload(&id0).unwrap(), sample_payload("b"));
+ }
+
+ #[test]
+ fn keys_are_per_app_and_per_type() {
+ let d = tempfile::tempdir().unwrap();
+ let mut v = vault(&d);
+ let mut slack_cookie = item(ItemKind::Cookie, Some("github.com"), "user_session");
+ slack_cookie.provider_id = "slack".into();
+ let out = v
+ .upsert_items(vec![
+ (
+ item(ItemKind::Cookie, Some("github.com"), "user_session"),
+ sample_payload("1"),
+ ),
+ // Same domain and key in another app: a different item.
+ (slack_cookie, sample_payload("2")),
+ // Same domain and key, another type: a different item.
+ (
+ item(ItemKind::LocalStorage, Some("github.com"), "user_session"),
+ sample_payload("3"),
+ ),
+ // Domains compare case-insensitively.
+ (
+ item(ItemKind::Cookie, Some("GitHub.com"), "user_session"),
+ sample_payload("4"),
+ ),
+ ])
+ .unwrap();
+ assert_eq!(v.meta().unwrap().items.len(), 3);
+ assert_eq!(out.len(), 3, "one result per distinct key");
+ assert_eq!(v.read_payload(&out[0].id).unwrap(), sample_payload("4"));
+ }
+
+ #[test]
+ fn delete_items_is_one_write_and_crypto_shreds() {
+ let d = tempfile::tempdir().unwrap();
+ let mut v = vault(&d);
+ let ids: Vec<String> = v
+ .upsert_items(vec![
+ (
+ item(ItemKind::Cookie, Some("a.test"), "a"),
+ sample_payload("a"),
+ ),
+ (
+ item(ItemKind::Cookie, Some("b.test"), "b"),
+ sample_payload("b"),
+ ),
+ (item(ItemKind::File, None, "x/y"), sample_payload("c")),
+ ])
+ .unwrap()
+ .into_iter()
+ .map(|u| u.id)
+ .collect();
+ let before = v.meta().unwrap().generation;
+ let removed = v
+ .delete_items(&[ids[0].clone(), ids[1].clone(), ids[0].clone()])
+ .unwrap();
+ assert_eq!(removed.len(), 2);
+ assert_eq!(v.meta().unwrap().generation, before + 1);
+ assert_eq!(v.meta().unwrap().items.len(), 1);
+ for id in &ids[..2] {
+ assert!(
+ !d.path()
+ .join("kv/items")
+ .join(format!("{id}.sealed"))
+ .exists()
+ );
+ }
+ // An unknown id deletes nothing.
+ assert!(v.delete_items(&[ids[2].clone(), "nope".into()]).is_err());
+ assert_eq!(v.meta().unwrap().items.len(), 1);
+ }
+
+ #[test]
+ fn a_format_1_vault_is_reported_not_misread() {
+ let d = tempfile::tempdir().unwrap();
+ let dir = d.path().join("kv");
+ drop(Vault::create(&dir, &[&pp()]).unwrap());
+ let mut header: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(dir.join("vault.json")).unwrap()).unwrap();
+ header["format"] = 1.into();
+ std::fs::write(dir.join("vault.json"), serde_json::to_vec(&header).unwrap()).unwrap();
+ assert!(matches!(Vault::open(&dir), Err(Error::OldFormat(1))));
+ }
+
+ #[test]
+ fn big_files_become_content_addressed_blobs_and_come_back_inline() {
+ use base64::Engine as _;
+ let d = tempfile::tempdir().unwrap();
+ let mut v = vault(&d);
+ let big = vec![7u8; crate::record::INLINE_FILE_LIMIT + 1];
+ let rec = |path: &str, bytes: &[u8]| {
+ let n = crate::record::file_record(path, 0o600, bytes).unwrap();
+ let (m, p) = n.into_item("chrome", "Chrome", "Default", "full");
+ (m, p)
+ };
+ let out = v
+ .upsert_items(vec![
+ rec("Default/History", &big),
+ rec("Default/History.copy", &big),
+ rec("Default/Bookmarks", b"{}"),
+ ])
+ .unwrap();
+ let meta = v.meta().unwrap().items.clone();
+ let hash = meta[&out[0].id].blob.clone().expect("a big file is a blob");
+ assert_eq!(
+ meta[&out[1].id].blob.as_ref(),
+ Some(&hash),
+ "same bytes, one blob"
+ );
+ assert!(meta[&out[2].id].blob.is_none(), "a small file stays inline");
+ assert_eq!(
+ std::fs::read_dir(d.path().join("kv/blobs"))
+ .unwrap()
+ .count(),
+ 1
+ );
+
+ // The record never carries the bytes.
+ let p = v.read_payload(&out[0].id).unwrap();
+ assert!(
+ !p.record.contains("content") && p.record.contains(&hash),
+ "{}",
+ p.record
+ );
+ let inlined = v.inline_blobs(&p).unwrap();
+ let f: crate::record::FileRecord = serde_json::from_str(&inlined.record).unwrap();
+ assert_eq!(
+ base64::engine::general_purpose::STANDARD
+ .decode(f.content.clone().unwrap())
+ .unwrap(),
+ big
+ );
+ assert_eq!(&v.read_blob(&hash).unwrap()[..], &big[..]);
+
+ // No plaintext, and a swapped blob is refused.
+ let blob = d.path().join("kv/blobs").join(format!("{hash}.sealed"));
+ let on_disk = std::fs::read(&blob).unwrap();
+ assert!(!String::from_utf8_lossy(&on_disk).contains("BwcHBwcH"));
+ std::fs::write(&blob, b"{}").unwrap();
+ assert!(v.read_blob(&hash).is_err());
+ std::fs::write(&blob, &on_disk).unwrap();
+
+ // Deleting one holder keeps the blob; deleting the last shreds it.
+ v.delete_items(&[out[0].id.clone()]).unwrap();
+ assert!(blob.exists());
+ v.delete_items(&[out[1].id.clone()]).unwrap();
+ assert!(!blob.exists(), "no item names it any more");
+ // Saving the same big file again is "unchanged".
+ let again = v
+ .upsert_items(vec![rec("Default/Bookmarks", b"{}")])
+ .unwrap();
+ assert_eq!(again[0].outcome, UpsertOutcome::Unchanged);
+ }
}
diff --git a/libs/cua/crates/cua-keyvault/tests/broker.rs b/libs/cua/crates/cua-keyvault/tests/broker.rs
index ef16a15fc8..3ce4c3920b 100644
--- a/libs/cua/crates/cua-keyvault/tests/broker.rs
+++ b/libs/cua/crates/cua-keyvault/tests/broker.rs
@@ -9,21 +9,23 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use cua_keyvault::broker::{
- AccessRequest, ApproveOptions, Backend, Broker, BrokerConfig, Candidate, Captured, Decision,
+ AccessRequest, ApproveOptions, Backend, Broker, BrokerConfig, Captured, Decision,
DeliveryOutcome, FakePresence, ImportSpec, InitRequest, Inventory, RuleSpec, Selector,
SiteChoice, TeleportRequest, TeleportStage, UnlockRequest,
};
use cua_keyvault::model::{
- CookieInfo, ItemKind, ItemMeta, ItemPayload, ItemPolicy, ItemSummary, NO_EXPIRY, PayloadEntry,
- RuleCaller,
+ ItemKind, ItemMeta, ItemPolicy, LoginRecord, NO_EXPIRY, PayloadEntry, RuleCaller,
};
use cua_keyvault::protector::ProtectorKind;
+use cua_keyvault::record::{self, CookieRecord};
use cua_keyvault::{CallerIdentity, Error, Signing};
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct FakeBackend {
delivered: Mutex<Vec<(String, String, Vec<String>, u64)>>,
+ /// The cookie hosts each delivery carried (from its `cookies.json`).
+ delivered_hosts: Mutex<Vec<Vec<String>>>,
wiped: Mutex<Vec<(String, String)>>,
notified: Mutex<Vec<String>>,
/// The `launch` flag of every launching delivery.
@@ -46,48 +48,56 @@ impl FakeBackend {
}
}
-fn site_item(app: &str, site: &str, passwords: bool) -> Captured {
- Captured {
- meta: ItemMeta {
- id: String::new(),
- kind: if passwords {
- ItemKind::SitePasswords
- } else {
- ItemKind::BrowserSite
- },
- label: format!("{site} ({app})"),
- provider_id: app.into(),
- app_display: app.into(),
- site: Some(site.into()),
- account: None,
- source: "Default".into(),
- summary: ItemSummary {
- cookies: vec![CookieInfo {
- name: "user_session".into(),
- domain: format!(".{site}"),
- session: true,
- expires_ms: None,
- }],
- ..Default::default()
- },
- warnings: vec![],
- identity_provider: false,
- policy: ItemPolicy::default(),
- created_ms: 0,
- updated_ms: 0,
- rev: 0,
- record_digest: String::new(),
- },
- payload: ItemPayload {
- provider_id: app.into(),
- scope: "full".into(),
- entries: vec![PayloadEntry {
- rel_path: format!("cookies/{site}"),
- mode: 0o600,
- data: "RklYVFVSRS1TRUNSRVQ=".into(),
- }],
- },
- }
+fn cap(n: record::NewRecord, app: &str) -> Captured {
+ let (mut meta, payload) = n.into_item(app, app, "Default", "full");
+ meta.session = true;
+ Captured { meta, payload }
+}
+
+/// One cookie of `site`.
+fn cookie_item(app: &str, site: &str, name: &str) -> Captured {
+ cap(
+ record::cookie_record(&CookieRecord {
+ creation_utc: None,
+ expires_utc: 0,
+ host_key: format!(".{site}"),
+ http_only: true,
+ last_update_utc: None,
+ name: name.into(),
+ partition_key: None,
+ last_access_utc: None,
+ source_type: None,
+ has_cross_site_ancestor: None,
+ path: "/".into(),
+ priority: None,
+ same_site: 1,
+ secure: true,
+ source_port: None,
+ source_scheme: None,
+ value: b"FIXTURE-SECRET".to_vec(),
+ })
+ .unwrap(),
+ app,
+ )
+}
+
+fn file_item(app: &str, path: &str) -> Captured {
+ cap(
+ record::file_record(path, 0o600, b"FILE-SECRET").unwrap(),
+ app,
+ )
+}
+
+fn password_item(app: &str, site: &str, user: &str) -> Captured {
+ cap(
+ record::password_record(&LoginRecord {
+ origin: format!("https://{site}"),
+ username: user.into(),
+ password: "PW-SECRET".into(),
+ })
+ .unwrap(),
+ app,
+ )
}
#[async_trait::async_trait]
@@ -107,13 +117,10 @@ impl Backend for FakeBackend {
provider_id: app.into(),
app_display: app.into(),
profile: None,
- candidates: vec![Candidate {
- kind: ItemKind::BrowserSite,
- site: Some("github.com".into()),
- accounts: vec![],
- label: "github.com".into(),
- summary: ItemSummary::default(),
- warnings: vec![],
+ domains: vec![cua_keyvault::broker::DomainInventory {
+ domain: "github.com".into(),
+ cookies: 2,
+ ..Default::default()
}],
notes: vec![],
})
@@ -123,16 +130,19 @@ impl Backend for FakeBackend {
self.captures.lock().unwrap().push(spec.clone());
let mut out = Vec::new();
for s in &spec.sites {
- out.push(site_item(&spec.app, &s.site, false));
+ out.push(cookie_item(&spec.app, &s.site, "user_session"));
if s.include_passwords {
- out.push(site_item(&spec.app, &s.site, true));
+ out.push(password_item(&spec.app, &s.site, "octo"));
}
}
if spec.whole_app {
- let mut c = site_item(&spec.app, "app", false);
- c.meta.kind = ItemKind::AppSession;
- c.meta.site = None;
- out.push(c);
+ for p in spec
+ .paths
+ .clone()
+ .unwrap_or_else(|| vec!["app/session.json".into()])
+ {
+ out.push(file_item(&spec.app, &p));
+ }
}
Ok(out)
}
@@ -141,13 +151,26 @@ impl Backend for FakeBackend {
&self,
target: &str,
provider_id: &str,
- payloads: Vec<ItemPayload>,
+ _scope: &str,
+ entries: Vec<PayloadEntry>,
expires_ms: u64,
) -> cua_keyvault::Result<DeliveryOutcome> {
- let paths: Vec<String> = payloads
+ let paths: Vec<String> = entries.iter().map(|e| e.rel_path.clone()).collect();
+ let hosts: Vec<String> = entries
.iter()
- .flat_map(|p| p.entries.iter().map(|e| e.rel_path.clone()))
+ .filter(|e| e.rel_path == record::COOKIES_ENTRY)
+ .flat_map(|e| {
+ use base64::Engine as _;
+ let raw = base64::engine::general_purpose::STANDARD
+ .decode(&e.data)
+ .unwrap();
+ let rows: Vec<serde_json::Value> = serde_json::from_slice(&raw).unwrap();
+ rows.iter()
+ .map(|r| r["host_key"].as_str().unwrap().to_string())
+ .collect::<Vec<_>>()
+ })
.collect();
+ self.delivered_hosts.lock().unwrap().push(hosts);
let mut d = self.delivered.lock().unwrap();
d.push((target.into(), provider_id.into(), paths.clone(), expires_ms));
Ok(DeliveryOutcome {
@@ -162,7 +185,8 @@ impl Backend for FakeBackend {
&self,
target: &str,
provider_id: &str,
- payloads: Vec<ItemPayload>,
+ scope: &str,
+ entries: Vec<PayloadEntry>,
expires_ms: u64,
stage: cua_keyvault::broker::StageSink,
) -> cua_keyvault::Result<DeliveryOutcome> {
@@ -170,22 +194,24 @@ impl Backend for FakeBackend {
stage(TeleportStage::Uploading { done: 0, total: 8 });
stage(TeleportStage::Uploading { done: 8, total: 8 });
stage(TeleportStage::Importing);
- self.deliver(target, provider_id, payloads, expires_ms)
+ self.deliver(target, provider_id, scope, entries, expires_ms)
.await
}
+ #[allow(clippy::too_many_arguments)]
async fn deliver_launching(
&self,
target: &str,
provider_id: &str,
- payloads: Vec<ItemPayload>,
+ scope: &str,
+ entries: Vec<PayloadEntry>,
expires_ms: u64,
stage: cua_keyvault::broker::StageSink,
launch: bool,
) -> cua_keyvault::Result<DeliveryOutcome> {
self.launches.lock().unwrap().push(launch);
let mut out = self
- .deliver_with_progress(target, provider_id, payloads, expires_ms, stage)
+ .deliver_with_progress(target, provider_id, scope, entries, expires_ms, stage)
.await?;
out.launched = launch;
Ok(out)
@@ -253,6 +279,13 @@ async fn rig() -> Rig {
}
}
+/// Every item, with names visible (opens the browse window).
+async fn all_items(r: &Rig) -> Vec<ItemMeta> {
+ r.broker.browse(&r.cua).await.unwrap();
+ r.broker.list_items(&r.cua, 0, 1000).await.unwrap().items
+}
+
+/// Imports `sites` and returns their cookie items, in site order.
async fn import_sites(r: &Rig, sites: &[&str]) -> Vec<ItemMeta> {
r.broker
.import(
@@ -271,7 +304,20 @@ async fn import_sites(r: &Rig, sites: &[&str]) -> Vec<ItemMeta> {
},
)
.await
- .unwrap()
+ .unwrap();
+ let items = all_items(r).await;
+ sites
+ .iter()
+ .filter_map(|s| {
+ items
+ .iter()
+ .find(|i| {
+ i.kind == ItemKind::Cookie
+ && i.domain.as_deref().map(|d| d.trim_start_matches('.')) == Some(*s)
+ })
+ .cloned()
+ })
+ .collect()
}
async fn grant(
@@ -288,7 +334,6 @@ async fn grant(
selectors: vec![Selector::Site {
app: "chrome".into(),
site: site.into(),
- account: None,
}],
targets: vec![target.into()],
uses: Some(0),
@@ -317,7 +362,7 @@ async fn third_parties_cannot_use_first_party_operations() {
let r = rig().await;
import_sites(&r, &["github.com"]).await;
for res in [
- r.broker.list_items(&r.koala).await.map(|_| ()),
+ r.broker.list_items(&r.koala, 0, 10).await.map(|_| ()),
r.broker.list_pending(&r.koala).await.map(|_| ()),
r.broker.set_disabled(&r.koala, false).await,
r.broker.list_grants(&r.koala).await.map(|_| ()),
@@ -338,7 +383,6 @@ async fn third_parties_cannot_use_first_party_operations() {
selectors: vec![Selector::Site {
app: "chrome".into(),
site: "github.com".into(),
- account: None,
}],
targets: vec!["dev-1".into()],
..Default::default()
@@ -364,11 +408,11 @@ async fn consent_grants_a_caller_bound_scoped_token() {
let items = import_sites(&r, &["github.com", "gitlab.com"]).await;
let github = items
.iter()
- .find(|i| i.site.as_deref() == Some("github.com"))
+ .find(|i| i.domain.as_deref() == Some(".github.com"))
.unwrap();
let gitlab = items
.iter()
- .find(|i| i.site.as_deref() == Some("gitlab.com"))
+ .find(|i| i.domain.as_deref() == Some(".gitlab.com"))
.unwrap();
let (token, granted) = grant(&r, &r.koala, "github.com", "dev-1").await;
assert_eq!(granted, vec![github.id.clone()]);
@@ -384,6 +428,8 @@ async fn consent_grants_a_caller_bound_scoped_token() {
token: Some(token.clone()),
items,
target: target.into(),
+ include_passwords: false,
+ launch: false,
};
let out = r
.broker
@@ -423,6 +469,8 @@ async fn consent_grants_a_caller_bound_scoped_token() {
token: Some(forged),
items: vec![github.id.clone()],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
}
)
.await
@@ -437,6 +485,8 @@ async fn consent_grants_a_caller_bound_scoped_token() {
token: None,
items: vec![github.id.clone()],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
}
)
.await,
@@ -456,6 +506,8 @@ async fn f1_grant_is_bound_to_the_immutable_target_id_not_the_name() {
token: Some(token),
items: granted.clone(),
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
};
// While the id is unchanged the token works.
r.broker.teleport(&r.koala, req.clone()).await.unwrap();
@@ -512,6 +564,8 @@ async fn f1_unattended_rule_is_bound_to_the_immutable_target_id() {
token: None,
items: vec![id],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
};
let out = r.broker.teleport(&r.koala, req.clone()).await.unwrap();
assert_eq!(out.authority, format!("rule={}", rule.id));
@@ -570,6 +624,8 @@ async fn single_use_grants_and_other_callers_cannot_collect_decisions() {
token: Some(token),
items: vec![items[0].id.clone()],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
};
r.broker.teleport(&r.koala, req.clone()).await.unwrap();
// Default grants are single use.
@@ -614,6 +670,8 @@ async fn presence_is_required_to_expand_access() {
token: None,
items: vec![items[0].id.clone()],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
}
)
.await,
@@ -647,7 +705,10 @@ async fn presence_is_required_to_expand_access() {
assert!(err.to_string().contains("confirm_passwords"), "{err}");
}
-async fn import_sites_result(r: &Rig, site: &str) -> cua_keyvault::Result<Vec<ItemMeta>> {
+async fn import_sites_result(
+ r: &Rig,
+ site: &str,
+) -> cua_keyvault::Result<cua_keyvault::broker::ImportReport> {
r.broker
.import(
&r.cua,
@@ -674,6 +735,8 @@ async fn kill_switch_blocks_everything_and_kills_old_tokens() {
token: Some(token),
items: vec![items[0].id.clone()],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
};
assert!(matches!(
r.broker.teleport(&r.koala, req.clone()).await,
@@ -722,7 +785,9 @@ async fn revoking_one_site_leaves_the_others() {
TeleportRequest {
token: Some(t1),
items: i1,
- target: "dev-1".into()
+ target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
}
)
.await
@@ -735,6 +800,8 @@ async fn revoking_one_site_leaves_the_others() {
token: Some(t2),
items: i2.clone(),
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -742,11 +809,14 @@ async fn revoking_one_site_leaves_the_others() {
// Deleting github.com wipes nothing of gitlab's delivery.
let github = items
.iter()
- .find(|i| i.site.as_deref() == Some("github.com"))
+ .find(|i| i.domain.as_deref() == Some(".github.com"))
+ .unwrap();
+ r.broker
+ .delete_items(&r.cua, vec![github.id.clone()])
+ .await
.unwrap();
- r.broker.delete_item(&r.cua, &github.id).await.unwrap();
assert!(r.backend.wiped.lock().unwrap().is_empty());
- let left = r.broker.list_items(&r.cua).await.unwrap();
+ let left = all_items(&r).await;
assert_eq!(left.len(), 1);
assert_eq!(left[0].id, i2[0]);
}
@@ -818,6 +888,8 @@ async fn unattended_rules_need_signed_known_callers_and_expire() {
token: None,
items: vec![id.clone()],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
};
let asked_before = r.presence.asked.lock().unwrap().len();
let out = r.broker.teleport(&r.koala, req.clone()).await.unwrap();
@@ -863,6 +935,8 @@ async fn deliveries_supersede_and_release_wipes() {
token: None,
items: vec![id.clone()],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -871,8 +945,16 @@ async fn deliveries_supersede_and_release_wipes() {
let delivered = r.backend.delivered.lock().unwrap().clone();
assert_eq!(delivered.len(), 2);
// The second delivery carries both sites (one live import per target and
- // browser) and supersedes the first.
- assert_eq!(delivered[1].2.len(), 2);
+ // browser) and supersedes the first. Cookies travel as one `cookies.json`.
+ assert_eq!(delivered[1].2, vec!["cookies.json".to_string()]);
+ let hosts = r.backend.delivered_hosts.lock().unwrap().clone();
+ assert_eq!(hosts[0], vec![".github.com".to_string()]);
+ let mut both = hosts[1].clone();
+ both.sort();
+ assert_eq!(
+ both,
+ vec![".github.com".to_string(), ".gitlab.com".to_string()]
+ );
assert_eq!(
r.backend.wiped.lock().unwrap().as_slice(),
[("dev-1".to_string(), "imp-1".to_string())]
@@ -901,6 +983,8 @@ async fn teleport_to(r: &Rig, id: &str, target: &str) {
token: None,
items: vec![id.to_string()],
target: target.into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -993,7 +1077,10 @@ async fn a_copy_without_expiry_still_goes_on_wipe_delete_and_the_kill_switch() {
["dev-2", "dev-3"]
);
// Deleting the item wipes its copies.
- r.broker.delete_item(&r.cua, &items[1].id).await.unwrap();
+ r.broker
+ .delete_items(&r.cua, vec![items[1].id.clone()])
+ .await
+ .unwrap();
assert!(live(r.broker.list_deliveries(&r.cua).await.unwrap()).is_empty());
// The kill switch wipes the rest.
teleport_to(&r, &items[0].id, "dev-4").await;
@@ -1013,6 +1100,8 @@ async fn audit_records_decisions_without_secrets_or_sites() {
token: Some(token.clone()),
items,
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -1025,6 +1114,8 @@ async fn audit_records_decisions_without_secrets_or_sites() {
token: Some(token.clone()),
items: vec!["00".into()],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await;
@@ -1100,12 +1191,10 @@ async fn approval_imports_missing_sites_and_can_narrow() {
Selector::Site {
app: "chrome".into(),
site: "github.com".into(),
- account: None,
},
Selector::Site {
app: "chrome".into(),
site: "bank.example".into(),
- account: None,
},
],
targets: vec!["dev-1".into(), "dev-2".into()],
@@ -1137,7 +1226,7 @@ async fn approval_imports_missing_sites_and_can_narrow() {
caps.iter()
.all(|c| c.sites.iter().all(|s| !s.include_passwords))
);
- assert_eq!(r.broker.list_items(&r.cua).await.unwrap().len(), 2);
+ assert_eq!(all_items(&r).await.len(), 2);
}
#[tokio::test]
@@ -1146,7 +1235,7 @@ async fn lock_and_unlock() {
import_sites(&r, &["github.com"]).await;
r.broker.lock(&r.cua).await.unwrap();
assert!(matches!(
- r.broker.list_items(&r.cua).await,
+ r.broker.list_items(&r.cua, 0, 10).await,
Err(Error::Locked)
));
assert!(
@@ -1171,7 +1260,7 @@ async fn lock_and_unlock() {
)
.await
.unwrap();
- assert_eq!(r.broker.list_items(&r.cua).await.unwrap().len(), 1);
+ assert_eq!(all_items(&r).await.len(), 1);
let v = r.broker.verify_audit(&r.cua).await.unwrap();
assert!(v.ok());
assert!(v.entries >= v.unauthenticated);
@@ -1200,7 +1289,6 @@ async fn unsigned_callers_share_one_prompt_budget() {
selectors: vec![Selector::Site {
app: "chrome".into(),
site: "github.com".into(),
- account: None,
}],
targets: vec!["dev-1".into()],
..Default::default()
@@ -1223,43 +1311,88 @@ async fn unsigned_callers_share_one_prompt_budget() {
assert!(ask(r.koala.clone()).await.is_ok());
}
-/// Red-team F17: bulk `ListItems` returns coarse metadata only (no cookie names
-/// or domains); the full detail needs user presence via `DescribeItem`.
+/// Red-team F17: bulk `ListItems` returns the app, type and lock state only
+/// (no domains or keys); names need the browse window, which needs user
+/// presence, and a third party never gets them at all.
#[tokio::test]
-async fn bulk_enumeration_is_coarse_and_detail_needs_presence() {
+async fn bulk_enumeration_hides_names_until_the_browse_window_opens() {
let r = rig().await;
- let items = import_sites(&r, &["github.com"]).await;
- let id = items[0].id.clone();
+ import_sites(&r, &["github.com"]).await;
+ // (the helper browsed to read the names back: close the window)
+ r.broker.end_browse(&r.cua).await.unwrap();
- let listed = r.broker.list_items(&r.cua).await.unwrap();
- let it = listed.iter().find(|i| i.id == id).unwrap();
- // The item is present with its label and cookie count, but the cookie name
- // and domain are stripped.
- assert_eq!(it.summary.cookies.len(), 1);
+ let page = r.broker.list_items(&r.cua, 0, 100).await.unwrap();
+ assert!(!page.names_visible);
+ assert_eq!(page.total, 1);
+ let it = &page.items[0];
+ assert_eq!(it.provider_id, "chrome");
+ assert_eq!(it.kind, ItemKind::Cookie);
assert!(
- it.summary.cookies[0].name.is_empty(),
- "cookie name leaked in bulk list"
+ it.domain.is_none() && it.key.is_empty(),
+ "names leaked in the bulk list"
);
+ let json = serde_json::to_string(&page).unwrap();
assert!(
- it.summary.cookies[0].domain.is_empty(),
- "cookie domain leaked in bulk list"
+ !json.contains("github.com") && !json.contains("user_session"),
+ "{json}"
);
- // DescribeItem needs presence.
+ // Browsing needs presence.
r.presence.set(false);
assert!(matches!(
- r.broker.describe_item(&r.cua, &id).await,
+ r.broker.browse(&r.cua).await,
Err(Error::PresenceFailed(_))
));
- // With presence it returns the full cookie name and domain.
+ assert!(
+ !r.broker
+ .list_items(&r.cua, 0, 100)
+ .await
+ .unwrap()
+ .names_visible
+ );
+ // Inventory is a name map of the host app too: it needs the window.
+ assert!(matches!(
+ r.broker.inventory(&r.cua, "chrome", None).await,
+ Err(Error::PresenceFailed(_))
+ ));
+ // With presence the window opens and the names appear.
+ r.presence.set(true);
+ r.broker.browse(&r.cua).await.unwrap();
+ let page = r.broker.list_items(&r.cua, 0, 100).await.unwrap();
+ assert!(page.names_visible);
+ assert_eq!(page.items[0].domain.as_deref(), Some(".github.com"));
+ assert_eq!(page.items[0].key, "user_session");
+ // While it is open, the inventory does not ask again.
+ r.presence.set(false);
+ assert!(r.broker.inventory(&r.cua, "chrome", None).await.is_ok());
+ // Locking the vault closes the window.
r.presence.set(true);
- let full = r.broker.describe_item(&r.cua, &id).await.unwrap();
- assert_eq!(full.summary.cookies[0].name, "user_session");
- assert_eq!(full.summary.cookies[0].domain, ".github.com");
+ r.broker.lock(&r.cua).await.unwrap();
+ r.broker
+ .unlock(
+ &r.cua,
+ UnlockRequest {
+ passphrase: Some("correct horse battery".into()),
+ recovery_key: None,
+ },
+ )
+ .await
+ .unwrap();
+ assert!(
+ !r.broker
+ .list_items(&r.cua, 0, 100)
+ .await
+ .unwrap()
+ .names_visible
+ );
- // A third party cannot describe items at all.
+ // A third party cannot browse or list at all.
+ assert!(matches!(
+ r.broker.browse(&r.koala).await,
+ Err(Error::Forbidden(_))
+ ));
assert!(matches!(
- r.broker.describe_item(&r.koala, &id).await,
+ r.broker.list_items(&r.koala, 0, 10).await,
Err(Error::Forbidden(_))
));
}
@@ -1291,6 +1424,8 @@ async fn broker_records_counts_and_verified_caller_kinds_only() {
token: Some(token.clone()),
items: granted.clone(),
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -1304,6 +1439,8 @@ async fn broker_records_counts_and_verified_caller_kinds_only() {
token: Some(token),
items: granted,
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await;
@@ -1634,6 +1771,8 @@ async fn a_delivery_the_audit_log_cannot_record_is_refused() {
token: Some(token),
items: ids,
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await;
@@ -1647,6 +1786,8 @@ async fn a_delivery_the_audit_log_cannot_record_is_refused() {
token: None,
items: vec![items[0].id.clone()],
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await;
@@ -1669,6 +1810,8 @@ async fn deliveries_are_authorized_in_the_log_and_the_kill_switch_wipes_them() {
token: Some(token),
items: ids,
target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -1680,6 +1823,8 @@ async fn deliveries_are_authorized_in_the_log_and_the_kill_switch_wipes_them() {
token: None,
items: vec![items[0].id.clone()],
target: "dev-2".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -1819,7 +1964,7 @@ async fn import_and_teleport_asks_presence_once_and_delivers_and_saves() {
assert_eq!(r.backend.delivered.lock().unwrap().len(), 1);
assert_eq!(r.backend.delivered.lock().unwrap()[0].0, "dev-1");
// Saved: the item is still in the vault afterward.
- let items = r.broker.list_items(&r.cua).await.unwrap();
+ let items = all_items(&r).await;
assert_eq!(items.len(), 1, "{items:?}");
}
@@ -1847,7 +1992,7 @@ async fn import_and_teleport_with_save_false_forgets_the_item_but_keeps_the_deli
// ...and was never wiped (a save:false teleport is not an undo).
assert!(r.backend.wiped.lock().unwrap().is_empty());
// ...but the vault no longer holds the item.
- assert!(r.broker.list_items(&r.cua).await.unwrap().is_empty());
+ assert!(all_items(&r).await.is_empty());
// The audit still shows the whole story: capture, authorize, deliver,
// and the forgetting.
let tail = r.broker.audit_tail(&r.cua, 100).await.unwrap();
diff --git a/libs/cua/crates/cua-keyvault/tests/common/mod.rs b/libs/cua/crates/cua-keyvault/tests/common/mod.rs
index 6d38d31482..a65012e7be 100644
--- a/libs/cua/crates/cua-keyvault/tests/common/mod.rs
+++ b/libs/cua/crates/cua-keyvault/tests/common/mod.rs
@@ -15,9 +15,8 @@ use cua_keyvault::broker::{
Backend, Broker, BrokerConfig, Captured, DeliveryOutcome, FakePresence, ImportSpec,
InitRequest, Inventory, LoginFill, LoginFilled, PasswordImportSpec,
};
-use cua_keyvault::model::{
- ItemKind, ItemMeta, ItemPayload, ItemPolicy, ItemSummary, LoginRecord, PayloadEntry,
-};
+use cua_keyvault::model::{ItemKind, ItemMeta, LoginRecord, PayloadEntry};
+use cua_keyvault::record::{self, CookieRecord};
pub const PASSWORD: &str = "s3cret-Pa55";
@@ -30,49 +29,97 @@ pub struct FakeBackend {
pub delivered: Mutex<Vec<(String, Vec<String>)>>,
/// Refuse the fill (a page on the wrong origin).
pub refuse_fill: Mutex<bool>,
+ /// (target, import id) of every wipe.
+ pub wiped: Mutex<Vec<(String, String)>>,
+ /// Bumped to make the next capture read different values.
+ pub generation: Mutex<u32>,
+ /// The cookie hosts each delivery carried.
+ pub delivered_hosts: Mutex<Vec<Vec<String>>>,
+ /// The icons the source browser's local store holds (site, png bytes).
+ pub icons: Mutex<Vec<(String, Vec<u8>)>>,
+}
+
+fn captured(n: record::NewRecord, app: &str) -> Captured {
+ let (meta, payload) = n.into_item(app, "Chrome", "Default", "full");
+ Captured { meta, payload }
}
-pub fn logins_item(site: &str, logins: &[(&str, &str, &str)]) -> Captured {
- let records: Vec<LoginRecord> = logins
+/// One captured Password item per login (the vault keeps one secret per
+/// item, keyed by origin and username).
+pub fn logins_items(logins: &[(&str, &str, &str)]) -> Vec<Captured> {
+ logins
.iter()
- .map(|(o, u, p)| LoginRecord {
- origin: (*o).into(),
- username: (*u).into(),
- password: (*p).into(),
+ .map(|(o, u, p)| {
+ captured(
+ record::password_record(&LoginRecord {
+ origin: (*o).into(),
+ username: (*u).into(),
+ password: (*p).into(),
+ })
+ .unwrap(),
+ "chrome",
+ )
})
- .collect();
- Captured {
- meta: ItemMeta {
- id: String::new(),
- kind: ItemKind::SitePasswords,
- label: format!("{site} passwords (chrome)"),
- provider_id: "chrome".into(),
- app_display: "Chrome".into(),
- site: Some(site.into()),
- account: None,
- source: "Default".into(),
- summary: ItemSummary {
- passwords: records.len() as u32,
- ..Default::default()
- },
- warnings: vec![],
- identity_provider: false,
- policy: ItemPolicy::default(),
- created_ms: 0,
- updated_ms: 0,
- rev: 0,
- record_digest: String::new(),
- },
- payload: ItemPayload {
- provider_id: "chrome".into(),
- scope: "full".into(),
- entries: vec![ItemPayload::logins_entry(&records).unwrap()],
- },
- }
+ .collect()
+}
+
+pub fn meta(kind: ItemKind, domain: Option<&str>, key: &str) -> ItemMeta {
+ ItemMeta::draft(kind, "chrome", "Chrome", domain, key)
+}
+
+/// A captured cookie (host `domain`, root path).
+pub fn cookie(domain: &str, name: &str, value: &str) -> Captured {
+ captured(
+ record::cookie_record(&CookieRecord {
+ creation_utc: None,
+ expires_utc: 0,
+ host_key: domain.into(),
+ http_only: true,
+ last_update_utc: None,
+ name: name.into(),
+ partition_key: None,
+ last_access_utc: None,
+ source_type: None,
+ has_cross_site_ancestor: None,
+ path: "/".into(),
+ priority: None,
+ same_site: -1,
+ secure: true,
+ source_port: None,
+ source_scheme: None,
+ value: value.as_bytes().to_vec(),
+ })
+ .unwrap(),
+ "chrome",
+ )
+}
+
+/// A captured file.
+pub fn file(path: &str, contents: &str) -> Captured {
+ captured(
+ record::file_record(path, 0o600, contents.as_bytes()).unwrap(),
+ "chrome",
+ )
}
#[async_trait::async_trait]
impl Backend for FakeBackend {
+ fn favicons(
+ &self,
+ _app: &str,
+ _profile: Option<&str>,
+ sites: &[String],
+ ) -> cua_keyvault::Result<Vec<(String, Vec<u8>)>> {
+ Ok(self
+ .icons
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(s, _)| sites.contains(s))
+ .cloned()
+ .collect())
+ }
+
fn inventory(&self, app: &str, _profile: Option<&str>) -> cua_keyvault::Result<Inventory> {
Ok(Inventory {
provider_id: app.into(),
@@ -82,21 +129,35 @@ impl Backend for FakeBackend {
}
fn capture(&self, spec: &ImportSpec) -> cua_keyvault::Result<Vec<Captured>> {
- // A browser-site item carrying one cookie bundle entry.
- Ok(spec
- .sites
- .iter()
- .map(|s| {
- let mut c = logins_item(&s.site, &[]);
- c.meta.kind = ItemKind::BrowserSite;
- c.payload.entries = vec![PayloadEntry {
- rel_path: format!("cookies/{}", s.site),
- mode: 0o600,
- data: "Q09PS0lF".into(),
- }];
- c
- })
- .collect())
+ // Two cookies per site (a session and a csrf token), and the files
+ // the spec's paths name (a browser's bookmarks and local state by
+ // default). A domain filter keeps only those sites.
+ let wanted = |d: &str| {
+ spec.domains
+ .as_ref()
+ .is_none_or(|ds| ds.iter().any(|x| x == d))
+ };
+ let mut out = Vec::new();
+ let gen_ = *self.generation.lock().unwrap();
+ for s in spec.sites.iter().filter(|s| wanted(&s.site)) {
+ let host = format!(".{}", s.site);
+ out.push(cookie(&host, "session", &format!("sess-{}-{gen_}", s.site)));
+ out.push(cookie(&host, "csrf", &format!("csrf-{}-{gen_}", s.site)));
+ }
+ if spec.whole_app {
+ let paths = spec
+ .paths
+ .clone()
+ .unwrap_or_else(|| vec!["Default/Bookmarks".into(), "Local State".into()]);
+ for p in paths {
+ out.push(file(&p, &format!("contents of {p}")));
+ }
+ }
+ for c in &mut out {
+ c.meta.provider_id = spec.app.clone();
+ c.payload.provider_id = spec.app.clone();
+ }
+ Ok(out)
}
fn capture_passwords(&self, spec: &PasswordImportSpec) -> cua_keyvault::Result<Vec<Captured>> {
@@ -117,7 +178,7 @@ impl Backend for FakeBackend {
Ok(all
.iter()
.filter(|(site, _)| spec.sites.is_empty() || spec.sites.iter().any(|s| s == site))
- .map(|(site, l)| logins_item(site, l))
+ .flat_map(|(_, l)| logins_items(l))
.collect())
}
@@ -125,25 +186,40 @@ impl Backend for FakeBackend {
&self,
target: &str,
_provider_id: &str,
- payloads: Vec<ItemPayload>,
+ _scope: &str,
+ entries: Vec<PayloadEntry>,
_expires_ms: u64,
) -> cua_keyvault::Result<DeliveryOutcome> {
- let paths: Vec<String> = payloads
+ use base64::Engine as _;
+ let paths: Vec<String> = entries.iter().map(|e| e.rel_path.clone()).collect();
+ let hosts: Vec<String> = entries
.iter()
- .flat_map(|p| p.entries.iter().map(|e| e.rel_path.clone()))
+ .filter(|e| e.rel_path == record::COOKIES_ENTRY)
+ .flat_map(|e| {
+ let raw = base64::engine::general_purpose::STANDARD
+ .decode(&e.data)
+ .unwrap();
+ let rows: Vec<serde_json::Value> = serde_json::from_slice(&raw).unwrap();
+ rows.iter()
+ .map(|r| r["host_key"].as_str().unwrap().to_string())
+ .collect::<Vec<_>>()
+ })
.collect();
- self.delivered
- .lock()
- .unwrap()
- .push((target.into(), paths.clone()));
+ self.delivered_hosts.lock().unwrap().push(hosts);
+ let mut d = self.delivered.lock().unwrap();
+ d.push((target.into(), paths.clone()));
Ok(DeliveryOutcome {
- import_id: "imp".into(),
+ import_id: format!("imp-{}", d.len()),
imported: paths,
..Default::default()
})
}
- async fn wipe(&self, _target: &str, _import_id: &str) -> cua_keyvault::Result<Vec<String>> {
+ async fn wipe(&self, target: &str, import_id: &str) -> cua_keyvault::Result<Vec<String>> {
+ self.wiped
+ .lock()
+ .unwrap()
+ .push((target.into(), import_id.into()));
Ok(vec![])
}
@@ -217,7 +293,18 @@ pub async fn rig() -> Rig {
}
}
-/// Imports the fake browser's saved passwords (first party, presence yes).
+/// Every item with its names visible (opens the browse window first).
+pub async fn all_items(r: &Rig) -> Vec<ItemMeta> {
+ let page = r.broker.list_items(&r.cua, 0, 1000).await.unwrap();
+ if page.names_visible {
+ return page.items;
+ }
+ r.broker.browse(&r.cua).await.unwrap();
+ r.broker.list_items(&r.cua, 0, 1000).await.unwrap().items
+}
+
+/// Imports the fake browser's saved passwords (first party, presence yes)
+/// and returns the password items.
pub async fn import_passwords(r: &Rig) -> Vec<ItemMeta> {
r.broker
.import_passwords(
@@ -228,5 +315,10 @@ pub async fn import_passwords(r: &Rig) -> Vec<ItemMeta> {
},
)
.await
- .unwrap()
+ .unwrap();
+ all_items(r)
+ .await
+ .into_iter()
+ .filter(|i| i.kind == ItemKind::Password)
+ .collect()
}
diff --git a/libs/cua/crates/cua-keyvault/tests/default_policy.rs b/libs/cua/crates/cua-keyvault/tests/default_policy.rs
index 71d633f0ea..333f14502f 100644
--- a/libs/cua/crates/cua-keyvault/tests/default_policy.rs
+++ b/libs/cua/crates/cua-keyvault/tests/default_policy.rs
@@ -15,7 +15,7 @@ mod common;
use std::time::Duration;
-use common::{PASSWORD, import_passwords, rig};
+use common::{PASSWORD, all_items, import_passwords, rig};
use cua_keyvault::broker::{
AccessRequest, ApproveOptions, Decision, ImportSpec, LoginRequest, RuleSpec, Selector,
SiteChoice, TeleportRequest,
@@ -41,11 +41,10 @@ async fn a_fresh_vault_asks_for_everything() {
// Items default to "never unattended" with a bounded lifetime on target.
assert!(!ItemPolicy::default().unattended);
for it in import_passwords(&r).await {
- assert!(!it.policy.unattended, "{}", it.label);
+ assert!(!it.policy.unattended, "{}", it.label());
assert!(it.policy.allowed_targets.is_empty());
}
- let sites = r
- .broker
+ r.broker
.import(
&r.cua,
ImportSpec {
@@ -60,6 +59,11 @@ async fn a_fresh_vault_asks_for_everything() {
)
.await
.unwrap();
+ let sites: Vec<_> = all_items(&r)
+ .await
+ .into_iter()
+ .filter(|i| i.kind == cua_keyvault::ItemKind::Cookie)
+ .collect();
assert!(!sites[0].policy.unattended);
// A rule naming an item that was not opted in is refused.
let err = r
@@ -213,8 +217,7 @@ async fn an_approval_covers_exactly_one_use_by_default() {
#[tokio::test]
async fn a_teleport_token_is_one_use_by_default_and_needs_approval() {
let r = rig().await;
- let items = r
- .broker
+ r.broker
.import(
&r.cua,
ImportSpec {
@@ -229,6 +232,7 @@ async fn a_teleport_token_is_one_use_by_default_and_needs_approval() {
)
.await
.unwrap();
+ let items = all_items(&r).await;
let no_token = r
.broker
.teleport(
@@ -237,6 +241,8 @@ async fn a_teleport_token_is_one_use_by_default_and_needs_approval() {
token: None,
items: vec![items[0].id.clone()],
target: "work".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -272,6 +278,8 @@ async fn a_teleport_token_is_one_use_by_default_and_needs_approval() {
token: Some(token),
items: vec![items[0].id.clone()],
target: "work".into(),
+ include_passwords: false,
+ launch: false,
};
r.broker.teleport(&r.agent, req.clone()).await.unwrap();
assert!(r.broker.teleport(&r.agent, req).await.is_err());
diff --git a/libs/cua/crates/cua-keyvault/tests/items.rs b/libs/cua/crates/cua-keyvault/tests/items.rs
new file mode 100644
index 0000000000..2b7429cc60
--- /dev/null
+++ b/libs/cua/crates/cua-keyvault/tests/items.rs
@@ -0,0 +1,931 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The per-app secret items: upsert by key, the unattended lock (one
+//! presence for a batch, an agent answered without a prompt, never a value
+//! back), batch delete that wipes live copies, the "never ask again"
+//! setting, selective send and the old-vault reset. A fake backend and a
+//! throwaway vault: nothing touches the machine.
+
+mod common;
+
+use std::time::Duration;
+
+use common::{FakeBackend, Rig, all_items, import_passwords, rig};
+use cua_keyvault::broker::{
+ AccessRequest, Backend, Broker, BrokerConfig, Decision, FakePresence, ImportSpec, LoginRequest,
+ Selector, SiteChoice, TeleportRequest,
+};
+use cua_keyvault::model::{ItemKind, ItemMeta};
+use cua_keyvault::{Action, Error};
+use std::sync::Arc;
+
+fn spec(sites: &[&str], whole_app: bool) -> ImportSpec {
+ ImportSpec {
+ app: "chrome".into(),
+ sites: sites
+ .iter()
+ .map(|s| SiteChoice {
+ site: s.to_string(),
+ include_storage: false,
+ include_passwords: false,
+ })
+ .collect(),
+ whole_app,
+ ..Default::default()
+ }
+}
+
+async fn import(r: &Rig, sites: &[&str], whole_app: bool) -> cua_keyvault::broker::ImportReport {
+ r.broker
+ .import(&r.cua, spec(sites, whole_app))
+ .await
+ .unwrap()
+}
+
+fn ids(items: &[ItemMeta]) -> Vec<String> {
+ items.iter().map(|i| i.id.clone()).collect()
+}
+
+fn find<'a>(items: &'a [ItemMeta], domain: &str, key: &str) -> &'a ItemMeta {
+ items
+ .iter()
+ .find(|i| i.domain.as_deref() == Some(domain) && i.key == key)
+ .unwrap_or_else(|| panic!("no {domain} / {key}"))
+}
+
+fn asked(r: &Rig) -> usize {
+ r.presence.asked.lock().unwrap().len()
+}
+
+/// An agent asks to write `site`'s cookies into `target`.
+fn ask(site: &str, target: &str) -> AccessRequest {
+ AccessRequest {
+ selectors: vec![Selector::Site {
+ app: "chrome".into(),
+ site: site.into(),
+ }],
+ targets: vec![target.into()],
+ ..Default::default()
+ }
+}
+
+// ---------------------------------------------------------------- upsert
+
+#[tokio::test]
+async fn saving_the_same_app_twice_upserts_by_key_and_never_duplicates() {
+ let r = rig().await;
+ let first = import(&r, &["github.com", "slack.com"], true).await;
+ assert_eq!((first.saved, first.created), (6, 6), "{first:?}");
+ let before = all_items(&r).await;
+ assert_eq!(before.len(), 6);
+ assert_eq!(
+ before.iter().filter(|i| i.kind == ItemKind::Cookie).count(),
+ 4
+ );
+ assert_eq!(
+ before.iter().filter(|i| i.kind == ItemKind::File).count(),
+ 2
+ );
+
+ // The user unlocks one item between the two saves.
+ let session = find(&before, ".github.com", "session").clone();
+ r.broker
+ .set_locked(&r.cua, vec![session.id.clone()], false)
+ .await
+ .unwrap();
+ tokio::time::sleep(Duration::from_millis(3)).await;
+
+ // Teleporting Chrome again with Save to Keyvault: same keys, same values.
+ let again = import(&r, &["github.com", "slack.com"], true).await;
+ assert_eq!(
+ (again.created, again.updated, again.unchanged),
+ (0, 0, 6),
+ "{again:?}"
+ );
+ let after = all_items(&r).await;
+ assert_eq!(after.len(), 6, "no duplicates");
+ let kept = find(&after, ".github.com", "session");
+ assert_eq!(kept.id, session.id, "the same item");
+ assert!(!kept.locked(), "the unlock survived the second save");
+ assert_eq!(kept.created_ms, session.created_ms);
+ assert!(kept.updated_ms > session.updated_ms, "updated-at moved");
+ assert_eq!(kept.rev, session.rev, "an unchanged value is not rewritten");
+
+ // A changed value updates the item in place.
+ *r.backend.generation.lock().unwrap() = 1;
+ let changed = import(&r, &["github.com"], false).await;
+ assert_eq!((changed.created, changed.updated), (0, 2), "{changed:?}");
+ let after = all_items(&r).await;
+ assert_eq!(after.len(), 6);
+ assert_eq!(find(&after, ".github.com", "session").rev, session.rev + 1);
+ // A site not in this save is left alone.
+ assert_eq!(find(&after, ".slack.com", "session").rev, 1);
+}
+
+#[tokio::test]
+async fn a_changed_file_updates_and_a_cookie_and_a_file_never_collide() {
+ let r = rig().await;
+ import(&r, &["github.com"], true).await;
+ let a = all_items(&r).await;
+ let files: Vec<_> = a.iter().filter(|i| i.kind == ItemKind::File).collect();
+ assert_eq!(
+ files.iter().map(|f| f.key.as_str()).collect::<Vec<_>>(),
+ ["Default/Bookmarks", "Local State"],
+ "a file's key is its path"
+ );
+ assert!(files.iter().all(|f| f.domain.is_none()));
+ let cookies: Vec<_> = a.iter().filter(|i| i.kind == ItemKind::Cookie).collect();
+ assert!(
+ cookies
+ .iter()
+ .all(|c| c.domain.as_deref() == Some(".github.com") && c.path.as_deref() == Some("/")),
+ "a cookie's key is its host, name and path"
+ );
+}
+
+// ------------------------------------------------------------------ lock
+
+#[tokio::test]
+async fn items_start_locked_and_unlocking_a_batch_asks_presence_once() {
+ let r = rig().await;
+ import(&r, &["github.com", "gitlab.com"], false).await;
+ let items = all_items(&r).await;
+ assert!(items.iter().all(|i| i.locked()), "locked by default");
+
+ // A declined presence changes nothing.
+ r.presence.set(false);
+ let err = r
+ .broker
+ .set_locked(&r.cua, ids(&items), false)
+ .await
+ .unwrap_err();
+ assert!(matches!(err, Error::PresenceFailed(_)), "{err:?}");
+ assert!(all_items(&r).await.iter().all(|i| i.locked()));
+
+ // One prompt for the whole batch, naming what it allows.
+ r.presence.set(true);
+ let before = asked(&r);
+ let out = r
+ .broker
+ .set_locked(&r.cua, ids(&items), false)
+ .await
+ .unwrap();
+ assert_eq!(asked(&r) - before, 1, "one presence for the batch");
+ assert_eq!(out.changed.len(), 4);
+ assert!(out.skipped.is_empty());
+ let prompt = r.presence.asked.lock().unwrap().last().cloned().unwrap();
+ assert!(
+ prompt.contains("4 Keyvault items") && prompt.contains("Cua Spaces MCP"),
+ "{prompt}"
+ );
+ assert!(all_items(&r).await.iter().all(|i| !i.locked()));
+
+ // Unlocking what is already unlocked asks nothing.
+ let before = asked(&r);
+ let out = r
+ .broker
+ .set_locked(&r.cua, ids(&items), false)
+ .await
+ .unwrap();
+ assert!(out.changed.is_empty());
+ assert_eq!(asked(&r), before);
+
+ // Locking narrows access: no presence, one call for the batch.
+ r.presence.set(false);
+ let before = asked(&r);
+ let out = r
+ .broker
+ .set_locked(&r.cua, ids(&items[..3]), true)
+ .await
+ .unwrap();
+ assert_eq!(out.changed.len(), 3);
+ assert_eq!(asked(&r), before, "the declined gate was not even asked");
+ let now = all_items(&r).await;
+ assert_eq!(now.iter().filter(|i| i.locked()).count(), 3);
+
+ // Unknown ids change nothing; third parties cannot lock.
+ assert!(matches!(
+ r.broker
+ .set_locked(&r.cua, vec![items[3].id.clone(), "nope".into()], true)
+ .await,
+ Err(Error::NotFound(_))
+ ));
+ assert!(matches!(
+ r.broker.set_locked(&r.agent, ids(&items), false).await,
+ Err(Error::Forbidden(_))
+ ));
+}
+
+#[tokio::test]
+async fn an_identity_provider_session_always_asks() {
+ let r = rig().await;
+ import(&r, &["google.com", "github.com"], false).await;
+ let items = all_items(&r).await;
+ let google = find(&items, ".google.com", "session");
+ assert!(google.identity_provider, "Google is an identity provider");
+ assert_eq!(
+ google.policy.ttl_secs,
+ cua_keyvault::model::IDP_TTL_SECS,
+ "a short lifetime by default"
+ );
+ let out = r
+ .broker
+ .set_locked(&r.cua, ids(&items), false)
+ .await
+ .unwrap();
+ assert_eq!(out.skipped.len(), 2, "both Google cookies are skipped");
+ assert_eq!(out.changed.len(), 2);
+ let after = all_items(&r).await;
+ assert!(find(&after, ".google.com", "session").locked());
+ assert!(!find(&after, ".github.com", "session").locked());
+ // And the policy path cannot sneak it in.
+ let mut p = google.policy.clone();
+ p.unattended = true;
+ assert!(matches!(
+ r.broker.set_item_policy(&r.cua, &google.id, p).await,
+ Err(Error::Forbidden(_))
+ ));
+}
+
+#[tokio::test]
+async fn the_never_ask_again_setting_is_stored_visible_and_revertible() {
+ let r = rig().await;
+ assert_eq!(
+ r.broker.status(&r.cua).await.skip_unlock_prompt,
+ Some(false),
+ "the prompt is on by default"
+ );
+ let before = asked(&r);
+ r.broker.set_skip_unlock_prompt(&r.cua, true).await.unwrap();
+ assert_eq!(asked(&r), before, "a prompt preference needs no presence");
+ assert_eq!(r.broker.status(&r.cua).await.skip_unlock_prompt, Some(true));
+ // It survives a lock and an unlock (it is in the sealed settings).
+ r.broker.lock(&r.cua).await.unwrap();
+ r.broker
+ .unlock(
+ &r.cua,
+ cua_keyvault::broker::UnlockRequest {
+ passphrase: Some("correct horse battery".into()),
+ recovery_key: None,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(r.broker.status(&r.cua).await.skip_unlock_prompt, Some(true));
+ // It never skips the presence check that unlocking asks for.
+ import(&r, &["github.com"], false).await;
+ let items = all_items(&r).await;
+ let before = asked(&r);
+ r.broker
+ .set_locked(&r.cua, ids(&items), false)
+ .await
+ .unwrap();
+ assert_eq!(asked(&r), before + 1, "Touch ID is still asked");
+ // Settings can turn it back on; a third party never sees it.
+ r.broker
+ .set_skip_unlock_prompt(&r.cua, false)
+ .await
+ .unwrap();
+ assert_eq!(
+ r.broker.status(&r.cua).await.skip_unlock_prompt,
+ Some(false)
+ );
+ assert_eq!(r.broker.status(&r.agent).await.skip_unlock_prompt, None);
+ assert!(matches!(
+ r.broker.set_skip_unlock_prompt(&r.agent, true).await,
+ Err(Error::Forbidden(_))
+ ));
+}
+
+// ---------------------------------------------------- unattended access
+
+#[tokio::test]
+async fn unlocked_items_answer_an_agent_without_asking_and_no_value_comes_back() {
+ let r = rig().await;
+ import(&r, &["github.com", "gitlab.com"], false).await;
+ let items = all_items(&r).await;
+ let github: Vec<ItemMeta> = items
+ .iter()
+ .filter(|i| i.domain.as_deref() == Some(".github.com"))
+ .cloned()
+ .collect();
+ r.broker
+ .set_locked(&r.cua, ids(&github), false)
+ .await
+ .unwrap();
+
+ // A locked site still waits for the user.
+ let locked = r
+ .broker
+ .request_access(&r.agent, ask("gitlab.com", "dev-1"))
+ .await
+ .unwrap();
+ assert_eq!(r.broker.list_pending(&r.cua).await.unwrap().len(), 1);
+ assert!(matches!(
+ r.broker
+ .await_decision(&r.agent, &locked.id, Duration::from_millis(5))
+ .await
+ .unwrap(),
+ Decision::Pending
+ ));
+
+ // The unlocked one is answered at once: no pending request, no prompt.
+ let before = asked(&r);
+ let view = r
+ .broker
+ .request_access(&r.agent, ask("github.com", "dev-1"))
+ .await
+ .unwrap();
+ assert_eq!(asked(&r), before, "no presence for an unlocked item");
+ assert_eq!(r.broker.list_pending(&r.cua).await.unwrap().len(), 1);
+ let Decision::Granted {
+ token, items: ids, ..
+ } = r
+ .broker
+ .await_decision(&r.agent, &view.id, Duration::from_millis(5))
+ .await
+ .unwrap()
+ else {
+ panic!("granted without asking")
+ };
+ assert_eq!(ids.len(), 2);
+
+ // The agent writes the items into the Space; nothing it receives holds a
+ // value, a domain or a key.
+ let outcome = r
+ .broker
+ .teleport(
+ &r.agent,
+ TeleportRequest {
+ token: Some(token.clone()),
+ items: ids,
+ target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(r.backend.delivered.lock().unwrap().len(), 1);
+ assert_eq!(
+ r.backend.delivered_hosts.lock().unwrap()[0],
+ vec![".github.com".to_string(), ".github.com".to_string()]
+ );
+ for seen in [
+ serde_json::to_string(&view).unwrap(),
+ serde_json::to_string(&outcome).unwrap(),
+ token.clone(),
+ ] {
+ assert!(
+ !seen.contains("sess-github") && !seen.contains("csrf-github"),
+ "a value reached the agent: {seen}"
+ );
+ }
+ assert!(
+ view.items
+ .iter()
+ .all(|i| i.domain.is_none() && i.key.is_empty()),
+ "names are not handed to the agent either"
+ );
+ // The grant is single use, and the audit says it was unattended.
+ assert!(
+ r.broker
+ .teleport(
+ &r.agent,
+ TeleportRequest {
+ token: Some(token),
+ items: vec![github[0].id.clone()],
+ target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
+ },
+ )
+ .await
+ .is_err()
+ );
+ let audit = r.broker.audit_tail(&r.cua, 100).await.unwrap();
+ assert!(audit.iter().any(|e| e.event.kind == "consent.allow"
+ && e.event.detail.contains("unattended (items unlocked)")));
+}
+
+#[tokio::test]
+async fn a_request_that_mixes_locked_and_unlocked_items_still_asks() {
+ let r = rig().await;
+ import(&r, &["github.com"], false).await;
+ let items = all_items(&r).await;
+ // Only one of the two cookies is unlocked.
+ r.broker
+ .set_locked(&r.cua, vec![items[0].id.clone()], false)
+ .await
+ .unwrap();
+ r.broker
+ .request_access(&r.agent, ask("github.com", "dev-1"))
+ .await
+ .unwrap();
+ assert_eq!(r.broker.list_pending(&r.cua).await.unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn an_unlocked_item_still_respects_its_allowed_targets_and_the_kill_switch() {
+ let r = rig().await;
+ import(&r, &["github.com"], false).await;
+ let items = all_items(&r).await;
+ r.broker
+ .set_locked(&r.cua, ids(&items), false)
+ .await
+ .unwrap();
+ // Restrict one item to another Space: a request for dev-1 asks.
+ let mut p = items[0].policy.clone();
+ p.unattended = true;
+ p.allowed_targets = vec!["prod".into()];
+ r.broker
+ .set_item_policy(&r.cua, &items[0].id, p)
+ .await
+ .unwrap();
+ r.broker
+ .request_access(&r.agent, ask("github.com", "dev-1"))
+ .await
+ .unwrap();
+ assert_eq!(
+ r.broker.list_pending(&r.cua).await.unwrap().len(),
+ 1,
+ "not auto-answered for a Space the item may not go to"
+ );
+
+ // The kill switch refuses unattended requests and further unlocking.
+ r.broker.set_disabled(&r.cua, true).await.unwrap();
+ assert!(matches!(
+ r.broker
+ .request_access(&r.agent, ask("github.com", "prod"))
+ .await,
+ Err(Error::Disabled)
+ ));
+ assert!(matches!(
+ r.broker.set_locked(&r.cua, ids(&items), false).await,
+ Err(Error::Disabled)
+ ));
+ // Locking is still allowed while it is on.
+ assert!(r.broker.set_locked(&r.cua, ids(&items), true).await.is_ok());
+}
+
+#[tokio::test]
+async fn locking_an_item_revokes_the_unattended_grants_it_backed() {
+ let r = rig().await;
+ import(&r, &["github.com"], false).await;
+ let items = all_items(&r).await;
+ r.broker
+ .set_locked(&r.cua, ids(&items), false)
+ .await
+ .unwrap();
+ let mut req = ask("github.com", "dev-1");
+ req.uses = Some(0);
+ let view = r.broker.request_access(&r.agent, req).await.unwrap();
+ let Decision::Granted {
+ token, items: held, ..
+ } = r
+ .broker
+ .await_decision(&r.agent, &view.id, Duration::from_millis(5))
+ .await
+ .unwrap()
+ else {
+ panic!("granted")
+ };
+ r.broker
+ .set_locked(&r.cua, vec![items[0].id.clone()], true)
+ .await
+ .unwrap();
+ let err = r
+ .broker
+ .teleport(
+ &r.agent,
+ TeleportRequest {
+ token: Some(token),
+ items: held,
+ target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
+ },
+ )
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(err, Error::Capability(_) | Error::Forbidden(_)),
+ "{err:?}"
+ );
+ assert!(r.backend.delivered.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn an_unlocked_password_signs_in_without_asking_and_never_echoes_it() {
+ let r = rig().await;
+ let pw = import_passwords(&r).await;
+ let example = pw
+ .iter()
+ .find(|i| i.domain.as_deref() == Some("http://login.example.test:8000"))
+ .unwrap();
+ assert_eq!(example.key, "[email protected]");
+ r.broker
+ .set_locked(&r.cua, vec![example.id.clone()], false)
+ .await
+ .unwrap();
+ let view = r
+ .broker
+ .request_access(
+ &r.agent,
+ AccessRequest {
+ selectors: vec![Selector::Login {
+ site: "example.test".into(),
+ }],
+ targets: vec!["work".into()],
+ actions: vec![Action::Login],
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert!(r.broker.list_pending(&r.cua).await.unwrap().is_empty());
+ let Decision::Granted { token, .. } = r
+ .broker
+ .await_decision(&r.agent, &view.id, Duration::from_millis(5))
+ .await
+ .unwrap()
+ else {
+ panic!("granted")
+ };
+ let out = r
+ .broker
+ .login(
+ &r.agent,
+ LoginRequest {
+ token: Some(token),
+ url: "http://login.example.test:8000/".into(),
+ target: "work".into(),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(r.backend.fills.lock().unwrap().len(), 1);
+ let seen = serde_json::to_string(&out).unwrap();
+ assert!(
+ !seen.contains(common::PASSWORD) && !seen.contains("[email protected]"),
+ "{seen}"
+ );
+ // The other password (github) is still locked and still asks.
+ r.broker
+ .request_access(
+ &r.agent,
+ AccessRequest {
+ selectors: vec![Selector::Login {
+ site: "github.com".into(),
+ }],
+ targets: vec!["work".into()],
+ actions: vec![Action::Login],
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(r.broker.list_pending(&r.cua).await.unwrap().len(), 1);
+}
+
+// ----------------------------------------------------------------- delete
+
+#[tokio::test]
+async fn deleting_a_batch_wipes_their_live_copies_and_is_all_or_nothing() {
+ let r = rig().await;
+ import(&r, &["github.com", "gitlab.com"], true).await;
+ let items = all_items(&r).await;
+ let github: Vec<ItemMeta> = items
+ .iter()
+ .filter(|i| i.domain.as_deref() == Some(".github.com"))
+ .cloned()
+ .collect();
+ let gitlab: Vec<ItemMeta> = items
+ .iter()
+ .filter(|i| i.domain.as_deref() == Some(".gitlab.com"))
+ .cloned()
+ .collect();
+ for set in [&github, &gitlab] {
+ r.broker
+ .teleport(
+ &r.cua,
+ TeleportRequest {
+ token: None,
+ items: ids(set),
+ target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
+ },
+ )
+ .await
+ .unwrap();
+ }
+
+ // An unknown id deletes and wipes nothing. (The second teleport already
+ // superseded, and so wiped, the first copy.)
+ let wiped_before = r.backend.wiped.lock().unwrap().len();
+ let mut bad = ids(&github);
+ bad.push("deadbeef".into());
+ assert!(matches!(
+ r.broker.delete_items(&r.cua, bad).await,
+ Err(Error::NotFound(_))
+ ));
+ assert_eq!(all_items(&r).await.len(), items.len());
+ assert_eq!(r.backend.wiped.lock().unwrap().len(), wiped_before);
+
+ // Deleting github's items wipes the copy that carried them, in the
+ // Space, and removes them from the vault in one call.
+ let wiped = r.broker.delete_items(&r.cua, ids(&github)).await.unwrap();
+ assert!(!wiped.is_empty(), "the live copy was wiped");
+ assert!(
+ r.backend.wiped.lock().unwrap().len() > wiped_before,
+ "the Space was told to wipe"
+ );
+ let left = all_items(&r).await;
+ assert_eq!(left.len(), items.len() - github.len());
+ assert!(
+ left.iter()
+ .all(|i| i.domain.as_deref() != Some(".github.com"))
+ );
+ let audit = r.broker.audit_tail(&r.cua, 100).await.unwrap();
+ assert!(
+ audit
+ .iter()
+ .any(|e| e.event.kind == "item.delete" && e.event.detail.contains("count=2"))
+ );
+ // Third parties cannot delete.
+ assert!(matches!(
+ r.broker.delete_items(&r.agent, ids(&gitlab)).await,
+ Err(Error::Forbidden(_))
+ ));
+}
+
+// ------------------------------------------------------- selective send
+
+#[tokio::test]
+async fn sending_part_of_an_app_filters_records_and_nothing_else_leaves() {
+ let r = rig().await;
+ import(&r, &["github.com", "gitlab.com", "slack.com"], true).await;
+ let items = all_items(&r).await;
+ let chosen: Vec<ItemMeta> = items
+ .iter()
+ .filter(|i| {
+ matches!(
+ i.domain.as_deref(),
+ Some(".github.com") | Some(".slack.com")
+ ) || i.key == "Local State"
+ })
+ .cloned()
+ .collect();
+ r.broker
+ .teleport(
+ &r.cua,
+ TeleportRequest {
+ token: None,
+ items: ids(&chosen),
+ target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
+ },
+ )
+ .await
+ .unwrap();
+ let delivered = r.backend.delivered.lock().unwrap().clone();
+ let mut paths = delivered[0].1.clone();
+ paths.sort();
+ assert_eq!(paths, ["Local State", "cookies.json"]);
+ let mut hosts = r.backend.delivered_hosts.lock().unwrap()[0].clone();
+ hosts.sort();
+ assert_eq!(
+ hosts,
+ [".github.com", ".github.com", ".slack.com", ".slack.com"],
+ "gitlab and the other file stayed home"
+ );
+}
+
+#[tokio::test]
+async fn saved_passwords_are_delivered_only_when_the_user_ticked_them_and_never_to_an_agent() {
+ let r = rig().await;
+ let pw = import_passwords(&r).await;
+ assert!(!pw.is_empty());
+ let target = |include: bool, items: Vec<String>| TeleportRequest {
+ token: None,
+ items,
+ target: "dev-1".into(),
+ include_passwords: include,
+ launch: false,
+ };
+ // Without the explicit choice a password is never part of a delivery.
+ let err = r
+ .broker
+ .teleport(&r.cua, target(false, ids(&pw)))
+ .await
+ .unwrap_err();
+ assert!(matches!(err, Error::Invalid(_)), "{err:?}");
+ assert!(r.backend.delivered.lock().unwrap().is_empty());
+ // A third party cannot ask for them, token or not.
+ let agent = r.broker.teleport(&r.agent, target(true, ids(&pw))).await;
+ assert!(agent.is_err(), "an agent never gets a password delivered");
+ assert!(r.backend.delivered.lock().unwrap().is_empty());
+ // The user's own, explicit choice carries them in their reserved entry,
+ // and the audit log says so.
+ r.broker
+ .teleport(&r.cua, target(true, ids(&pw)))
+ .await
+ .unwrap();
+ let delivered = r.backend.delivered.lock().unwrap().clone();
+ assert_eq!(delivered.len(), 1);
+ assert!(
+ delivered[0].1.iter().any(|p| p == "logins.json"),
+ "{delivered:?}"
+ );
+ let log = r.broker.audit_tail(&r.cua, 50).await.unwrap();
+ assert!(
+ log.iter()
+ .any(|e| e.event.detail.contains("INCLUDING SAVED PASSWORDS")),
+ "{log:?}"
+ );
+}
+
+// ------------------------------------------------------------- old vault
+
+#[tokio::test]
+async fn a_preview_vault_is_set_aside_with_a_notice_never_misread_or_deleted() {
+ let dir = tempfile::tempdir().unwrap();
+ let kv = dir.path().join("keyvault");
+ {
+ let r = Broker::new(
+ BrokerConfig {
+ dir: kv.clone(),
+ keychain_path: None,
+ os_protector: false,
+ },
+ Arc::new(FakeBackend::default()),
+ Arc::new(FakePresence::new(true)),
+ )
+ .unwrap();
+ let cua = cua_keyvault::CallerIdentity::for_tests("com.trycua.cua", true);
+ r.init(
+ &cua,
+ cua_keyvault::broker::InitRequest {
+ passphrase: Some("correct horse battery".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ }
+ // Make it look like an earlier preview wrote it.
+ let header_path = kv.join("vault.json");
+ let mut header: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(&header_path).unwrap()).unwrap();
+ header["format"] = 1.into();
+ std::fs::write(&header_path, serde_json::to_vec(&header).unwrap()).unwrap();
+
+ let b = Broker::new(
+ BrokerConfig {
+ dir: kv.clone(),
+ keychain_path: None,
+ os_protector: false,
+ },
+ Arc::new(FakeBackend::default()),
+ Arc::new(FakePresence::new(true)),
+ )
+ .unwrap();
+ let cua = cua_keyvault::CallerIdentity::for_tests("com.trycua.cua", true);
+ let status = b.status(&cua).await;
+ assert!(!status.initialized, "a new vault is set up");
+ let notice = status.reset_notice.expect("one line for the UI");
+ assert!(notice.contains("set aside"), "{notice}");
+ assert!(
+ dir.path().join("keyvault.preview-v1/vault.json").is_file(),
+ "the old vault is kept, not deleted"
+ );
+ assert!(!kv.exists());
+ // A new vault can be created in its place.
+ b.init(
+ &cua,
+ cua_keyvault::broker::InitRequest {
+ passphrase: Some("correct horse battery".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert!(b.status(&cua).await.initialized);
+}
+
+// ------------------------------------------------------------- big files
+
+#[tokio::test]
+async fn a_big_file_is_stored_as_a_blob_and_delivered_whole() {
+ use cua_keyvault::broker::Captured;
+ struct Big;
+ #[async_trait::async_trait]
+ impl Backend for Big {
+ fn inventory(
+ &self,
+ _: &str,
+ _: Option<&str>,
+ ) -> cua_keyvault::Result<cua_keyvault::broker::Inventory> {
+ Ok(Default::default())
+ }
+ fn capture(&self, _: &ImportSpec) -> cua_keyvault::Result<Vec<Captured>> {
+ let bytes = vec![9u8; cua_keyvault::record::INLINE_FILE_LIMIT * 3];
+ let n = cua_keyvault::record::file_record("Default/History", 0o600, &bytes)?;
+ let (meta, payload) = n.into_item("chrome", "Chrome", "Default", "full");
+ Ok(vec![Captured { meta, payload }])
+ }
+ async fn deliver(
+ &self,
+ _: &str,
+ _: &str,
+ _: &str,
+ entries: Vec<cua_keyvault::model::PayloadEntry>,
+ _: u64,
+ ) -> cua_keyvault::Result<cua_keyvault::broker::DeliveryOutcome> {
+ use base64::Engine as _;
+ let e = &entries[0];
+ let got = base64::engine::general_purpose::STANDARD
+ .decode(&e.data)
+ .unwrap();
+ assert_eq!(got.len(), cua_keyvault::record::INLINE_FILE_LIMIT * 3);
+ assert!(got.iter().all(|b| *b == 9));
+ Ok(Default::default())
+ }
+ async fn wipe(&self, _: &str, _: &str) -> cua_keyvault::Result<Vec<String>> {
+ Ok(vec![])
+ }
+ }
+ let dir = tempfile::tempdir().unwrap();
+ let b = Broker::new(
+ BrokerConfig {
+ dir: dir.path().join("kv"),
+ keychain_path: None,
+ os_protector: false,
+ },
+ Arc::new(Big),
+ Arc::new(FakePresence::new(true)),
+ )
+ .unwrap();
+ let cua = cua_keyvault::CallerIdentity::for_tests("com.trycua.cua", true);
+ b.init(
+ &cua,
+ cua_keyvault::broker::InitRequest {
+ passphrase: Some("correct horse battery".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ b.import(&cua, spec(&[], true)).await.unwrap();
+ b.browse(&cua).await.unwrap();
+ let items = b.list_items(&cua, 0, 10).await.unwrap().items;
+ assert!(items[0].blob.is_some(), "stored as a blob");
+ assert!(dir.path().join("kv/blobs").is_dir());
+ b.teleport(
+ &cua,
+ TeleportRequest {
+ token: None,
+ items: ids(&items),
+ target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
+ },
+ )
+ .await
+ .unwrap();
+ // Deleting the item shreds the blob.
+ b.delete_items(&cua, ids(&items)).await.unwrap();
+ assert_eq!(
+ std::fs::read_dir(dir.path().join("kv/blobs"))
+ .unwrap()
+ .count(),
+ 0
+ );
+}
+
+#[tokio::test]
+async fn site_icons_are_captured_locally_hidden_until_browse_and_pruned_with_the_site() {
+ let r = rig().await;
+ r.backend
+ .icons
+ .lock()
+ .unwrap()
+ .push(("example.com".into(), b"\x89PNG\r\n\x1a\nicon".to_vec()));
+ import(&r, &["example.com"], false).await;
+ // Names (and so the sites) stay hidden until the browse window opens.
+ assert!(r.broker.list_favicons(&r.cua).await.unwrap().is_empty());
+ r.broker.browse(&r.cua).await.unwrap();
+ let icons = r.broker.list_favicons(&r.cua).await.unwrap();
+ assert_eq!(icons.len(), 1);
+ assert_eq!(icons[0].site, "example.com");
+ // A third party never reads them.
+ assert!(r.broker.list_favicons(&r.agent).await.is_err());
+ // Deleting the site's last item drops its icon.
+ let items = all_items(&r).await;
+ r.broker.delete_items(&r.cua, ids(&items)).await.unwrap();
+ assert!(r.broker.list_favicons(&r.cua).await.unwrap().is_empty());
+}
diff --git a/libs/cua/crates/cua-keyvault/tests/site_login.rs b/libs/cua/crates/cua-keyvault/tests/site_login.rs
index 62221c5ff4..61362d7f82 100644
--- a/libs/cua/crates/cua-keyvault/tests/site_login.rs
+++ b/libs/cua/crates/cua-keyvault/tests/site_login.rs
@@ -14,7 +14,7 @@ use cua_keyvault::broker::{
AccessRequest, ApproveOptions, BrowserRef, Decision, LoginRequest, RuleSpec, Selector,
TeleportRequest,
};
-use cua_keyvault::model::{ItemKind, ItemPolicy, LOGINS_ENTRY, RuleCaller};
+use cua_keyvault::model::{ItemKind, ItemPolicy, RuleCaller};
use cua_keyvault::{Action, Error};
async fn approved_token(r: &common::Rig, site: &str, target: &str) -> String {
@@ -53,8 +53,8 @@ async fn import_makes_one_sealed_item_per_site() {
let items = import_passwords(&r).await;
assert_eq!(items.len(), 2);
for it in &items {
- assert_eq!(it.kind, ItemKind::SitePasswords);
- assert_eq!(it.summary.passwords, 1);
+ assert_eq!(it.kind, ItemKind::Password);
+ assert!(it.domain.is_some() && !it.key.is_empty(), "{it:?}");
}
// Presence was asked once, naming the browser.
let asked = r.presence.asked.lock().unwrap().clone();
@@ -78,8 +78,10 @@ async fn import_makes_one_sealed_item_per_site() {
)
.await
.unwrap();
- assert_eq!(one.len(), 1);
- assert_eq!(one[0].site.as_deref(), Some("github.com"));
+ assert_eq!(one.saved, 1);
+ let held = common::all_items(&r2).await;
+ assert_eq!(held[0].domain.as_deref(), Some("https://github.com"));
+ assert_eq!(held[0].key, "octo");
// A third party may not import.
assert!(matches!(
r.broker
@@ -252,7 +254,7 @@ async fn unattended_login_only_after_the_user_writes_a_rule() {
let items = import_passwords(&r).await;
let item = items
.iter()
- .find(|i| i.site.as_deref() == Some("example.test"))
+ .find(|i| i.domain.as_deref() == Some("http://login.example.test:8000"))
.unwrap();
let req = LoginRequest {
url: "http://login.example.test:8000/".into(),
@@ -319,6 +321,8 @@ async fn saved_logins_are_never_teleported() {
token: None,
items: vec![items[0].id.clone()],
target: "work".into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -342,7 +346,6 @@ async fn saved_logins_are_never_teleported() {
.await
.unwrap_err();
assert!(matches!(none, Error::NotFound(_)), "{none:?}");
- let _ = LOGINS_ENTRY;
}
#[tokio::test]
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/keyvault-approve-deny.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/keyvault-approve-deny.json
index cda8a03160..646efaa2f8 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/keyvault-approve-deny.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/keyvault-approve-deny.json
@@ -3,16 +3,15 @@
"frames": [
{
"sidebar": {
+ "apps": [
+ "Chrome (6) waiting",
+ "Slack (2)"
+ ],
"categories": [
- "All:4",
+ "All Items:8",
"Waiting:2",
"Access:3",
"Recent"
- ],
- "sites": [
- "accounts.example-idp.test (1)",
- "github.example.test (2) waiting",
- "Slack (1)"
]
}
},
@@ -40,12 +39,8 @@
"empty": null,
"pending": [],
"recent": [],
- "sites": [
- "accounts.example-idp.test [off]: [email protected] off locked <asks:Asks every time>",
- "github.example.test [off]: [email protected] off <pending:Waiting: com.example.koalabot; pending:Waiting: com.example.koalabot> | [email protected] off <pending:Waiting: com.example.koalabot>",
- "Slack [on]: Example Workspace on <delivered:In dev-2, wiped in 30 min; granted:com.example.koalabot → dev-2, 10 min; rule:Rule: com.example.koalabot → any Space>"
- ],
- "title": "All"
+ "title": "All Items",
+ "vault": true
},
"list": {
"category": "all",
@@ -57,12 +52,12 @@
"access": [],
"empty": null,
"pending": [
- "com.example.koalabot (ad hoc, untrusted) github.example.test (2 accounts) → aurora for 15 min",
- "com.example.koalabot (ad hoc, untrusted) github.example.test, linear.example.test (not imported) → aurora for 15 min"
+ "com.example.koalabot (ad hoc, untrusted) example.test (2 items) → aurora for 15 min",
+ "com.example.koalabot (ad hoc, untrusted) example.test, linear.example.test (not saved) → aurora for 15 min"
],
"recent": [],
- "sites": [],
- "title": "Waiting"
+ "title": "Waiting",
+ "vault": false
},
"list": {
"category": "waiting",
@@ -72,15 +67,15 @@
{
"frame": {
"access": [
- "com.example.koalabot → dev-2 / Slack (whole app session) · 10 min [Revoke]",
- "Rule: com.example.koalabot → any Space / Slack (whole app session) [Remove]",
+ "com.example.koalabot → dev-2 / storage/root-state.json · 10 min [Revoke]",
+ "Rule: com.example.koalabot → any Space / storage/root-state.json [Remove]",
"Copy in dev-2 / wiped in 30 min [Wipe]"
],
"empty": null,
"pending": [],
"recent": [],
- "sites": [],
- "title": "Access"
+ "title": "Access",
+ "vault": false
},
"list": {
"category": "access",
@@ -94,12 +89,12 @@
"pending": [],
"recent": [
"Keyvault turned off Cua (info) now",
- "Refused github.example.test (Chrome, Default) → dev-9 (deny) now",
- "Approved Slack (whole app session) → dev-2 (ok) 1 min ago",
- "Asked Slack (whole app session) (info) 2 min ago"
+ "Refused example.test / _gh_sess → dev-9 (deny) now",
+ "Approved storage/root-state.json → dev-2 (ok) 1 min ago",
+ "Asked storage/root-state.json (info) 2 min ago"
],
- "sites": [],
- "title": "Recent"
+ "title": "Recent",
+ "vault": false
},
"list": {
"category": "recent",
@@ -112,14 +107,12 @@
"empty": null,
"pending": [],
"recent": [],
- "sites": [
- "github.example.test [off]: [email protected] off <pending:Waiting: com.example.koalabot; pending:Waiting: com.example.koalabot> | [email protected] off <pending:Waiting: com.example.koalabot>"
- ],
- "title": "github.example.test"
+ "title": "Slack",
+ "vault": true
},
"list": {
- "key": "chrome:github.example.test",
- "kind": "site"
+ "key": "slack",
+ "kind": "app"
}
},
{
@@ -135,20 +128,19 @@
"Says: \"open the pull request\" (unverified)"
],
"rows": [
- "[ ] github.example.test [email protected]",
- "[ ] github.example.test [email protected]"
+ "[ ] example.test 2 cookies"
],
"title": "Allow com.example.koalabot?"
}
},
{
"action": {
- "key": "gh-bob",
+ "key": "chrome|example.test",
"type": "toggle"
},
"approval": "req-1",
"frame": {
- "approveLabel": "Approve 1 item",
+ "approveLabel": "Approve 2 items",
"badge": "ad hoc, untrusted",
"blockedReason": null,
"canApprove": true,
@@ -157,8 +149,7 @@
"Says: \"open the pull request\" (unverified)"
],
"rows": [
- "[ ] github.example.test [email protected]",
- "[x] github.example.test [email protected]"
+ "[x] example.test 2 cookies"
],
"title": "Allow com.example.koalabot?"
}
@@ -170,7 +161,7 @@
},
"approval": "req-1",
"frame": {
- "approveLabel": "Approve 1 item",
+ "approveLabel": "Approve 2 items",
"badge": "ad hoc, untrusted",
"blockedReason": null,
"canApprove": true,
@@ -179,8 +170,7 @@
"Says: \"open the pull request\" (unverified)"
],
"rows": [
- "[ ] github.example.test [email protected]",
- "[x] github.example.test [email protected]"
+ "[x] example.test 2 cookies"
],
"title": "Allow com.example.koalabot?"
}
@@ -200,20 +190,40 @@
"Says: \"open the pull request\" (unverified)"
],
"rows": [
- "[x] github.example.test [email protected]",
- "[x] github.example.test [email protected]"
+ "[x] example.test 2 cookies"
],
"title": "Allow com.example.koalabot?"
}
},
{
"action": {
- "key": "gh-ada",
+ "key": "chrome|example.test",
"type": "toggle"
},
"approval": "req-1",
"frame": {
- "approveLabel": "Approve 1 item",
+ "approveLabel": "Approve",
+ "badge": "ad hoc, untrusted",
+ "blockedReason": null,
+ "canApprove": false,
+ "claims": [
+ "Calls itself \"OpenKoalaBots\" (unverified)",
+ "Says: \"open the pull request\" (unverified)"
+ ],
+ "rows": [
+ "[ ] example.test 2 cookies"
+ ],
+ "title": "Allow com.example.koalabot?"
+ }
+ },
+ {
+ "action": {
+ "key": "chrome|example.test",
+ "type": "toggle"
+ },
+ "approval": "req-1",
+ "frame": {
+ "approveLabel": "Approve 2 items",
"badge": "ad hoc, untrusted",
"blockedReason": null,
"canApprove": true,
@@ -222,8 +232,7 @@
"Says: \"open the pull request\" (unverified)"
],
"rows": [
- "[ ] github.example.test [email protected]",
- "[x] github.example.test [email protected]"
+ "[x] example.test 2 cookies"
],
"title": "Allow com.example.koalabot?"
}
@@ -232,6 +241,7 @@
"approval": "req-1",
"approveCommand": {
"items": [
+ "gh-ada",
"gh-bob"
],
"requestId": "req-1",
@@ -250,29 +260,29 @@
"Says: \"check the build\" (unverified)"
],
"rows": [
- "[ ] github.example.test [email protected]",
- "[ ] linear.example.test Not imported yet"
+ "[ ] example.test 1 cookie",
+ "[ ] linear.example.test Not saved yet"
],
"title": "Allow com.example.koalabot?"
}
},
{
"action": {
- "key": "gh-ada",
+ "key": "chrome|example.test",
"type": "toggle"
},
"approval": "req-2",
"frame": {
"approveLabel": "Approve 1 item",
"badge": "ad hoc, untrusted",
- "blockedReason": "This request imports new items; select all or deny.",
+ "blockedReason": "This request saves new items; select all or deny.",
"canApprove": false,
"claims": [
"Says: \"check the build\" (unverified)"
],
"rows": [
- "[x] github.example.test [email protected]",
- "[ ] linear.example.test Not imported yet"
+ "[x] example.test 1 cookie",
+ "[ ] linear.example.test Not saved yet"
],
"title": "Allow com.example.koalabot?"
}
@@ -284,7 +294,7 @@
},
"approval": "req-2",
"frame": {
- "approveLabel": "Approve 2 items",
+ "approveLabel": "Approve 1 item",
"badge": "ad hoc, untrusted",
"blockedReason": null,
"canApprove": true,
@@ -292,8 +302,8 @@
"Says: \"check the build\" (unverified)"
],
"rows": [
- "[x] github.example.test [email protected]",
- "[x] linear.example.test Not imported yet"
+ "[x] example.test 1 cookie",
+ "[x] linear.example.test Not saved yet"
],
"title": "Allow com.example.koalabot?"
}
@@ -312,8 +322,8 @@
"Says: \"check the build\" (unverified)"
],
"rows": [
- "[ ] github.example.test [email protected]",
- "[ ] linear.example.test Not imported yet"
+ "[ ] example.test 1 cookie",
+ "[ ] linear.example.test Not saved yet"
],
"title": "Allow com.example.koalabot?"
}
@@ -329,20 +339,317 @@
}
},
{
- "siteDetail": {
- "enabled": true,
- "state": "off",
- "switch": true
+ "frame": {
+ "canLock": false,
+ "canUnlock": false,
+ "empty": null,
+ "lines": [
+ "[ ] Chrome chrome | 6 items, 1 unlocked | mixed | 5 min ago",
+ " [ ] example-idp.test | 1 cookie | locked | 24 h ago",
+ " [ ] example.test | 1 password, 2 cookies, 1 storage value | mixed | 5 min ago",
+ " [ ] files (1) | locked",
+ "[ ] Slack slack | 2 items | locked | 3 h ago",
+ " [ ] example.test | 1 cookie | locked | 24 h ago",
+ " [ ] files (1) | locked"
+ ],
+ "selection": "0 selected (unlock 0 / lock 0 / always ask 0)",
+ "shown": "8/8"
},
- "siteToggle": {
- "itemIds": [
- "gh-ada",
- "gh-bob"
+ "vault": "open"
+ },
+ {
+ "frame": {
+ "canLock": false,
+ "canUnlock": false,
+ "empty": null,
+ "lines": [
+ "[ ] Chrome chrome | 6 items, 1 unlocked | mixed | 5 min ago",
+ " [ ] example-idp.test | 1 cookie | locked | 24 h ago",
+ " [ ] example.test | 1 password, 2 cookies, 1 storage value | mixed | 5 min ago | open",
+ " [ ] Password [email protected] | https://github.example.test | lock.fill | 24 h ago",
+ " [ ] Cookie _gh_sess | .github.example.test | lock.fill | 5 min ago",
+ " [ ] Cookie user_session | .github.example.test | lock.open | 5 min ago",
+ " [ ] Local storage theme | https://github.example.test | lock.fill | 24 h ago",
+ " [ ] files (1) | locked",
+ "[ ] Slack slack | 2 items | locked | 3 h ago",
+ " [ ] example.test | 1 cookie | locked | 24 h ago",
+ " [ ] files (1) | locked"
+ ],
+ "selection": "0 selected (unlock 0 / lock 0 / always ask 0)",
+ "shown": "8/8"
+ },
+ "vault": {
+ "key": "chrome|example.test",
+ "type": "toggle-open"
+ }
+ },
+ {
+ "frame": {
+ "canLock": false,
+ "canUnlock": true,
+ "empty": null,
+ "lines": [
+ "[-] Chrome chrome | 6 items, 1 unlocked | mixed | 5 min ago",
+ " [ ] example-idp.test | 1 cookie | locked | 24 h ago",
+ " [-] example.test | 1 password, 2 cookies, 1 storage value | mixed | 5 min ago | open",
+ " [ ] Password [email protected] | https://github.example.test | lock.fill | 24 h ago",
+ " [x] Cookie _gh_sess | .github.example.test | lock.fill | 5 min ago",
+ " [ ] Cookie user_session | .github.example.test | lock.open | 5 min ago",
+ " [ ] Local storage theme | https://github.example.test | lock.fill | 24 h ago",
+ " [ ] files (1) | locked",
+ "[ ] Slack slack | 2 items | locked | 3 h ago",
+ " [ ] example.test | 1 cookie | locked | 24 h ago",
+ " [ ] files (1) | locked"
+ ],
+ "selection": "1 selected (unlock 1 / lock 0 / always ask 0)",
+ "shown": "8/8"
+ },
+ "vault": {
+ "id": "gh-bob",
+ "type": "toggle"
+ }
+ },
+ {
+ "frame": {
+ "canLock": true,
+ "canUnlock": true,
+ "empty": null,
+ "lines": [
+ "[-] Chrome chrome | 6 items, 1 unlocked | mixed | 5 min ago",
+ " [ ] example-idp.test | 1 cookie | locked | 24 h ago",
+ " [x] example.test | 1 password, 2 cookies, 1 storage value | mixed | 5 min ago | open",
+ " [x] Password [email protected] | https://github.example.test | lock.fill | 24 h ago",
+ " [x] Cookie _gh_sess | .github.example.test | lock.fill | 5 min ago",
+ " [x] Cookie user_session | .github.example.test | lock.open | 5 min ago",
+ " [x] Local storage theme | https://github.example.test | lock.fill | 24 h ago",
+ " [ ] files (1) | locked",
+ "[ ] Slack slack | 2 items | locked | 3 h ago",
+ " [ ] example.test | 1 cookie | locked | 24 h ago",
+ " [ ] files (1) | locked"
+ ],
+ "selection": "4 selected (unlock 3 / lock 1 / always ask 0)",
+ "shown": "8/8"
+ },
+ "vault": {
+ "key": "chrome|example.test",
+ "type": "toggle-group"
+ }
+ },
+ {
+ "frame": {
+ "canLock": true,
+ "canUnlock": true,
+ "empty": null,
+ "lines": [
+ "[x] Chrome chrome | 6 items, 1 unlocked | mixed | 5 min ago",
+ " [x] example-idp.test | 1 cookie | locked | 24 h ago",
+ " [x] example.test | 1 password, 2 cookies, 1 storage value | mixed | 5 min ago | open",
+ " [x] Password [email protected] | https://github.example.test | lock.fill | 24 h ago",
+ " [x] Cookie _gh_sess | .github.example.test | lock.fill | 5 min ago",
+ " [x] Cookie user_session | .github.example.test | lock.open | 5 min ago",
+ " [x] Local storage theme | https://github.example.test | lock.fill | 24 h ago",
+ " [x] files (1) | locked",
+ "[ ] Slack slack | 2 items | locked | 3 h ago",
+ " [ ] example.test | 1 cookie | locked | 24 h ago",
+ " [ ] files (1) | locked"
],
- "type": "set-unattended",
- "unattended": true
+ "selection": "6 selected (unlock 4 / lock 1 / always ask 1)",
+ "shown": "8/8"
+ },
+ "vault": {
+ "key": "chrome",
+ "type": "toggle-group"
}
},
+ {
+ "frame": {
+ "canLock": false,
+ "canUnlock": false,
+ "empty": null,
+ "lines": [
+ "[ ] Chrome chrome | 6 items, 1 unlocked | mixed | 5 min ago",
+ " [ ] example-idp.test | 1 cookie | locked | 24 h ago",
+ " [ ] example.test | 1 password, 2 cookies, 1 storage value | mixed | 5 min ago | open",
+ " [ ] Password [email protected] | https://github.example.test | lock.fill | 24 h ago",
+ " [ ] Cookie _gh_sess | .github.example.test | lock.fill | 5 min ago",
+ " [ ] Cookie user_session | .github.example.test | lock.open | 5 min ago",
+ " [ ] Local storage theme | https://github.example.test | lock.fill | 24 h ago",
+ " [ ] files (1) | locked",
+ "[ ] Slack slack | 2 items | locked | 3 h ago",
+ " [ ] example.test | 1 cookie | locked | 24 h ago",
+ " [ ] files (1) | locked"
+ ],
+ "selection": "0 selected (unlock 0 / lock 0 / always ask 0)",
+ "shown": "8/8"
+ },
+ "vault": {
+ "type": "clear"
+ }
+ },
+ {
+ "frame": {
+ "canLock": false,
+ "canUnlock": false,
+ "empty": null,
+ "lines": [
+ "[ ] Chrome chrome | 3 items, 1 unlocked | mixed | 5 min ago",
+ " [ ] example-idp.test | 1 cookie | locked | 24 h ago | open",
+ " [ ] Cookie SID | .accounts.example-idp.test | lock.fill | 24 h ago | always asks",
+ " [ ] example.test | 2 cookies | mixed | 5 min ago | open",
+ " [ ] Cookie _gh_sess | .github.example.test | lock.fill | 5 min ago",
+ " [ ] Cookie user_session | .github.example.test | lock.open | 5 min ago",
+ "[ ] Slack slack | 1 item | locked | 24 h ago",
+ " [ ] example.test | 1 cookie | locked | 24 h ago | open",
+ " [ ] Cookie d | .slack.example.test | lock.fill | 24 h ago"
+ ],
+ "selection": "0 selected (unlock 0 / lock 0 / always ask 0)",
+ "shown": "4/8"
+ },
+ "vault": {
+ "text": "cookie",
+ "type": "query"
+ }
+ },
+ {
+ "frame": {
+ "canLock": true,
+ "canUnlock": true,
+ "empty": null,
+ "lines": [
+ "[x] Chrome chrome | 3 items, 1 unlocked | mixed | 5 min ago",
+ " [x] example-idp.test | 1 cookie | locked | 24 h ago | open",
+ " [x] Cookie SID | .accounts.example-idp.test | lock.fill | 24 h ago | always asks",
+ " [x] example.test | 2 cookies | mixed | 5 min ago | open",
+ " [x] Cookie _gh_sess | .github.example.test | lock.fill | 5 min ago",
+ " [x] Cookie user_session | .github.example.test | lock.open | 5 min ago",
+ "[x] Slack slack | 1 item | locked | 24 h ago",
+ " [x] example.test | 1 cookie | locked | 24 h ago | open",
+ " [x] Cookie d | .slack.example.test | lock.fill | 24 h ago"
+ ],
+ "selection": "4 selected (unlock 2 / lock 1 / always ask 1)",
+ "shown": "4/8"
+ },
+ "vault": {
+ "type": "select-all"
+ }
+ },
+ {
+ "frame": {
+ "canLock": false,
+ "canUnlock": true,
+ "empty": null,
+ "lines": [
+ "[-] Slack slack | 2 items | locked | 3 h ago",
+ " [x] example.test | 1 cookie | locked | 24 h ago | open",
+ " [x] Cookie d | .slack.example.test | lock.fill | 24 h ago",
+ " [ ] files (1) | locked | open",
+ " [ ] File root-state.json | storage | lock.fill | 3 h ago"
+ ],
+ "selection": "1 selected (unlock 1 / lock 0 / always ask 0)",
+ "shown": "2/8"
+ },
+ "vault": {
+ "text": "slack",
+ "type": "query"
+ }
+ },
+ {
+ "frame": {
+ "canLock": false,
+ "canUnlock": true,
+ "empty": null,
+ "lines": [
+ "[x] Slack slack | 2 items | locked | 3 h ago",
+ " [x] example.test | 1 cookie | locked | 24 h ago | open",
+ " [x] Cookie d | .slack.example.test | lock.fill | 24 h ago",
+ " [x] files (1) | locked | open",
+ " [x] File root-state.json | storage | lock.fill | 3 h ago"
+ ],
+ "selection": "2 selected (unlock 2 / lock 0 / always ask 0)",
+ "shown": "2/8"
+ },
+ "vault": {
+ "type": "select-all"
+ }
+ },
+ {
+ "frame": {
+ "canLock": false,
+ "canUnlock": false,
+ "empty": "No matches",
+ "lines": [],
+ "selection": "0 selected (unlock 0 / lock 0 / always ask 0)",
+ "shown": "0/8"
+ },
+ "vault": {
+ "text": "nothing-like-this",
+ "type": "query"
+ }
+ },
+ {
+ "frame": {
+ "canLock": false,
+ "canUnlock": false,
+ "empty": null,
+ "lines": [
+ "[ ] Slack slack | 2 items | locked | 3 h ago",
+ " [ ] example.test | 1 cookie | locked | 24 h ago",
+ " [ ] files (1) | locked"
+ ],
+ "selection": "0 selected (unlock 0 / lock 0 / always ask 0)",
+ "shown": "2/8"
+ },
+ "vaultApp": "slack"
+ },
+ {
+ "frame": [
+ "Allow unattended access?",
+ "This will allow any agent with access to the Cua Spaces MCP to write this key into your connected Spaces. The secrets are not sent directly to any agents.",
+ "user_session",
+ "Deny / Allow / Never ask again"
+ ],
+ "unlockPrompt": {
+ "count": 1,
+ "name": "user_session"
+ }
+ },
+ {
+ "frame": [
+ "Allow unattended access?",
+ "This will allow any agent with access to the Cua Spaces MCP to write these keys into your connected Spaces. The secrets are not sent directly to any agents.",
+ "3 items",
+ "Deny / Allow / Never ask again"
+ ],
+ "unlockPrompt": {
+ "count": 3,
+ "name": null
+ }
+ },
+ {
+ "unlockPromptSkipped": null
+ },
+ {
+ "deleteConfirm": {
+ "count": 1,
+ "liveCopies": 0
+ },
+ "frame": [
+ "Delete this item?",
+ "It is removed from the Keyvault and cannot be recovered.",
+ "Delete / Cancel"
+ ]
+ },
+ {
+ "deleteConfirm": {
+ "count": 3,
+ "liveCopies": 1
+ },
+ "frame": [
+ "Delete 3 items?",
+ "They are removed from the Keyvault and cannot be recovered. Copies delivered to a Space will be wiped as well.",
+ "Delete / Cancel"
+ ]
+ },
{
"page": {
"disabled": true,
@@ -373,15 +680,14 @@
"Says: \"open the pull request\" (unverified)"
],
"rows": [
- "[x] github.example.test [email protected]",
- "[x] github.example.test [email protected]"
+ "[x] example.test 2 cookies"
],
"title": "Allow com.example.koalabot?"
}
},
{
"badges": [
- "All:-",
+ "All Items:-",
"Waiting:2",
"Access:-",
"Recent:-"
@@ -398,10 +704,7 @@
"unlock: Unlock",
"revokeAll: Revoke all",
"confirmNote: Touch ID confirms in the Cua daemon.",
- "protectionTitle: Protection",
- "accountsTitle: Accounts",
- "appLabel: App",
- "everyAccount: Every account unattended"
+ "protectionTitle: Protection"
],
"recoveryKey": "Recovery key, shown once: ABCD-EFGH"
}
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/keyvault-approve-deny.json b/libs/cua/crates/cua-spaces-app-core/parity/keyvault-approve-deny.json
index 4fa27c8027..aeb67dee83 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/keyvault-approve-deny.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/keyvault-approve-deny.json
@@ -1,6 +1,6 @@
{
"name": "keyvault-approve-deny",
- "about": "Keyvault: categories, an approval with nothing selected, narrowing to one item, an all-or-nothing import request, deny, and the kill switch blocking approval.",
+ "about": "Keyvault: the vault list grouped by app and site (search, multi-select, locks), the unlock prompt and delete confirm, categories, an approval grouped by site with nothing selected, narrowing to one site, an all-or-nothing import request, deny, and the kill switch blocking approval.",
"now": 1800000000000,
"overview": {
"availability": "ready",
@@ -12,27 +12,41 @@
"disabled": false,
"caller_first_party": true,
"caller_display": "Cua (team YCK386LBJ7, signed id \"com.trycua.spaces.macos\")",
- "items": 4,
+ "items": 8,
"pending": 2,
- "unlock_policy": "auto"
+ "unlock_policy": "auto",
+ "skip_unlock_prompt": false
},
"items": [
{
"id": "gh-ada",
- "kind": "browser_site",
- "label": "github.example.test (Chrome, Default)",
+ "kind": "cookie",
"provider_id": "chrome",
"app_display": "Chrome",
"source": "Default",
- "summary": {
- "cookies": [],
- "storage_origins": [],
- "passwords": 0,
- "files": [],
- "keychain_services": [],
- "bytes": 0
+ "bytes": 64,
+ "identity_provider": false,
+ "policy": {
+ "allowed_targets": [],
+ "ttl_secs": 3600,
+ "unattended": true
},
- "warnings": [],
+ "created_ms": 1799913600000,
+ "updated_ms": 1799999700000,
+ "rev": 1,
+ "record_digest": "00",
+ "key": "user_session",
+ "domain": ".github.example.test",
+ "path": "/",
+ "session": false
+ },
+ {
+ "id": "gh-bob",
+ "kind": "cookie",
+ "provider_id": "chrome",
+ "app_display": "Chrome",
+ "source": "Default",
+ "bytes": 64,
"identity_provider": false,
"policy": {
"allowed_targets": [],
@@ -40,28 +54,41 @@
"unattended": false
},
"created_ms": 1799913600000,
- "updated_ms": 1799913600000,
+ "updated_ms": 1799999700000,
"rev": 1,
"record_digest": "00",
- "site": "github.example.test",
- "account": "[email protected]"
+ "key": "_gh_sess",
+ "domain": ".github.example.test",
+ "path": "/",
+ "session": false
},
{
- "id": "gh-bob",
- "kind": "browser_site",
- "label": "github.example.test (Chrome, Default)",
+ "id": "gh-pw",
+ "kind": "password",
"provider_id": "chrome",
"app_display": "Chrome",
"source": "Default",
- "summary": {
- "cookies": [],
- "storage_origins": [],
- "passwords": 0,
- "files": [],
- "keychain_services": [],
- "bytes": 0
+ "bytes": 64,
+ "identity_provider": false,
+ "policy": {
+ "allowed_targets": [],
+ "ttl_secs": 3600,
+ "unattended": false
},
- "warnings": [],
+ "created_ms": 1799913600000,
+ "updated_ms": 1799913600000,
+ "rev": 1,
+ "record_digest": "00",
+ "key": "[email protected]",
+ "domain": "https://github.example.test"
+ },
+ {
+ "id": "gh-ls",
+ "kind": "local_storage",
+ "provider_id": "chrome",
+ "app_display": "Chrome",
+ "source": "Default",
+ "bytes": 64,
"identity_provider": false,
"policy": {
"allowed_targets": [],
@@ -72,25 +99,16 @@
"updated_ms": 1799913600000,
"rev": 1,
"record_digest": "00",
- "site": "github.example.test",
- "account": "[email protected]"
+ "key": "theme",
+ "domain": "https://github.example.test"
},
{
"id": "idp",
- "kind": "browser_site",
- "label": "accounts.example-idp.test (Chrome, Default)",
+ "kind": "cookie",
"provider_id": "chrome",
"app_display": "Chrome",
"source": "Default",
- "summary": {
- "cookies": [],
- "storage_origins": [],
- "passwords": 0,
- "files": [],
- "keychain_services": [],
- "bytes": 0
- },
- "warnings": [],
+ "bytes": 64,
"identity_provider": true,
"policy": {
"allowed_targets": [],
@@ -101,36 +119,70 @@
"updated_ms": 1799913600000,
"rev": 1,
"record_digest": "00",
- "site": "accounts.example-idp.test",
- "account": "[email protected]"
+ "key": "SID",
+ "domain": ".accounts.example-idp.test",
+ "path": "/",
+ "session": false
+ },
+ {
+ "id": "chrome-bm",
+ "kind": "file",
+ "provider_id": "chrome",
+ "app_display": "Chrome",
+ "source": "Default",
+ "bytes": 64,
+ "identity_provider": false,
+ "policy": {
+ "allowed_targets": [],
+ "ttl_secs": 3600,
+ "unattended": false
+ },
+ "created_ms": 1799913600000,
+ "updated_ms": 1799913600000,
+ "rev": 1,
+ "record_digest": "00",
+ "key": "Default/Bookmarks"
},
{
"id": "slack",
- "kind": "app_session",
- "label": "Slack (whole app session)",
+ "kind": "file",
"provider_id": "slack",
"app_display": "Slack",
"source": "Default",
- "summary": {
- "cookies": [],
- "storage_origins": [],
- "passwords": 0,
- "files": [],
- "keychain_services": [],
- "bytes": 0
+ "bytes": 64,
+ "identity_provider": false,
+ "policy": {
+ "allowed_targets": [],
+ "ttl_secs": 3600,
+ "unattended": false
},
- "warnings": [],
+ "created_ms": 1799913600000,
+ "updated_ms": 1799990000000,
+ "rev": 1,
+ "record_digest": "00",
+ "key": "storage/root-state.json"
+ },
+ {
+ "id": "slack-d",
+ "kind": "cookie",
+ "provider_id": "slack",
+ "app_display": "Slack",
+ "source": "Default",
+ "bytes": 64,
"identity_provider": false,
"policy": {
"allowed_targets": [],
"ttl_secs": 3600,
- "unattended": true
+ "unattended": false
},
"created_ms": 1799913600000,
"updated_ms": 1799913600000,
"rev": 1,
"record_digest": "00",
- "account": "Example Workspace"
+ "key": "d",
+ "domain": ".slack.example.test",
+ "path": "/",
+ "session": false
}
],
"pending": [
@@ -174,49 +226,33 @@
"items": [
{
"id": "gh-ada",
- "kind": "browser_site",
- "label": "github.example.test (Chrome, Default)",
+ "kind": "cookie",
"provider_id": "chrome",
"app_display": "Chrome",
"source": "Default",
- "summary": {
- "cookies": [],
- "storage_origins": [],
- "passwords": 0,
- "files": [],
- "keychain_services": [],
- "bytes": 0
- },
- "warnings": [],
+ "bytes": 64,
"identity_provider": false,
"policy": {
"allowed_targets": [],
"ttl_secs": 3600,
- "unattended": false
+ "unattended": true
},
"created_ms": 1799913600000,
- "updated_ms": 1799913600000,
+ "updated_ms": 1799999700000,
"rev": 1,
"record_digest": "00",
- "site": "github.example.test",
- "account": "[email protected]"
+ "key": "user_session",
+ "domain": ".github.example.test",
+ "path": "/",
+ "session": false
},
{
"id": "gh-bob",
- "kind": "browser_site",
- "label": "github.example.test (Chrome, Default)",
+ "kind": "cookie",
"provider_id": "chrome",
"app_display": "Chrome",
"source": "Default",
- "summary": {
- "cookies": [],
- "storage_origins": [],
- "passwords": 0,
- "files": [],
- "keychain_services": [],
- "bytes": 0
- },
- "warnings": [],
+ "bytes": 64,
"identity_provider": false,
"policy": {
"allowed_targets": [],
@@ -224,11 +260,13 @@
"unattended": false
},
"created_ms": 1799913600000,
- "updated_ms": 1799913600000,
+ "updated_ms": 1799999700000,
"rev": 1,
"record_digest": "00",
- "site": "github.example.test",
- "account": "[email protected]"
+ "key": "_gh_sess",
+ "domain": ".github.example.test",
+ "path": "/",
+ "session": false
}
],
"needs_import": [],
@@ -275,32 +313,25 @@
"items": [
{
"id": "gh-ada",
- "kind": "browser_site",
- "label": "github.example.test (Chrome, Default)",
+ "kind": "cookie",
"provider_id": "chrome",
"app_display": "Chrome",
"source": "Default",
- "summary": {
- "cookies": [],
- "storage_origins": [],
- "passwords": 0,
- "files": [],
- "keychain_services": [],
- "bytes": 0
- },
- "warnings": [],
+ "bytes": 64,
"identity_provider": false,
"policy": {
"allowed_targets": [],
"ttl_secs": 3600,
- "unattended": false
+ "unattended": true
},
"created_ms": 1799913600000,
- "updated_ms": 1799913600000,
+ "updated_ms": 1799999700000,
"rev": 1,
"record_digest": "00",
- "site": "github.example.test",
- "account": "[email protected]"
+ "key": "user_session",
+ "domain": ".github.example.test",
+ "path": "/",
+ "session": false
}
],
"needs_import": [
@@ -440,7 +471,9 @@
"entries": 5,
"unauthenticated": 0
},
- "partialErrors": []
+ "partialErrors": [],
+ "namesVisible": true,
+ "itemsTotal": 8
},
"selections": [
{
@@ -460,8 +493,8 @@
"category": "recent"
},
{
- "kind": "site",
- "key": "chrome:github.example.test"
+ "kind": "app",
+ "key": "slack"
}
],
"approvals": [
@@ -470,7 +503,7 @@
"actions": [
{
"type": "toggle",
- "key": "gh-bob"
+ "key": "chrome|example.test"
},
{
"type": "toggle",
@@ -481,7 +514,11 @@
},
{
"type": "toggle",
- "key": "gh-ada"
+ "key": "chrome|example.test"
+ },
+ {
+ "type": "toggle",
+ "key": "chrome|example.test"
}
]
},
@@ -490,7 +527,7 @@
"actions": [
{
"type": "toggle",
- "key": "gh-ada"
+ "key": "chrome|example.test"
},
{
"type": "toggle",
@@ -503,10 +540,6 @@
}
],
"deny": "req-2",
- "siteToggle": {
- "key": "chrome:github.example.test",
- "on": true
- },
"disabled": {
"request": "req-1",
"actions": [
@@ -514,5 +547,72 @@
"type": "select-all"
}
]
+ },
+ "vault": {
+ "state": {
+ "query": "",
+ "selected": [],
+ "expanded": []
+ },
+ "actions": [
+ {
+ "type": "toggle-open",
+ "key": "chrome|example.test"
+ },
+ {
+ "type": "toggle",
+ "id": "gh-bob"
+ },
+ {
+ "type": "toggle-group",
+ "key": "chrome|example.test"
+ },
+ {
+ "type": "toggle-group",
+ "key": "chrome"
+ },
+ {
+ "type": "clear"
+ },
+ {
+ "type": "query",
+ "text": "cookie"
+ },
+ {
+ "type": "select-all"
+ },
+ {
+ "type": "query",
+ "text": "slack"
+ },
+ {
+ "type": "select-all"
+ },
+ {
+ "type": "query",
+ "text": "nothing-like-this"
+ }
+ ],
+ "unlock": [
+ {
+ "count": 1,
+ "name": "user_session"
+ },
+ {
+ "count": 3,
+ "name": null
+ }
+ ],
+ "delete": [
+ {
+ "count": 1,
+ "liveCopies": 0
+ },
+ {
+ "count": 3,
+ "liveCopies": 1
+ }
+ ],
+ "app": "slack"
}
-}
\ No newline at end of file
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
index da15dfa48e..19788ed48c 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
@@ -9,7 +9,7 @@
//!
//! [`METHODS`] lists every method; `dispatch_covers_every_method` checks it.
-use crate::keyvault::{approval, browse, view as kv};
+use crate::keyvault::{approval, browse, vault, view as kv};
use crate::model::*;
use crate::spaces::{self, creating, roster, sidebar, stream};
use crate::teleport::{drag, flow, grid, transfer, windows};
@@ -122,17 +122,17 @@ pub const METHODS: &[&str] = &[
"keyvault.ago",
"keyvault.shortCaller",
"keyvault.signingBadge",
- "keyvault.accountOf",
- "keyvault.groupItems",
"keyvault.recentDecisions",
"keyvault.pendingSummary",
"keyvault.pendingRows",
"keyvault.accessRows",
"keyvault.page",
- "keyvault.siteToggle",
"keyvault.sidebar",
"keyvault.list",
- "keyvault.siteDetail",
+ "keyvault.vaultReduce",
+ "keyvault.vaultView",
+ "keyvault.unlockPrompt",
+ "keyvault.deleteConfirm",
"keyvault.labels",
"keyvault.recoveryKeyText",
"keyvault.credentialForm",
@@ -511,12 +511,6 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
"keyvault.ago" => out(kv::ago(a.get("ms")?)),
"keyvault.shortCaller" => out(kv::short_caller(&a.get::<String>("display")?)),
"keyvault.signingBadge" => out(kv::signing_badge(&a.get("caller")?)),
- "keyvault.accountOf" => out(kv::account_of(&a.get("item")?)),
- "keyvault.groupItems" => out(kv::group_items(
- &a.get("overview")?,
- a.get("now")?,
- &a.get::<Option<String>>("query")?.unwrap_or_default(),
- )),
"keyvault.recentDecisions" => out(kv::recent_decisions(
&a.get("overview")?,
a.get::<Option<usize>>("limit")?.unwrap_or(12),
@@ -525,19 +519,30 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
"keyvault.pendingRows" => out(kv::pending_rows(&a.get("overview")?)),
"keyvault.accessRows" => out(kv::access_rows(&a.get("overview")?, a.get("now")?)),
"keyvault.page" => out(kv::page(&a.get("overview")?, a.get("now")?)),
- "keyvault.siteToggle" => out(kv::site_toggle(&a.get("group")?, a.get("on")?)),
"keyvault.sidebar" => out(browse::sidebar(&a.get("overview")?, a.get("now")?)),
"keyvault.list" => out(browse::list(
&a.get("overview")?,
&a.get("selection")?,
a.get("now")?,
- &a.get::<Option<String>>("query")?.unwrap_or_default(),
)),
- "keyvault.siteDetail" => out(browse::site_detail(
+ "keyvault.vaultReduce" => out(vault::reduce(
+ &a.get("overview")?,
+ &a.get("state")?,
+ &a.get("action")?,
+ )),
+ "keyvault.vaultView" => out(vault::view(
&a.get("overview")?,
- &a.get::<String>("key")?,
+ &a.get("state")?,
a.get("now")?,
)),
+ "keyvault.unlockPrompt" => out(vault::unlock_prompt(
+ &a.get("overview")?,
+ a.get("count")?,
+ a.get::<Option<String>>("name")?.as_deref(),
+ )),
+ "keyvault.deleteConfirm" => {
+ out(vault::delete_confirm(a.get("count")?, a.get("liveCopies")?))
+ }
"keyvault.labels" => out(kv::labels()),
"keyvault.recoveryKeyText" => out(kv::recovery_key_text(&a.get::<String>("key")?)),
"keyvault.credentialForm" => out(crate::keyvault::credential::credential_form(
diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/approval.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/approval.rs
index 27d882c716..435c77173c 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/approval.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/approval.rs
@@ -4,8 +4,9 @@
//! The approval sheet for a waiting request.
//!
//! Nothing is selected by default: Approve stays disabled until the user
-//! ticks at least one item, and approves only those. A request that would
-//! import new items (sites the vault does not hold yet) is all or nothing,
+//! ticks at least one site, and approves only the items of those. A request
+//! that would save new items (sites the vault does not hold yet) is all or
+//! nothing,
//! because the broker imports them on approval and their ids are not known
//! before: the user ticks every row or denies. The daemon then asks for
//! Touch ID or the login password; no shell runs its own prompt.
@@ -20,7 +21,7 @@ use serde::{Deserialize, Serialize};
pub struct ApprovalState {
/// The request.
pub request_id: String,
- /// Ticked row keys (item ids, or `import:<n>` for new items).
+ /// Ticked row keys (`<app>|<site>`, or `import:<n>` for new items).
pub selected: Vec<String>,
}
@@ -47,16 +48,23 @@ pub enum ApprovalAction {
Clear,
}
-/// One row of the sheet.
+/// One row of the sheet: a site (or an app's files) with how many items
+/// it carries, or an app the approval would save.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalRow {
- /// Row key.
+ /// Row key: `<app>|<site>`, `<app>|files`, or `import:<n>`.
pub key: String,
- /// Site or app.
+ /// The site, or the app for files and imports.
pub title: String,
- /// Account, or "Not imported yet".
+ /// "3 cookies, 1 password", or "Not saved yet".
pub account: String,
+ /// The app's provider id (its icon), when known.
+ pub provider_id: String,
+ /// Items the row stands for.
+ pub items: u32,
+ /// The items' ids.
+ pub item_ids: Vec<String>,
/// Ticked.
pub selected: bool,
/// A new item the approval imports.
@@ -96,33 +104,74 @@ pub struct ApprovalView {
}
fn rows(o: &KeyvaultOverview, state: &ApprovalState) -> Vec<ApprovalRow> {
+ use super::vault::{KvKind, site_of};
let Some(p) = o.pending.iter().find(|p| p.id == state.request_id) else {
return vec![];
};
- let mut out: Vec<ApprovalRow> = p
- .items
- .iter()
- .map(|i| ApprovalRow {
- key: i.id.clone(),
- title: i.site.clone().unwrap_or_else(|| i.app_display.clone()),
- account: super::view::account_of(i),
- selected: state.selected.contains(&i.id),
- is_import: false,
+ // Group the request's items by app and site (files apart).
+ let mut groups: Vec<(String, String, String, Vec<&super::wire::KvItem>)> = Vec::new();
+ for i in &p.items {
+ let is_file = KvKind::from_wire(&i.kind) == KvKind::File;
+ let (key, title) = if is_file {
+ (
+ format!("{}|files", i.provider_id),
+ format!("{} files", i.app_display),
+ )
+ } else {
+ let site = i.domain.as_deref().map(site_of).filter(|s| !s.is_empty());
+ (
+ format!("{}|{}", i.provider_id, site.clone().unwrap_or_default()),
+ site.unwrap_or_else(|| i.app_display.clone()),
+ )
+ };
+ match groups.iter_mut().find(|g| g.0 == key) {
+ Some(g) => g.3.push(i),
+ None => groups.push((key, title, i.provider_id.clone(), vec![i])),
+ }
+ }
+ let mut out: Vec<ApprovalRow> = groups
+ .into_iter()
+ .map(|(key, title, provider_id, its)| {
+ let mut kinds: Vec<(KvKind, u32)> = Vec::new();
+ for i in &its {
+ let k = KvKind::from_wire(&i.kind);
+ match kinds.iter_mut().find(|(x, _)| *x == k) {
+ Some((_, n)) => *n += 1,
+ None => kinds.push((k, 1)),
+ }
+ }
+ ApprovalRow {
+ selected: state.selected.contains(&key),
+ account: kinds
+ .iter()
+ .map(|(k, n)| k.plural(*n))
+ .collect::<Vec<_>>()
+ .join(", "),
+ items: its.len() as u32,
+ item_ids: its.iter().map(|i| i.id.clone()).collect(),
+ key,
+ title,
+ provider_id,
+ is_import: false,
+ }
})
.collect();
out.extend(p.needs_import.iter().enumerate().map(|(n, s)| {
let key = format!("import:{n}");
- let title = match s {
- KvSelector::Site { site, .. } => site.clone(),
- KvSelector::App { app } => app.clone(),
- KvSelector::Item { id } => id.clone(),
- KvSelector::Login { site } => site.clone(),
+ let (title, provider_id) = match s {
+ KvSelector::Site { site, app } => (site.clone(), app.clone()),
+ KvSelector::App { app } => (app.clone(), app.clone()),
+ KvSelector::Item { id } => (id.clone(), String::new()),
+ KvSelector::Login { site } => (site.clone(), String::new()),
};
ApprovalRow {
selected: state.selected.contains(&key),
key,
title,
- account: "Not imported yet".into(),
+ account: "Not saved yet".into(),
+ provider_id,
+ items: 0,
+ item_ids: vec![],
is_import: true,
}
}));
@@ -172,7 +221,7 @@ pub fn view(o: &KeyvaultOverview, state: &ApprovalState) -> ApprovalView {
} else if disabled {
Some("Keyvault is off. Turn it on to approve.".to_string())
} else if ticked > 0 && imports_unticked {
- Some("This request imports new items; select all or deny.".to_string())
+ Some("This request saves new items; select all or deny.".to_string())
} else {
None
};
@@ -207,8 +256,13 @@ pub fn view(o: &KeyvaultOverview, state: &ApprovalState) -> ApprovalView {
wants: wants_s,
summary,
claims: claims_v,
- approve_label: match ticked {
- 0 => "Approve".into(),
+ approve_label: match rows
+ .iter()
+ .filter(|r| r.selected)
+ .map(|r| r.items)
+ .sum::<u32>()
+ {
+ 0 if ticked == 0 => "Approve".into(),
1 => "Approve 1 item".into(),
n => format!("Approve {n} items"),
},
@@ -237,7 +291,7 @@ pub fn approve_command(o: &KeyvaultOverview, state: &ApprovalState) -> Option<Kv
v.rows
.iter()
.filter(|r| r.selected && !r.is_import)
- .map(|r| r.key.clone())
+ .flat_map(|r| r.item_ids.iter().cloned())
.collect(),
)
},
diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/browse.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/browse.rs
index 967f346ca4..7d836a3273 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/browse.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/browse.rs
@@ -1,16 +1,16 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-//! The Keyvault browser: a sidebar of
-//! categories (All, Waiting, Access, Recent) and one row per site, a list
-//! for the chosen category, and a detail pane per site with each account's
-//! unattended switch.
+//! The Keyvault browser: a sidebar of categories (All, Waiting, Access,
+//! Recent) and one row per app, and the list for the chosen one. The vault
+//! list itself (items grouped by app and site, with their locks) is
+//! [`super::vault`]; this picks what the page shows.
use super::view::{
- AccessRow, Decision, PendingRow, SiteGroup, Tri, access_rows, ago, group_items, pending_rows,
- recent_decisions,
+ AccessRow, Decision, PendingRow, access_rows, ago, pending_rows, recent_decisions,
};
use super::wire::KeyvaultOverview;
+use crate::util::collate;
use serde::{Deserialize, Serialize};
/// How many decisions Recent shows.
@@ -20,7 +20,7 @@ pub const RECENT_LIMIT: usize = 12;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KvCategory {
- /// Every site.
+ /// Every item, grouped by app.
All,
/// Requests waiting for approval.
Waiting,
@@ -34,7 +34,7 @@ impl KvCategory {
/// Title.
pub fn title(self) -> &'static str {
match self {
- KvCategory::All => "All",
+ KvCategory::All => "All Items",
KvCategory::Waiting => "Waiting",
KvCategory::Access => "Access",
KvCategory::Recent => "Recent",
@@ -67,31 +67,30 @@ pub struct CategoryRow {
pub badge: Option<u32>,
}
-/// A site row.
+/// An app row: everything saved from one app.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct SiteRow {
- /// Group key.
+pub struct AppRow {
+ /// The provider id (`chrome`): the key, and what the icon is looked up by.
pub key: String,
- /// "github.com" or "Slack".
+ /// "Google Chrome".
pub title: String,
- /// Accounts.
- pub accounts: u32,
- /// Something waits for this site.
+ /// Items.
+ pub items: u32,
+ /// Something waits for this app.
pub waiting: bool,
}
/// The Keyvault sidebar.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KvSidebar {
- /// All, Waiting, Access, Recent.
+ /// All Items, Waiting, Access, Recent.
pub categories: Vec<CategoryRow>,
- /// One row per site or app.
- pub sites: Vec<SiteRow>,
+ /// One row per app, by name.
+ pub apps: Vec<AppRow>,
}
/// The sidebar.
pub fn sidebar(o: &KeyvaultOverview, now: i64) -> KvSidebar {
- let groups = group_items(o, now, "");
let row = |c: KvCategory, count: Option<u32>| CategoryRow {
category: c,
title: c.title().into(),
@@ -102,6 +101,22 @@ pub fn sidebar(o: &KeyvaultOverview, now: i64) -> KvSidebar {
.flatten()
.filter(|n| *n > 0),
};
+ let mut apps: Vec<AppRow> = Vec::new();
+ for i in &o.items {
+ match apps.iter_mut().find(|a| a.key == i.provider_id) {
+ Some(a) => a.items += 1,
+ None => apps.push(AppRow {
+ key: i.provider_id.clone(),
+ title: i.app_display.clone(),
+ items: 1,
+ waiting: o
+ .pending
+ .iter()
+ .any(|p| p.items.iter().any(|x| x.provider_id == i.provider_id)),
+ }),
+ }
+ }
+ apps.sort_by(|a, b| collate(&a.title, &b.title));
KvSidebar {
categories: vec![
row(KvCategory::All, Some(o.items.len() as u32)),
@@ -109,19 +124,7 @@ pub fn sidebar(o: &KeyvaultOverview, now: i64) -> KvSidebar {
row(KvCategory::Access, Some(access_rows(o, now).len() as u32)),
row(KvCategory::Recent, None),
],
- sites: groups
- .iter()
- .map(|g| SiteRow {
- key: g.key.clone(),
- title: g.title.clone(),
- accounts: g.rows.len() as u32,
- waiting: g.rows.iter().any(|r| {
- r.consent
- .iter()
- .any(|c| c.kind == super::view::ConsentChipKind::Pending)
- }),
- })
- .collect(),
+ apps,
}
}
@@ -134,9 +137,9 @@ pub enum KvSelection {
/// Which.
category: KvCategory,
},
- /// A site.
- Site {
- /// Group key.
+ /// One app's items.
+ App {
+ /// Its provider id.
key: String,
},
}
@@ -150,29 +153,31 @@ pub struct RecentRow {
pub age: String,
}
-/// The list pane for a selection.
+/// The pane for a selection other than the vault list.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KvListView {
/// Title.
pub title: String,
- /// Sites (All, or the one site).
- pub sites: Vec<SiteGroup>,
+ /// The vault list shows (All Items, or one app).
+ pub vault: bool,
/// Waiting.
pub pending: Vec<PendingRow>,
/// Access.
pub access: Vec<AccessRow>,
/// Recent.
pub recent: Vec<RecentRow>,
- /// "No items yet." and friends.
+ /// "Nothing is waiting." and friends.
pub empty_text: Option<String>,
}
-/// The list for `selection`, filtered by `query` (sites only).
-pub fn list(o: &KeyvaultOverview, selection: &KvSelection, now: i64, query: &str) -> KvListView {
+/// The pane for `selection`. For All Items and an app, `vault` is true and
+/// the list is [`super::vault::view`] (narrowed to the app by
+/// [`super::vault::VaultState::app`]).
+pub fn list(o: &KeyvaultOverview, selection: &KvSelection, now: i64) -> KvListView {
let mut v = KvListView {
title: String::new(),
- sites: vec![],
+ vault: false,
pending: vec![],
access: vec![],
recent: vec![],
@@ -182,16 +187,7 @@ pub fn list(o: &KeyvaultOverview, selection: &KvSelection, now: i64, query: &str
KvSelection::Category { category } => {
v.title = category.title().into();
match category {
- KvCategory::All => {
- v.sites = group_items(o, now, query);
- if v.sites.is_empty() {
- v.empty_text = Some(if o.items.is_empty() {
- "No items yet.".into()
- } else {
- "No matches".into()
- });
- }
- }
+ KvCategory::All => v.vault = true,
KvCategory::Waiting => {
v.pending = pending_rows(o);
if v.pending.is_empty() {
@@ -218,49 +214,13 @@ pub fn list(o: &KeyvaultOverview, selection: &KvSelection, now: i64, query: &str
}
}
}
- KvSelection::Site { key } => {
- let groups = group_items(o, now, "");
- match groups.into_iter().find(|g| &g.key == key) {
- Some(g) => {
- v.title = g.title.clone();
- v.sites = vec![g];
- }
- None => v.empty_text = Some("This site is gone.".into()),
+ KvSelection::App { key } => match o.items.iter().find(|i| &i.provider_id == key) {
+ Some(i) => {
+ v.title = i.app_display.clone();
+ v.vault = true;
}
- }
+ None => v.empty_text = Some("Nothing is saved from this app.".into()),
+ },
}
v
}
-
-/// The detail pane of one site: the site switch and each account.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SiteDetail {
- /// The group.
- pub group: SiteGroup,
- /// The site switch shows (more than one account).
- pub site_switch: bool,
- /// The site switch's state.
- pub site_state: Tri,
- /// The site switch can be flipped.
- pub site_switch_enabled: bool,
- /// Its tooltip.
- pub site_switch_help: String,
-}
-
-/// The detail of the site `key`.
-pub fn site_detail(o: &KeyvaultOverview, key: &str, now: i64) -> Option<SiteDetail> {
- let group = group_items(o, now, "").into_iter().find(|g| g.key == key)?;
- let disabled = o.status.as_ref().is_some_and(|s| s.disabled);
- Some(SiteDetail {
- site_switch: group.rows.len() > 1,
- site_state: group.unattended,
- site_switch_enabled: !group.locked && !disabled,
- site_switch_help: if group.locked {
- "Identity providers always ask".into()
- } else {
- "Every account on this site".into()
- },
- group,
- })
-}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/client.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/client.rs
index 6827dbfe65..28ff2fde52 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/client.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/client.rs
@@ -19,13 +19,15 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;
pub use cua_keyvault::Zeroizing;
-use cua_keyvault::broker::{ApproveOptions, InitRequest, Status, UnlockRequest};
+use cua_keyvault::broker::{
+ ApproveOptions, InitRequest, Inventory, ItemPage, LockOutcome, Status, UnlockRequest,
+};
use cua_keyvault::ipc::{Request, VerificationView};
-use cua_keyvault::model::{Grant, ItemMeta, ItemPolicy};
+use cua_keyvault::model::Grant;
use serde::Serialize;
use serde_json::Value;
-use super::wire::{KeyvaultOverview, KvCommand, KvGrant, KvItem};
+use super::wire::{KeyvaultOverview, KvCommand, KvFavicon, KvGrant, KvInventory, KvItem};
/// How many audit entries the page reads.
pub const AUDIT_TAIL: usize = 200;
@@ -222,10 +224,25 @@ pub enum KvOutcome {
/// Key.
key: Option<String>,
},
- /// Items after a policy change.
- Items {
- /// Items.
- items: Vec<KvItem>,
+ /// Items locked or unlocked. Identity providers always ask: they are in
+ /// `skipped`, never changed.
+ Locked {
+ /// Items whose lock changed.
+ changed: Vec<String>,
+ /// Items left locked (identity providers).
+ skipped: Vec<String>,
+ },
+ /// Items deleted.
+ Deleted {
+ /// Items deleted.
+ count: u32,
+ /// Copies wiped in Spaces.
+ wiped: Vec<String>,
+ },
+ /// The browse window is open until then, Unix ms.
+ Browsing {
+ /// When it closes.
+ until_ms: u64,
},
/// Grants revoked.
Revoked {
@@ -307,12 +324,12 @@ impl KeyvaultCommands {
out.message = Some(message);
return out;
}
- match self
- .typed::<Value>(Request::ListItems)
- .await
- .and_then(decode)
- {
- Ok(items) => out.items = items,
+ match self.items().await {
+ Ok((items, names_visible, total)) => {
+ out.items = items;
+ out.names_visible = names_visible;
+ out.items_total = total;
+ }
Err(f) => {
out.availability = f.code;
out.message = Some(f.message);
@@ -352,6 +369,37 @@ impl KeyvaultCommands {
out
}
+ /// Every item, page by page: whether their names are visible, and how
+ /// many the vault holds.
+ /// Site icons from the vault (empty while the browse window is closed).
+ /// Not secret; fetched apart from the overview so views stay small.
+ pub async fn favicons(&self) -> Vec<KvFavicon> {
+ self.typed::<Vec<KvFavicon>>(Request::ListFavicons)
+ .await
+ .unwrap_or_default()
+ }
+
+ async fn items(&self) -> Result<(Vec<KvItem>, bool, u32), KvFailure> {
+ let mut all: Vec<KvItem> = Vec::new();
+ loop {
+ let page: ItemPage = self
+ .typed(Request::ListItems {
+ offset: all.len(),
+ limit: None,
+ })
+ .await?;
+ let visible = page.names_visible;
+ let total = page.total as u32;
+ let empty = page.items.is_empty();
+ for i in &page.items {
+ all.push(mirror(i)?);
+ }
+ if empty || all.len() as u32 >= total {
+ return Ok((all, visible, total));
+ }
+ }
+ }
+
async fn init(&self, req: InitRequest) -> Result<Option<String>, KvFailure> {
let v = self.transport.call(Request::Init(req)).await?;
Ok(v.get("recovery_key")
@@ -433,50 +481,85 @@ impl KeyvaultCommands {
.map(|_| ())
}
- /// Whether `item_ids` may be used by unattended rules. Off only narrows;
- /// on widens, so the daemon asks for presence. Identity providers never
- /// go unattended.
+ /// Locks or unlocks `item_ids` together. Locking only narrows. Unlocking
+ /// allows unattended access (any agent with the Cua Spaces MCP may have
+ /// the item written into a connected Space), so the daemon asks for
+ /// presence once for the whole batch. Identity providers always ask and
+ /// come back in `skipped`.
+ pub async fn set_locked(
+ &self,
+ item_ids: &[String],
+ locked: bool,
+ ) -> Result<LockOutcome, KvFailure> {
+ if item_ids.is_empty() {
+ return Ok(LockOutcome::default());
+ }
+ self.typed(Request::SetLocked {
+ ids: item_ids.to_vec(),
+ locked,
+ })
+ .await
+ }
+
+ /// [`Self::set_locked`] under the name the Tauri app's command uses
+ /// (`unattended` is "unlocked"). Returns no items: the page re-reads.
pub async fn set_unattended(
&self,
item_ids: &[String],
unattended: bool,
) -> Result<Vec<KvItem>, KvFailure> {
+ self.set_locked(item_ids, !unattended).await?;
+ Ok(vec![])
+ }
+
+ /// Deletes `item_ids` and wipes every live copy of them in Spaces.
+ /// Returns the copies wiped.
+ pub async fn delete_items(&self, item_ids: &[String]) -> Result<Vec<String>, KvFailure> {
if item_ids.is_empty() {
return Ok(vec![]);
}
- let current: Vec<ItemMeta> = self.typed(Request::ListItems).await?;
- let mut out = Vec::new();
- for id in item_ids {
- let item = current.iter().find(|i| &i.id == id).ok_or(KvFailure {
- code: "not_found".into(),
- message: format!("item {id} is not in the Keyvault"),
- })?;
- if unattended && item.identity_provider {
- return Err(KvFailure {
- code: "forbidden".into(),
- message: format!(
- "{} is an identity provider; it always asks and never runs unattended",
- item.label
- ),
- });
- }
- if item.policy.unattended == unattended {
- out.push(mirror(item)?);
- continue;
- }
- let policy = ItemPolicy {
- unattended,
- ..item.policy.clone()
- };
- let updated: ItemMeta = self
- .typed(Request::SetItemPolicy {
- id: id.clone(),
- policy,
- })
- .await?;
- out.push(mirror(&updated)?);
- }
- Ok(out)
+ self.typed(Request::DeleteItems {
+ ids: item_ids.to_vec(),
+ })
+ .await
+ }
+
+ /// "Never ask again" on the unlock prompt.
+ pub async fn set_skip_unlock_prompt(&self, on: bool) -> Result<(), KvFailure> {
+ self.transport
+ .call(Request::SetSkipUnlockPrompt { on })
+ .await
+ .map(|_| ())
+ }
+
+ /// Opens the browse window (the daemon asks for presence): item names
+ /// show for a few minutes. Returns when it closes, Unix ms.
+ pub async fn browse(&self) -> Result<u64, KvFailure> {
+ let v = self.transport.call(Request::Browse).await?;
+ Ok(v.get("browse_until_ms")
+ .and_then(Value::as_u64)
+ .unwrap_or(0))
+ }
+
+ /// Closes the browse window.
+ pub async fn end_browse(&self) -> Result<(), KvFailure> {
+ self.transport.call(Request::EndBrowse).await.map(|_| ())
+ }
+
+ /// What `app` holds, per domain with counts (the daemon asks for
+ /// presence when the browse window is closed). Never values.
+ pub async fn inventory(
+ &self,
+ app: &str,
+ profile: Option<String>,
+ ) -> Result<KvInventory, KvFailure> {
+ let inv: Inventory = self
+ .typed(Request::Inventory {
+ app: app.into(),
+ profile,
+ })
+ .await?;
+ mirror(&inv)
}
/// Imports a browser's saved passwords (`browser`: `chrome`), one item
@@ -487,17 +570,15 @@ impl KeyvaultCommands {
browser: &str,
profile: Option<String>,
sites: Vec<String>,
- ) -> Result<Vec<KvItem>, KvFailure> {
- let items: Vec<cua_keyvault::ItemMeta> = self
- .typed(Request::ImportPasswords(
- cua_keyvault::broker::PasswordImportSpec {
- app: browser.into(),
- profile,
- sites,
- },
- ))
- .await?;
- items.iter().map(mirror).collect()
+ ) -> Result<cua_keyvault::broker::ImportReport, KvFailure> {
+ self.typed(Request::ImportPasswords(
+ cua_keyvault::broker::PasswordImportSpec {
+ app: browser.into(),
+ profile,
+ sites,
+ },
+ ))
+ .await
}
/// Revokes one grant, or every grant with `*`.
@@ -573,9 +654,35 @@ impl KeyvaultCommands {
KvCommand::SetUnattended {
item_ids,
unattended,
- } => KvOutcome::Items {
- items: self.set_unattended(item_ids, *unattended).await?,
+ } => {
+ let out = self.set_locked(item_ids, !*unattended).await?;
+ KvOutcome::Locked {
+ changed: out.changed,
+ skipped: out.skipped,
+ }
+ }
+ KvCommand::SetLocked { item_ids, locked } => {
+ let out = self.set_locked(item_ids, *locked).await?;
+ KvOutcome::Locked {
+ changed: out.changed,
+ skipped: out.skipped,
+ }
+ }
+ KvCommand::DeleteItems { item_ids } => KvOutcome::Deleted {
+ count: item_ids.len() as u32,
+ wiped: self.delete_items(item_ids).await?,
+ },
+ KvCommand::SetSkipUnlockPrompt { on } => {
+ self.set_skip_unlock_prompt(*on).await?;
+ KvOutcome::Done
+ }
+ KvCommand::Browse => KvOutcome::Browsing {
+ until_ms: self.browse().await?,
},
+ KvCommand::EndBrowse => {
+ self.end_browse().await?;
+ KvOutcome::Done
+ }
KvCommand::RevokeGrant { id } => KvOutcome::Revoked {
count: self.revoke_grant(id).await? as u32,
},
diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/credential.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/credential.rs
index 5957d7b98d..a207cf95d2 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/credential.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/credential.rs
@@ -257,6 +257,9 @@ mod tests {
os_protector_available: os,
passphrase_available: true,
unlock_protectors: unlock.iter().map(|s| s.to_string()).collect(),
+ browse_until_ms: None,
+ skip_unlock_prompt: None,
+ reset_notice: None,
}),
..Default::default()
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/mod.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/mod.rs
index da33417431..4f21886666 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/mod.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/mod.rs
@@ -6,10 +6,12 @@
//! nothing here sees a secret value (the broker never returns one).
//!
//! - [`wire`]: the broker's redacted records and the page overview;
-//! - [`view`]: items per site and account with consent chips, recent
-//! decisions, live access, the page chrome;
-//! - [`browse`]: the Passwords-style sidebar (All, Waiting, Access, Recent,
-//! one row per site) and its lists;
+//! - [`vault`]: the vault list (items grouped by app and site, with locks,
+//! multi-select and search), the unlock prompt and the delete confirm;
+//! - [`view`]: recent decisions, live access, waiting requests, the page
+//! chrome;
+//! - [`browse`]: the sidebar (All Items, Waiting, Access, Recent, one row
+//! per app) and the panes for the lists other than the vault;
//! - [`approval`]: the approval sheet (nothing selected by default);
//! - [`credential`]: the setup and unlock form (Touch ID or a passphrase);
//! - `client` (feature `keyvault-client`): the broker client both shells run.
@@ -19,6 +21,7 @@ pub mod browse;
#[cfg(feature = "keyvault-client")]
pub mod client;
pub mod credential;
+pub mod vault;
pub mod view;
pub mod wire;
diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/vault.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/vault.rs
new file mode 100644
index 0000000000..b7ceea6b52
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/vault.rs
@@ -0,0 +1,1452 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The vault list: a password manager's list, grouped by the app each secret
+//! came from.
+//!
+//! The vault holds one item per secret (a cookie, a localStorage value, a
+//! password, a file). The list groups them by app, and inside an app by
+//! site (the domain), with files together. Each item shows a lock: locked
+//! needs the user's approval for every use; unlocked allows unattended
+//! access. Items, a whole site or a whole app can be selected and locked,
+//! unlocked or deleted together. Search matches a domain, a key, an app or
+//! a type.
+//!
+//! Pure shaping of what the broker returned, plus a small reducer for the
+//! list's own state (the query, the selection, the open groups). Nothing here
+//! decides access, and no value is ever here: the broker has none to give.
+
+use super::view::{Tri, ago};
+use super::wire::{KeyvaultOverview, KvCommand, KvItem};
+use crate::util::collate;
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+
+/// The type of a secret, as the list draws it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum KvKind {
+ /// A cookie.
+ Cookie,
+ /// A localStorage value.
+ LocalStorage,
+ /// A saved password.
+ Password,
+ /// A file.
+ File,
+}
+
+impl KvKind {
+ /// From the broker's tag (`cookie`, `local_storage`, `password`, `file`).
+ pub fn from_wire(kind: &str) -> KvKind {
+ match kind {
+ "cookie" => KvKind::Cookie,
+ "local_storage" => KvKind::LocalStorage,
+ "password" => KvKind::Password,
+ _ => KvKind::File,
+ }
+ }
+
+ /// "Cookie", "Local storage", "Password", "File".
+ pub fn label(self) -> &'static str {
+ match self {
+ KvKind::Cookie => "Cookie",
+ KvKind::LocalStorage => "Local storage",
+ KvKind::Password => "Password",
+ KvKind::File => "File",
+ }
+ }
+
+ /// The plural a count uses ("3 cookies").
+ pub fn plural(self, n: u32) -> String {
+ let (one, many) = match self {
+ KvKind::Cookie => ("cookie", "cookies"),
+ KvKind::LocalStorage => ("storage value", "storage values"),
+ KvKind::Password => ("password", "passwords"),
+ KvKind::File => ("file", "files"),
+ };
+ format!("{n} {}", if n == 1 { one } else { many })
+ }
+
+ /// The SF Symbol of the type.
+ pub fn symbol(self) -> &'static str {
+ match self {
+ KvKind::Cookie => "circle.hexagongrid.fill",
+ KvKind::LocalStorage => "cylinder.split.1x2",
+ KvKind::Password => "key.fill",
+ KvKind::File => "doc",
+ }
+ }
+
+ /// Display order inside a site.
+ fn rank(self) -> u8 {
+ match self {
+ KvKind::Password => 0,
+ KvKind::Cookie => 1,
+ KvKind::LocalStorage => 2,
+ KvKind::File => 3,
+ }
+ }
+}
+
+/// The lock of a row or a group.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum KvLock {
+ /// Every item needs approval for each use.
+ Locked,
+ /// Every item allows unattended access.
+ Unlocked,
+ /// Some of each.
+ Mixed,
+}
+
+impl KvLock {
+ /// The SF Symbol: `lock.fill` while locked, `lock.open` otherwise.
+ pub fn symbol(self) -> &'static str {
+ match self {
+ KvLock::Locked => "lock.fill",
+ KvLock::Unlocked => "lock.open",
+ // Some are unlocked: the open lock, drawn dimmer by the shell.
+ KvLock::Mixed => "lock.open",
+ }
+ }
+}
+
+fn lock_of(items: &[&KvItem]) -> KvLock {
+ let open = items.iter().filter(|i| i.policy.unattended).count();
+ if open == 0 {
+ KvLock::Locked
+ } else if open == items.len() {
+ KvLock::Unlocked
+ } else {
+ KvLock::Mixed
+ }
+}
+
+/// The list's own state.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultState {
+ /// The search text.
+ pub query: String,
+ /// Selected item ids.
+ pub selected: Vec<String>,
+ /// Open groups (their keys); the rest are closed.
+ pub expanded: Vec<String>,
+ /// Narrowed to one app (its provider id), as the sidebar picks it.
+ #[serde(default)]
+ pub app: Option<String>,
+}
+
+/// An input to the list.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "kebab-case")]
+pub enum VaultAction {
+ /// The search text changed.
+ Query {
+ /// Text.
+ text: String,
+ },
+ /// Select or deselect one item.
+ Toggle {
+ /// Item id.
+ id: String,
+ },
+ /// Select or deselect every shown item of an app, a site or the files
+ /// of an app (all of them when any is unselected, none when all are).
+ ToggleGroup {
+ /// Group key.
+ key: String,
+ },
+ /// Select every shown item.
+ SelectAll,
+ /// Deselect everything.
+ Clear,
+ /// Open or close a group.
+ ToggleOpen {
+ /// Group key.
+ key: String,
+ },
+}
+
+/// What the list shows for an item row.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultRow {
+ /// Item id.
+ pub id: String,
+ /// Type.
+ pub kind: KvKind,
+ /// "Cookie".
+ pub kind_label: String,
+ /// The type's SF Symbol.
+ pub symbol: String,
+ /// The key: a cookie name, storage key, username or file name.
+ pub title: String,
+ /// Grey line: the domain, or the file's folder.
+ pub subtitle: String,
+ /// Grey time: "2 min ago".
+ pub updated: String,
+ /// Locked (needs approval for every use).
+ pub locked: bool,
+ /// The lock icon: `lock.fill` or `lock.open`.
+ pub lock_symbol: String,
+ /// The lock's tooltip and accessibility label.
+ pub lock_help: String,
+ /// Identity provider: always asks, cannot be unlocked.
+ pub identity_provider: bool,
+ /// Selected.
+ pub selected: bool,
+}
+
+/// A site inside an app: its items.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultSite {
+ /// Group key.
+ pub key: String,
+ /// "github.com".
+ pub site: String,
+ /// Items (all of them, even while closed).
+ pub count: u32,
+ /// "12 cookies, 2 storage values".
+ pub counts: String,
+ /// Grey time of the newest save.
+ pub updated: String,
+ /// Selection of its items.
+ pub selected: Tri,
+ /// Lock of its items.
+ pub lock: KvLock,
+ /// Items a click on the lock unlocks (locked, not identity providers).
+ pub unlock_ids: Vec<String>,
+ /// Items a click on the lock locks (unlocked).
+ pub lock_ids: Vec<String>,
+ /// Open.
+ pub open: bool,
+ /// Its rows (empty while closed, unless searching).
+ pub rows: Vec<VaultRow>,
+}
+
+/// The files of an app.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultFiles {
+ /// Group key.
+ pub key: String,
+ /// Files.
+ pub count: u32,
+ /// Selection of its items.
+ pub selected: Tri,
+ /// Lock of its items.
+ pub lock: KvLock,
+ /// Items a click on the lock unlocks (locked, not identity providers).
+ pub unlock_ids: Vec<String>,
+ /// Items a click on the lock locks (unlocked).
+ pub lock_ids: Vec<String>,
+ /// Open.
+ pub open: bool,
+ /// Its rows (empty while closed, unless searching).
+ pub rows: Vec<VaultRow>,
+}
+
+/// An app and everything saved from it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultApp {
+ /// Group key: the provider id (`chrome`).
+ pub key: String,
+ /// The provider id, for the app's icon.
+ pub provider_id: String,
+ /// "Google Chrome".
+ pub name: String,
+ /// Items.
+ pub count: u32,
+ /// "212 items, 14 unlocked".
+ pub summary: String,
+ /// Grey time of the newest save.
+ pub updated: String,
+ /// Selection of its items.
+ pub selected: Tri,
+ /// Lock of its items.
+ pub lock: KvLock,
+ /// Items a click on the lock unlocks (locked, not identity providers).
+ pub unlock_ids: Vec<String>,
+ /// Items a click on the lock locks (unlocked).
+ pub lock_ids: Vec<String>,
+ /// Open.
+ pub open: bool,
+ /// Sites with their items, by name.
+ pub sites: Vec<VaultSite>,
+ /// Files, when it has any.
+ pub files: Option<VaultFiles>,
+}
+
+/// What the batch bar offers for the current selection.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultSelection {
+ /// Selected items.
+ pub count: u32,
+ /// Their ids, in list order.
+ pub ids: Vec<String>,
+ /// "3 selected".
+ pub title: String,
+ /// Some selected item is locked and may be unlocked.
+ pub can_unlock: bool,
+ /// Some selected item is unlocked.
+ pub can_lock: bool,
+ /// Selected items that always ask (identity providers).
+ pub always_ask: u32,
+ /// The ids to send when unlocking (locked, not identity providers).
+ pub unlock_ids: Vec<String>,
+ /// The ids to send when locking (unlocked).
+ pub lock_ids: Vec<String>,
+}
+
+/// The list as drawn.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultView {
+ /// Apps, by name.
+ pub apps: Vec<VaultApp>,
+ /// Items shown (after search).
+ pub shown: u32,
+ /// Items in the vault.
+ pub total: u32,
+ /// "No items yet." and friends.
+ pub empty_text: Option<String>,
+ /// Domains and keys are hidden until the user confirms with Touch ID.
+ pub names_hidden: bool,
+ /// What to say about it.
+ pub hidden_note: Option<String>,
+ /// The button that opens the names.
+ pub show_names_label: String,
+ /// The search field's prompt.
+ pub search_prompt: String,
+ /// The selection.
+ pub selection: VaultSelection,
+ /// Select all is offered.
+ pub can_select_all: bool,
+}
+
+/// The search prompt.
+pub const SEARCH_PROMPT: &str = "Search by domain, key, app or type";
+
+fn tokens(query: &str) -> Vec<String> {
+ query.split_whitespace().map(|t| t.to_lowercase()).collect()
+}
+
+/// Whether `item` matches every word of the query: a word may be found in
+/// the domain, the key (or path), the app or the type.
+pub fn matches(item: &KvItem, words: &[String]) -> bool {
+ if words.is_empty() {
+ return true;
+ }
+ let kind = KvKind::from_wire(&item.kind);
+ let hay = [
+ item.app_display.to_lowercase(),
+ item.provider_id.to_lowercase(),
+ item.domain.clone().unwrap_or_default().to_lowercase(),
+ item.key.to_lowercase(),
+ item.path.clone().unwrap_or_default().to_lowercase(),
+ kind.label().to_lowercase(),
+ item.kind.replace('_', " "),
+ if item.policy.unattended {
+ "unlocked".into()
+ } else {
+ "locked".into()
+ },
+ ];
+ words.iter().all(|w| hay.iter().any(|h| h.contains(w)))
+}
+
+fn site_key(provider: &str, site: &str) -> String {
+ format!("{provider}|{site}")
+}
+
+fn files_key(provider: &str) -> String {
+ format!("{provider}|\u{1}files")
+}
+
+/// The site an item sits under: its registrable domain (`github.com`).
+fn site_of_item(i: &KvItem) -> String {
+ i.domain
+ .as_deref()
+ .map(site_of)
+ .filter(|s| !s.is_empty())
+ .unwrap_or_default()
+}
+
+/// A conservative registrable domain for a cookie host, an origin or a host
+/// (the broker's grouping; see `cua_keyvault::record::site_of`).
+pub fn site_of(domain: &str) -> String {
+ const MULTI: [&str; 10] = [
+ "co.uk", "org.uk", "gov.uk", "ac.uk", "co.jp", "com.au", "com.br", "co.nz", "co.in",
+ "com.cn",
+ ];
+ let d = domain.trim();
+ let d = d.split_once("://").map_or(d, |(_, r)| r);
+ let d = d.split(['/', '?', '#']).next().unwrap_or(d);
+ let d = d.rsplit_once('@').map_or(d, |(_, r)| r);
+ let d = match d.rsplit_once(':') {
+ Some((h, port)) if port.chars().all(|c| c.is_ascii_digit()) && !h.contains(':') => h,
+ _ => d,
+ };
+ let host = d.trim_start_matches('.').to_ascii_lowercase();
+ let labels: Vec<&str> = host.split('.').filter(|l| !l.is_empty()).collect();
+ if labels.len() <= 2 || host.chars().all(|c| c.is_ascii_digit() || c == '.') {
+ return host;
+ }
+ let last_two = format!("{}.{}", labels[labels.len() - 2], labels[labels.len() - 1]);
+ if MULTI.contains(&last_two.as_str()) {
+ return format!("{}.{last_two}", labels[labels.len() - 3]);
+ }
+ last_two
+}
+
+/// The folder part of a file path ("Default" for `Default/Bookmarks`).
+fn folder_of(path: &str) -> String {
+ path.rsplit_once('/')
+ .map(|(d, _)| d.to_string())
+ .unwrap_or_default()
+}
+
+fn file_name(path: &str) -> String {
+ path.rsplit('/').next().unwrap_or(path).to_string()
+}
+
+fn lock_help(i: &KvItem) -> String {
+ if i.identity_provider {
+ "Identity providers always ask".into()
+ } else if i.policy.unattended {
+ "Unlocked: any agent with the Cua Spaces MCP can write this into your Spaces. Click to lock.".into()
+ } else {
+ "Locked: every use needs your approval. Click to allow unattended access.".into()
+ }
+}
+
+fn row(i: &KvItem, selected: bool, now: i64) -> VaultRow {
+ let kind = KvKind::from_wire(&i.kind);
+ let (title, subtitle) = if i.key.is_empty() && i.domain.is_none() {
+ // The names are hidden.
+ (kind.label().to_string(), String::new())
+ } else if kind == KvKind::File {
+ (file_name(&i.key), folder_of(&i.key))
+ } else {
+ let mut sub = i.domain.clone().unwrap_or_default();
+ if kind == KvKind::Cookie
+ && let Some(p) = i.path.as_deref().filter(|p| *p != "/")
+ {
+ sub = format!("{sub}{p}");
+ }
+ (i.key.clone(), sub)
+ };
+ VaultRow {
+ id: i.id.clone(),
+ kind,
+ kind_label: kind.label().into(),
+ symbol: kind.symbol().into(),
+ title,
+ subtitle,
+ updated: ago(now - i.updated_ms as i64),
+ locked: !i.policy.unattended,
+ lock_symbol: if i.policy.unattended {
+ "lock.open"
+ } else {
+ "lock.fill"
+ }
+ .into(),
+ lock_help: lock_help(i),
+ identity_provider: i.identity_provider,
+ selected,
+ }
+}
+
+/// The ids a click on a group's lock acts on: (unlock, lock).
+fn lock_targets(items: &[&KvItem]) -> (Vec<String>, Vec<String>) {
+ let unlock = items
+ .iter()
+ .filter(|i| !i.policy.unattended && !i.identity_provider)
+ .map(|i| i.id.clone())
+ .collect();
+ let lock = items
+ .iter()
+ .filter(|i| i.policy.unattended)
+ .map(|i| i.id.clone())
+ .collect();
+ (unlock, lock)
+}
+
+fn tri(selected: usize, of: usize) -> Tri {
+ if selected == 0 {
+ Tri::Off
+ } else if selected == of {
+ Tri::On
+ } else {
+ Tri::Mixed
+ }
+}
+
+/// The items the list shows: the vault's, filtered by the query, in list
+/// order (app, then files last inside it; sites by name; type, then key).
+fn shown<'a>(o: &'a KeyvaultOverview, state: &VaultState) -> Vec<&'a KvItem> {
+ let words = tokens(&state.query);
+ let mut items: Vec<&KvItem> = o
+ .items
+ .iter()
+ .filter(|i| state.app.as_ref().is_none_or(|a| a == &i.provider_id))
+ .filter(|i| matches(i, &words))
+ .collect();
+ items.sort_by(|a, b| {
+ let (ka, kb) = (KvKind::from_wire(&a.kind), KvKind::from_wire(&b.kind));
+ collate(&a.app_display, &b.app_display)
+ .then_with(|| a.provider_id.cmp(&b.provider_id))
+ .then_with(|| (ka == KvKind::File).cmp(&(kb == KvKind::File)))
+ .then_with(|| collate(&site_of_item(a), &site_of_item(b)))
+ .then_with(|| ka.rank().cmp(&kb.rank()))
+ .then_with(|| collate(&a.key, &b.key))
+ .then_with(|| {
+ collate(
+ &a.domain.clone().unwrap_or_default(),
+ &b.domain.clone().unwrap_or_default(),
+ )
+ })
+ .then_with(|| a.id.cmp(&b.id))
+ });
+ items
+}
+
+/// The ids a group key stands for among the shown items.
+fn group_ids(o: &KeyvaultOverview, state: &VaultState, key: &str) -> Vec<String> {
+ shown(o, state)
+ .into_iter()
+ .filter(|i| {
+ let app = i.provider_id.as_str();
+ let is_file = KvKind::from_wire(&i.kind) == KvKind::File;
+ key == app
+ || (is_file && key == files_key(app))
+ || (!is_file && key == site_key(app, &site_of_item(i)))
+ })
+ .map(|i| i.id.clone())
+ .collect()
+}
+
+/// Advances the list.
+pub fn reduce(o: &KeyvaultOverview, state: &VaultState, action: &VaultAction) -> VaultState {
+ let mut s = state.clone();
+ match action {
+ VaultAction::Query { text } => {
+ s.query = text.clone();
+ // Selecting what a search hides would act on rows the user
+ // cannot see: keep only what is still shown.
+ let visible: Vec<String> = shown(o, &s).iter().map(|i| i.id.clone()).collect();
+ s.selected.retain(|id| visible.contains(id));
+ }
+ VaultAction::Toggle { id } => {
+ if !o.items.iter().any(|i| &i.id == id) {
+ return s;
+ }
+ match s.selected.iter().position(|x| x == id) {
+ Some(n) => {
+ s.selected.remove(n);
+ }
+ None => s.selected.push(id.clone()),
+ }
+ }
+ VaultAction::ToggleGroup { key } => {
+ let ids = group_ids(o, &s, key);
+ if ids.is_empty() {
+ return s;
+ }
+ if ids.iter().all(|id| s.selected.contains(id)) {
+ s.selected.retain(|id| !ids.contains(id));
+ } else {
+ for id in ids {
+ if !s.selected.contains(&id) {
+ s.selected.push(id);
+ }
+ }
+ }
+ }
+ VaultAction::SelectAll => {
+ s.selected = shown(o, &s).iter().map(|i| i.id.clone()).collect();
+ }
+ VaultAction::Clear => s.selected.clear(),
+ VaultAction::ToggleOpen { key } => match s.expanded.iter().position(|k| k == key) {
+ Some(n) => {
+ s.expanded.remove(n);
+ }
+ None => s.expanded.push(key.clone()),
+ },
+ }
+ // Keep the selection in list order, without ids that are gone.
+ let order: Vec<String> = shown(o, &s).iter().map(|i| i.id.clone()).collect();
+ s.selected = order
+ .into_iter()
+ .filter(|id| s.selected.contains(id))
+ .collect();
+ s
+}
+
+/// Drops what the vault no longer holds from the selection (after a delete
+/// or a refresh).
+pub fn prune(o: &KeyvaultOverview, state: &VaultState) -> VaultState {
+ let mut s = state.clone();
+ s.selected.retain(|id| o.items.iter().any(|i| &i.id == id));
+ s
+}
+
+fn newest(items: &[&KvItem]) -> u64 {
+ items.iter().map(|i| i.updated_ms).max().unwrap_or(0)
+}
+
+/// The list as drawn.
+pub fn view(o: &KeyvaultOverview, state: &VaultState, now: i64) -> VaultView {
+ let items = shown(o, state);
+ let searching = !state.query.trim().is_empty();
+ let names_hidden = !o.items.is_empty() && !o.names_visible;
+ let open = |key: &str| searching || state.expanded.iter().any(|k| k == key);
+ let sel = |i: &KvItem| state.selected.contains(&i.id);
+
+ // app key -> (name, items)
+ let mut by_app: BTreeMap<String, (String, Vec<&KvItem>)> = BTreeMap::new();
+ let mut order: Vec<String> = Vec::new();
+ for i in &items {
+ if !by_app.contains_key(&i.provider_id) {
+ order.push(i.provider_id.clone());
+ }
+ by_app
+ .entry(i.provider_id.clone())
+ .or_insert_with(|| (i.app_display.clone(), Vec::new()))
+ .1
+ .push(i);
+ }
+ let mut apps = Vec::new();
+ for key in order {
+ let (name, group) = by_app.remove(&key).expect("keyed above");
+ let (files, rest): (Vec<&KvItem>, Vec<&KvItem>) = group
+ .iter()
+ .copied()
+ .partition(|i| KvKind::from_wire(&i.kind) == KvKind::File);
+ let mut sites: Vec<VaultSite> = Vec::new();
+ let mut cur: Option<(String, Vec<&KvItem>)> = None;
+ let flush = |cur: &mut Option<(String, Vec<&KvItem>)>, sites: &mut Vec<VaultSite>| {
+ if let Some((site, its)) = cur.take() {
+ let k = site_key(&key, &site);
+ let mut kinds: Vec<(KvKind, u32)> = Vec::new();
+ for i in &its {
+ let kk = KvKind::from_wire(&i.kind);
+ match kinds.iter_mut().find(|(x, _)| *x == kk) {
+ Some((_, n)) => *n += 1,
+ None => kinds.push((kk, 1)),
+ }
+ }
+ kinds.sort_by_key(|(k, _)| k.rank());
+ let is_open = open(&k);
+ let (unlock_ids, lock_ids) = lock_targets(&its);
+ sites.push(VaultSite {
+ selected: tri(its.iter().filter(|i| sel(i)).count(), its.len()),
+ lock: lock_of(&its),
+ unlock_ids,
+ lock_ids,
+ count: its.len() as u32,
+ counts: kinds
+ .iter()
+ .map(|(kk, n)| kk.plural(*n))
+ .collect::<Vec<_>>()
+ .join(", "),
+ updated: ago(now - newest(&its) as i64),
+ open: is_open,
+ rows: if is_open {
+ its.iter().map(|i| row(i, sel(i), now)).collect()
+ } else {
+ vec![]
+ },
+ site: if site.is_empty() {
+ "Unnamed".into()
+ } else {
+ site
+ },
+ key: k,
+ });
+ }
+ };
+ for i in rest {
+ let site = site_of_item(i);
+ match cur.as_mut() {
+ Some((s, its)) if *s == site => its.push(i),
+ _ => {
+ flush(&mut cur, &mut sites);
+ cur = Some((site, vec![i]));
+ }
+ }
+ }
+ flush(&mut cur, &mut sites);
+ let files_group = (!files.is_empty()).then(|| {
+ let k = files_key(&key);
+ let is_open = open(&k);
+ let (unlock_ids, lock_ids) = lock_targets(&files);
+ VaultFiles {
+ count: files.len() as u32,
+ selected: tri(files.iter().filter(|i| sel(i)).count(), files.len()),
+ lock: lock_of(&files),
+ unlock_ids,
+ lock_ids,
+ open: is_open,
+ rows: if is_open {
+ files.iter().map(|i| row(i, sel(i), now)).collect()
+ } else {
+ vec![]
+ },
+ key: k,
+ }
+ });
+ let unlocked = group.iter().filter(|i| i.policy.unattended).count();
+ let n = group.len();
+ let (unlock_ids, lock_ids) = lock_targets(&group);
+ apps.push(VaultApp {
+ unlock_ids,
+ lock_ids,
+ provider_id: key.clone(),
+ name,
+ count: n as u32,
+ summary: if unlocked == 0 {
+ format!("{n} item{}", if n == 1 { "" } else { "s" })
+ } else {
+ format!(
+ "{n} item{}, {unlocked} unlocked",
+ if n == 1 { "" } else { "s" }
+ )
+ },
+ updated: ago(now - newest(&group) as i64),
+ selected: tri(group.iter().filter(|i| sel(i)).count(), n),
+ lock: lock_of(&group),
+ open: open(&key),
+ sites,
+ files: files_group,
+ key,
+ });
+ }
+
+ let selected: Vec<&KvItem> = items.iter().copied().filter(|i| sel(i)).collect();
+ let unlock_ids: Vec<String> = selected
+ .iter()
+ .filter(|i| !i.policy.unattended && !i.identity_provider)
+ .map(|i| i.id.clone())
+ .collect();
+ let lock_ids: Vec<String> = selected
+ .iter()
+ .filter(|i| i.policy.unattended)
+ .map(|i| i.id.clone())
+ .collect();
+ let selection = VaultSelection {
+ count: selected.len() as u32,
+ ids: selected.iter().map(|i| i.id.clone()).collect(),
+ title: format!("{} selected", selected.len()),
+ can_unlock: !unlock_ids.is_empty(),
+ can_lock: !lock_ids.is_empty(),
+ always_ask: selected
+ .iter()
+ .filter(|i| i.identity_provider && !i.policy.unattended)
+ .count() as u32,
+ unlock_ids,
+ lock_ids,
+ };
+ let empty_text = if !apps.is_empty() {
+ None
+ } else if o.items.is_empty() {
+ Some(
+ "Nothing saved yet. Teleport an app with Save to Keyvault, or import passwords.".into(),
+ )
+ } else {
+ Some("No matches".into())
+ };
+ VaultView {
+ shown: items.len() as u32,
+ total: o.items.len() as u32,
+ can_select_all: !items.is_empty(),
+ apps,
+ empty_text,
+ names_hidden,
+ hidden_note: names_hidden
+ .then(|| "Names are hidden. Confirm with Touch ID to see what is saved.".into()),
+ show_names_label: "Show Items".into(),
+ search_prompt: SEARCH_PROMPT.into(),
+ selection,
+ }
+}
+
+/// The broker request that locks `ids`.
+pub fn lock_command(ids: &[String]) -> KvCommand {
+ KvCommand::SetLocked {
+ item_ids: ids.to_vec(),
+ locked: true,
+ }
+}
+
+/// The broker request that unlocks `ids` (the daemon asks for Touch ID once
+/// for the batch).
+pub fn unlock_command(ids: &[String]) -> KvCommand {
+ KvCommand::SetLocked {
+ item_ids: ids.to_vec(),
+ locked: false,
+ }
+}
+
+/// The broker request that deletes `ids` and wipes their copies in Spaces.
+pub fn delete_command(ids: &[String]) -> KvCommand {
+ KvCommand::DeleteItems {
+ item_ids: ids.to_vec(),
+ }
+}
+
+/// What the Keyvault holds for one app that a teleport can send (passwords
+/// never are): how many, when the newest was saved, and their ids.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct KvVaultSource {
+ /// Items that can be sent.
+ pub count: u32,
+ /// When the newest was saved, Unix ms (0: none).
+ pub newest_ms: i64,
+ /// Their ids, in list order.
+ pub ids: Vec<String>,
+ /// The app's saved passwords (ids), never part of `ids`: they are sent
+ /// only when ticked in the review.
+ #[serde(default)]
+ pub password_ids: Vec<String>,
+}
+
+/// The saved items of `provider_id` a teleport can send.
+pub fn vault_source(o: &KeyvaultOverview, provider_id: &str) -> KvVaultSource {
+ let state = VaultState {
+ app: Some(provider_id.into()),
+ ..Default::default()
+ };
+ let all = shown(o, &state);
+ let password_ids: Vec<String> = all
+ .iter()
+ .filter(|i| KvKind::from_wire(&i.kind) == KvKind::Password)
+ .map(|i| i.id.clone())
+ .collect();
+ let items: Vec<&KvItem> = all
+ .into_iter()
+ .filter(|i| KvKind::from_wire(&i.kind) != KvKind::Password)
+ .collect();
+ KvVaultSource {
+ password_ids,
+ count: items.len() as u32,
+ newest_ms: items.iter().map(|i| i.updated_ms as i64).max().unwrap_or(0),
+ ids: items.iter().map(|i| i.id.clone()).collect(),
+ }
+}
+
+/// The unlock prompt: what the user is agreeing to before the daemon asks
+/// for Touch ID.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UnlockPrompt {
+ /// "Allow unattended access?"
+ pub title: String,
+ /// What it allows.
+ pub message: String,
+ /// "3 items" (a batch), or the one item's name.
+ pub subject: String,
+ /// "Deny".
+ pub deny: String,
+ /// "Allow".
+ pub allow: String,
+ /// "Never ask again".
+ pub never_ask: String,
+}
+
+/// The unlock prompt for `count` items (`name` is the one item's name, for
+/// a single item). `None` when the user chose "Never ask again": unlocking
+/// then goes straight to the Touch ID check the broker asks for.
+pub fn unlock_prompt(o: &KeyvaultOverview, count: u32, name: Option<&str>) -> Option<UnlockPrompt> {
+ if o.status.as_ref().and_then(|s| s.skip_unlock_prompt) == Some(true) {
+ return None;
+ }
+ Some(unlock_prompt_always(count, name))
+}
+
+/// The prompt itself, whatever the setting says.
+pub fn unlock_prompt_always(count: u32, name: Option<&str>) -> UnlockPrompt {
+ let one = count == 1;
+ UnlockPrompt {
+ title: "Allow unattended access?".into(),
+ message: format!(
+ "This will allow any agent with access to the Cua Spaces MCP to write {} into your connected Spaces. The secrets are not sent directly to any agents.",
+ if one { "this key" } else { "these keys" }
+ ),
+ subject: match (one, name) {
+ (true, Some(n)) if !n.is_empty() => n.to_string(),
+ _ => format!("{count} items"),
+ },
+ deny: "Deny".into(),
+ allow: "Allow".into(),
+ never_ask: "Never ask again".into(),
+ }
+}
+
+/// The delete confirmation.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct KvDeleteConfirm {
+ /// "Delete 3 items?"
+ pub title: String,
+ /// What deleting does.
+ pub message: String,
+ /// "Delete".
+ pub confirm: String,
+ /// "Cancel".
+ pub cancel: String,
+}
+
+/// The delete confirmation for `count` items, saying when live copies in
+/// Spaces will be wiped too (`live_copies`: Spaces holding any of them).
+pub fn delete_confirm(count: u32, live_copies: u32) -> KvDeleteConfirm {
+ let one = count == 1;
+ let mut message = format!(
+ "{} removed from the Keyvault and cannot be recovered.",
+ if one { "It is" } else { "They are" }
+ );
+ if live_copies > 0 {
+ message.push_str(&format!(
+ " Copies delivered to {} will be wiped as well.",
+ if live_copies == 1 {
+ "a Space".to_string()
+ } else {
+ format!("{live_copies} Spaces")
+ }
+ ));
+ }
+ KvDeleteConfirm {
+ title: if one {
+ "Delete this item?".into()
+ } else {
+ format!("Delete {count} items?")
+ },
+ message,
+ confirm: "Delete".into(),
+ cancel: "Cancel".into(),
+ }
+}
+
+/// How many Spaces hold a live copy of any of `ids` (for
+/// [`delete_confirm`]).
+pub fn live_copy_spaces(o: &KeyvaultOverview, ids: &[String], now: i64) -> u32 {
+ let mut targets: Vec<&str> = o
+ .deliveries
+ .iter()
+ .filter(|d| super::view::live_delivery(d, now) && d.items.iter().any(|i| ids.contains(i)))
+ .map(|d| d.target.as_str())
+ .collect();
+ targets.sort_unstable();
+ targets.dedup();
+ targets.len() as u32
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::keyvault::wire::{KvDelivery, KvItemPolicy, KvStatus};
+
+ const NOW: i64 = 1_800_000_000_000;
+
+ fn item(id: &str, app: (&str, &str), kind: &str, domain: Option<&str>, key: &str) -> KvItem {
+ KvItem {
+ id: id.into(),
+ kind: kind.into(),
+ provider_id: app.0.into(),
+ app_display: app.1.into(),
+ domain: domain.map(str::to_string),
+ key: key.into(),
+ path: None,
+ source: "Default".into(),
+ session: false,
+ expires_ms: None,
+ bytes: 10,
+ blob: None,
+ identity_provider: false,
+ policy: KvItemPolicy {
+ allowed_targets: vec![],
+ ttl_secs: 3600,
+ unattended: false,
+ },
+ created_ms: (NOW - 3_600_000) as u64,
+ updated_ms: (NOW - 120_000) as u64,
+ rev: 1,
+ record_digest: "00".into(),
+ }
+ }
+
+ const CHROME: (&str, &str) = ("chrome", "Google Chrome");
+ const SLACK: (&str, &str) = ("slack", "Slack");
+
+ fn vault() -> KeyvaultOverview {
+ let mut items = vec![
+ item("c1", CHROME, "cookie", Some(".github.com"), "user_session"),
+ item("c2", CHROME, "cookie", Some(".github.com"), "logged_in"),
+ item("c3", CHROME, "cookie", Some("api.github.com"), "_gh_sess"),
+ item("p1", CHROME, "password", Some("https://github.com"), "octo"),
+ item("c4", CHROME, "cookie", Some(".notion.so"), "token_v2"),
+ item(
+ "l1",
+ CHROME,
+ "local_storage",
+ Some("https://notion.so"),
+ "theme",
+ ),
+ item("f1", CHROME, "file", None, "Default/Bookmarks"),
+ item("f2", CHROME, "file", None, "Local State"),
+ item("s1", SLACK, "file", None, "storage/root-state.json"),
+ item("s2", SLACK, "cookie", Some(".slack.com"), "d"),
+ ];
+ items[0].policy.unattended = true;
+ let mut google = item("g1", CHROME, "cookie", Some(".google.com"), "SID");
+ google.identity_provider = true;
+ items.push(google);
+ KeyvaultOverview {
+ availability: "ready".into(),
+ names_visible: true,
+ items_total: items.len() as u32,
+ items,
+ ..Default::default()
+ }
+ }
+
+ fn st() -> VaultState {
+ VaultState::default()
+ }
+
+ fn ids(v: &VaultView) -> Vec<String> {
+ v.selection.ids.clone()
+ }
+
+ #[test]
+ fn items_group_by_app_then_site_with_files_apart() {
+ let v = view(&vault(), &st(), NOW);
+ assert_eq!(
+ v.apps.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(),
+ ["Google Chrome", "Slack"]
+ );
+ let chrome = &v.apps[0];
+ assert_eq!(chrome.count, 9);
+ assert_eq!(
+ chrome
+ .sites
+ .iter()
+ .map(|s| s.site.as_str())
+ .collect::<Vec<_>>(),
+ ["github.com", "google.com", "notion.so"],
+ "api.github.com and .github.com are one site"
+ );
+ assert_eq!(chrome.sites[0].count, 4);
+ assert_eq!(chrome.sites[0].counts, "1 password, 3 cookies");
+ assert_eq!(chrome.sites[2].counts, "1 cookie, 1 storage value");
+ assert_eq!(chrome.files.as_ref().unwrap().count, 2);
+ assert_eq!(chrome.summary, "9 items, 1 unlocked");
+ assert_eq!(v.apps[1].summary, "2 items");
+ assert!(v.empty_text.is_none());
+ assert_eq!((v.shown, v.total), (11, 11));
+ // Grey times, and no value anywhere.
+ assert_eq!(chrome.updated, "2 min ago");
+ let json = serde_json::to_string(&v).unwrap();
+ assert!(!json.contains("record_digest"));
+ }
+
+ #[test]
+ fn groups_open_on_demand_and_while_searching() {
+ let mut s = st();
+ let v = view(&vault(), &s, NOW);
+ assert!(v.apps[0].sites[0].rows.is_empty(), "closed: no rows");
+ assert!(!v.apps[0].sites[0].open);
+ s = reduce(
+ &vault(),
+ &s,
+ &VaultAction::ToggleOpen {
+ key: "chrome|github.com".into(),
+ },
+ );
+ let v = view(&vault(), &s, NOW);
+ let rows = &v.apps[0].sites[0].rows;
+ assert_eq!(
+ rows.iter().map(|r| r.title.as_str()).collect::<Vec<_>>(),
+ ["octo", "_gh_sess", "logged_in", "user_session"],
+ "a password first, then cookies by name"
+ );
+ assert_eq!(rows[0].symbol, "key.fill");
+ assert_eq!(rows[1].subtitle, "api.github.com");
+ assert_eq!(rows[3].subtitle, ".github.com");
+ assert!(rows[3].lock_symbol == "lock.open" && rows[0].lock_symbol == "lock.fill");
+ s = reduce(
+ &vault(),
+ &s,
+ &VaultAction::ToggleOpen {
+ key: "chrome|github.com".into(),
+ },
+ );
+ assert!(!view(&vault(), &s, NOW).apps[0].sites[0].open);
+ // Searching opens what matches.
+ s = reduce(
+ &vault(),
+ &s,
+ &VaultAction::Query {
+ text: "user_session".into(),
+ },
+ );
+ let v = view(&vault(), &s, NOW);
+ assert!(v.apps[0].sites[0].open);
+ assert_eq!(v.apps[0].sites[0].rows.len(), 1);
+ }
+
+ #[test]
+ fn search_matches_domain_key_app_and_type() {
+ let o = vault();
+ let q = |text: &str| {
+ let s = reduce(&o, &st(), &VaultAction::Query { text: text.into() });
+ view(&o, &s, NOW)
+ };
+ assert_eq!(q("notion").shown, 2, "by domain");
+ assert_eq!(q("token_v2").shown, 1, "by key");
+ assert_eq!(q("slack").shown, 2, "by app");
+ assert_eq!(q("google chrome").shown, 9, "by app name");
+ assert_eq!(q("password").shown, 1, "by type");
+ assert_eq!(q("local storage").shown, 1, "by type, two words");
+ assert_eq!(q("cookie github").shown, 3, "type and domain together");
+ assert_eq!(q("bookmarks").shown, 1, "a file by path");
+ assert_eq!(q("unlocked").shown, 1, "by lock");
+ let none = q("nothing-like-this");
+ assert_eq!(none.shown, 0);
+ assert_eq!(none.empty_text.as_deref(), Some("No matches"));
+ assert!(none.apps.is_empty());
+ assert_eq!(q(" ").shown, 11, "blank shows everything");
+ }
+
+ #[test]
+ fn selecting_items_a_site_or_an_app_and_the_batch_bar() {
+ let o = vault();
+ let mut s = st();
+ s = reduce(&o, &s, &VaultAction::Toggle { id: "c2".into() });
+ s = reduce(&o, &s, &VaultAction::Toggle { id: "p1".into() });
+ let v = view(&o, &s, NOW);
+ assert_eq!(v.selection.count, 2);
+ assert_eq!(v.selection.title, "2 selected");
+ assert_eq!(v.apps[0].sites[0].selected, Tri::Mixed);
+ assert_eq!(v.apps[0].selected, Tri::Mixed);
+ // A whole site: every item of it (mixed selects the rest).
+ s = reduce(
+ &o,
+ &s,
+ &VaultAction::ToggleGroup {
+ key: "chrome|github.com".into(),
+ },
+ );
+ let v = view(&o, &s, NOW);
+ assert_eq!(v.apps[0].sites[0].selected, Tri::On);
+ assert_eq!(ids(&v).len(), 4);
+ // And again: none of it.
+ s = reduce(
+ &o,
+ &s,
+ &VaultAction::ToggleGroup {
+ key: "chrome|github.com".into(),
+ },
+ );
+ assert_eq!(view(&o, &s, NOW).selection.count, 0);
+ // A whole app, files included.
+ s = reduce(
+ &o,
+ &s,
+ &VaultAction::ToggleGroup {
+ key: "chrome".into(),
+ },
+ );
+ let v = view(&o, &s, NOW);
+ assert_eq!(v.selection.count, 9);
+ assert_eq!(v.apps[0].selected, Tri::On);
+ assert_eq!(v.apps[1].selected, Tri::Off);
+ // Only the files of an app.
+ s = reduce(
+ &o,
+ &st(),
+ &VaultAction::ToggleGroup {
+ key: "chrome|\u{1}files".into(),
+ },
+ );
+ assert_eq!(ids(&view(&o, &s, NOW)), ["f1", "f2"]);
+ // Select all, clear, and unknown ids are ignored.
+ s = reduce(&o, &s, &VaultAction::SelectAll);
+ assert_eq!(view(&o, &s, NOW).selection.count, 11);
+ s = reduce(&o, &s, &VaultAction::Toggle { id: "ghost".into() });
+ assert_eq!(view(&o, &s, NOW).selection.count, 11);
+ s = reduce(&o, &s, &VaultAction::Clear);
+ assert_eq!(view(&o, &s, NOW).selection.count, 0);
+ }
+
+ #[test]
+ fn a_search_never_leaves_hidden_rows_selected_and_groups_select_only_what_is_shown() {
+ let o = vault();
+ let mut s = reduce(&o, &st(), &VaultAction::SelectAll);
+ s = reduce(
+ &o,
+ &s,
+ &VaultAction::Query {
+ text: "notion".into(),
+ },
+ );
+ assert_eq!(
+ ids(&view(&o, &s, NOW)),
+ ["c4", "l1"],
+ "what the search hides is deselected"
+ );
+ // With a search on, selecting a whole app selects only its matches.
+ s = reduce(
+ &o,
+ &st(),
+ &VaultAction::Query {
+ text: "cookie".into(),
+ },
+ );
+ s = reduce(
+ &o,
+ &s,
+ &VaultAction::ToggleGroup {
+ key: "chrome".into(),
+ },
+ );
+ let v = view(&o, &s, NOW);
+ assert!(
+ v.selection
+ .ids
+ .iter()
+ .all(|id| id.starts_with('c') || id.starts_with('g'))
+ );
+ assert!(!v.selection.ids.contains(&"p1".to_string()));
+ }
+
+ #[test]
+ fn lock_state_and_what_the_batch_can_do() {
+ let o = vault();
+ let v = view(&o, &st(), NOW);
+ assert_eq!(
+ v.apps[0].sites[0].lock,
+ KvLock::Mixed,
+ "github has one unlocked cookie"
+ );
+ assert_eq!(v.apps[0].sites[1].lock, KvLock::Locked);
+ assert_eq!(v.apps[1].lock, KvLock::Locked);
+ // A click on a group's lock acts on its eligible items.
+ assert_eq!(v.apps[0].sites[0].unlock_ids.len(), 3, "github: 3 locked");
+ assert_eq!(v.apps[0].sites[0].lock_ids, ["c1"]);
+ assert!(
+ v.apps[0].sites[1].unlock_ids.is_empty(),
+ "an identity provider never unlocks"
+ );
+ assert_eq!(v.apps[0].lock_ids, ["c1"]);
+ assert_eq!(KvLock::Locked.symbol(), "lock.fill");
+ assert_eq!(KvLock::Unlocked.symbol(), "lock.open");
+ // Everything selected: c1 is unlocked, the identity provider always
+ // asks, the rest can be unlocked.
+ let s = reduce(&o, &st(), &VaultAction::SelectAll);
+ let sel = view(&o, &s, NOW).selection;
+ assert!(sel.can_lock && sel.can_unlock);
+ assert_eq!(sel.lock_ids, ["c1"]);
+ assert_eq!(sel.unlock_ids.len(), 9);
+ assert!(!sel.unlock_ids.contains(&"g1".to_string()));
+ assert_eq!(sel.always_ask, 1);
+ assert_eq!(
+ unlock_command(&sel.unlock_ids),
+ KvCommand::SetLocked {
+ item_ids: sel.unlock_ids.clone(),
+ locked: false
+ }
+ );
+ assert_eq!(
+ lock_command(&sel.lock_ids),
+ KvCommand::SetLocked {
+ item_ids: vec!["c1".into()],
+ locked: true
+ }
+ );
+ // Only the identity provider: nothing to unlock.
+ let s = reduce(&o, &st(), &VaultAction::Toggle { id: "g1".into() });
+ let sel = view(&o, &s, NOW).selection;
+ assert!(!sel.can_unlock && !sel.can_lock);
+ // Rows say why.
+ let mut open = st();
+ open.expanded = vec!["chrome|google.com".into()];
+ let r = &view(&o, &open, NOW).apps[0].sites[1].rows[0];
+ assert!(r.identity_provider);
+ assert_eq!(r.lock_help, "Identity providers always ask");
+ }
+
+ #[test]
+ fn the_unlock_prompt_says_what_it_allows_and_is_skipped_only_by_the_setting() {
+ let mut o = vault();
+ let p = unlock_prompt(&o, 1, Some("user_session")).unwrap();
+ assert_eq!(p.title, "Allow unattended access?");
+ assert_eq!(
+ p.message,
+ "This will allow any agent with access to the Cua Spaces MCP to write this key into your connected Spaces. The secrets are not sent directly to any agents."
+ );
+ assert_eq!(p.subject, "user_session");
+ assert_eq!(
+ (p.deny.as_str(), p.allow.as_str(), p.never_ask.as_str()),
+ ("Deny", "Allow", "Never ask again")
+ );
+ let batch = unlock_prompt(&o, 3, None).unwrap();
+ assert!(
+ batch
+ .message
+ .contains("write these keys into your connected Spaces")
+ );
+ assert_eq!(batch.subject, "3 items");
+ for text in [&p.title, &p.message, &p.subject, &batch.message] {
+ assert!(
+ !text.contains('\u{2014}') && !text.contains('\u{2013}'),
+ "no dashes: {text}"
+ );
+ }
+ // "Never ask again" skips the prompt, never the Touch ID check.
+ o.status = Some(KvStatus {
+ version: "0".into(),
+ initialized: true,
+ unlocked: true,
+ disabled: false,
+ caller_first_party: true,
+ caller_display: "Cua".into(),
+ items: 11,
+ pending: 0,
+ unlock_policy: None,
+ auto_wipe: None,
+ os_protector_available: true,
+ passphrase_available: true,
+ unlock_protectors: vec![],
+ browse_until_ms: None,
+ skip_unlock_prompt: Some(true),
+ reset_notice: None,
+ });
+ assert!(unlock_prompt(&o, 1, None).is_none());
+ assert!(unlock_prompt_always(1, None).message.contains("this key"));
+ }
+
+ #[test]
+ fn deleting_names_the_copies_it_will_wipe() {
+ let one = delete_confirm(1, 0);
+ assert_eq!(one.title, "Delete this item?");
+ assert!(one.message.starts_with("It is removed"));
+ let many = delete_confirm(4, 2);
+ assert_eq!(many.title, "Delete 4 items?");
+ assert!(
+ many.message
+ .contains("Copies delivered to 2 Spaces will be wiped")
+ );
+ assert!(delete_confirm(2, 1).message.contains("a Space"));
+ let mut o = vault();
+ o.deliveries = vec![
+ KvDelivery {
+ import_id: "i1".into(),
+ target: "dev-1".into(),
+ provider_id: "chrome".into(),
+ items: vec!["c1".into()],
+ caller_fp: "x".into(),
+ delivered_ms: 1,
+ expires_ms: 0,
+ wiped: false,
+ },
+ KvDelivery {
+ import_id: "i2".into(),
+ target: "dev-1".into(),
+ provider_id: "chrome".into(),
+ items: vec!["c2".into()],
+ caller_fp: "x".into(),
+ delivered_ms: 1,
+ expires_ms: 0,
+ wiped: false,
+ },
+ KvDelivery {
+ import_id: "i3".into(),
+ target: "dev-2".into(),
+ provider_id: "chrome".into(),
+ items: vec!["c3".into()],
+ caller_fp: "x".into(),
+ delivered_ms: 1,
+ expires_ms: 0,
+ wiped: true,
+ },
+ ];
+ assert_eq!(
+ live_copy_spaces(&o, &["c1".into(), "c2".into(), "c3".into()], NOW),
+ 1
+ );
+ assert_eq!(live_copy_spaces(&o, &["c4".into()], NOW), 0);
+ assert_eq!(
+ delete_command(&["c1".into()]),
+ KvCommand::DeleteItems {
+ item_ids: vec!["c1".into()]
+ }
+ );
+ }
+
+ #[test]
+ fn hidden_names_group_by_app_and_offer_to_show_them() {
+ let mut o = vault();
+ o.names_visible = false;
+ for i in &mut o.items {
+ i.domain = None;
+ i.key = String::new();
+ i.path = None;
+ }
+ let v = view(&o, &st(), NOW);
+ assert!(v.names_hidden);
+ assert_eq!(v.show_names_label, "Show Items");
+ assert!(v.hidden_note.as_deref().unwrap().contains("Touch ID"));
+ assert_eq!(v.apps[0].count, 9, "counts survive");
+ // Rows still render (type only), and nothing names a site.
+ assert!(v.apps[0].sites.iter().all(|s| s.site == "Unnamed"));
+ let empty = view(&KeyvaultOverview::default(), &st(), NOW);
+ assert!(!empty.names_hidden);
+ assert!(
+ empty
+ .empty_text
+ .as_deref()
+ .unwrap()
+ .starts_with("Nothing saved yet")
+ );
+ }
+
+ #[test]
+ fn the_vault_source_of_an_app_leaves_out_passwords() {
+ let o = vault();
+ let src = vault_source(&o, "chrome");
+ assert_eq!(
+ src.count, 8,
+ "nine Chrome items less the password... and the IdP cookie stays"
+ );
+ assert!(!src.ids.contains(&"p1".to_string()));
+ assert_eq!(src.newest_ms, (NOW - 120_000));
+ assert_eq!(vault_source(&o, "slack").count, 2);
+ assert_eq!(vault_source(&o, "arc"), KvVaultSource::default());
+ }
+
+ #[test]
+ fn site_grouping_covers_hosts_origins_and_cookie_domains() {
+ assert_eq!(site_of(".github.com"), "github.com");
+ assert_eq!(site_of("https://gist.github.com:8443/x"), "github.com");
+ assert_eq!(site_of("www.bbc.co.uk"), "bbc.co.uk");
+ assert_eq!(site_of("localhost"), "localhost");
+ assert_eq!(site_of("http://127.0.0.1:8000"), "127.0.0.1");
+ }
+
+ #[test]
+ fn the_selection_survives_a_refresh_only_for_items_that_still_exist() {
+ let o = vault();
+ let s = reduce(&o, &st(), &VaultAction::SelectAll);
+ let mut after = o.clone();
+ after.items.retain(|i| i.id != "c1");
+ assert_eq!(prune(&after, &s).selected.len(), 10);
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/view.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/view.rs
index dad3ebde22..8971139841 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/view.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/view.rs
@@ -7,7 +7,6 @@
//! access, and the page's unavailable and protection states.
use super::wire::*;
-use crate::util::collate;
use serde::{Deserialize, Serialize};
/// A live grant: not revoked, not expired, uses left.
@@ -218,47 +217,6 @@ pub fn signing_badge(c: &KvCaller) -> SigningBadge {
}
}
-/// What a consent chip says.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "lowercase")]
-pub enum ConsentChipKind {
- /// A request waits.
- Pending,
- /// A copy is in a Space.
- Delivered,
- /// A live grant.
- Granted,
- /// An unattended rule.
- Rule,
- /// Nothing: asks every time.
- Asks,
-}
-
-/// One consent state of an item.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct ConsentChip {
- /// Kind.
- pub kind: ConsentChipKind,
- /// Text.
- pub text: String,
-}
-
-/// One account of a site.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ItemRow {
- /// The item.
- pub item: KvItem,
- /// "[email protected]", "Whole app session", or the profile.
- pub account: String,
- /// Strongest first; `asks` when nothing else applies.
- pub consent: Vec<ConsentChip>,
- /// The unattended switch can be changed (not an identity provider).
- pub toggle_enabled: bool,
- /// The switch's tooltip.
- pub toggle_help: String,
-}
-
/// Mixed on/off.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -271,90 +229,6 @@ pub enum Tri {
Mixed,
}
-/// A site (browsers) or app (whole-app sessions) with its accounts.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct SiteGroup {
- /// Stable key.
- pub key: String,
- /// "github.com" or "Slack".
- pub title: String,
- /// "Chrome", "Slack".
- pub app: String,
- /// Accounts.
- pub rows: Vec<ItemRow>,
- /// Unattended across rows.
- pub unattended: Tri,
- /// Every row is an identity provider.
- pub locked: bool,
-}
-
-const IDP_HELP: &str = "Identity providers always ask";
-const UNATTENDED_HELP: &str = "Unattended rules may use it; turning on asks for Touch ID";
-
-fn consent_for(item: &KvItem, o: &KeyvaultOverview, now: i64) -> Vec<ConsentChip> {
- let mut chips = Vec::new();
- for p in o
- .pending
- .iter()
- .filter(|p| p.items.iter().any(|i| i.id == item.id))
- {
- chips.push(ConsentChip {
- kind: ConsentChipKind::Pending,
- text: format!("Waiting: {}", short_caller(&p.caller_display)),
- });
- }
- for d in o
- .deliveries
- .iter()
- .filter(|d| live_delivery(d, now) && d.items.contains(&item.id))
- {
- chips.push(ConsentChip {
- kind: ConsentChipKind::Delivered,
- text: format!("In {}, {}", d.target, delivery_lifetime(d.expires_ms, now)),
- });
- }
- for g in o
- .grants
- .iter()
- .filter(|g| live_grant(g, now) && g.items.contains(&item.id))
- {
- chips.push(ConsentChip {
- kind: ConsentChipKind::Granted,
- text: format!(
- "{} \u{2192} {}, {}",
- short_caller(&g.caller_display),
- g.targets.join(", "),
- duration(g.not_after_ms as i64 - now)
- ),
- });
- }
- for r in o
- .rules
- .iter()
- .filter(|r| live_rule(r, now) && r.items.contains(&item.id))
- {
- chips.push(ConsentChip {
- kind: ConsentChipKind::Rule,
- text: format!(
- "Rule: {} \u{2192} {}",
- r.callers
- .iter()
- .map(|c| short_caller(&c.display))
- .collect::<Vec<_>>()
- .join(", "),
- rule_targets(r)
- ),
- });
- }
- if chips.is_empty() {
- chips.push(ConsentChip {
- kind: ConsentChipKind::Asks,
- text: "Asks every time".into(),
- });
- }
- chips
-}
-
fn rule_targets(r: &KvRule) -> String {
if r.targets.iter().any(|t| t == "*") {
"any Space".into()
@@ -363,101 +237,8 @@ fn rule_targets(r: &KvRule) -> String {
}
}
-/// The account line of an item.
-pub fn account_of(item: &KvItem) -> String {
- if let Some(a) = item.account.as_deref().filter(|a| !a.is_empty()) {
- return a.to_string();
- }
- match item.kind.as_str() {
- "app_session" => "Whole app session".into(),
- "site_passwords" => "Saved passwords".into(),
- _ if !item.source.is_empty() => format!("{} profile", item.source),
- _ => "Default profile".into(),
- }
-}
-
-/// Items grouped per site (browsers) or per app, filtered by `query`.
-pub fn group_items(o: &KeyvaultOverview, now: i64, query: &str) -> Vec<SiteGroup> {
- let needle = query.trim().to_lowercase();
- let mut groups: Vec<SiteGroup> = Vec::new();
- for item in &o.items {
- if !needle.is_empty()
- && ![
- item.label.as_str(),
- item.site.as_deref().unwrap_or(""),
- item.account.as_deref().unwrap_or(""),
- item.app_display.as_str(),
- ]
- .iter()
- .any(|f| f.to_lowercase().contains(&needle))
- {
- continue;
- }
- let key = format!(
- "{}:{}",
- item.provider_id,
- item.site.as_deref().unwrap_or("*")
- );
- let row = ItemRow {
- account: account_of(item),
- consent: consent_for(item, o, now),
- toggle_enabled: !item.identity_provider,
- toggle_help: if item.identity_provider {
- IDP_HELP
- } else {
- UNATTENDED_HELP
- }
- .into(),
- item: item.clone(),
- };
- match groups.iter_mut().find(|g| g.key == key) {
- Some(g) => g.rows.push(row),
- None => groups.push(SiteGroup {
- title: item
- .site
- .clone()
- .unwrap_or_else(|| item.app_display.clone()),
- app: item.app_display.clone(),
- key,
- rows: vec![row],
- unattended: Tri::Off,
- locked: false,
- }),
- }
- }
- for g in &mut groups {
- g.rows.sort_by(|a, b| collate(&a.account, &b.account));
- let on = g.rows.iter().filter(|r| r.item.policy.unattended).count();
- g.unattended = if on == 0 {
- Tri::Off
- } else if on == g.rows.len() {
- Tri::On
- } else {
- Tri::Mixed
- };
- g.locked = g.rows.iter().all(|r| r.item.identity_provider);
- }
- groups.sort_by(|a, b| collate(&a.title, &b.title).then_with(|| collate(&a.app, &b.app)));
- groups
-}
-
-/// The site-level switch: on widens only the eligible accounts; off
-/// narrows every account.
-pub fn site_toggle(group: &SiteGroup, on: bool) -> KvCommand {
- let item_ids = group
- .rows
- .iter()
- .filter(|r| !on || !r.item.identity_provider)
- .map(|r| r.item.id.clone())
- .collect();
- KvCommand::SetUnattended {
- item_ids,
- unattended: on,
- }
-}
-
/// The audit kinds the Recent list shows, with their verbs.
-pub const DECISION_KINDS: [(&str, &str); 13] = [
+pub const DECISION_KINDS: [(&str, &str); 16] = [
("consent.request", "Asked"),
("consent.allow", "Approved"),
("consent.deny", "Denied"),
@@ -468,6 +249,9 @@ pub const DECISION_KINDS: [(&str, &str); 13] = [
("rule.add", "Rule added"),
("rule.remove", "Rule removed"),
("item.policy", "Policy changed"),
+ ("item.unlock", "Unlocked"),
+ ("item.lock", "Locked"),
+ ("item.delete", "Deleted"),
("vault.disable", "Keyvault turned off"),
("vault.enable", "Keyvault turned on"),
("caller.reject", "Caller refused"),
@@ -504,8 +288,12 @@ pub fn recent_decisions(o: &KeyvaultOverview, limit: usize) -> Vec<Decision> {
o.items
.iter()
.find(|i| i.id == id)
- .map(|i| i.label.clone())
- .unwrap_or_else(|| id.to_string())
+ .filter(|i| !i.key.is_empty())
+ .map(|i| match &i.domain {
+ Some(d) => format!("{} / {}", super::vault::site_of(d), i.key),
+ None => i.key.clone(),
+ })
+ .unwrap_or_else(|| "an item".to_string())
};
let mut entries: Vec<&KvAuditEntry> = o
.audit
@@ -556,11 +344,16 @@ pub fn recent_decisions(o: &KeyvaultOverview, limit: usize) -> Vec<Decision> {
.collect()
}
-/// What a pending request would move, as one line.
+/// What a pending request would move, as one line: sites with their item
+/// counts, files, and what the approval would import.
pub fn pending_summary(p: &KvPending) -> String {
let mut counts: Vec<(String, usize)> = Vec::new();
for i in &p.items {
- let key = i.site.clone().unwrap_or_else(|| i.app_display.clone());
+ let key = match i.domain.as_deref().filter(|d| !d.is_empty()) {
+ Some(d) => super::vault::site_of(d),
+ None if i.kind == "file" => format!("{} files", i.app_display),
+ None => i.app_display.clone(),
+ };
match counts.iter_mut().find(|(k, _)| *k == key) {
Some((_, n)) => *n += 1,
None => counts.push((key, 1)),
@@ -568,17 +361,11 @@ pub fn pending_summary(p: &KvPending) -> String {
}
let mut what: Vec<String> = counts
.into_iter()
- .map(|(k, n)| {
- if n > 1 {
- format!("{k} ({n} accounts)")
- } else {
- k
- }
- })
+ .map(|(k, n)| if n > 1 { format!("{k} ({n} items)") } else { k })
.collect();
what.extend(p.needs_import.iter().map(|s| match s {
- KvSelector::Site { site, .. } => format!("{site} (not imported)"),
- KvSelector::App { app } => format!("{app} (not imported)"),
+ KvSelector::Site { site, .. } => format!("{site} (not saved)"),
+ KvSelector::App { app } => format!("{app} (not saved)"),
KvSelector::Item { id } => id.clone(),
KvSelector::Login { site } => format!("the saved password for {site}"),
}));
@@ -695,16 +482,27 @@ pub struct AccessRow {
/// Live grants, rules and delivery targets, with their undo.
pub fn access_rows(o: &KeyvaultOverview, now: i64) -> Vec<AccessRow> {
let names = |ids: &[String]| {
- ids.iter()
- .map(|id| {
- o.items
- .iter()
- .find(|i| &i.id == id)
- .map(|i| i.label.clone())
- .unwrap_or_else(|| id.clone())
- })
- .collect::<Vec<_>>()
- .join(", ")
+ let named = |id: &String| {
+ o.items
+ .iter()
+ .find(|i| &i.id == id)
+ .filter(|i| !i.key.is_empty())
+ .map(|i| match &i.domain {
+ Some(d) => format!("{} / {}", super::vault::site_of(d), i.key),
+ None => i.key.clone(),
+ })
+ };
+ let shown: Vec<String> = ids
+ .iter()
+ .take(3)
+ .map(|id| named(id).unwrap_or_else(|| "an item".into()))
+ .collect();
+ let more = ids.len().saturating_sub(3);
+ let mut text = shown.join(", ");
+ if more > 0 {
+ text.push_str(&format!(" and {more} more"));
+ }
+ text
};
let mut rows = Vec::new();
for g in o.grants.iter().filter(|g| live_grant(g, now)) {
@@ -813,8 +611,12 @@ pub struct KeyvaultPage {
pub revoke_all: bool,
/// Items exist.
pub has_items: bool,
- /// Search shows (more than six items).
+ /// Search shows (any item exists).
pub search_visible: bool,
+ /// "Never ask again" on the unlock prompt is on (Settings turns it off).
+ pub skip_unlock_prompt: bool,
+ /// An earlier preview's vault was set aside: one line to show.
+ pub reset_notice: Option<String>,
/// Pending requests (the sidebar badge).
pub pending_count: u32,
/// The switch's tooltip (it reads "on" while the Keyvault works).
@@ -845,12 +647,6 @@ pub struct KvLabels {
pub confirm_note: String,
/// "Protection".
pub protection_title: String,
- /// A site's accounts section.
- pub accounts_title: String,
- /// A site's app fact.
- pub app_label: String,
- /// A site's switch.
- pub every_account: String,
}
/// The Keyvault's fixed words.
@@ -864,9 +660,6 @@ pub fn labels() -> KvLabels {
revoke_all: "Revoke all".into(),
confirm_note: "Touch ID confirms in the Cua daemon.".into(),
protection_title: "Protection".into(),
- accounts_title: "Accounts".into(),
- app_label: "App".into(),
- every_account: "Every account unattended".into(),
}
}
@@ -967,7 +760,9 @@ pub fn page(o: &KeyvaultOverview, now: i64) -> KeyvaultPage {
protection,
revoke_all: live_grants > 1,
has_items: !o.items.is_empty(),
- search_visible: o.items.len() > 6,
+ search_visible: !o.items.is_empty(),
+ skip_unlock_prompt: s.and_then(|s| s.skip_unlock_prompt).unwrap_or(false),
+ reset_notice: s.and_then(|s| s.reset_notice.clone()),
pending_count: o.pending.len() as u32,
kill_switch_help: if disabled {
"Turning it back on asks for Touch ID"
diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/wire.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/wire.rs
index a3a80116b1..08f6e298ac 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/wire.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/wire.rs
@@ -11,43 +11,6 @@
use serde::{Deserialize, Serialize};
-/// A cookie's metadata (never its value).
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct KvCookieInfo {
- /// Name.
- pub name: String,
- /// Domain.
- pub domain: String,
- /// Session cookie.
- pub session: bool,
- /// Expiry.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub expires_ms: Option<i64>,
-}
-
-/// What an item holds, as counts and names.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct KvItemSummary {
- /// Cookies.
- #[serde(default)]
- pub cookies: Vec<KvCookieInfo>,
- /// Storage origins.
- #[serde(default)]
- pub storage_origins: Vec<String>,
- /// Saved passwords.
- #[serde(default)]
- pub passwords: u32,
- /// Files.
- #[serde(default)]
- pub files: Vec<String>,
- /// Keychain services.
- #[serde(default)]
- pub keychain_services: Vec<String>,
- /// Bytes.
- #[serde(default)]
- pub bytes: u64,
-}
-
/// An item's policy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KvItemPolicy {
@@ -60,41 +23,53 @@ pub struct KvItemPolicy {
pub unattended: bool,
}
-/// One saved item (redacted).
+/// One secret item of the vault: a cookie, a localStorage value, a password
+/// or a file, in the app it came from (`cua_keyvault::ItemMeta`). Domains and
+/// keys are present only inside the browse window; a value never is.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KvItem {
/// Id.
pub id: String,
- /// `browser_site`, `site_passwords`, `app_session`.
+ /// `cookie`, `local_storage`, `password` or `file`.
pub kind: String,
- /// Label.
- pub label: String,
- /// Provider.
+ /// The source app (`chrome`, `slack`).
pub provider_id: String,
- /// App.
+ /// The app's name.
pub app_display: String,
- /// Site.
+ /// A cookie's host, a storage value's or password's origin; none for a
+ /// file or when the names are hidden.
#[serde(default, skip_serializing_if = "Option::is_none")]
- pub site: Option<String>,
- /// Account.
+ pub domain: Option<String>,
+ /// A cookie name, storage key, username or file path; empty when the
+ /// names are hidden.
+ #[serde(default)]
+ pub key: String,
+ /// A cookie's path.
#[serde(default, skip_serializing_if = "Option::is_none")]
- pub account: Option<String>,
+ pub path: Option<String>,
/// Profile.
#[serde(default)]
pub source: String,
- /// Summary.
- pub summary: KvItemSummary,
- /// Warnings.
+ /// A cookie without an expiry.
#[serde(default)]
- pub warnings: Vec<String>,
- /// Identity providers always ask.
+ pub session: bool,
+ /// A cookie's expiry, Unix ms.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub expires_ms: Option<i64>,
+ /// Bytes.
+ #[serde(default)]
+ pub bytes: u64,
+ /// The blob a big file's bytes live in.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub blob: Option<String>,
+ /// Identity providers always ask: they cannot be unlocked.
#[serde(default)]
pub identity_provider: bool,
- /// Policy.
+ /// Policy: `unattended` is the unlock.
pub policy: KvItemPolicy,
/// Created.
pub created_ms: u64,
- /// Updated.
+ /// Last saved.
pub updated_ms: u64,
/// Revision.
pub rev: u64,
@@ -102,6 +77,52 @@ pub struct KvItem {
pub record_digest: String,
}
+/// One domain a browser holds secrets for, with counts (never values).
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct KvDomainCount {
+ /// Registrable domain.
+ pub domain: String,
+ /// Cookies.
+ #[serde(default)]
+ pub cookies: u32,
+ /// Cookies without an expiry.
+ #[serde(default)]
+ pub session_cookies: u32,
+ /// localStorage values.
+ #[serde(default)]
+ pub local_storage: u32,
+ /// Saved passwords.
+ #[serde(default)]
+ pub passwords: u32,
+ /// Looks like it keeps a sign-in.
+ #[serde(default)]
+ pub signin: bool,
+ /// An identity provider.
+ #[serde(default)]
+ pub identity_provider: bool,
+ /// Cookies that cannot be read (Chrome's app-bound encryption).
+ #[serde(default)]
+ pub unavailable: u32,
+ /// Why they cannot be read.
+ #[serde(default)]
+ pub unavailable_reason: String,
+}
+
+/// What a host app offers, per domain (`cua_keyvault::broker::Inventory`).
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct KvInventory {
+ /// Provider id.
+ pub provider_id: String,
+ /// App name.
+ pub app_display: String,
+ /// Domains with counts.
+ #[serde(default)]
+ pub domains: Vec<KvDomainCount>,
+ /// Notes.
+ #[serde(default)]
+ pub notes: Vec<String>,
+}
+
/// How a caller is signed (`cua_keyvault::caller::Signing`: tagged by
/// `kind`, snake_case).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -168,9 +189,6 @@ pub enum KvSelector {
app: String,
/// Site.
site: String,
- /// Account.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- account: Option<String>,
},
/// A whole app.
App {
@@ -391,6 +409,16 @@ pub struct KvStatus {
/// `windows-credential`, `passphrase`, `recovery`).
#[serde(default)]
pub unlock_protectors: Vec<String>,
+ /// The browse window is open until this time, Unix ms: item names are
+ /// visible until then.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub browse_until_ms: Option<u64>,
+ /// "Never ask again" on the unlock prompt is on.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub skip_unlock_prompt: Option<bool>,
+ /// An earlier preview's vault was found and set aside.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub reset_notice: Option<String>,
}
/// The audit chain check.
@@ -425,9 +453,15 @@ pub struct KeyvaultOverview {
pub status: Option<KvStatus>,
/// The daemon was checked against Cua's signature.
pub server_verified: bool,
- /// Items.
+ /// The vault's secret items, in order (app, domain, key).
#[serde(default)]
pub items: Vec<KvItem>,
+ /// Domains and keys are present in `items` (the browse window is open).
+ #[serde(default)]
+ pub names_visible: bool,
+ /// Items in the vault.
+ #[serde(default)]
+ pub items_total: u32,
/// Pending requests.
#[serde(default)]
pub pending: Vec<KvPending>,
@@ -451,6 +485,16 @@ pub struct KeyvaultOverview {
pub partial_errors: Vec<String>,
}
+/// A site's icon, read from the source browser's own local store when its
+/// items were saved. Not secret. `png` is base64.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct KvFavicon {
+ /// The site (registrable domain).
+ pub site: String,
+ /// PNG, base64.
+ pub png: String,
+}
+
/// A page action: one broker request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
@@ -468,7 +512,8 @@ pub enum KvCommand {
/// On.
disabled: bool,
},
- /// Per-item unattended (turning on asks for Touch ID).
+ /// Per-item unattended (turning on asks for Touch ID): the same as
+ /// [`KvCommand::SetLocked`] with `locked` the other way round.
#[serde(rename_all = "camelCase")]
SetUnattended {
/// Items.
@@ -476,6 +521,31 @@ pub enum KvCommand {
/// On.
unattended: bool,
},
+ /// Lock or unlock items together. Unlocking allows unattended access and
+ /// asks for Touch ID once for the whole batch; locking does not.
+ #[serde(rename_all = "camelCase")]
+ SetLocked {
+ /// Items.
+ item_ids: Vec<String>,
+ /// Lock (true) or unlock.
+ locked: bool,
+ },
+ /// Delete items, wiping every live copy of them in Spaces.
+ #[serde(rename_all = "camelCase")]
+ DeleteItems {
+ /// Items.
+ item_ids: Vec<String>,
+ },
+ /// "Never ask again" on the unlock prompt (Settings turns it back on).
+ #[serde(rename_all = "camelCase")]
+ SetSkipUnlockPrompt {
+ /// On.
+ on: bool,
+ },
+ /// Show item names for a few minutes (the daemon asks for Touch ID).
+ Browse,
+ /// Hide item names again.
+ EndBrowse,
/// Revoke a grant (`*`: all).
RevokeGrant {
/// Id.
diff --git a/libs/cua/crates/cua-spaces-app-core/src/parity.rs b/libs/cua/crates/cua-spaces-app-core/src/parity.rs
index f3420d7c97..ed3a89a59a 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/parity.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/parity.rs
@@ -601,9 +601,6 @@ pub mod frame {
"revokeAll",
"confirmNote",
"protectionTitle",
- "accountsTitle",
- "appLabel",
- "everyAccount",
];
/// The This machine page.
@@ -1269,24 +1266,17 @@ pub mod frame {
Some(n) => format!("{}:{n}", c["title"].as_str().unwrap_or("")),
None => c["title"].as_str().unwrap_or("").to_string(),
})).collect::<Vec<_>>()).unwrap_or_default(),
- "sites": v["sites"].as_array().map(|a| a.iter().map(|x| Value::String(format!("{} ({}){}",
- x["title"].as_str().unwrap_or(""), x["accounts"], if x["waiting"] == true { " waiting" } else { "" }))).collect::<Vec<_>>()).unwrap_or_default(),
+ "apps": v["apps"].as_array().map(|a| a.iter().map(|x| Value::String(format!("{} ({}){}",
+ x["title"].as_str().unwrap_or(""), x["items"], if x["waiting"] == true { " waiting" } else { "" }))).collect::<Vec<_>>()).unwrap_or_default(),
})
}
- /// A Keyvault list.
+ /// A Keyvault list (the panes other than the vault list).
pub fn kv_list(v: &Value) -> Value {
let text = |x: &Value| x.as_str().unwrap_or("").to_string();
json!({
"title": v["title"],
- "sites": v["sites"].as_array().map(|a| a.iter().map(|g| Value::String(format!("{} [{}]: {}",
- text(&g["title"]), text(&g["unattended"]),
- g["rows"].as_array().map(|r| r.iter().map(|row| format!("{} {}{} <{}>",
- text(&row["account"]),
- if row["item"]["policy"]["unattended"] == true { "on" } else { "off" },
- if row["toggleEnabled"] == true { "" } else { " locked" },
- row["consent"].as_array().map(|c| c.iter().map(|chip| format!("{}:{}", text(&chip["kind"]), text(&chip["text"]))).collect::<Vec<_>>().join("; ")).unwrap_or_default()
- )).collect::<Vec<_>>().join(" | ")).unwrap_or_default()))).collect::<Vec<_>>()).unwrap_or_default(),
+ "vault": v["vault"],
"pending": v["pending"].as_array().map(|a| a.iter().map(|p| Value::String(format!("{} ({}) {} for {}",
text(&p["caller"]), text(&p["badge"]["text"]), text(&p["summary"]), text(&p["wants"])))).collect::<Vec<_>>()).unwrap_or_default(),
"access": v["access"].as_array().map(|a| a.iter().map(|x| Value::String(format!("{} / {} [{}]",
@@ -1297,6 +1287,117 @@ pub mod frame {
})
}
+ /// The vault list: each app with its sites and files, one line each,
+ /// the selection and the batch bar.
+ pub fn kv_vault(v: &Value) -> Value {
+ let text = |x: &Value| x.as_str().unwrap_or("").to_string();
+ let mark = |x: &Value| match x.as_str().unwrap_or("") {
+ "on" => "[x]",
+ "mixed" => "[-]",
+ _ => "[ ]",
+ };
+ let row = |r: &Value| {
+ format!(
+ "{} {} {} | {} | {} | {}{}",
+ if r["selected"] == true { "[x]" } else { "[ ]" },
+ text(&r["kindLabel"]),
+ text(&r["title"]),
+ text(&r["subtitle"]),
+ text(&r["lockSymbol"]),
+ text(&r["updated"]),
+ if r["identityProvider"] == true {
+ " | always asks"
+ } else {
+ ""
+ }
+ )
+ };
+ let lines: Vec<Value> = v["apps"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .flat_map(|a| {
+ let mut out = vec![Value::String(format!(
+ "{} {} {} | {} | {} | {}",
+ mark(&a["selected"]),
+ text(&a["name"]),
+ text(&a["providerId"]),
+ text(&a["summary"]),
+ text(&a["lock"]),
+ text(&a["updated"])
+ ))];
+ for s in a["sites"].as_array().into_iter().flatten() {
+ out.push(Value::String(format!(
+ " {} {} | {} | {} | {}{}",
+ mark(&s["selected"]),
+ text(&s["site"]),
+ text(&s["counts"]),
+ text(&s["lock"]),
+ text(&s["updated"]),
+ if s["open"] == true { " | open" } else { "" }
+ )));
+ for r in s["rows"].as_array().into_iter().flatten() {
+ out.push(Value::String(format!(" {}", row(r))));
+ }
+ }
+ if !a["files"].is_null() {
+ let f = &a["files"];
+ out.push(Value::String(format!(
+ " {} files ({}) | {}{}",
+ mark(&f["selected"]),
+ f["count"],
+ text(&f["lock"]),
+ if f["open"] == true { " | open" } else { "" }
+ )));
+ for r in f["rows"].as_array().into_iter().flatten() {
+ out.push(Value::String(format!(" {}", row(r))));
+ }
+ }
+ out
+ })
+ .collect();
+ let sel = &v["selection"];
+ json!({
+ "shown": format!("{}/{}", v["shown"], v["total"]),
+ "lines": lines,
+ "empty": v["emptyText"],
+ "selection": format!("{} (unlock {} / lock {} / always ask {})",
+ text(&sel["title"]),
+ sel["unlockIds"].as_array().map(|a| a.len()).unwrap_or(0),
+ sel["lockIds"].as_array().map(|a| a.len()).unwrap_or(0),
+ sel["alwaysAsk"]),
+ "canUnlock": sel["canUnlock"],
+ "canLock": sel["canLock"],
+ })
+ }
+
+ /// The unlock prompt (`null`: skipped).
+ pub fn kv_unlock_prompt(v: &Value) -> Value {
+ if v.is_null() {
+ return Value::Null;
+ }
+ json!([
+ v["title"],
+ v["message"],
+ v["subject"],
+ format!(
+ "{} / {} / {}",
+ str_of(&v["deny"]),
+ str_of(&v["allow"]),
+ str_of(&v["neverAsk"])
+ ),
+ ])
+ }
+
+ /// The delete confirmation.
+ pub fn kv_delete_confirm(v: &Value) -> Value {
+ json!([
+ v["title"],
+ v["message"],
+ format!("{} / {}", str_of(&v["confirm"]), str_of(&v["cancel"]))
+ ])
+ }
+
/// The approval sheet.
pub fn approval(v: &Value) -> Value {
json!({
@@ -2272,7 +2373,7 @@ fn run_keyvault(f: &Value, h: &dyn Host) -> Result<Value, String> {
let l = c(
h,
"keyvault.list",
- json!({ "overview": o, "selection": sel, "now": now, "query": "" }),
+ json!({ "overview": o, "selection": sel, "now": now }),
)?;
frames.push(json!({ "list": sel, "frame": frame::kv_list(&l) }));
}
@@ -2306,21 +2407,60 @@ fn run_keyvault(f: &Value, h: &dyn Host) -> Result<Value, String> {
json!({ "state": { "requestId": f["deny"], "selected": [] } }),
)?;
frames.push(json!({ "denyCommand": deny }));
- let t = &f["siteToggle"];
- let detail = c(
+ let vault = &f["vault"];
+ let mut st = vault["state"].clone();
+ let v = c(
h,
- "keyvault.siteDetail",
- json!({ "overview": o, "key": t["key"], "now": now }),
+ "keyvault.vaultView",
+ json!({ "overview": o, "state": st, "now": now }),
)?;
- let toggle = c(
+ frames.push(json!({ "vault": "open", "frame": frame::kv_vault(&v) }));
+ for action in vault["actions"].as_array().into_iter().flatten() {
+ st = c(
+ h,
+ "keyvault.vaultReduce",
+ json!({ "overview": o, "state": st, "action": action }),
+ )?;
+ let v = c(
+ h,
+ "keyvault.vaultView",
+ json!({ "overview": o, "state": st, "now": now }),
+ )?;
+ frames.push(json!({ "vault": action, "frame": frame::kv_vault(&v) }));
+ }
+ // One app's list: the sidebar's pick narrows the state.
+ let mut one = vault["state"].clone();
+ one["app"] = vault["app"].clone();
+ let v = c(
h,
- "keyvault.siteToggle",
- json!({ "group": detail["group"], "on": t["on"] }),
+ "keyvault.vaultView",
+ json!({ "overview": o, "state": one, "now": now }),
)?;
- frames.push(json!({
- "siteDetail": { "switch": detail["siteSwitch"], "state": detail["siteState"], "enabled": detail["siteSwitchEnabled"] },
- "siteToggle": toggle,
- }));
+ frames.push(json!({ "vaultApp": vault["app"], "frame": frame::kv_vault(&v) }));
+ for u in vault["unlock"].as_array().into_iter().flatten() {
+ let p = c(
+ h,
+ "keyvault.unlockPrompt",
+ json!({ "overview": o, "count": u["count"], "name": u["name"] }),
+ )?;
+ frames.push(json!({ "unlockPrompt": u, "frame": frame::kv_unlock_prompt(&p) }));
+ }
+ let mut skip = o.clone();
+ skip["status"]["skip_unlock_prompt"] = Value::Bool(true);
+ let p = c(
+ h,
+ "keyvault.unlockPrompt",
+ json!({ "overview": skip, "count": 1, "name": null }),
+ )?;
+ frames.push(json!({ "unlockPromptSkipped": frame::kv_unlock_prompt(&p) }));
+ for d in vault["delete"].as_array().into_iter().flatten() {
+ let p = c(
+ h,
+ "keyvault.deleteConfirm",
+ json!({ "count": d["count"], "liveCopies": d["liveCopies"] }),
+ )?;
+ frames.push(json!({ "deleteConfirm": d, "frame": frame::kv_delete_confirm(&p) }));
+ }
let mut off = o.clone();
off["status"]["disabled"] = Value::Bool(true);
let page = c(h, "keyvault.page", json!({ "overview": off, "now": now }))?;
diff --git a/libs/cua/crates/cua-spaces-app-core/src/settings.rs b/libs/cua/crates/cua-spaces-app-core/src/settings.rs
index e1e1421961..35ff726a49 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/settings.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/settings.rs
@@ -61,6 +61,13 @@ pub struct AppSettings {
/// longer shows them, nothing is revoked or wiped
/// ([`crate::keyvault::view::prune_dismissed`] forgets the gone ones).
pub dismissed_access: Vec<String>,
+ /// Keyvault rows may load a site's icon from Google's favicon service
+ /// when the source browser had none (Settings, Keyvault; on by default).
+ /// Off, only icons read locally are shown.
+ pub keyvault_site_icons: bool,
+ /// The sites the user sent to each Space last time, per app
+ /// ([`crate::teleport::review::remember`]): the review starts from them.
+ pub teleport_choices: Vec<crate::teleport::review::RememberedChoice>,
/// Settings, General: a running Space's desktop streams as soon as it
/// is opened (on by default); off, it waits for Connect
/// ([`crate::spaces::cover`]).
@@ -81,6 +88,8 @@ impl Default for AppSettings {
launch_at_login: None,
experiments: Experiments::default(),
dismissed_access: vec![],
+ keyvault_site_icons: true,
+ teleport_choices: vec![],
auto_connect: true,
}
}
@@ -248,6 +257,17 @@ pub struct SettingsInput {
/// The Keyvault's auto-wipe, once the broker told it (none: no
/// Keyvault section).
pub keyvault_auto_wipe: Option<bool>,
+ /// The unlock prompt shows (false once the user chose "Never ask
+ /// again"); none until the broker told it.
+ pub keyvault_unlock_prompt: Option<bool>,
+ /// Load site icons from Google when the browser had none
+ /// ([`AppSettings::keyvault_site_icons`]).
+ #[serde(default = "default_true")]
+ pub keyvault_site_icons: bool,
+ /// The Keyvault's protection facts (Touch ID, the daemon's signature),
+ /// shown in the section.
+ #[serde(default)]
+ pub keyvault_protection: Vec<crate::spaces::sidebar::Fact>,
/// "Connect to the desktop automatically" (none: no row; a shell
/// without the preview cover leaves it out).
pub auto_connect: Option<bool>,
@@ -271,11 +291,25 @@ impl Default for SettingsInput {
login_item: None,
experiments: Experiments::default(),
keyvault_auto_wipe: None,
+ keyvault_unlock_prompt: None,
+ keyvault_site_icons: true,
+ keyvault_protection: vec![],
auto_connect: None,
}
}
}
+fn default_true() -> bool {
+ true
+}
+
+/// The site icons switch's label.
+pub const SITE_ICONS_LABEL: &str = "Load site icons from Google";
+
+/// The line under it.
+pub const SITE_ICONS_NOTE: &str =
+ "Sends only the site's domain. Off uses your browser's own icons.";
+
/// The auto-connect switch's label.
pub const AUTO_CONNECT_LABEL: &str = "Connect to the desktop automatically";
@@ -297,9 +331,23 @@ pub const AUTO_WIPE_LABEL: &str = "Wipe access from Spaces automatically";
/// The line under it.
pub const AUTO_WIPE_NOTE: &str = "When off, sign-ins stay in a Space until you wipe them.";
+/// The unlock prompt switch's label.
+pub const UNLOCK_PROMPT_LABEL: &str = "Explain unattended access before allowing it";
+
+/// The line under it.
+pub const UNLOCK_PROMPT_NOTE: &str = "Unlocking an item always asks for Touch ID. Turn this on to see the explanation again after choosing Never ask again.";
+
/// The Keyvault section: the auto-wipe switch (off by default) and its
-/// line. Row id `keyvault-auto-wipe`; its options are `on` and `off`.
-pub fn keyvault_section(auto_wipe: bool) -> SettingsSection {
+/// line, the unlock prompt switch (on by default; "Never ask again" turns it
+/// off and this turns it back on), and the protection facts. Row ids
+/// `keyvault-auto-wipe`, `keyvault-unlock-prompt` and `keyvault-protection:<label>`;
+/// the switches' options are `on` and `off`.
+pub fn keyvault_section(
+ auto_wipe: bool,
+ unlock_prompt: Option<bool>,
+ site_icons: bool,
+ protection: &[crate::spaces::sidebar::Fact],
+) -> SettingsSection {
let mut toggle = row(
"keyvault-auto-wipe",
SettingsRowKind::Toggle,
@@ -311,20 +359,61 @@ pub fn keyvault_section(auto_wipe: bool) -> SettingsSection {
} else {
"Wipes sign-ins after an hour (15 minutes for identity providers)".into()
});
+ let mut rows = vec![
+ toggle,
+ row(
+ "keyvault-auto-wipe-note",
+ SettingsRowKind::Note,
+ AUTO_WIPE_NOTE,
+ ),
+ ];
+ if let Some(shows) = unlock_prompt {
+ let mut t = row(
+ "keyvault-unlock-prompt",
+ SettingsRowKind::Toggle,
+ UNLOCK_PROMPT_LABEL,
+ );
+ t.options = vec![opt("on", "On", shows), opt("off", "Off", !shows)];
+ t.help = Some(if shows {
+ "Choosing Never ask again on the prompt turns this off".into()
+ } else {
+ "You chose Never ask again. Turn this on to see the prompt again".into()
+ });
+ rows.push(t);
+ rows.push(row(
+ "keyvault-unlock-prompt-note",
+ SettingsRowKind::Note,
+ UNLOCK_PROMPT_NOTE,
+ ));
+ }
+ let mut icons = row(
+ "keyvault-site-icons",
+ SettingsRowKind::Toggle,
+ SITE_ICONS_LABEL,
+ );
+ icons.options = vec![opt("on", "On", site_icons), opt("off", "Off", !site_icons)];
+ rows.push(icons);
+ rows.push(row(
+ "keyvault-site-icons-note",
+ SettingsRowKind::Note,
+ SITE_ICONS_NOTE,
+ ));
+ for f in protection {
+ let mut r = row(
+ &format!("keyvault-protection:{}", f.label),
+ SettingsRowKind::Text,
+ &f.label,
+ );
+ r.value = Some(f.value.clone());
+ rows.push(r);
+ }
SettingsSection {
id: "keyvault".into(),
title: "Keyvault".into(),
button: None,
button_enabled: false,
button_help: None,
- rows: vec![
- toggle,
- row(
- "keyvault-auto-wipe-note",
- SettingsRowKind::Note,
- AUTO_WIPE_NOTE,
- ),
- ],
+ rows,
}
}
@@ -595,7 +684,12 @@ pub fn page(input: &SettingsInput) -> SettingsPage {
}
if let Some(on) = input.keyvault_auto_wipe {
- sections.push(keyvault_section(on));
+ sections.push(keyvault_section(
+ on,
+ input.keyvault_unlock_prompt,
+ input.keyvault_site_icons,
+ &input.keyvault_protection,
+ ));
}
let agents = input.agents.clone().unwrap_or_default();
@@ -771,9 +865,55 @@ mod tests {
);
let on = |r: &SettingsRow| r.options.iter().find(|o| o.id == "on").unwrap().active;
assert!(!on(toggle), "off by default");
- assert!(on(&keyvault_section(true).rows[0]));
+ assert!(on(&keyvault_section(true, None, true, &[]).rows[0]));
assert_eq!(kv.rows[1].kind, SettingsRowKind::Note);
assert!(!AUTO_WIPE_NOTE.contains('\u{2014}'), "no em dashes in copy");
+ assert!(
+ !UNLOCK_PROMPT_NOTE.contains('\u{2014}') && !UNLOCK_PROMPT_LABEL.contains('\u{2014}')
+ );
+ // Without the setting told, no prompt row; told, it is a switch that
+ // is on until "Never ask again" turns it off, with the protection
+ // facts under it.
+ assert!(!kv.rows.iter().any(|r| r.id == "keyvault-unlock-prompt"));
+ let fact = |l: &str, v: &str| crate::spaces::sidebar::Fact {
+ label: l.into(),
+ value: v.into(),
+ copy: None,
+ help: None,
+ warning: None,
+ };
+ let with = keyvault_section(
+ false,
+ Some(false),
+ true,
+ &[fact("Touch ID", "Asked by the Cua daemon")],
+ );
+ let prompt = with
+ .rows
+ .iter()
+ .find(|r| r.id == "keyvault-unlock-prompt")
+ .unwrap();
+ assert!(!on(prompt), "Never ask again turned it off");
+ assert!(on(&keyvault_section(false, Some(true), true, &[]).rows[2]));
+ let last = with.rows.last().unwrap();
+ assert_eq!(last.id, "keyvault-protection:Touch ID");
+ assert_eq!(last.value.as_deref(), Some("Asked by the Cua daemon"));
+ // The site icons switch is on by default and named for Google.
+ let icons = with
+ .rows
+ .iter()
+ .find(|r| r.id == "keyvault-site-icons")
+ .unwrap();
+ assert!(on(icons));
+ assert_eq!(icons.label, "Load site icons from Google");
+ assert!(!on(keyvault_section(false, None, false, &[])
+ .rows
+ .iter()
+ .find(|r| r.id == "keyvault-site-icons")
+ .unwrap()));
+ assert!(AppSettings::default().keyvault_site_icons);
+ let old: AppSettings = serde_json::from_str(r#"{"menuBar":true}"#).unwrap();
+ assert!(old.keyvault_site_icons, "a missing field is on");
// A settings file from before dismissals: none dismissed.
let old: AppSettings = serde_json::from_str(r#"{"menuBar":true}"#).unwrap();
assert!(old.dismissed_access.is_empty());
diff --git a/libs/cua/crates/cua-spaces-app-core/src/teleport/flow.rs b/libs/cua/crates/cua-spaces-app-core/src/teleport/flow.rs
index 03c0ab4ce2..35cc6de481 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/teleport/flow.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/teleport/flow.rs
@@ -10,6 +10,8 @@
//! webview uses; `json` carries the SDK's own JSON for the entry or plan so
//! the shell can hand it back to `plan` / `run` untouched.
+use super::review::{self, ReviewChoice, ReviewDomain, ReviewToggle, SendSource, VaultSource};
+use crate::keyvault::wire::KvInventory;
use crate::util::{contains_word, to_fixed};
use serde::{Deserialize, Serialize};
@@ -289,7 +291,7 @@ pub struct RunReport {
}
/// The consent the run carries (`cua_teleport::ux::Consent`).
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Consent {
/// Confirmed.
@@ -302,6 +304,23 @@ pub struct Consent {
/// [`Plan::relay_unsealed`]'s warning acknowledged (S1).
#[serde(default)]
pub acknowledge_relay_plaintext: bool,
+ /// The sites whose cookies to send (the review's per-site choice);
+ /// `None` when the review did not list sites.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cookie_domains: Option<Vec<String>>,
+ /// Consent items (keys) the user turned off.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub exclude: Vec<String>,
+ /// Send these saved Keyvault items instead of reading the live app.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub from_vault: Option<Vec<String>>,
+ /// Also send the saved passwords (ticked in the review).
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub include_passwords: bool,
+}
+
+fn is_false(b: &bool) -> bool {
+ !*b
}
/// The "needs the Cua app" prompt for a Keyvault refusal.
@@ -419,6 +438,9 @@ pub struct PickerState {
/// [`Plan::relay_unsealed`]'s warning acknowledged (S1).
#[serde(default)]
pub acknowledged_relay_plaintext: bool,
+ /// What the review sends: which sites, which items, from where.
+ #[serde(default)]
+ pub choice: ReviewChoice,
/// Run events (last [`MAX_EVENTS`]).
pub events: Vec<RunEvent>,
/// The run's report.
@@ -521,6 +543,68 @@ pub enum PickerEvent {
/// Checked.
value: bool,
},
+ /// The browser's sites with counts arrived (and what was picked last time
+ /// for this app and Space, if anything).
+ DomainsLoaded {
+ /// The inventory.
+ inventory: KvInventory,
+ /// The sites sent last time.
+ #[serde(default)]
+ remembered: Option<Vec<String>>,
+ },
+ /// The inventory could not be read (the review then sends what the plan
+ /// lists, as before).
+ DomainsFailed,
+ /// Pick or drop one site.
+ ToggleDomain {
+ /// The site.
+ domain: String,
+ },
+ /// Pick or drop every site the search shows.
+ SelectShownDomains {
+ /// Pick (true) or drop.
+ value: bool,
+ },
+ /// The sites list's search text.
+ DomainQuery {
+ /// Text.
+ text: String,
+ },
+ /// Turn a consent line on or off.
+ ToggleItem {
+ /// The consent item's key.
+ key: String,
+ },
+ /// Where to send from.
+ SendFrom {
+ /// The source.
+ source: SendSource,
+ },
+ /// The app's saved Keyvault items (what the Keyvault holds for it).
+ #[serde(rename_all = "camelCase")]
+ VaultItems {
+ /// How many can be sent.
+ count: u32,
+ /// When the newest was saved, Unix ms.
+ newest_ms: i64,
+ /// Now, Unix ms.
+ now_ms: i64,
+ /// The ones chosen to send (ids).
+ selected: Vec<String>,
+ /// The app's saved passwords (ids): sent only when ticked.
+ #[serde(default)]
+ password_ids: Vec<String>,
+ },
+ /// Tick or untick "Also send saved passwords".
+ TogglePasswords {
+ /// Ticked.
+ value: bool,
+ },
+ /// The chosen saved items changed.
+ VaultSelection {
+ /// The ids.
+ selected: Vec<String>,
+ },
/// Confirm the review.
Confirm,
/// A run event.
@@ -553,6 +637,7 @@ pub fn initial(space_name: &str) -> PickerState {
acknowledged: false,
save_to_keyvault: false,
acknowledged_relay_plaintext: false,
+ choice: ReviewChoice::default(),
events: vec![],
report: None,
error: None,
@@ -581,6 +666,7 @@ fn to_options(s: &PickerState, entry: &CatalogEntry, files: Vec<String>) -> Pick
acknowledged: false,
save_to_keyvault: false,
acknowledged_relay_plaintext: false,
+ choice: ReviewChoice::default(),
error: None,
install_prompt: None,
..s.clone()
@@ -687,21 +773,80 @@ pub fn can_plan(s: &PickerState) -> bool {
}
}
+/// The saved passwords can be offered: the Keyvault holds some for the app
+/// (sending from it), or a chosen site holds some in the browser (reading it
+/// now).
+pub fn passwords_offered(s: &PickerState) -> bool {
+ match s.choice.source {
+ SendSource::Vault => !s.choice.vault.password_ids.is_empty(),
+ SendSource::Live => password_count(s) > 0,
+ }
+}
+
+/// How many saved passwords ticking the box would send.
+pub fn password_count(s: &PickerState) -> u32 {
+ match s.choice.source {
+ SendSource::Vault => s.choice.vault.password_ids.len() as u32,
+ SendSource::Live => s
+ .choice
+ .domains
+ .iter()
+ .filter(|d| s.choice.selected_domains.contains(&d.domain))
+ .map(|d| d.passwords)
+ .sum(),
+ }
+}
+
/// The review can be confirmed: a plan, secrets acknowledged when any, and
/// the relay-plaintext warning acknowledged when it applies (S1).
pub fn can_confirm(s: &PickerState) -> bool {
- s.plan.as_ref().is_some_and(|p| {
- (!p.sensitive || s.acknowledged) && (!p.relay_unsealed || s.acknowledged_relay_plaintext)
- })
+ let from_vault_ok = s.choice.source != SendSource::Vault || !s.choice.vault.selected.is_empty();
+ from_vault_ok
+ && s.plan.as_ref().is_some_and(|p| {
+ (!(p.sensitive || s.choice.include_passwords) || s.acknowledged)
+ && (!p.relay_unsealed || s.acknowledged_relay_plaintext)
+ })
+}
+
+/// Whether a consent key is the browser's cookie store.
+fn is_cookie_key(key: &str) -> bool {
+ key.rsplit('/')
+ .next()
+ .unwrap_or(key)
+ .eq_ignore_ascii_case("cookies")
+}
+
+/// The plan sends a browser's cookies.
+fn sends_cookies(plan: &Plan) -> bool {
+ plan.consent.iter().any(|c| is_cookie_key(&c.key))
+}
+
+/// Consent lines the user may turn off: not installs, and not the cookie
+/// store while its sites are listed (the site choice is that line).
+fn toggleable(c: &ConsentItem, choice: &ReviewChoice) -> bool {
+ c.kind != ConsentKind::Install && !(is_cookie_key(&c.key) && !choice.domains.is_empty())
}
/// The consent the confirmed review carries.
pub fn consent(s: &PickerState) -> Consent {
+ let vault = s.choice.source == SendSource::Vault;
Consent {
approved: can_confirm(s),
acknowledge_sensitive: s.acknowledged,
- save_to_keyvault: s.save_to_keyvault,
+ // Items sent from the vault are already saved.
+ save_to_keyvault: s.save_to_keyvault && !vault,
acknowledge_relay_plaintext: s.acknowledged_relay_plaintext,
+ cookie_domains: (!vault && !s.choice.domains.is_empty())
+ .then(|| s.choice.selected_domains.clone()),
+ exclude: s.choice.excluded.clone(),
+ from_vault: vault.then(|| {
+ let mut ids = s.choice.vault.selected.clone();
+ if s.choice.include_passwords {
+ ids.extend(s.choice.vault.password_ids.iter().cloned());
+ }
+ ids
+ }),
+ include_passwords: passwords_offered(s) && s.choice.include_passwords,
}
}
@@ -934,6 +1079,7 @@ pub fn reduce(s: &PickerState, e: &PickerEvent) -> PickerState {
n.acknowledged = false;
n.save_to_keyvault = false;
n.acknowledged_relay_plaintext = false;
+ n.choice = ReviewChoice::default();
}
}
PickerEvent::Acknowledge { value } => {
@@ -954,6 +1100,92 @@ pub fn reduce(s: &PickerState, e: &PickerEvent) -> PickerState {
n.acknowledged_relay_plaintext = *value;
}
}
+ PickerEvent::DomainsLoaded {
+ inventory,
+ remembered,
+ } => {
+ if s.step == Step::Consent {
+ let keep = n.choice.clone();
+ n.choice = review::with_inventory(keep, inventory, remembered.as_deref());
+ n.choice.loaded = true;
+ }
+ }
+ PickerEvent::DomainsFailed => {
+ if s.step == Step::Consent {
+ n.choice.loaded = true;
+ }
+ }
+ PickerEvent::ToggleDomain { domain } => {
+ if s.step == Step::Consent {
+ review::toggle_domain(&mut n.choice, domain);
+ }
+ }
+ PickerEvent::SelectShownDomains { value } => {
+ if s.step == Step::Consent {
+ review::set_shown_domains(&mut n.choice, *value);
+ }
+ }
+ PickerEvent::DomainQuery { text } => {
+ if s.step == Step::Consent {
+ n.choice.query = text.clone();
+ }
+ }
+ PickerEvent::ToggleItem { key } => {
+ let ok = s.step == Step::Consent
+ && s.plan.as_ref().is_some_and(|p| {
+ p.consent
+ .iter()
+ .any(|c| &c.key == key && toggleable(c, &s.choice))
+ });
+ if ok {
+ match n.choice.excluded.iter().position(|k| k == key) {
+ Some(i) => {
+ n.choice.excluded.remove(i);
+ }
+ None => n.choice.excluded.push(key.clone()),
+ }
+ }
+ }
+ PickerEvent::SendFrom { source } => {
+ if s.step == Step::Consent && (*source == SendSource::Live || s.choice.vault.available)
+ {
+ n.choice.source = *source;
+ }
+ }
+ PickerEvent::VaultItems {
+ count,
+ newest_ms,
+ now_ms,
+ selected,
+ password_ids,
+ } => {
+ if s.step == Step::Consent {
+ n.choice.vault = VaultSource {
+ password_ids: password_ids.clone(),
+ available: *count > 0,
+ items: *count,
+ saved: if *newest_ms > 0 {
+ format!("saved {}", crate::keyvault::view::ago(now_ms - newest_ms))
+ } else {
+ String::new()
+ },
+ selected: selected.clone(),
+ };
+ if *count == 0 {
+ n.choice.source = SendSource::Live;
+ }
+ }
+ }
+ PickerEvent::TogglePasswords { value } => {
+ if s.step == Step::Consent && passwords_offered(s) {
+ n.choice.include_passwords = *value;
+ }
+ }
+ PickerEvent::VaultSelection { selected } => {
+ if s.step == Step::Consent && s.choice.vault.available {
+ n.choice.vault.selected = selected.clone();
+ }
+ }
PickerEvent::Confirm => {
if s.step == Step::Consent && can_confirm(s) {
n.step = Step::Running;
@@ -986,6 +1218,7 @@ pub fn reduce(s: &PickerState, e: &PickerEvent) -> PickerState {
n.acknowledged = false;
n.save_to_keyvault = false;
n.acknowledged_relay_plaintext = false;
+ n.choice = ReviewChoice::default();
}
Step::Error => {
n.step = s.error_back;
@@ -1029,6 +1262,41 @@ pub struct ReviewView {
pub leaves_text: Option<String>,
/// Caveats.
pub warnings: Vec<String>,
+ /// Lines the user can turn off (files, folders, state, secrets), each
+ /// with whether it is sent. The cookie store is the site list below.
+ pub toggles: Vec<ReviewToggle>,
+ /// The plan sends a browser's cookies, so the sites can be chosen.
+ pub offers_domains: bool,
+ /// The sites have not been read yet (the shell asks the Keyvault for
+ /// them, which may ask for Touch ID).
+ pub needs_domains: bool,
+ /// The sites with counts, filtered by the search.
+ pub domains: Vec<ReviewDomain>,
+ /// "3 of 12 sites".
+ pub domain_summary: String,
+ /// The sites search text.
+ pub domain_query: String,
+ /// The sites chosen (what is remembered for next time).
+ pub selected_domains: Vec<String>,
+ /// Where it sends from.
+ pub source: SendSource,
+ /// The app has saved Keyvault items to send instead of reading the live
+ /// app.
+ pub offers_vault: bool,
+ /// The saved items.
+ pub vault: VaultSource,
+ /// "Send from the Keyvault (212 items, saved 2 days ago)".
+ pub vault_label: String,
+ /// "Read Chrome now (macOS asks for Keychain access)".
+ pub live_label: String,
+ /// "Also send saved passwords" shows (there are some to send).
+ pub offers_passwords: bool,
+ /// Ticked.
+ pub include_passwords: bool,
+ /// "Also send 14 saved passwords".
+ pub passwords_label: String,
+ /// What the Keychain will do for this source, in a line.
+ pub source_note: String,
}
/// The review, when a plan is under review.
@@ -1043,19 +1311,102 @@ pub fn review(s: &PickerState) -> Option<ReviewView> {
if plan.relay_unsealed {
warnings.push(RELAY_PLAINTEXT_WARNING.into());
}
+ let choice = &s.choice;
+ let vault = choice.source == SendSource::Vault;
+ let cookies = sends_cookies(plan);
+ // What leaves, less what was turned off (and the cookie store when no
+ // site is chosen).
+ let no_sites = !choice.domains.is_empty() && choice.selected_domains.is_empty();
+ let bytes: u64 = plan
+ .consent
+ .iter()
+ .filter(|c| !choice.excluded.contains(&c.key) && !(no_sites && is_cookie_key(&c.key)))
+ .map(|c| c.bytes)
+ .sum();
+ let leaves_text = if vault {
+ let n = choice.vault.selected.len();
+ Some(format!(
+ "{n} saved item{} from the Keyvault",
+ if n == 1 { "" } else { "s" }
+ ))
+ } else {
+ (bytes > 0).then(|| format!("{} leaves this Mac", format_bytes(bytes)))
+ };
+ let app = &plan.app.name;
Some(ReviewView {
title: format!("Teleport {} to {}", plan.app.name, s.space_name),
items: plan.consent.clone(),
steps: plan.steps.clone(),
- needs_acknowledgement: plan.sensitive,
+ toggles: plan
+ .consent
+ .iter()
+ .filter(|c| toggleable(c, choice))
+ .map(|c| ReviewToggle {
+ key: c.key.clone(),
+ label: c.label.clone(),
+ detail: c.detail.clone(),
+ bytes: c.bytes,
+ sensitive: c.sensitive,
+ selected: !choice.excluded.contains(&c.key),
+ })
+ .collect(),
+ offers_domains: cookies && !vault,
+ needs_domains: cookies && !vault && !choice.loaded,
+ domains: review::domain_rows(choice),
+ domain_summary: review::domain_summary(choice),
+ domain_query: choice.query.clone(),
+ selected_domains: choice.selected_domains.clone(),
+ source: choice.source,
+ offers_vault: choice.vault.available,
+ vault: choice.vault.clone(),
+ vault_label: if choice.vault.available {
+ let n = choice.vault.items;
+ let saved = if choice.vault.saved.is_empty() {
+ String::new()
+ } else {
+ format!(", {}", choice.vault.saved)
+ };
+ format!(
+ "Send from the Keyvault ({n} item{}{saved})",
+ if n == 1 { "" } else { "s" }
+ )
+ } else {
+ String::new()
+ },
+ live_label: if cookies {
+ format!("Read {app} now")
+ } else {
+ format!("Read {app} on this Mac")
+ },
+ source_note: if vault {
+ "Nothing is read from this Mac, so macOS does not ask for Keychain access.".into()
+ } else if cookies {
+ format!("Reading {app}'s cookies makes macOS ask for Keychain access.")
+ } else {
+ String::new()
+ },
+ offers_passwords: passwords_offered(s),
+ include_passwords: s.choice.include_passwords && passwords_offered(s),
+ passwords_label: {
+ let n = password_count(s);
+ if n == 0 {
+ String::new()
+ } else {
+ format!(
+ "Also send {n} saved password{}",
+ if n == 1 { "" } else { "s" }
+ )
+ }
+ },
+ needs_acknowledgement: plan.sensitive
+ || (s.choice.include_passwords && passwords_offered(s)),
acknowledged: s.acknowledged,
offers_save_to_keyvault: plan.sensitive,
save_to_keyvault: s.save_to_keyvault,
needs_relay_plaintext_acknowledgement: plan.relay_unsealed,
acknowledged_relay_plaintext: s.acknowledged_relay_plaintext,
can_confirm: can_confirm(s),
- leaves_text: (plan.total_bytes > 0)
- .then(|| format!("{} leaves this Mac", format_bytes(plan.total_bytes))),
+ leaves_text,
warnings,
})
}
@@ -1335,4 +1686,345 @@ mod tests {
let ns = reduce(&ns, &PickerEvent::SaveToKeyvault { value: true });
assert!(!ns.save_to_keyvault);
}
+
+ /// A chrome plan that sends its cookie store, a bookmarks file and tabs.
+ fn browser_plan() -> Plan {
+ let mut p = plan(true);
+ p.consent = vec![
+ ConsentItem {
+ kind: ConsentKind::Install,
+ key: "chrome".into(),
+ label: "Google Chrome".into(),
+ detail: "pinned".into(),
+ bytes: 0,
+ sensitive: false,
+ },
+ ConsentItem {
+ kind: ConsentKind::State,
+ key: "Default/Bookmarks".into(),
+ label: "Bookmarks".into(),
+ detail: "".into(),
+ bytes: 200,
+ sensitive: false,
+ },
+ ConsentItem {
+ kind: ConsentKind::Secret,
+ key: ".config/google-chrome/Default/Cookies".into(),
+ label: "Cookies".into(),
+ detail: "".into(),
+ bytes: 800,
+ sensitive: true,
+ },
+ ];
+ p.total_bytes = 1000;
+ p
+ }
+
+ fn inventory() -> KvInventory {
+ use crate::keyvault::wire::KvDomainCount;
+ let d = |domain: &str, cookies: u32, signin: bool, idp: bool| KvDomainCount {
+ domain: domain.into(),
+ cookies,
+ signin,
+ identity_provider: idp,
+ ..Default::default()
+ };
+ KvInventory {
+ provider_id: "chrome".into(),
+ app_display: "Google Chrome".into(),
+ domains: vec![
+ d("github.com", 12, true, false),
+ d("google.com", 30, true, true),
+ d("notion.so", 4, true, false),
+ d("doubleclick.net", 9, false, false),
+ ],
+ notes: vec![],
+ }
+ }
+
+ fn review_state() -> PickerState {
+ let s = reduce(
+ &consent_state(),
+ &PickerEvent::Planned {
+ plan: browser_plan(),
+ },
+ );
+ reduce(&s, &PickerEvent::Acknowledge { value: true })
+ }
+
+ /// The browser's sites are asked for once, start minimal (or from what
+ /// was picked last time), and the consent carries exactly the chosen ones.
+ #[test]
+ fn the_review_lists_sites_with_counts_and_sends_only_the_chosen_ones() {
+ let s = review_state();
+ let rv = review(&s).unwrap();
+ assert!(rv.offers_domains && rv.needs_domains && rv.domains.is_empty());
+ assert_eq!(
+ rv.toggles
+ .iter()
+ .map(|t| t.key.as_str())
+ .collect::<Vec<_>>(),
+ ["Default/Bookmarks", ".config/google-chrome/Default/Cookies"],
+ "until the sites are listed the cookie line is a plain line"
+ );
+ assert!(consent(&s).cookie_domains.is_none());
+
+ let s = reduce(
+ &s,
+ &PickerEvent::DomainsLoaded {
+ inventory: inventory(),
+ remembered: None,
+ },
+ );
+ let rv = review(&s).unwrap();
+ assert!(!rv.needs_domains);
+ assert_eq!(
+ rv.domain_summary, "2 of 4 sites",
+ "minimal: sign-in sites, never an identity provider"
+ );
+ assert_eq!(rv.selected_domains, ["github.com", "notion.so"]);
+ assert_eq!(rv.domains[0].counts, "9 cookies");
+ assert_eq!(
+ rv.toggles
+ .iter()
+ .map(|t| t.key.as_str())
+ .collect::<Vec<_>>(),
+ ["Default/Bookmarks"],
+ "the cookie line is now the site list"
+ );
+ assert_eq!(
+ consent(&s).cookie_domains,
+ Some(vec!["github.com".to_string(), "notion.so".to_string()])
+ );
+
+ // Pick one more, drop one, search, turn the bookmarks off.
+ let s = reduce(
+ &s,
+ &PickerEvent::ToggleDomain {
+ domain: "google.com".into(),
+ },
+ );
+ let s = reduce(
+ &s,
+ &PickerEvent::ToggleDomain {
+ domain: "github.com".into(),
+ },
+ );
+ let s = reduce(
+ &s,
+ &PickerEvent::ToggleItem {
+ key: "Default/Bookmarks".into(),
+ },
+ );
+ let s = reduce(
+ &s,
+ &PickerEvent::ToggleItem {
+ key: "chrome".into(),
+ },
+ );
+ let s = reduce(
+ &s,
+ &PickerEvent::ToggleItem {
+ key: "unknown".into(),
+ },
+ );
+ let c = consent(&s);
+ assert_eq!(
+ c.cookie_domains,
+ Some(vec!["google.com".to_string(), "notion.so".to_string()])
+ );
+ assert_eq!(
+ c.exclude,
+ ["Default/Bookmarks"],
+ "installs and unknown lines cannot be turned off"
+ );
+ assert!(c.approved && c.from_vault.is_none());
+ let rv = review(&s).unwrap();
+ assert_eq!(rv.leaves_text.as_deref(), Some("800 B leaves this Mac"));
+ let s2 = reduce(&s, &PickerEvent::DomainQuery { text: "not".into() });
+ assert_eq!(review(&s2).unwrap().domains.len(), 1);
+ let s3 = reduce(&s2, &PickerEvent::SelectShownDomains { value: false });
+ assert_eq!(
+ consent(&s3).cookie_domains,
+ Some(vec!["google.com".to_string()])
+ );
+
+ // No sites chosen: no cookies leave, and the bytes follow.
+ let none = reduce(&s, &PickerEvent::SelectShownDomains { value: false });
+ let none = reduce(
+ &none,
+ &PickerEvent::DomainQuery {
+ text: String::new(),
+ },
+ );
+ let none = reduce(&none, &PickerEvent::SelectShownDomains { value: false });
+ assert_eq!(consent(&none).cookie_domains, Some(vec![]));
+ assert_eq!(review(&none).unwrap().leaves_text, None);
+
+ // What was picked last time wins over the minimal default.
+ let r = reduce(
+ &review_state(),
+ &PickerEvent::DomainsLoaded {
+ inventory: inventory(),
+ remembered: Some(vec!["doubleclick.net".into()]),
+ },
+ );
+ assert_eq!(review(&r).unwrap().selected_domains, ["doubleclick.net"]);
+
+ // A failed read leaves the plan as it was.
+ let f = reduce(&review_state(), &PickerEvent::DomainsFailed);
+ assert!(!review(&f).unwrap().needs_domains);
+ assert!(consent(&f).cookie_domains.is_none());
+ // Going Back forgets the choices.
+ assert_eq!(
+ reduce(&s, &PickerEvent::Back).choice,
+ ReviewChoice::default()
+ );
+ }
+
+ /// Sending from the Keyvault: offered only when the app has saved items,
+ /// reads nothing from the host, needs a selection, and carries the ids.
+ #[test]
+ fn the_review_can_send_the_apps_saved_keyvault_items_instead_of_reading_it() {
+ let s = review_state();
+ assert!(!review(&s).unwrap().offers_vault);
+ // Not offered: choosing it does nothing.
+ let nope = reduce(
+ &s,
+ &PickerEvent::SendFrom {
+ source: SendSource::Vault,
+ },
+ );
+ assert_eq!(review(&nope).unwrap().source, SendSource::Live);
+
+ let now = 1_800_000_000_000_i64;
+ let s = reduce(
+ &s,
+ &PickerEvent::VaultItems {
+ count: 212,
+ newest_ms: now - 2 * 24 * 3_600_000,
+ now_ms: now,
+ selected: vec!["a".into(), "b".into()],
+ password_ids: vec![],
+ },
+ );
+ let rv = review(&s).unwrap();
+ assert!(rv.offers_vault);
+ assert_eq!(
+ rv.vault_label,
+ "Send from the Keyvault (212 items, saved 2 days ago)"
+ );
+ assert_eq!(
+ rv.source,
+ SendSource::Live,
+ "reading the live app stays the default"
+ );
+ assert!(rv.source_note.contains("Keychain access"));
+
+ let s = reduce(
+ &s,
+ &PickerEvent::SendFrom {
+ source: SendSource::Vault,
+ },
+ );
+ let rv = review(&s).unwrap();
+ assert_eq!(rv.source, SendSource::Vault);
+ assert!(
+ !rv.offers_domains,
+ "no sites to pick: the saved items are the list"
+ );
+ assert!(rv.source_note.contains("Nothing is read from this Mac"));
+ assert_eq!(
+ rv.leaves_text.as_deref(),
+ Some("2 saved items from the Keyvault")
+ );
+ let c = consent(&s);
+ assert_eq!(c.from_vault, Some(vec!["a".to_string(), "b".to_string()]));
+ assert!(c.cookie_domains.is_none() && !c.save_to_keyvault);
+ assert!(c.approved);
+
+ // Nothing selected: nothing to send.
+ let empty = reduce(&s, &PickerEvent::VaultSelection { selected: vec![] });
+ assert!(!review(&empty).unwrap().can_confirm);
+ assert!(!consent(&empty).approved);
+ let back = reduce(
+ &empty,
+ &PickerEvent::VaultSelection {
+ selected: vec!["c".into()],
+ },
+ );
+ assert_eq!(consent(&back).from_vault, Some(vec!["c".to_string()]));
+
+ // The saved items vanished (deleted): back to the live app.
+ let gone = reduce(
+ &s,
+ &PickerEvent::VaultItems {
+ count: 0,
+ newest_ms: 0,
+ now_ms: now,
+ selected: vec![],
+ password_ids: vec![],
+ },
+ );
+ assert_eq!(review(&gone).unwrap().source, SendSource::Live);
+ assert!(!review(&gone).unwrap().offers_vault);
+ }
+
+ /// Saved passwords are offered, off by default, never remembered, and
+ /// ticking them adds exactly their ids (from the Keyvault) or the chosen
+ /// sites' passwords (from the app), needs the secrets acknowledged, and
+ /// is refused where there are none.
+ #[test]
+ fn saved_passwords_are_an_explicit_choice_in_the_review() {
+ let now = 1_800_000_000_000_i64;
+ let s = review_state();
+ // Nothing to send: the toggle does nothing and is not offered.
+ let nope = reduce(&s, &PickerEvent::TogglePasswords { value: true });
+ assert!(!review(&nope).unwrap().offers_passwords);
+ assert!(!consent(&nope).include_passwords);
+
+ // From the Keyvault: its password items are offered, off.
+ let s = reduce(
+ &s,
+ &PickerEvent::VaultItems {
+ count: 2,
+ newest_ms: now,
+ now_ms: now,
+ selected: vec!["a".into(), "b".into()],
+ password_ids: vec!["p1".into(), "p2".into(), "p3".into()],
+ },
+ );
+ let s = reduce(
+ &s,
+ &PickerEvent::SendFrom {
+ source: SendSource::Vault,
+ },
+ );
+ let rv = review(&s).unwrap();
+ assert!(rv.offers_passwords && !rv.include_passwords);
+ assert_eq!(rv.passwords_label, "Also send 3 saved passwords");
+ let c = consent(&s);
+ assert!(!c.include_passwords);
+ assert_eq!(c.from_vault, Some(vec!["a".to_string(), "b".to_string()]));
+
+ let on = reduce(&s, &PickerEvent::TogglePasswords { value: true });
+ let c = consent(&on);
+ assert!(c.include_passwords);
+ assert_eq!(
+ c.from_vault,
+ Some(
+ ["a", "b", "p1", "p2", "p3"]
+ .iter()
+ .map(|x| x.to_string())
+ .collect()
+ )
+ );
+ assert!(
+ review(&on).unwrap().needs_acknowledgement,
+ "a password is a secret that must be acknowledged"
+ );
+ // Off again, and a different source forgets nothing but also sends none.
+ let off = reduce(&on, &PickerEvent::TogglePasswords { value: false });
+ assert!(!consent(&off).include_passwords);
+ }
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/teleport/mod.rs b/libs/cua/crates/cua-spaces-app-core/src/teleport/mod.rs
index 29508223e7..63e2f17ed4 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/teleport/mod.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/teleport/mod.rs
@@ -5,6 +5,8 @@
//!
//! - [`flow`]: "Teleport an app..." (pick, options, plan, the consent review
//! with its secrets acknowledgement, run, done);
+//! - [`review`]: the review's choice of what to send (sites with counts,
+//! items, the Keyvault as the source) and what is remembered per Space;
//! - [`windows`]: the window lists (open windows here, a Space's remote
//! windows), their filters and the primary button;
//! - [`drag`]: dragging a real window to the notch;
@@ -16,5 +18,6 @@
pub mod drag;
pub mod flow;
pub mod grid;
+pub mod review;
pub mod transfer;
pub mod windows;
diff --git a/libs/cua/crates/cua-spaces-app-core/src/teleport/review.rs b/libs/cua/crates/cua-spaces-app-core/src/teleport/review.rs
new file mode 100644
index 0000000000..8604fc046e
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/teleport/review.rs
@@ -0,0 +1,450 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The review's choice of what to send.
+//!
+//! The consent review is the vault list again: for a browser the user picks
+//! which sites (domains) and which other items to send instead of the whole
+//! profile, with counts per site; and they can choose to send from the saved
+//! Keyvault items of the app instead of reading the live app (no fresh
+//! capture, so the host's Keychain is never asked).
+//!
+//! What was picked last time for an app and a Space is remembered (a list of
+//! sites per `app|space`); a first review starts from a minimal default:
+//! only the sites that look like they keep a sign-in, and never an identity
+//! provider (its session unlocks other apps). Pure shaping: the SDK's
+//! approval check (`cua_teleport::ux`) enforces what is sent.
+
+use crate::keyvault::vault::site_of;
+use crate::keyvault::wire::{KvDomainCount, KvInventory};
+use crate::util::collate;
+use serde::{Deserialize, Serialize};
+
+/// Where the review sends from.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SendSource {
+ /// Read the live app now (a browser's cookies are decrypted, so macOS asks
+ /// for Keychain access).
+ #[default]
+ Live,
+ /// Send the items saved in the Keyvault for this app. Nothing is read from
+ /// the host.
+ Vault,
+}
+
+/// What the user picked last time for one app and Space.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct RememberedChoice {
+ /// `<app>|<space>`.
+ pub key: String,
+ /// The sites (registrable domains) that were sent.
+ pub domains: Vec<String>,
+}
+
+/// The key a choice is remembered under.
+pub fn remember_key(app: &str, space: &str) -> String {
+ format!("{app}|{space}")
+}
+
+/// What was picked last time for `key`, if anything.
+pub fn remembered(choices: &[RememberedChoice], key: &str) -> Option<Vec<String>> {
+ choices
+ .iter()
+ .find(|c| c.key == key)
+ .map(|c| c.domains.clone())
+}
+
+/// `choices` with `domains` remembered for `key` (replacing any earlier
+/// choice; the list stays bounded).
+pub fn remember(
+ choices: &[RememberedChoice],
+ key: &str,
+ domains: &[String],
+) -> Vec<RememberedChoice> {
+ const MAX: usize = 64;
+ let mut out: Vec<RememberedChoice> = choices.iter().filter(|c| c.key != key).cloned().collect();
+ out.push(RememberedChoice {
+ key: key.into(),
+ domains: domains.to_vec(),
+ });
+ let excess = out.len().saturating_sub(MAX);
+ out.drain(..excess);
+ out
+}
+
+/// One site of a browser, with its counts.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ReviewDomain {
+ /// The site (`github.com`).
+ pub domain: String,
+ /// "12 cookies, 2 storage values".
+ pub counts: String,
+ /// Items the site holds.
+ pub count: u32,
+ /// It looks like it keeps a sign-in.
+ pub signin: bool,
+ /// An identity provider: its session unlocks other apps.
+ pub identity_provider: bool,
+ /// Chosen to send.
+ pub selected: bool,
+ /// Can be chosen: it holds something that can be sent. A site whose
+ /// cookies are all unreadable is greyed out.
+ pub selectable: bool,
+ /// Cookies that cannot be read, shown greyed with `unavailable_note`.
+ pub unavailable: u32,
+ /// "3 cookies cannot be sent: Chrome protects them with ...", or empty.
+ pub unavailable_note: String,
+}
+
+/// A non-cookie consent line the user can turn off.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ReviewToggle {
+ /// The consent item's key.
+ pub key: String,
+ /// Label.
+ pub label: String,
+ /// Detail.
+ pub detail: String,
+ /// Bytes that leave.
+ pub bytes: u64,
+ /// A secret.
+ pub sensitive: bool,
+ /// Sent (not turned off).
+ pub selected: bool,
+}
+
+/// The saved Keyvault items of the app being teleported.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultSource {
+ /// The app has saved items that can be sent (passwords never are).
+ pub available: bool,
+ /// How many.
+ pub items: u32,
+ /// "saved 2 days ago".
+ pub saved: String,
+ /// The items chosen to send (ids).
+ pub selected: Vec<String>,
+ /// The app's saved passwords (ids), sent only when ticked.
+ #[serde(default)]
+ pub password_ids: Vec<String>,
+}
+
+/// The review's choices.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ReviewChoice {
+ /// Where to send from.
+ pub source: SendSource,
+ /// The browser's sites with counts (none until read, or for an app that
+ /// is not a browser).
+ pub domains: Vec<KvDomainCount>,
+ /// The sites chosen.
+ pub selected_domains: Vec<String>,
+ /// The sites list's search text.
+ pub query: String,
+ /// Consent items (keys) turned off.
+ pub excluded: Vec<String>,
+ /// The saved items.
+ pub vault: VaultSource,
+ /// The sites were asked for (a failure counts: the review then sends
+ /// what the plan lists).
+ #[serde(default)]
+ pub loaded: bool,
+ /// The saved passwords are ticked to send (off unless the user ticks
+ /// them; never remembered).
+ #[serde(default)]
+ pub include_passwords: bool,
+}
+
+/// The sites the minimal default picks: those that look like they keep a
+/// sign-in, never an identity provider.
+pub fn default_domains(domains: &[KvDomainCount]) -> Vec<String> {
+ domains
+ .iter()
+ .filter(|d| d.signin && !d.identity_provider && sendable(d))
+ .map(|d| d.domain.clone())
+ .collect()
+}
+
+/// The choice after the inventory arrived: what was picked last time (only
+/// the sites that still exist), else the minimal default.
+pub fn with_inventory(
+ mut c: ReviewChoice,
+ inventory: &KvInventory,
+ remembered: Option<&[String]>,
+) -> ReviewChoice {
+ let mut domains = inventory.domains.clone();
+ domains.sort_by(|a, b| collate(&a.domain, &b.domain));
+ c.selected_domains = match remembered {
+ Some(r) => domains
+ .iter()
+ .filter(|d| r.iter().any(|x| site_of(x) == d.domain))
+ .map(|d| d.domain.clone())
+ .collect(),
+ None => default_domains(&domains),
+ };
+ c.domains = domains;
+ c
+}
+
+/// The site holds something that can be sent.
+fn sendable(d: &KvDomainCount) -> bool {
+ d.cookies + d.local_storage + d.passwords > 0
+}
+
+fn unavailable_note(d: &KvDomainCount) -> String {
+ if d.unavailable == 0 {
+ return String::new();
+ }
+ format!(
+ "{} cookie{} cannot be sent: {}",
+ d.unavailable,
+ if d.unavailable == 1 { "" } else { "s" },
+ d.unavailable_reason
+ )
+}
+
+fn counts_text(d: &KvDomainCount) -> String {
+ let mut parts = Vec::new();
+ let mut add = |n: u32, one: &str, many: &str| {
+ if n > 0 {
+ parts.push(format!("{n} {}", if n == 1 { one } else { many }));
+ }
+ };
+ add(d.cookies, "cookie", "cookies");
+ add(d.local_storage, "storage value", "storage values");
+ add(d.passwords, "password", "passwords");
+ parts.join(", ")
+}
+
+/// The sites as the review lists them (filtered by the search text).
+pub fn domain_rows(c: &ReviewChoice) -> Vec<ReviewDomain> {
+ let words: Vec<String> = c
+ .query
+ .split_whitespace()
+ .map(|w| w.to_lowercase())
+ .collect();
+ c.domains
+ .iter()
+ .filter(|d| words.iter().all(|w| d.domain.to_lowercase().contains(w)))
+ .map(|d| ReviewDomain {
+ counts: counts_text(d),
+ count: d.cookies + d.local_storage + d.passwords,
+ signin: d.signin,
+ identity_provider: d.identity_provider,
+ selected: c.selected_domains.contains(&d.domain),
+ selectable: sendable(d),
+ unavailable: d.unavailable,
+ unavailable_note: unavailable_note(d),
+ domain: d.domain.clone(),
+ })
+ .collect()
+}
+
+/// "3 of 12 sites".
+pub fn domain_summary(c: &ReviewChoice) -> String {
+ format!(
+ "{} of {} site{}",
+ c.selected_domains.len(),
+ c.domains.len(),
+ if c.domains.len() == 1 { "" } else { "s" }
+ )
+}
+
+/// Toggles one site.
+pub fn toggle_domain(c: &mut ReviewChoice, domain: &str) {
+ if !c.domains.iter().any(|d| d.domain == domain && sendable(d)) {
+ return;
+ }
+ match c.selected_domains.iter().position(|d| d == domain) {
+ Some(n) => {
+ c.selected_domains.remove(n);
+ }
+ None => c.selected_domains.push(domain.into()),
+ }
+ sort_selected(c);
+}
+
+/// Selects or clears every site the search shows.
+pub fn set_shown_domains(c: &mut ReviewChoice, value: bool) {
+ let shown: Vec<String> = domain_rows(c)
+ .into_iter()
+ .filter(|r| r.selectable)
+ .map(|r| r.domain)
+ .collect();
+ c.selected_domains.retain(|d| !shown.contains(d));
+ if value {
+ c.selected_domains.extend(shown);
+ }
+ sort_selected(c);
+}
+
+fn sort_selected(c: &mut ReviewChoice) {
+ let order: Vec<&str> = c.domains.iter().map(|d| d.domain.as_str()).collect();
+ c.selected_domains
+ .sort_by_key(|d| order.iter().position(|x| x == d).unwrap_or(usize::MAX));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn d(domain: &str, cookies: u32, ls: u32, signin: bool, idp: bool) -> KvDomainCount {
+ KvDomainCount {
+ domain: domain.into(),
+ cookies,
+ session_cookies: 0,
+ local_storage: ls,
+ passwords: 0,
+ signin,
+ identity_provider: idp,
+ unavailable: 0,
+ unavailable_reason: String::new(),
+ }
+ }
+
+ fn inventory() -> KvInventory {
+ KvInventory {
+ provider_id: "chrome".into(),
+ app_display: "Google Chrome".into(),
+ domains: vec![
+ d("notion.so", 4, 2, true, false),
+ d("github.com", 12, 0, true, false),
+ d("google.com", 30, 0, true, true),
+ d("doubleclick.net", 9, 0, false, false),
+ ],
+ notes: vec![],
+ }
+ }
+
+ #[test]
+ fn the_first_review_starts_minimal_and_never_picks_an_identity_provider() {
+ let c = with_inventory(ReviewChoice::default(), &inventory(), None);
+ assert_eq!(
+ c.domains
+ .iter()
+ .map(|x| x.domain.as_str())
+ .collect::<Vec<_>>(),
+ ["doubleclick.net", "github.com", "google.com", "notion.so"],
+ "listed by name"
+ );
+ assert_eq!(c.selected_domains, ["github.com", "notion.so"]);
+ let rows = domain_rows(&c);
+ assert_eq!(rows[1].counts, "12 cookies");
+ assert_eq!(rows[3].counts, "4 cookies, 2 storage values");
+ assert!(rows[2].identity_provider && !rows[2].selected);
+ assert_eq!(domain_summary(&c), "2 of 4 sites");
+ }
+
+ #[test]
+ fn what_was_picked_last_time_wins_over_the_default() {
+ let remembered = vec![
+ "google.com".to_string(),
+ "gone.test".to_string(),
+ "api.github.com".to_string(),
+ ];
+ let c = with_inventory(ReviewChoice::default(), &inventory(), Some(&remembered));
+ assert_eq!(
+ c.selected_domains,
+ ["github.com", "google.com"],
+ "a remembered host maps to its site; a site that no longer exists is dropped"
+ );
+ // Remembering replaces the earlier choice for the same app and Space,
+ // and keeps others.
+ let key = remember_key("chrome", "aurora");
+ let a = remember(&[], &key, &["github.com".into()]);
+ let b = remember(&a, "chrome|dev-1", &["notion.so".into()]);
+ let c2 = remember(&b, &key, &["notion.so".into(), "github.com".into()]);
+ assert_eq!(remembered_of(&c2, &key), vec!["notion.so", "github.com"]);
+ assert_eq!(remembered_of(&c2, "chrome|dev-1"), vec!["notion.so"]);
+ assert!(super::remembered(&c2, "chrome|other").is_none());
+ // Bounded.
+ let mut many = vec![];
+ for i in 0..100 {
+ many = remember(&many, &format!("a|{i}"), &[]);
+ }
+ assert_eq!(many.len(), 64);
+ assert_eq!(many.last().unwrap().key, "a|99");
+ }
+
+ fn remembered_of(c: &[RememberedChoice], key: &str) -> Vec<String> {
+ super::remembered(c, key).unwrap()
+ }
+
+ #[test]
+ fn toggling_and_searching_sites() {
+ let mut c = with_inventory(ReviewChoice::default(), &inventory(), None);
+ toggle_domain(&mut c, "google.com");
+ assert_eq!(
+ c.selected_domains,
+ ["github.com", "google.com", "notion.so"]
+ );
+ toggle_domain(&mut c, "github.com");
+ toggle_domain(&mut c, "nope.test");
+ assert_eq!(c.selected_domains, ["google.com", "notion.so"]);
+ // Select all shown follows the search.
+ c.query = "git".into();
+ assert_eq!(domain_rows(&c).len(), 1);
+ set_shown_domains(&mut c, true);
+ assert_eq!(
+ c.selected_domains,
+ ["github.com", "google.com", "notion.so"]
+ );
+ set_shown_domains(&mut c, false);
+ assert_eq!(
+ c.selected_domains,
+ ["google.com", "notion.so"],
+ "the rest are kept"
+ );
+ c.query.clear();
+ set_shown_domains(&mut c, false);
+ assert!(c.selected_domains.is_empty());
+ set_shown_domains(&mut c, true);
+ assert_eq!(c.selected_domains.len(), 4);
+ }
+
+ #[test]
+ fn unreadable_cookies_are_greyed_with_why_and_never_selected() {
+ let mut bank = d("bank.test", 0, 0, true, false);
+ bank.unavailable = 3;
+ bank.unavailable_reason = "Chrome protects it with app-bound encryption".into();
+ let mut mixed = d("mixed.test", 2, 0, true, false);
+ mixed.unavailable = 1;
+ mixed.unavailable_reason = "Chrome protects it with app-bound encryption".into();
+ let inv = KvInventory {
+ provider_id: "chrome".into(),
+ domains: vec![bank, mixed, d("plain.test", 1, 0, true, false)],
+ ..Default::default()
+ };
+ let mut c = with_inventory(ReviewChoice::default(), &inv, None);
+ // Only what can be sent is picked by default.
+ assert_eq!(c.selected_domains, ["mixed.test", "plain.test"]);
+ let rows = domain_rows(&c);
+ let by = |n: &str| rows.iter().find(|r| r.domain == n).unwrap();
+ assert!(!by("bank.test").selectable);
+ assert_eq!(
+ by("bank.test").unavailable_note,
+ "3 cookies cannot be sent: Chrome protects it with app-bound encryption"
+ );
+ assert!(by("mixed.test").selectable);
+ assert_eq!(
+ by("mixed.test").count,
+ 2,
+ "the unreadable one is not counted"
+ );
+ assert!(
+ by("mixed.test")
+ .unavailable_note
+ .starts_with("1 cookie cannot")
+ );
+ assert!(by("plain.test").unavailable_note.is_empty());
+ // It cannot be toggled on, singly or with select all.
+ toggle_domain(&mut c, "bank.test");
+ set_shown_domains(&mut c, true);
+ assert_eq!(c.selected_domains, ["mixed.test", "plain.test"]);
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/tests/keyvault_credential.rs b/libs/cua/crates/cua-spaces-app-core/tests/keyvault_credential.rs
index b80efd2963..cbea2bef9e 100644
--- a/libs/cua/crates/cua-spaces-app-core/tests/keyvault_credential.rs
+++ b/libs/cua/crates/cua-spaces-app-core/tests/keyvault_credential.rs
@@ -12,7 +12,7 @@ use std::sync::Arc;
use cua_keyvault::broker::{
Backend, BrokerConfig, Captured, DeliveryOutcome, FakePresence, ImportSpec, Inventory,
};
-use cua_keyvault::model::ItemPayload;
+use cua_keyvault::model::PayloadEntry;
use cua_keyvault::{Broker, CallerIdentity, Zeroizing};
use cua_spaces_app_core::keyvault::client::{DirectTransport, KeyvaultCommands};
use cua_spaces_app_core::keyvault::credential::{KvFormMode, KvMethod};
@@ -32,7 +32,8 @@ impl Backend for NoBackend {
&self,
_target: &str,
_provider_id: &str,
- _payloads: Vec<ItemPayload>,
+ _scope: &str,
+ _entries: Vec<PayloadEntry>,
_expires_ms: u64,
) -> cua_keyvault::Result<DeliveryOutcome> {
Err(cua_keyvault::Error::Unsupported("test".into()))
@@ -115,3 +116,242 @@ async fn a_development_daemon_sets_up_and_unlocks_with_a_passphrase() {
.unwrap();
assert_eq!(page.overview().await.availability, "ready");
}
+
+/// A backend that captures a small fixed profile and records what is
+/// delivered and wiped.
+#[derive(Default)]
+struct Profile {
+ delivered: std::sync::Mutex<Vec<(String, Vec<String>)>>,
+ wiped: std::sync::Mutex<Vec<String>>,
+}
+
+#[async_trait::async_trait]
+impl Backend for Profile {
+ fn inventory(&self, app: &str, _profile: Option<&str>) -> cua_keyvault::Result<Inventory> {
+ Ok(Inventory {
+ provider_id: app.into(),
+ app_display: "Google Chrome".into(),
+ domains: vec![cua_keyvault::broker::DomainInventory {
+ domain: "github.com".into(),
+ cookies: 2,
+ signin: true,
+ ..Default::default()
+ }],
+ ..Default::default()
+ })
+ }
+ fn capture(&self, spec: &ImportSpec) -> cua_keyvault::Result<Vec<Captured>> {
+ use cua_keyvault::record;
+ let mut out = Vec::new();
+ for host in [".github.com", "api.github.com", ".notion.so"] {
+ let n = record::cookie_record(&record::CookieRecord {
+ creation_utc: None,
+ expires_utc: 0,
+ host_key: host.into(),
+ http_only: true,
+ last_update_utc: None,
+ name: "session".into(),
+ partition_key: None,
+ last_access_utc: None,
+ source_type: None,
+ has_cross_site_ancestor: None,
+ path: "/".into(),
+ priority: None,
+ same_site: 1,
+ secure: true,
+ source_port: None,
+ source_scheme: None,
+ value: b"cookie-value-SECRET".to_vec(),
+ })?;
+ let (meta, payload) = n.into_item(&spec.app, "Google Chrome", "Default", "full");
+ out.push(Captured { meta, payload });
+ }
+ let n = record::file_record("Default/Bookmarks", 0o600, b"{}")?;
+ let (meta, payload) = n.into_item(&spec.app, "Google Chrome", "Default", "full");
+ out.push(Captured { meta, payload });
+ Ok(out)
+ }
+ async fn deliver(
+ &self,
+ target: &str,
+ _provider_id: &str,
+ _scope: &str,
+ entries: Vec<PayloadEntry>,
+ _expires_ms: u64,
+ ) -> cua_keyvault::Result<DeliveryOutcome> {
+ let mut d = self.delivered.lock().unwrap();
+ d.push((
+ target.into(),
+ entries.iter().map(|e| e.rel_path.clone()).collect(),
+ ));
+ Ok(DeliveryOutcome {
+ import_id: format!("imp-{}", d.len()),
+ ..Default::default()
+ })
+ }
+ async fn wipe(&self, _target: &str, import_id: &str) -> cua_keyvault::Result<Vec<String>> {
+ self.wiped.lock().unwrap().push(import_id.into());
+ Ok(vec![])
+ }
+}
+
+/// The page, end to end through the shells' client over a real broker: names
+/// stay hidden until the browse window opens, the list groups by app and
+/// site, items lock and unlock in one batch, "Never ask again" is stored,
+/// delete wipes the live copy, and no value is ever in what the page sees.
+#[tokio::test]
+async fn the_vault_page_end_to_end_through_the_client() {
+ use cua_spaces_app_core::keyvault::KvCommand;
+ use cua_spaces_app_core::keyvault::client::KvOutcome;
+ use cua_spaces_app_core::keyvault::vault::{self, VaultAction, VaultState};
+
+ let dir = tempfile::tempdir().unwrap();
+ let presence = Arc::new(FakePresence::new(true));
+ let backend = Arc::new(Profile::default());
+ let broker = Arc::new(
+ Broker::new(
+ BrokerConfig {
+ dir: dir.path().join("keyvault"),
+ keychain_path: None,
+ os_protector: false,
+ },
+ backend.clone(),
+ presence.clone(),
+ )
+ .unwrap(),
+ );
+ let cua = CallerIdentity::for_tests("com.trycua.spaces.macos", true);
+ let page = KeyvaultCommands::new(Arc::new(DirectTransport {
+ broker: broker.clone(),
+ caller: cua.clone(),
+ }));
+ page.setup_with_passphrase(secret("orbit lantern pickle harbor"))
+ .await
+ .unwrap();
+ broker
+ .import(
+ &cua,
+ ImportSpec {
+ app: "chrome".into(),
+ whole_app: true,
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+
+ // Names are hidden until the user confirms with Touch ID.
+ let o = page.overview().await;
+ assert_eq!(o.items.len(), 4);
+ assert!(!o.names_visible);
+ let v = vault::view(&o, &VaultState::default(), 0);
+ assert!(v.names_hidden);
+ assert_eq!(v.apps[0].count, 4, "counts survive");
+ let asked = presence.asked.lock().unwrap().len();
+ let KvOutcome::Browsing { until_ms } = page.execute(&KvCommand::Browse).await.unwrap() else {
+ panic!("browsing")
+ };
+ assert!(until_ms > 0);
+ assert_eq!(presence.asked.lock().unwrap().len(), asked + 1);
+ let o = page.overview().await;
+ assert!(o.names_visible);
+ let st = VaultState::default();
+ let v = vault::view(&o, &st, 0);
+ assert!(!v.names_hidden);
+ assert_eq!(v.apps.len(), 1);
+ assert_eq!(v.apps[0].name, "Google Chrome");
+ assert_eq!(
+ v.apps[0]
+ .sites
+ .iter()
+ .map(|s| (s.site.as_str(), s.count))
+ .collect::<Vec<_>>(),
+ [("github.com", 2), ("notion.so", 1)]
+ );
+ assert_eq!(v.apps[0].files.as_ref().unwrap().count, 1);
+ // Nothing the page was handed carries a value.
+ assert!(
+ !serde_json::to_string(&o)
+ .unwrap()
+ .contains("cookie-value-SECRET")
+ );
+
+ // Select github.com and unlock it: one presence for the batch.
+ let st = vault::reduce(
+ &o,
+ &st,
+ &VaultAction::ToggleGroup {
+ key: "chrome|github.com".into(),
+ },
+ );
+ let sel = vault::view(&o, &st, 0).selection;
+ assert_eq!(sel.unlock_ids.len(), 2);
+ let asked = presence.asked.lock().unwrap().len();
+ let KvOutcome::Locked { changed, skipped } = page
+ .execute(&vault::unlock_command(&sel.unlock_ids))
+ .await
+ .unwrap()
+ else {
+ panic!("locked")
+ };
+ assert_eq!((changed.len(), skipped.len()), (2, 0));
+ assert_eq!(
+ presence.asked.lock().unwrap().len(),
+ asked + 1,
+ "one Touch ID for the batch"
+ );
+ let o = page.overview().await;
+ let v = vault::view(&o, &VaultState::default(), 0);
+ assert_eq!(v.apps[0].sites[0].lock, vault::KvLock::Unlocked);
+ assert_eq!(v.apps[0].sites[1].lock, vault::KvLock::Locked);
+ assert_eq!(v.apps[0].summary, "4 items, 2 unlocked");
+
+ // "Never ask again" is stored in the vault and visible to the page.
+ assert!(vault::unlock_prompt(&o, 1, None).is_some());
+ page.execute(&KvCommand::SetSkipUnlockPrompt { on: true })
+ .await
+ .unwrap();
+ let o = page.overview().await;
+ assert!(vault::unlock_prompt(&o, 1, None).is_none());
+ assert!(view::page(&o, 0).skip_unlock_prompt);
+ page.execute(&KvCommand::SetSkipUnlockPrompt { on: false })
+ .await
+ .unwrap();
+ assert!(vault::unlock_prompt(&page.overview().await, 1, None).is_some());
+
+ // Teleport github.com's items, then delete them: the copy is wiped.
+ broker
+ .teleport(
+ &cua,
+ cua_keyvault::broker::TeleportRequest {
+ token: None,
+ items: sel.unlock_ids.clone(),
+ target: "dev-1".into(),
+ include_passwords: false,
+ launch: false,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(backend.delivered.lock().unwrap()[0].1, ["cookies.json"]);
+ let o = page.overview().await;
+ assert_eq!(
+ vault::live_copy_spaces(&o, &sel.unlock_ids, cua_keyvault::now_ms() as i64),
+ 1
+ );
+ let KvOutcome::Deleted { count, wiped } = page
+ .execute(&vault::delete_command(&sel.unlock_ids))
+ .await
+ .unwrap()
+ else {
+ panic!("deleted")
+ };
+ assert_eq!((count, wiped.len()), (2, 1));
+ assert_eq!(backend.wiped.lock().unwrap().len(), 1);
+ assert_eq!(page.overview().await.items.len(), 2);
+
+ // The inventory is a name map: it is shown over the open window, and
+ // never carries a value.
+ let inv = page.inventory("chrome", None).await.unwrap();
+ assert_eq!(inv.domains[0].domain, "github.com");
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/tests/wire_drift.rs b/libs/cua/crates/cua-spaces-app-core/tests/wire_drift.rs
index 082156184e..f2f19486cd 100644
--- a/libs/cua/crates/cua-spaces-app-core/tests/wire_drift.rs
+++ b/libs/cua/crates/cua-spaces-app-core/tests/wire_drift.rs
@@ -7,9 +7,7 @@
use cua_keyvault::audit::AuditEvent;
use cua_keyvault::broker::Status;
use cua_keyvault::caller::{CallerIdentity, Signing};
-use cua_keyvault::model::{
- Delivery, Grant, ItemKind, ItemMeta, ItemPolicy, ItemSummary, RuleCaller, UnattendedRule,
-};
+use cua_keyvault::model::{Delivery, Grant, ItemKind, ItemMeta, RuleCaller, UnattendedRule};
use cua_spaces_app_core::keyvault::{
KeyvaultOverview, KvCaller, KvDelivery, KvGrant, KvItem, KvRule, KvSigning, KvStatus,
};
@@ -22,27 +20,51 @@ fn round<T: serde::Serialize, U: serde::de::DeserializeOwned>(v: &T) -> U {
#[test]
fn items_callers_grants_rules_deliveries_status() {
- let item = ItemMeta {
- id: "i1".into(),
- kind: ItemKind::AppSession,
- label: "Slack (whole app session)".into(),
- provider_id: "slack".into(),
- app_display: "Slack".into(),
- site: None,
- account: Some("Example".into()),
- source: String::new(),
- summary: ItemSummary::default(),
- warnings: vec![],
- identity_provider: false,
- policy: ItemPolicy::default(),
- created_ms: 1,
- updated_ms: 2,
- rev: 3,
- record_digest: "00".into(),
- };
+ let mut item = ItemMeta::draft(
+ ItemKind::Cookie,
+ "chrome",
+ "Google Chrome",
+ Some(".github.com"),
+ "user_session",
+ );
+ item.id = "i1".into();
+ item.path = Some("/".into());
+ item.expires_ms = Some(1_900_000_000_000);
+ item.bytes = 12;
+ item.policy.unattended = true;
+ item.created_ms = 1;
+ item.updated_ms = 2;
+ item.rev = 3;
+ item.record_digest = "00".into();
let k: KvItem = round(&item);
- assert_eq!(k.kind, "app_session");
- assert_eq!(k.account.as_deref(), Some("Example"));
+ assert_eq!(k.kind, "cookie");
+ assert_eq!(k.domain.as_deref(), Some(".github.com"));
+ assert_eq!(k.key, "user_session");
+ assert_eq!(k.path.as_deref(), Some("/"));
+ assert!(k.policy.unattended);
+ // Every kind's wire tag is one the list knows.
+ for kind in [
+ ItemKind::Cookie,
+ ItemKind::LocalStorage,
+ ItemKind::Password,
+ ItemKind::File,
+ ] {
+ let tag = serde_json::to_value(kind).unwrap();
+ assert_eq!(tag, kind.tag(), "the serde tag is the stable tag");
+ assert_eq!(
+ cua_spaces_app_core::keyvault::vault::KvKind::from_wire(kind.tag()).label(),
+ kind.label()
+ );
+ }
+ // A redacted (no browse window) item still decodes.
+ let r: KvItem = round(&item.redacted());
+ assert!(r.domain.is_none() && r.key.is_empty());
+ let page = cua_keyvault::broker::ItemPage {
+ items: vec![item.clone()],
+ total: 1,
+ names_visible: true,
+ };
+ let _: Vec<KvItem> = round(&page.items);
for (signing, want) in [
(
@@ -97,6 +119,7 @@ fn items_callers_grants_rules_deliveries_status() {
uses_left: Some(1),
revoked: false,
agent: Some("ada".into()),
+ unattended: false,
};
let g: KvGrant = round(&grant);
assert_eq!(g.agent.as_deref(), Some("ada"));
@@ -143,10 +166,16 @@ fn items_callers_grants_rules_deliveries_status() {
cua_keyvault::protector::ProtectorKind::Passphrase,
cua_keyvault::protector::ProtectorKind::Recovery,
],
+ browse_until_ms: Some(9),
+ skip_unlock_prompt: Some(true),
+ reset_notice: Some("set aside".into()),
};
let kv: KvStatus = round(&st);
assert_eq!(kv.unlock_protectors, ["passphrase", "recovery"]);
assert_eq!(kv.auto_wipe, Some(true));
+ assert_eq!(kv.browse_until_ms, Some(9));
+ assert_eq!(kv.skip_unlock_prompt, Some(true));
+ assert_eq!(kv.reset_notice.as_deref(), Some("set aside"));
let ev = AuditEvent {
kind: "consent.allow".into(),
actor: "Cua".into(),
@@ -164,7 +193,7 @@ fn the_flow_fixture_is_a_valid_overview() {
let flow: serde_json::Value =
serde_json::from_str(include_str!("../parity/keyvault-approve-deny.json")).unwrap();
let o: KeyvaultOverview = serde_json::from_value(flow["overview"].clone()).unwrap();
- assert_eq!(o.items.len(), 4);
+ assert_eq!(o.items.len(), 8);
assert_eq!(o.pending.len(), 2);
}
@@ -175,3 +204,49 @@ fn the_passphrase_minimum_is_the_brokers() {
cua_keyvault::protector::MIN_PASSPHRASE_CHARS
);
}
+
+#[test]
+fn the_core_groups_sites_the_way_the_broker_does() {
+ for host in [
+ ".github.com",
+ "api.github.com",
+ "https://gist.github.com:8443/x",
+ "www.bbc.co.uk",
+ "localhost",
+ "127.0.0.1",
+ "http://127.0.0.1:8000",
+ "accounts.google.com",
+ ] {
+ assert_eq!(
+ cua_spaces_app_core::keyvault::vault::site_of(host),
+ cua_keyvault::record::site_of(host),
+ "{host}"
+ );
+ }
+}
+
+#[test]
+fn the_inventory_mirror_decodes_the_brokers() {
+ let inv = cua_keyvault::broker::Inventory {
+ provider_id: "chrome".into(),
+ app_display: "Google Chrome".into(),
+ profile: None,
+ domains: vec![cua_keyvault::broker::DomainInventory {
+ domain: "github.com".into(),
+ cookies: 4,
+ session_cookies: 1,
+ local_storage: 2,
+ passwords: 1,
+ signin: true,
+ identity_provider: false,
+ unavailable: 3,
+ unavailable_reason: "app-bound".into(),
+ }],
+ notes: vec!["n".into()],
+ };
+ let k: cua_spaces_app_core::keyvault::KvInventory = round(&inv);
+ assert_eq!(k.domains[0].cookies, 4);
+ assert_eq!(k.domains[0].unavailable, 3);
+ assert_eq!(k.domains[0].unavailable_reason, "app-bound");
+ assert!(k.domains[0].signin);
+}
diff --git a/libs/cua/crates/cua-spaces-cli/src/keyvault_cmd.rs b/libs/cua/crates/cua-spaces-cli/src/keyvault_cmd.rs
index 1d8935bfce..58686f43e2 100644
--- a/libs/cua/crates/cua-spaces-cli/src/keyvault_cmd.rs
+++ b/libs/cua/crates/cua-spaces-cli/src/keyvault_cmd.rs
@@ -359,7 +359,7 @@ pub async fn run(cmd: KeyvaultCmd, json: bool, out: &mut dyn Write) -> Result<i3
"The Cua daemon asks for Touch ID or your login password to import saved passwords."
);
}
- let items = c
+ let r = c
.import_passwords(cua_keyvault::broker::PasswordImportSpec {
app: a.browser,
profile: a.profile,
@@ -368,28 +368,11 @@ pub async fn run(cmd: KeyvaultCmd, json: bool, out: &mut dyn Write) -> Result<i3
.await
.map_err(kv_error)?;
if json {
- let rows: Vec<serde_json::Value> = items
- .iter()
- .map(|i| {
- serde_json::json!({"id": i.id, "site": i.site,
- "passwords": i.summary.passwords})
- })
- .collect();
- util::json_line(out, &serde_json::json!({ "imported": rows }));
- } else if items.is_empty() {
+ util::json_line(out, &serde_json::json!({ "imported": r }));
+ } else if r.saved == 0 {
line(out, "No saved passwords found.");
} else {
- for i in &items {
- line(
- out,
- format!(
- "{} {} saved password{}",
- i.site.as_deref().unwrap_or(&i.label),
- i.summary.passwords,
- if i.summary.passwords == 1 { "" } else { "s" }
- ),
- );
- }
+ line(out, import_summary(&r, "saved password"));
}
}
KeyvaultCmd::ImportSession(a) => {
@@ -419,44 +402,20 @@ pub async fn run(cmd: KeyvaultCmd, json: bool, out: &mut dyn Write) -> Result<i3
},
confirm_passwords: a.include_passwords,
paths: None,
+ domains: None,
+ passwords: false,
};
- let items = c.import(spec).await.map_err(kv_error)?;
+ let r = c.import(spec).await.map_err(kv_error)?;
if json {
- let rows: Vec<serde_json::Value> = items
- .iter()
- .map(|i| {
- serde_json::json!({"id": i.id, "label": i.label,
- "site": i.site, "cookies": i.summary.cookies.len(),
- "passwords": i.summary.passwords})
- })
- .collect();
- util::json_line(out, &serde_json::json!({ "imported": rows }));
- } else if items.is_empty() {
+ util::json_line(out, &serde_json::json!({ "imported": r }));
+ } else if r.saved == 0 {
line(out, "Nothing to import.");
} else {
- for i in &items {
- let what = match i.kind {
- cua_keyvault::ItemKind::BrowserSite => format!(
- "{} cookie{}",
- i.summary.cookies.len(),
- if i.summary.cookies.len() == 1 {
- ""
- } else {
- "s"
- }
- ),
- cua_keyvault::ItemKind::AppSession => "session".to_string(),
- cua_keyvault::ItemKind::SitePasswords => format!(
- "{} saved password{}",
- i.summary.passwords,
- if i.summary.passwords == 1 { "" } else { "s" }
- ),
- };
- line(out, format!("{} {what}", i.label));
- }
+ line(out, import_summary(&r, "item"));
line(
out,
- "Sealed in the Keyvault. Deliver it with `cua teleport push --sandbox NAME` \
+ "Sealed in the Keyvault, grouped by app. Saving the same app again updates \
+ these items. Deliver them with `cua teleport push --sandbox NAME` \
or the review sheet's \"Save to Keyvault\".",
);
}
@@ -470,7 +429,7 @@ pub async fn run(cmd: KeyvaultCmd, json: bool, out: &mut dyn Write) -> Result<i3
serde_json::json!({"id": p.id, "caller": p.caller_display,
"agent": p.request.agent, "actions": p.request.actions,
"targets": p.request.targets,
- "items": p.items.iter().map(|i| i.label.clone()).collect::<Vec<_>>()})
+ "items": p.items.iter().map(|i| i.redacted().label()).collect::<Vec<_>>()})
})
.collect();
util::json_line(out, &serde_json::json!({ "requests": rows }));
@@ -481,7 +440,14 @@ pub async fn run(cmd: KeyvaultCmd, json: bool, out: &mut dyn Write) -> Result<i3
let what: Vec<String> = p
.items
.iter()
- .map(|i| i.site.clone().unwrap_or_else(|| i.label.clone()))
+ .map(|i| {
+ i.domain
+ .as_deref()
+ .map(cua_keyvault::record::site_of)
+ .unwrap_or_else(|| i.label())
+ })
+ .collect::<std::collections::BTreeSet<_>>()
+ .into_iter()
.collect();
let verb = if p.request.actions.contains(&cua_keyvault::Action::Login) {
"sign in to"
@@ -530,6 +496,22 @@ pub async fn run(cmd: KeyvaultCmd, json: bool, out: &mut dyn Write) -> Result<i3
Ok(0)
}
+/// "Saved 4 items: 3 new, 1 updated" (counts only; never a name or a value).
+fn import_summary(r: &cua_keyvault::broker::ImportReport, noun: &str) -> String {
+ let plural = if r.saved == 1 { "" } else { "s" };
+ let mut parts = Vec::new();
+ if r.created > 0 {
+ parts.push(format!("{} new", r.created));
+ }
+ if r.updated > 0 {
+ parts.push(format!("{} updated", r.updated));
+ }
+ if r.unchanged > 0 {
+ parts.push(format!("{} unchanged", r.unchanged));
+ }
+ format!("Saved {} {noun}{plural}: {}", r.saved, parts.join(", "))
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/libs/cua/crates/cua-spaces-cli/src/teleport.rs b/libs/cua/crates/cua-spaces-cli/src/teleport.rs
index 206d6ece26..01c9b0df55 100644
--- a/libs/cua/crates/cua-spaces-cli/src/teleport.rs
+++ b/libs/cua/crates/cua-spaces-cli/src/teleport.rs
@@ -212,6 +212,8 @@ async fn push_through_keyvault(
cookies: cua_keyvault::broker::CookieFilter::default(),
confirm_passwords: true,
paths: Some(paths.clone()),
+ domains: None,
+ passwords: false,
};
let mut client = cua_keyvault::client::KeyvaultClient::connect_default()
.await
diff --git a/libs/cua/crates/cua-spaces-cli/src/teleport_session.rs b/libs/cua/crates/cua-spaces-cli/src/teleport_session.rs
index 556082342f..1ad2a418ac 100644
--- a/libs/cua/crates/cua-spaces-cli/src/teleport_session.rs
+++ b/libs/cua/crates/cua-spaces-cli/src/teleport_session.rs
@@ -42,10 +42,18 @@ impl Broker for KeyvaultBroker {
// will not match any requested site).
let site_of = match &decision {
cua_keyvault::broker::Decision::Granted { .. } => {
- let metas = client.list_items().await.map_err(kv_error)?;
- metas
+ // Names (domains) are only listed inside the browse window,
+ // which the daemon opens with Touch ID.
+ client.browse().await.map_err(kv_error)?;
+ let page = client.list_items().await.map_err(kv_error)?;
+ page.items
.into_iter()
- .filter_map(|m| m.site.map(|s| (m.id, s)))
+ .filter_map(|m| {
+ m.domain
+ .as_deref()
+ .map(cua_keyvault::record::site_of)
+ .map(|s| (m.id, s))
+ })
.collect()
}
_ => std::collections::HashMap::new(),
@@ -60,6 +68,8 @@ impl Broker for KeyvaultBroker {
token: Some(token.to_string()),
items: vec![item.to_string()],
target: target.to_string(),
+ include_passwords: false,
+ launch: false,
})
.await
.map_err(kv_error)?;
@@ -85,7 +95,6 @@ fn to_kv_access_request(request: &AccessRequest) -> cua_keyvault::broker::Access
.map(|s| cua_keyvault::broker::Selector::Site {
app: s.app.clone(),
site: s.site.clone(),
- account: None,
})
.collect(),
targets: request.targets.clone(),
@@ -286,12 +295,10 @@ mod tests {
cua_keyvault::broker::Selector::Site {
app: "chrome".into(),
site: "github.com".into(),
- account: None,
},
cua_keyvault::broker::Selector::Site {
app: "chrome".into(),
site: "news.ycombinator.com".into(),
- account: None,
},
]
);
diff --git a/libs/cua/crates/cua-spaces-cli/tests/keyvault.rs b/libs/cua/crates/cua-spaces-cli/tests/keyvault.rs
index 4d6844b852..27f526b516 100644
--- a/libs/cua/crates/cua-spaces-cli/tests/keyvault.rs
+++ b/libs/cua/crates/cua-spaces-cli/tests/keyvault.rs
@@ -19,7 +19,8 @@ use common::{Home, Out};
use cua_keyvault::broker::{
Backend, BrokerConfig, Captured, DeliveryOutcome, FakePresence, ImportSpec, Inventory,
};
-use cua_keyvault::model::{ItemKind, ItemMeta, ItemPayload, ItemPolicy, ItemSummary, PayloadEntry};
+use cua_keyvault::model::PayloadEntry;
+use cua_keyvault::record::{self, CookieRecord};
use cua_keyvault::{Broker, TrustPolicy};
use tokio::io::AsyncWriteExt;
@@ -37,7 +38,8 @@ impl Backend for NoBackend {
&self,
_: &str,
_: &str,
- _: Vec<ItemPayload>,
+ _: &str,
+ _: Vec<PayloadEntry>,
_: u64,
) -> cua_keyvault::Result<DeliveryOutcome> {
Err(cua_keyvault::Error::Unsupported("test".into()))
@@ -55,43 +57,32 @@ struct FakeImportBackend {
}
fn fake_captured(app: &str, site: Option<&str>) -> Captured {
- let label = match site {
- Some(s) => format!("{s} ({app})"),
- None => format!("{app} session"),
- };
- Captured {
- meta: ItemMeta {
- id: String::new(),
- kind: if site.is_some() {
- ItemKind::BrowserSite
- } else {
- ItemKind::AppSession
- },
- label,
- provider_id: app.into(),
- app_display: app.into(),
- site: site.map(str::to_string),
- account: None,
- source: "Default".into(),
- summary: ItemSummary::default(),
- warnings: vec![],
- identity_provider: false,
- policy: ItemPolicy::default(),
- created_ms: 0,
- updated_ms: 0,
- rev: 0,
- record_digest: String::new(),
- },
- payload: ItemPayload {
- provider_id: app.into(),
- scope: "full".into(),
- entries: vec![PayloadEntry {
- rel_path: format!("session/{}", site.unwrap_or("app")),
- mode: 0o600,
- data: "RklYVFVSRS1TRUNSRVQ=".into(),
- }],
- },
+ let n = match site {
+ // A site is one cookie; the whole app is one file.
+ Some(s) => record::cookie_record(&CookieRecord {
+ creation_utc: None,
+ expires_utc: 0,
+ host_key: format!(".{s}"),
+ http_only: true,
+ last_update_utc: None,
+ name: "session".into(),
+ partition_key: None,
+ last_access_utc: None,
+ source_type: None,
+ has_cross_site_ancestor: None,
+ path: "/".into(),
+ priority: None,
+ same_site: 1,
+ secure: true,
+ source_port: None,
+ source_scheme: None,
+ value: b"FIXTURE-SECRET".to_vec(),
+ }),
+ None => record::file_record("session/app", 0o600, b"FIXTURE-SECRET"),
}
+ .unwrap();
+ let (meta, payload) = n.into_item(app, app, "Default", "full");
+ Captured { meta, payload }
}
#[async_trait::async_trait]
@@ -115,7 +106,8 @@ impl Backend for FakeImportBackend {
&self,
_: &str,
_: &str,
- _: Vec<ItemPayload>,
+ _: &str,
+ _: Vec<PayloadEntry>,
_: u64,
) -> cua_keyvault::Result<DeliveryOutcome> {
Err(cua_keyvault::Error::Unsupported("test".into()))
@@ -363,9 +355,8 @@ async fn import_session_whole_app_or_named_sites() {
.run(&["keyvault", "import-session", "--app", "chrome", "--json"])
.await;
let v = o.ok().json();
- let imported = v["imported"].as_array().unwrap();
- assert_eq!(imported.len(), 1, "{v}");
- assert_eq!(imported[0]["site"], serde_json::Value::Null);
+ assert_eq!(v["imported"]["saved"], 1, "{v}");
+ assert_eq!(v["imported"]["created"], 1, "{v}");
{
let specs = backend.specs.lock().unwrap();
let last = specs.last().unwrap();
@@ -388,9 +379,7 @@ async fn import_session_whole_app_or_named_sites() {
])
.await;
let v = o.ok().json();
- let imported = v["imported"].as_array().unwrap();
- assert_eq!(imported.len(), 1, "{v}");
- assert_eq!(imported[0]["site"], "github.com");
+ assert_eq!(v["imported"]["saved"], 1, "{v}");
{
let specs = backend.specs.lock().unwrap();
let last = specs.last().unwrap();
@@ -408,5 +397,6 @@ async fn import_session_whole_app_or_named_sites() {
.await;
let o = o.ok();
assert!(o.stdout.contains("Sealed in the Keyvault"), "{}", o.stdout);
+ assert!(o.stdout.contains("Saved 1 item: 1 new"), "{}", o.stdout);
assert!(!o.stdout.contains("teleported") && !o.stdout.contains("delivered to"));
}
diff --git a/libs/cua/crates/cua-spaces-ext/Cargo.toml b/libs/cua/crates/cua-spaces-ext/Cargo.toml
index 0d46f6523f..f2ab1deb45 100644
--- a/libs/cua/crates/cua-spaces-ext/Cargo.toml
+++ b/libs/cua/crates/cua-spaces-ext/Cargo.toml
@@ -30,6 +30,7 @@ cua-daemon = { workspace = true, features = ["server", "client", "spaces"] }
cua-fleet.workspace = true
cua-auth.workspace = true
cua-teleport.workspace = true
+cua-chromium-storage.workspace = true
# The reserved `cookies.json` bundle entry format (`daemon::keyvault`'s
# per-site cookie capture): shared, effect-free wire format, not re-exported
# by `cua-teleport` (whose own `cookies` module is the unrelated site filter).
diff --git a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs
index c9bf618731..584ee2bcaf 100644
--- a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs
@@ -29,24 +29,18 @@ use crate::teleport::{AppSessions, TeleportScope};
use base64::Engine as _;
use cua_keyvault::broker::{
AccessRequest, Backend, Broker, BrokerConfig, Captured, CookieFilter, DeliveryOutcome,
- ImportSpec, Inventory, LoginFill, LoginFilled, PasswordImportSpec, Selector, TeleportRequest,
- TeleportStage, UserPresence,
+ DomainInventory, ImportSpec, Inventory, LoginFill, LoginFilled, PasswordImportSpec, Selector,
+ TeleportRequest, TeleportStage, UserPresence,
};
use cua_keyvault::caller::{CallerIdentity, Signing};
-use cua_keyvault::model::{
- ItemKind, ItemMeta, ItemPayload, ItemPolicy, ItemSummary, LoginRecord, PayloadEntry,
-};
+use cua_keyvault::model::{ItemKind, LoginRecord, PayloadEntry};
+use cua_keyvault::record::{self, CookieRecord, ExportOptions};
use cua_keyvault::{Error as KvError, Result as KvResult};
use cua_spaces::Spaces;
use cua_spacesd_client::pb;
use cua_teleport::bundle::{BundleReader, BundleWriter};
use cua_teleport::{BundleSource, SendOptions, TransferScope};
-// The reserved `cookies.json` bundle entry: decrypted cookies ride sealed in
-// the vault payload exactly like this, then travel unchanged into the
-// delivered bundle (never stripped like `LOGINS_ENTRY`, since cookies ARE
-// what restores the signed-in session -- the receiver's Chrome importer
-// re-encrypts them under the DESTINATION's own Safe Storage key).
-use cua_teleport_bundle::cookies::{COOKIES_ENTRY, CookieItem};
+use cua_teleport_bundle::cookies::CookieItem;
use sha2::{Digest, Sha256};
/// Base64 for [`PayloadEntry`] bytes (values stay sealed in the vault; only
@@ -109,6 +103,16 @@ impl DaemonBackend {
self
}
+ /// The name a provider shows (`Google Chrome`), falling back to its id.
+ fn app_display(&self, app: &str) -> String {
+ self.sessions
+ .catalog()
+ .into_iter()
+ .find(|p| p.id == app)
+ .map(|p| p.display_name)
+ .unwrap_or_else(|| app.to_string())
+ }
+
fn password_reader(&self, profile: Option<String>) -> cua_teleport::passwords::ChromePasswords {
cua_teleport::passwords::ChromePasswords::new(self.host.clone())
.with_platform(self.platform)
@@ -174,7 +178,7 @@ impl DaemonBackend {
&self,
app: &str,
override_paths: Option<&[String]>,
- ) -> KvResult<(String, Vec<PayloadEntry>)> {
+ ) -> KvResult<(String, String, Vec<PayloadEntry>)> {
let manifest = self
.sessions
.manifest(app, TeleportScope::Full)
@@ -208,6 +212,7 @@ impl DaemonBackend {
let reader =
BundleReader::open(Cursor::new(buf)).map_err(|e| backend_err("open bundle", e))?;
let scope = scope_str(reader.header().scope).to_string();
+ let display = manifest.display_name.clone();
let entries = reader
.read_all()
.map_err(|e| backend_err("read bundle", e))?
@@ -218,11 +223,36 @@ impl DaemonBackend {
data: B64.encode(&e.bytes),
})
.collect();
- Ok((scope, entries))
+ Ok((scope, display, entries))
}
}
impl DaemonBackend {
+ /// The decrypted saved logins of `sites` (every site when empty).
+ fn site_logins_for(
+ &self,
+ app: &str,
+ profile: Option<String>,
+ sites: &[String],
+ ) -> KvResult<Vec<LoginRecord>> {
+ if app != "chrome" {
+ return Err(KvError::Unsupported(format!(
+ "saved passwords from {app} are not read yet"
+ )));
+ }
+ Ok(self
+ .password_reader(profile)
+ .read(sites)
+ .map_err(|e| backend_err("read saved passwords", e))?
+ .into_iter()
+ .map(|l| LoginRecord {
+ origin: l.origin.clone(),
+ username: l.username.clone(),
+ password: l.password.to_string(),
+ })
+ .collect())
+ }
+
/// The decrypted saved logins of one site.
fn site_logins(
&self,
@@ -287,16 +317,7 @@ impl DaemonBackend {
}
true
})
- .map(|c| CookieItem {
- host_key: c.host_key,
- name: c.name,
- value: c.value.as_bytes().to_vec(),
- path: c.path,
- expires_utc: c.expires_utc,
- is_secure: c.is_secure,
- is_httponly: c.is_httponly,
- samesite: c.samesite,
- })
+ .map(cua_teleport::browser_cookies::DecryptedCookie::into_item)
.collect())
}
}
@@ -312,67 +333,52 @@ fn chrome_epoch_now_micros() -> i64 {
unix_micros + UNIX_TO_CHROME_EPOCH_MICROS
}
-/// Milliseconds between the Chrome/Windows epoch (1601-01-01 UTC) and the
-/// Unix epoch -- subtract this from `expires_utc / 1000` (Chrome's own unit,
-/// converted to milliseconds) to get [`CookieInfo::expires_ms`] (Unix ms).
-const CHROME_EPOCH_OFFSET_MS: i64 = 11_644_473_600_000;
-
-/// A sealed `cookies.json` payload entry for `items` (see
-/// [`cua_teleport_bundle::cookies`]): decrypted cookies, base64-encoded like
-/// every other [`PayloadEntry`], owner-only mode. The vault seals the whole
-/// payload at rest; this is only the wire shape.
-fn cookies_payload_entry(items: &[CookieItem]) -> PayloadEntry {
- PayloadEntry {
- rel_path: COOKIES_ENTRY.to_string(),
- mode: 0o600,
- data: B64.encode(cua_teleport_bundle::cookies::serialize(items)),
+/// Whether a cookie survives the capture's minimization.
+fn keep_cookie(c: &CookieRecord, filter: &CookieFilter) -> bool {
+ // 30 days, in Chrome's own `*_utc` unit (microseconds since
+ // 1601-01-01 UTC): the same "long-lived" cutoff a browser's own "clear
+ // cookies older than" setting uses.
+ const THIRTY_DAYS_CHROME_MICROS: i64 = 30 * 24 * 60 * 60 * 1_000_000;
+ let is_session = c.expires_utc == 0;
+ if filter.session_only && !is_session {
+ return false;
+ }
+ if filter.drop_long_lived
+ && !is_session
+ && c.expires_utc > chrome_epoch_now_micros() + THIRTY_DAYS_CHROME_MICROS
+ {
+ return false;
}
+ true
}
-fn browser_meta(app: &str, site: &str, passwords: bool) -> ItemMeta {
- ItemMeta {
- id: String::new(),
- kind: if passwords {
- ItemKind::SitePasswords
- } else {
- ItemKind::BrowserSite
- },
- label: format!("{site} ({app})"),
- provider_id: app.into(),
- app_display: app.into(),
- site: Some(site.into()),
- account: None,
- source: "default".into(),
- summary: ItemSummary::default(),
- warnings: vec![],
- identity_provider: false,
- policy: ItemPolicy::default(),
- created_ms: 0,
- updated_ms: 0,
- rev: 0,
- record_digest: String::new(),
+/// A cookie row the reader decrypted, as the vault's `cookie@1` record.
+fn cookie_record_of(c: &CookieItem) -> CookieRecord {
+ CookieRecord {
+ creation_utc: c.extra.creation_utc,
+ expires_utc: c.expires_utc,
+ has_cross_site_ancestor: c.extra.has_cross_site_ancestor,
+ host_key: c.host_key.clone(),
+ http_only: c.is_httponly,
+ last_access_utc: c.extra.last_access_utc,
+ last_update_utc: c.extra.last_update_utc,
+ name: c.name.clone(),
+ partition_key: c.extra.partition_key.clone().filter(|k| !k.is_empty()),
+ path: c.path.clone(),
+ priority: c.extra.priority,
+ same_site: c.samesite,
+ secure: c.is_secure,
+ source_port: c.extra.source_port,
+ source_scheme: c.extra.source_scheme,
+ source_type: c.extra.source_type,
+ value: c.value.clone(),
}
}
-fn app_meta(app: &str) -> ItemMeta {
- ItemMeta {
- id: String::new(),
- kind: ItemKind::AppSession,
- label: format!("{app} (whole app session)"),
- provider_id: app.into(),
- app_display: app.into(),
- site: None,
- account: None,
- source: "default".into(),
- summary: ItemSummary::default(),
- warnings: vec![],
- identity_provider: false,
- policy: ItemPolicy::default(),
- created_ms: 0,
- updated_ms: 0,
- rev: 0,
- record_digest: String::new(),
- }
+/// Whether a record's domain belongs to one of the chosen sites.
+fn in_sites(domain: &str, sites: &[String]) -> bool {
+ let site = record::site_of(domain);
+ sites.iter().any(|s| record::site_of(s) == site)
}
#[async_trait::async_trait]
@@ -381,92 +387,197 @@ impl Backend for DaemonBackend {
self.immutable_id(name)
}
- fn inventory(&self, app: &str, _profile: Option<&str>) -> KvResult<Inventory> {
+ fn favicons(
+ &self,
+ app: &str,
+ profile: Option<&str>,
+ sites: &[String],
+ ) -> KvResult<Vec<(String, Vec<u8>)>> {
+ if app != "chrome" {
+ return Ok(Vec::new());
+ }
+ let dir = self
+ .cookie_reader(profile.map(str::to_string))
+ .profile_dir()
+ .map_err(|e| backend_err("find the browser profile", e))?;
+ let db = cua_teleport::favicons::favicons_db(&dir);
+ Ok(cua_teleport::favicons::read_favicons(&db, sites)
+ .map_err(|e| backend_err("read favicons", e))?
+ .into_iter()
+ .map(|f| (f.site, f.png))
+ .collect())
+ }
+
+ fn inventory(&self, app: &str, profile: Option<&str>) -> KvResult<Inventory> {
let manifest = self
.sessions
.manifest(app, TeleportScope::Full)
.map_err(|e| backend_err("read manifest", e))?;
+ // A browser's domains with counts, from the plaintext columns of its
+ // cookie store: nothing is decrypted, so no Keychain prompt.
+ let mut domains: std::collections::BTreeMap<String, DomainInventory> = Default::default();
+ let mut notes = manifest.notes.clone();
+ if app == "chrome" {
+ match self.cookie_reader(profile.map(str::to_string)).host_rows() {
+ Ok(rows) => {
+ for r in rows {
+ let site = record::site_of(&r.host_key);
+ let d = domains
+ .entry(site.clone())
+ .or_insert_with(|| DomainInventory {
+ domain: site.clone(),
+ identity_provider: cua_keyvault::model::is_identity_provider(&site),
+ ..Default::default()
+ });
+ if r.app_bound {
+ d.unavailable += 1;
+ d.unavailable_reason =
+ cua_teleport::browser_cookies::APP_BOUND_REASON.into();
+ continue;
+ }
+ d.cookies += 1;
+ if r.expires_utc == 0 {
+ d.session_cookies += 1;
+ }
+ d.signin |= record::looks_like_signin(&r.name);
+ }
+ }
+ Err(e) => notes.push(format!("cookies were not listed: {e}")),
+ }
+ // Saved passwords per site, counted from the plaintext columns
+ // (nothing is decrypted); app-bound ones are listed as unreadable.
+ match self
+ .password_reader(profile.map(str::to_string))
+ .count_by_site()
+ {
+ Ok(counts) => {
+ for (site, (ok, bound)) in counts {
+ let d = domains
+ .entry(site.clone())
+ .or_insert_with(|| DomainInventory {
+ domain: site.clone(),
+ identity_provider: cua_keyvault::model::is_identity_provider(&site),
+ ..Default::default()
+ });
+ d.passwords += ok;
+ if bound > 0 {
+ d.unavailable += bound;
+ d.unavailable_reason =
+ cua_teleport::browser_cookies::APP_BOUND_REASON.into();
+ }
+ }
+ }
+ Err(e) => notes.push(format!("saved passwords were not listed: {e}")),
+ }
+ // localStorage values per site, counted from a private copy of the
+ // browser's store (no value is decoded).
+ let reader = self.cookie_reader(profile.map(str::to_string));
+ if let Ok(dir) = reader.profile_dir() {
+ match cua_chromium_storage::count_by_origin(&cua_chromium_storage::store_dir(&dir))
+ {
+ Ok(counts) => {
+ for (origin, n) in counts {
+ let site = record::site_of(&origin);
+ if site.is_empty() {
+ continue;
+ }
+ let d =
+ domains
+ .entry(site.clone())
+ .or_insert_with(|| DomainInventory {
+ domain: site.clone(),
+ identity_provider:
+ cua_keyvault::model::is_identity_provider(&site),
+ ..Default::default()
+ });
+ d.local_storage += n;
+ }
+ }
+ Err(e) => notes.push(format!("localStorage was not listed: {e}")),
+ }
+ }
+ }
Ok(Inventory {
provider_id: manifest.app.clone(),
app_display: manifest.display_name.clone(),
- profile: None,
- candidates: vec![],
- notes: manifest.notes,
+ profile: profile.map(str::to_string),
+ domains: domains.into_values().collect(),
+ notes,
})
}
fn capture(&self, spec: &ImportSpec) -> KvResult<Vec<Captured>> {
- let (scope, entries) = self.export_entries(&spec.app, spec.paths.as_deref())?;
- let payload = |kind_entries: &[PayloadEntry]| ItemPayload {
- provider_id: spec.app.clone(),
- scope: scope.clone(),
- entries: kind_entries.to_vec(),
+ let source = spec.profile.clone().unwrap_or_else(|| "default".into());
+ let mut out: Vec<Captured> = Vec::new();
+ let mut display = self.app_display(&spec.app);
+ let keep = |out: &mut Vec<Captured>, display: &str, scope: &str, n: record::NewRecord| {
+ let (meta, payload) = n.into_item(&spec.app, display, &source, scope);
+ out.push(Captured { meta, payload });
};
- let mut out = Vec::new();
+ // Sites named one by one (the MCP import path): their cookies, and
+ // on request their saved passwords.
for s in &spec.sites {
- let mut meta = browser_meta(&spec.app, &s.site, false);
- let mut site_entries = entries.clone();
- // Cookies are the whole point of a `BrowserSite` item (model.rs:
- // "cookies, and optionally its storage"), so they ride in the
- // SAME captured item as the rest of the site's profile state,
- // not a separate sealed-only entry like saved passwords below --
- // teleport delivers them (that is how the destination arrives
- // signed in), it just never delivers them as the raw
- // Safe-Storage-encrypted `Cookies` file: they travel already
- // decrypted, in the reserved `cookies.json` entry, and the
- // receiver re-encrypts under the DESTINATION's own key.
- match self.site_cookies(&spec.app, spec.profile.clone(), &s.site, &spec.cookies) {
- Ok(cookies) => {
- meta.summary.cookies = cookies
- .iter()
- .map(|c| cua_keyvault::model::CookieInfo {
- name: c.name.clone(),
- domain: c.host_key.clone(),
- session: c.expires_utc == 0,
- // `expires_utc` is Chrome's own epoch
- // (microseconds since 1601-01-01 UTC);
- // `CookieInfo::expires_ms` is Unix ms.
- expires_ms: (c.expires_utc != 0)
- .then_some(c.expires_utc / 1000 - CHROME_EPOCH_OFFSET_MS),
- })
- .collect();
- if !cookies.is_empty() {
- site_entries.push(cookies_payload_entry(&cookies));
- }
- }
- Err(e) => meta
- .warnings
- .push(format!("cookies were not read for this site: {e}")),
+ if spec.domains.as_ref().is_some_and(|d| !in_sites(&s.site, d)) {
+ continue;
+ }
+ for c in self
+ .site_cookies(&spec.app, spec.profile.clone(), &s.site, &spec.cookies)?
+ .iter()
+ {
+ keep(
+ &mut out,
+ &display,
+ "full",
+ record::cookie_record(&cookie_record_of(c))?,
+ );
}
- out.push(Captured {
- meta,
- payload: payload(&site_entries),
- });
if s.include_passwords && spec.confirm_passwords {
- let mut meta = browser_meta(&spec.app, &s.site, true);
- let mut entries = entries.clone();
- // The decrypted logins ride along sealed, for site login;
- // teleport never delivers them.
- match self.site_logins(&spec.app, spec.profile.clone(), &s.site) {
- Ok(logins) => {
- meta.summary.passwords = logins.len() as u32;
- entries.push(ItemPayload::logins_entry(&logins)?);
- }
- Err(e) => meta
- .warnings
- .push(format!("saved passwords were not read for site login: {e}")),
+ for l in self.site_logins(&spec.app, spec.profile.clone(), &s.site)? {
+ keep(&mut out, &display, "full", record::password_record(&l)?);
}
- out.push(Captured {
- meta,
- payload: payload(&entries),
- });
}
}
+ // The app itself: what the provider exports (a browser's selection
+ // or an app's files), turned into records by the app's codec. A
+ // consent-gated file is only exported when the user picked it.
if spec.whole_app {
- out.push(Captured {
- meta: app_meta(&spec.app),
- payload: payload(&entries),
- });
+ let (scope, name, entries) = self.export_entries(&spec.app, spec.paths.as_deref())?;
+ display = name;
+ let exported = record::codec_for(&spec.app).export(
+ entries,
+ &ExportOptions {
+ opted_in: spec.paths.clone().unwrap_or_default(),
+ },
+ )?;
+ // Saved passwords: only when the review ticked them. Read with the
+ // source's key here, never written to disk; the receiver
+ // re-encrypts them under its own.
+ if spec.passwords && spec.confirm_passwords {
+ let sites: Vec<String> = spec.domains.clone().unwrap_or_default();
+ for l in self.site_logins_for(&spec.app, spec.profile.clone(), &sites)? {
+ keep(&mut out, &display, &scope, record::password_record(&l)?);
+ }
+ }
+ for n in exported.records {
+ let pass = match n.kind {
+ ItemKind::Cookie => {
+ let c: CookieRecord = serde_json::from_str(&n.record)?;
+ keep_cookie(&c, &spec.cookies)
+ && spec
+ .domains
+ .as_ref()
+ .is_none_or(|d| in_sites(&c.host_key, d))
+ }
+ ItemKind::LocalStorage => spec
+ .domains
+ .as_ref()
+ .is_none_or(|d| n.domain.as_deref().is_some_and(|o| in_sites(o, d))),
+ _ => true,
+ };
+ if pass {
+ keep(&mut out, &display, &scope, n);
+ }
+ }
}
Ok(out)
}
@@ -482,31 +593,17 @@ impl Backend for DaemonBackend {
.password_reader(spec.profile.clone())
.read(&spec.sites)
.map_err(|e| backend_err("read saved passwords", e))?;
- let mut by_site: std::collections::BTreeMap<String, Vec<LoginRecord>> = Default::default();
- for l in logins {
- by_site
- .entry(l.site.clone())
- .or_default()
- .push(LoginRecord {
- origin: l.origin.clone(),
- username: l.username.clone(),
- password: l.password.to_string(),
- });
- }
+ let display = self.app_display(&spec.app);
+ let source = spec.profile.clone().unwrap_or_else(|| "default".into());
let mut out = Vec::new();
- for (site, logins) in by_site {
- let mut meta = browser_meta(&spec.app, &site, true);
- meta.label = format!("{site} passwords ({})", spec.app);
- meta.source = spec.profile.clone().unwrap_or_else(|| "default".into());
- meta.summary.passwords = logins.len() as u32;
- out.push(Captured {
- meta,
- payload: ItemPayload {
- provider_id: spec.app.clone(),
- scope: "full".into(),
- entries: vec![ItemPayload::logins_entry(&logins)?],
- },
- });
+ for l in logins {
+ let n = record::password_record(&LoginRecord {
+ origin: l.origin.clone(),
+ username: l.username.clone(),
+ password: l.password.to_string(),
+ })?;
+ let (meta, payload) = n.into_item(&spec.app, &display, &source, "full");
+ out.push(Captured { meta, payload });
}
Ok(out)
}
@@ -520,11 +617,19 @@ impl Backend for DaemonBackend {
&self,
target: &str,
provider_id: &str,
- payloads: Vec<ItemPayload>,
+ scope: &str,
+ entries: Vec<PayloadEntry>,
expires_ms: u64,
) -> KvResult<DeliveryOutcome> {
- self.deliver_with_progress(target, provider_id, payloads, expires_ms, Arc::new(|_| {}))
- .await
+ self.deliver_with_progress(
+ target,
+ provider_id,
+ scope,
+ entries,
+ expires_ms,
+ Arc::new(|_| {}),
+ )
+ .await
}
/// Packs, uploads (with bytes) and imports, telling `stage` each step.
@@ -532,21 +637,32 @@ impl Backend for DaemonBackend {
&self,
target: &str,
provider_id: &str,
- payloads: Vec<ItemPayload>,
+ scope: &str,
+ entries: Vec<PayloadEntry>,
expires_ms: u64,
stage: cua_keyvault::broker::StageSink,
) -> KvResult<DeliveryOutcome> {
- self.deliver_launching(target, provider_id, payloads, expires_ms, stage, false)
- .await
+ self.deliver_launching(
+ target,
+ provider_id,
+ scope,
+ entries,
+ expires_ms,
+ stage,
+ false,
+ )
+ .await
}
/// [`Self::deliver_with_progress`], with the receiver launching the app
/// afterwards (`launch`) and reporting whether it did.
+ #[allow(clippy::too_many_arguments)]
async fn deliver_launching(
&self,
target: &str,
provider_id: &str,
- payloads: Vec<ItemPayload>,
+ scope: &str,
+ entries: Vec<PayloadEntry>,
expires_ms: u64,
stage: cua_keyvault::broker::StageSink,
launch: bool,
@@ -556,21 +672,17 @@ impl Backend for DaemonBackend {
let spacesd = space
.spacesd()
.map_err(|e| backend_err("spacesd channel", e))?;
- let scope = payloads
- .first()
- .map(|p| scope_of(&p.scope))
- .unwrap_or(TransferScope::FullProfile);
- // Reassemble one SessionBundle in memory from the sealed payloads.
+ let scope = scope_of(scope);
+ // Reassemble one SessionBundle in memory from the codec's entries.
let mut writer = BundleWriter::new(Vec::new(), provider_id, provider_id, scope);
- for p in &payloads {
- for e in &p.entries {
- let bytes = B64
- .decode(&e.data)
- .map_err(|err| backend_err("decode payload", err))?;
- writer
- .add_bytes(&e.rel_path, e.mode, &bytes)
- .map_err(|err| backend_err("pack bundle", err))?;
- }
+ for e in &entries {
+ let bytes = cua_keyvault::Zeroizing::new(
+ B64.decode(&e.data)
+ .map_err(|err| backend_err("decode payload", err))?,
+ );
+ writer
+ .add_bytes(&e.rel_path, e.mode, &bytes)
+ .map_err(|err| backend_err("pack bundle", err))?;
}
let bytes = writer
.finish()
@@ -893,6 +1005,8 @@ impl SessionBroker for McpSessionBroker {
token: Some(token),
items: items.clone(),
target: target.into(),
+ include_passwords: false,
+ launch: false,
},
)
.await
diff --git a/libs/cua/crates/cua-spaces-ext/src/teleport.rs b/libs/cua/crates/cua-spaces-ext/src/teleport.rs
index 39a525ba7e..417fcefff2 100644
--- a/libs/cua/crates/cua-spaces-ext/src/teleport.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/teleport.rs
@@ -539,6 +539,25 @@ pub struct ImportOptions {
pub relay_plaintext_ack: bool,
}
+/// What the review chose beyond the approved paths: which sites' cookies to
+/// send, and whether to send saved Keyvault items instead of reading the
+/// live app.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct TeleportSelection {
+ /// The registrable domains whose cookies to send (`None`: every cookie in
+ /// the approved selection).
+ pub cookie_domains: Option<Vec<String>>,
+ /// Send these saved Keyvault items (ids) instead of capturing the live
+ /// app. Nothing is read from the host, so its Keychain is never asked;
+ /// the broker authorizes it with the user's presence as it does any
+ /// delivery.
+ pub from_vault: Option<Vec<String>>,
+ /// Also send the saved passwords (of `cookie_domains`, or every site):
+ /// only when the user ticked them in the review. They are re-encrypted
+ /// for the destination browser's own key.
+ pub include_passwords: bool,
+}
+
/// Session teleport on a [`Space`]: what it can import, and the export and
/// import of an approved app session.
#[allow(async_fn_in_trait)]
@@ -569,6 +588,17 @@ pub trait SpaceTeleport {
options: ImportOptions,
stage: &mut (dyn FnMut(cua_keyvault::broker::TeleportStage) + Send),
) -> Result<TeleportReceipt>;
+
+ /// [`Self::teleport_with_progress`] with the review's choices: cookies of
+ /// only some sites, or saved Keyvault items sent without a fresh capture.
+ async fn teleport_selected(
+ &self,
+ sessions: Arc<AppSessions>,
+ approval: &Approval,
+ options: ImportOptions,
+ selection: &TeleportSelection,
+ stage: &mut (dyn FnMut(cua_keyvault::broker::TeleportStage) + Send),
+ ) -> Result<TeleportReceipt>;
}
impl SpaceTeleport for Space {
@@ -646,6 +676,24 @@ impl SpaceTeleport for Space {
// `save_to_keyvault` is honored below.
options: ImportOptions,
stage: &mut (dyn FnMut(cua_keyvault::broker::TeleportStage) + Send),
+ ) -> Result<TeleportReceipt> {
+ self.teleport_selected(
+ sessions,
+ approval,
+ options,
+ &TeleportSelection::default(),
+ stage,
+ )
+ .await
+ }
+
+ async fn teleport_selected(
+ &self,
+ sessions: Arc<AppSessions>,
+ approval: &Approval,
+ options: ImportOptions,
+ selection: &TeleportSelection,
+ stage: &mut (dyn FnMut(cua_keyvault::broker::TeleportStage) + Send),
) -> Result<TeleportReceipt> {
if approval.space != self.id().to_string() {
return Err(Error::TeleportRefused(format!(
@@ -678,6 +726,8 @@ impl SpaceTeleport for Space {
cookies: cua_keyvault::broker::CookieFilter::default(),
confirm_passwords: true,
paths: Some(approval.paths.clone()),
+ domains: selection.cookie_domains.clone(),
+ passwords: selection.include_passwords,
};
let mut client = cua_keyvault::client::KeyvaultClient::connect_default()
.await
@@ -688,16 +738,35 @@ impl SpaceTeleport for Space {
as the signed `cua` app/CLI"
),
})?;
- let outcome = client
- .import_and_teleport_launching(
- spec,
- self.id().to_string(),
- options.save_to_keyvault,
- options.launch_after,
- stage,
- )
- .await
- .map_err(|e| Error::TeleportRefused(format!("{}: {e}", approval.app)))?;
+ let outcome = match &selection.from_vault {
+ // Saved items: no capture, so nothing is read from the host and
+ // the Keychain is never asked. One delivery, one presence check.
+ Some(items) => {
+ stage(cua_keyvault::broker::TeleportStage::Packing);
+ let out = client
+ .teleport(cua_keyvault::broker::TeleportRequest {
+ token: None,
+ items: items.clone(),
+ target: self.id().to_string(),
+ include_passwords: selection.include_passwords,
+ launch: options.launch_after,
+ })
+ .await
+ .map_err(|e| Error::TeleportRefused(format!("{}: {e}", approval.app)))?;
+ stage(cua_keyvault::broker::TeleportStage::Importing);
+ out
+ }
+ None => client
+ .import_and_teleport_launching(
+ spec,
+ self.id().to_string(),
+ options.save_to_keyvault,
+ options.launch_after,
+ stage,
+ )
+ .await
+ .map_err(|e| Error::TeleportRefused(format!("{}: {e}", approval.app)))?,
+ };
let delivery = outcome.deliveries.first();
Ok(TeleportReceipt {
app: approval.app.clone(),
diff --git a/libs/cua/crates/cua-spaces-ext/src/teleport_app.rs b/libs/cua/crates/cua-spaces-ext/src/teleport_app.rs
index f8dd5a16fd..72a27110ea 100644
--- a/libs/cua/crates/cua-spaces-ext/src/teleport_app.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/teleport_app.rs
@@ -25,7 +25,9 @@ pub use cua_teleport::ux::{
};
use cua_teleport::ux::{InstallSource, MoveKind};
-use crate::teleport::{AppSessions, ImportOptions, SpaceTeleport as _, TeleportScope};
+use crate::teleport::{
+ AppSessions, ImportOptions, SpaceTeleport as _, TeleportScope, TeleportSelection,
+};
use cua_spaces::Space;
use cua_spaces::error::{Error, Result};
@@ -309,10 +311,18 @@ impl SpaceAppTeleport for Space {
// The plan's consent already listed and acknowledged these
// exact items.
let approval = manifest.approving(&self.id().to_string(), items, plan.sensitive)?;
- let cookies = items.iter().any(|i| i.to_lowercase().contains("cookies"));
+ // Saved Keyvault items are sent without reading the live app,
+ // so the host's Keychain is never asked.
+ let cookies = plan.from_vault.is_none()
+ && items.iter().any(|i| i.to_lowercase().contains("cookies"));
+ let selection = TeleportSelection {
+ cookie_domains: plan.cookie_domains.clone(),
+ from_vault: plan.from_vault.clone(),
+ include_passwords: plan.include_passwords,
+ };
let app = plan.app.name.clone();
let receipt = self
- .teleport_with_progress(
+ .teleport_selected(
sessions.clone(),
&approval,
ImportOptions {
@@ -325,6 +335,7 @@ impl SpaceAppTeleport for Space {
// user's acknowledgement (S1).
relay_plaintext_ack: plan.relay_unsealed,
},
+ &selection,
&mut |st| {
let (done, total) = match &st {
TeleportStage::Uploading { done, total } => (*done, *total),
diff --git a/libs/cua/crates/cua-spaces-ext/tests/e2e_teleport_app.rs b/libs/cua/crates/cua-spaces-ext/tests/e2e_teleport_app.rs
index e88f410115..8a097bb666 100644
--- a/libs/cua/crates/cua-spaces-ext/tests/e2e_teleport_app.rs
+++ b/libs/cua/crates/cua-spaces-ext/tests/e2e_teleport_app.rs
@@ -134,6 +134,7 @@ async fn e2e_teleport_a_fixture_app_with_files_into_the_space() {
acknowledge_sensitive: false,
save_to_keyvault: false,
acknowledge_relay_plaintext: false,
+ ..Default::default()
})
.unwrap();
let report = tokio::time::timeout(
@@ -392,6 +393,7 @@ async fn e2e_teleport_chrome_without_sign_ins_into_a_macos_space() {
acknowledge_sensitive: false,
save_to_keyvault: false,
acknowledge_relay_plaintext: false,
+ ..Default::default()
})
.unwrap();
let started = std::time::Instant::now();
diff --git a/libs/cua/crates/cua-spaces-ext/tests/keyvault_delivery.rs b/libs/cua/crates/cua-spaces-ext/tests/keyvault_delivery.rs
index beabd838e5..dc5a191fa6 100644
--- a/libs/cua/crates/cua-spaces-ext/tests/keyvault_delivery.rs
+++ b/libs/cua/crates/cua-spaces-ext/tests/keyvault_delivery.rs
@@ -167,7 +167,7 @@ async fn rig() -> Rig {
}
}
-/// Third party requests the `github.com` chrome site into the target; the user
+/// Third party requests the chrome app into the target; the user
/// approves; the returned token authorizes exactly one delivery.
async fn grant(r: &Rig, target: &str) -> (String, Vec<String>) {
let pending = r
@@ -175,10 +175,8 @@ async fn grant(r: &Rig, target: &str) -> (String, Vec<String>) {
.request_access(
&r.koala,
AccessRequest {
- selectors: vec![Selector::Site {
+ selectors: vec![Selector::App {
app: "chrome".into(),
- site: "github.com".into(),
- account: None,
}],
targets: vec![target.into()],
uses: Some(0),
@@ -220,6 +218,8 @@ async fn broker_delivers_a_granted_capability_and_wipes_on_release() {
token: Some(token.clone()),
items: items.clone(),
target: r.target.clone(),
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -292,6 +292,8 @@ async fn a_capability_for_a_different_target_is_refused() {
token: Some(token),
items,
target: other,
+ include_passwords: false,
+ launch: false,
},
)
.await
@@ -317,6 +319,8 @@ async fn a_tripped_kill_switch_denies_delivery() {
token: Some(token),
items,
target: r.target.clone(),
+ include_passwords: false,
+ launch: false,
},
)
.await
diff --git a/libs/cua/crates/cua-spaces-ext/tests/keyvault_items.rs b/libs/cua/crates/cua-spaces-ext/tests/keyvault_items.rs
new file mode 100644
index 0000000000..d610c45692
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-ext/tests/keyvault_items.rs
@@ -0,0 +1,308 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The daemon's capture backend turns what a provider exports into the
+//! vault's per-secret records: cookies from the decrypted rows, files for the
+//! rest, a domain choice filtering cookies, consent-gated files held back
+//! unless the user picked them, and the inventory listing domains from the
+//! plaintext columns of the cookie store (so no Keychain prompt).
+//!
+//! Host-safe: a deterministic in-memory provider and a `FakeHost`; nothing
+//! reads a real profile.
+#![cfg(unix)]
+
+use std::collections::HashSet;
+use std::io::Write;
+use std::sync::Arc;
+
+use cua_keyvault::ItemKind;
+use cua_keyvault::broker::{Backend, CookieFilter, ImportSpec};
+use cua_keyvault::record::{COOKIES_ENTRY, CookieRecord};
+use cua_spaces::Spaces;
+use cua_spaces_ext::daemon::keyvault::DaemonBackend;
+use cua_spaces_ext::teleport::AppSessions;
+use cua_teleport::bundle::BundleWriter;
+use cua_teleport::{
+ AppRef, ExportProvider, ExportRegistry, FakeHost, HostEffects, ManifestItem, Platform,
+ TransferManifest, TransferScope, WindowRef,
+};
+
+/// A browser that exports decrypted cookie rows for three sites, two files
+/// and a consent-gated `Web Data`.
+struct Browser {
+ host: Arc<dyn HostEffects>,
+}
+
+const PATHS: [&str; 4] = [
+ "Default/Bookmarks",
+ "Default/Preferences",
+ "Default/Web Data",
+ "Default/Cookies",
+];
+
+impl ExportProvider for Browser {
+ fn id(&self) -> &str {
+ "chrome"
+ }
+ fn display_name(&self) -> &str {
+ "Google Chrome"
+ }
+ fn host(&self) -> &dyn HostEffects {
+ self.host.as_ref()
+ }
+ fn platform_supported(&self, _platform: Platform) -> bool {
+ true
+ }
+ fn matches(&self, app: &AppRef) -> bool {
+ app.app_id == "chrome"
+ }
+ fn app_ids(&self) -> &[&str] {
+ &["chrome"]
+ }
+ fn manifest(
+ &self,
+ _app: &AppRef,
+ _window: Option<&WindowRef>,
+ scope: TransferScope,
+ ) -> cua_teleport::Result<TransferManifest> {
+ Ok(TransferManifest {
+ provider_id: "chrome".into(),
+ app_display_name: "Google Chrome".into(),
+ scope,
+ items: PATHS
+ .iter()
+ .map(|p| ManifestItem {
+ label: (*p).into(),
+ rel_path: (*p).into(),
+ est_bytes: 10,
+ count: None,
+ count_noun: None,
+ sensitive: false,
+ default_checked: true,
+ })
+ .collect(),
+ total_est_bytes: 40,
+ notes: vec![],
+ })
+ }
+ fn capture_selected(
+ &self,
+ _app: &AppRef,
+ scope: TransferScope,
+ include: Option<&HashSet<String>>,
+ out: &mut dyn Write,
+ ) -> cua_teleport::Result<()> {
+ let wants = |p: &str| include.is_none_or(|i| i.contains(p));
+ let mut w = BundleWriter::new(out, "chrome", "Google Chrome", scope);
+ for p in [
+ "Default/Bookmarks",
+ "Default/Preferences",
+ "Default/Web Data",
+ ] {
+ if wants(p) {
+ w.add_bytes(p, 0o600, format!("bytes of {p}").as_bytes())?;
+ }
+ }
+ if wants("Default/Cookies") {
+ let rows = serde_json::json!([
+ row(".github.com", "user_session", "/", 0),
+ row("api.github.com", "_gh_sess", "/", 0),
+ row(".notion.so", "token_v2", "/", 13_397_000_000_000_000_i64),
+ row(".doubleclick.net", "IDE", "/", 13_397_000_000_000_000_i64),
+ row(".example.test", "pref", "/", 13_700_000_000_000_000_i64),
+ ]);
+ w.add_bytes(COOKIES_ENTRY, 0o600, rows.to_string().as_bytes())?;
+ }
+ w.finish()?;
+ Ok(())
+ }
+}
+
+fn row(host: &str, name: &str, path: &str, expires: i64) -> serde_json::Value {
+ use base64::Engine as _;
+ serde_json::json!({
+ "host_key": host, "name": name, "path": path, "expires_utc": expires,
+ "value": base64::engine::general_purpose::STANDARD.encode(format!("v-{name}")),
+ "is_secure": true, "is_httponly": true, "samesite": 1
+ })
+}
+
+fn backend() -> (DaemonBackend, tempfile::TempDir) {
+ let reg = tempfile::tempdir().unwrap();
+ let spaces = Spaces::builder()
+ .home(reg.path())
+ .operator_display(Arc::new(cua_spaces::operator::NoDisplay))
+ .build();
+ let mut registry = ExportRegistry::new();
+ registry.register(Box::new(Browser {
+ host: Arc::new(FakeHost::new()),
+ }));
+ let sessions = Arc::new(AppSessions::from_registry(registry));
+ (DaemonBackend::new(spaces, sessions), reg)
+}
+
+fn spec(paths: &[&str]) -> ImportSpec {
+ ImportSpec {
+ app: "chrome".into(),
+ whole_app: true,
+ paths: Some(paths.iter().map(|s| s.to_string()).collect()),
+ ..Default::default()
+ }
+}
+
+fn cookies(captured: &[cua_keyvault::broker::Captured]) -> Vec<(String, String)> {
+ captured
+ .iter()
+ .filter(|c| c.meta.kind == ItemKind::Cookie)
+ .map(|c| (c.meta.domain.clone().unwrap(), c.meta.key.clone()))
+ .collect()
+}
+
+#[test]
+fn a_browser_capture_is_one_item_per_cookie_and_file() {
+ let (b, _reg) = backend();
+ let out = b
+ .capture(&spec(&[
+ "Default/Bookmarks",
+ "Default/Preferences",
+ "Default/Cookies",
+ ]))
+ .unwrap();
+ assert_eq!(out.len(), 7, "five cookies and two files");
+ assert_eq!(
+ cookies(&out)[0],
+ (".github.com".to_string(), "user_session".to_string())
+ );
+ let files: Vec<&str> = out
+ .iter()
+ .filter(|c| c.meta.kind == ItemKind::File)
+ .map(|c| c.meta.key.as_str())
+ .collect();
+ assert_eq!(files, ["Default/Bookmarks", "Default/Preferences"]);
+ // Every item names its app and carries a versioned record, and a cookie
+ // keeps its attributes (the path is part of its key).
+ for c in &out {
+ assert_eq!(c.meta.provider_id, "chrome");
+ assert_eq!(c.meta.app_display, "Google Chrome");
+ }
+ let first = out
+ .iter()
+ .find(|c| c.meta.kind == ItemKind::Cookie)
+ .unwrap();
+ assert_eq!(first.payload.schema, "cookie@1");
+ assert_eq!(first.meta.path.as_deref(), Some("/"));
+ let rec: CookieRecord = serde_json::from_str(&first.payload.record).unwrap();
+ assert!(rec.secure && rec.http_only && rec.same_site == 1);
+ assert!(first.meta.session, "no expiry is a session cookie");
+ // The metadata names no value.
+ assert!(
+ !serde_json::to_string(&first.meta)
+ .unwrap()
+ .contains("v-user_session")
+ );
+}
+
+#[test]
+fn a_domain_choice_filters_cookies_by_site_and_leaves_files_alone() {
+ let (b, _reg) = backend();
+ let mut s = spec(&["Default/Bookmarks", "Default/Cookies"]);
+ s.domains = Some(vec!["github.com".into(), "notion.so".into()]);
+ let out = b.capture(&s).unwrap();
+ assert_eq!(
+ cookies(&out),
+ [
+ (".github.com".into(), "user_session".into()),
+ ("api.github.com".into(), "_gh_sess".into()),
+ (".notion.so".into(), "token_v2".into()),
+ ],
+ "api.github.com belongs to github.com; the tracker and the other site are gone"
+ );
+ assert_eq!(
+ out.iter().filter(|c| c.meta.kind == ItemKind::File).count(),
+ 1
+ );
+ // An empty choice sends no cookies at all.
+ s.domains = Some(vec![]);
+ assert!(cookies(&b.capture(&s).unwrap()).is_empty());
+ // Cookie minimization still applies: session cookies only.
+ let mut s = spec(&["Default/Cookies"]);
+ s.cookies = CookieFilter {
+ session_only: true,
+ drop_long_lived: false,
+ };
+ assert_eq!(cookies(&b.capture(&s).unwrap()).len(), 2);
+}
+
+#[test]
+fn consent_gated_files_need_the_user_to_pick_them() {
+ let (b, _reg) = backend();
+ // `Web Data` holds sign-in refresh tokens: in the provider's default
+ // selection it is not exported...
+ let out = b.capture(&ImportSpec {
+ app: "chrome".into(),
+ whole_app: true,
+ paths: None,
+ ..Default::default()
+ });
+ let keys: Vec<String> = out.unwrap().iter().map(|c| c.meta.key.clone()).collect();
+ assert!(!keys.iter().any(|k| k.ends_with("Web Data")), "{keys:?}");
+ // ...and when the user explicitly picks it, it is.
+ let out = b.capture(&spec(&["Default/Web Data"])).unwrap();
+ assert_eq!(out.len(), 1);
+ assert_eq!(out[0].meta.key, "Default/Web Data");
+}
+
+#[test]
+fn the_inventory_counts_cookies_per_site_without_decrypting_anything() {
+ use cua_teleport::browser_cookies::{TestCookieRow, write_cookies_db_for_tests};
+ let home = tempfile::tempdir().unwrap();
+ let profile = home
+ .path()
+ .join("Library/Application Support/Google/Chrome/Default");
+ let row = |host: &'static str, name: &'static str, expires: i64| TestCookieRow {
+ host_key: host,
+ name,
+ // Not a valid ciphertext: the inventory must never try to read it.
+ encrypted_value: b"v10-not-decryptable".to_vec(),
+ path: "/",
+ expires_utc: expires,
+ is_secure: true,
+ is_httponly: true,
+ samesite: 1,
+ };
+ write_cookies_db_for_tests(
+ &profile,
+ &[
+ row(".github.com", "user_session", 0),
+ row("api.github.com", "_gh_sess", 0),
+ row(".github.com", "_ga", 13_700_000_000_000_000),
+ row(".doubleclick.net", "IDE", 13_700_000_000_000_000),
+ row(".accounts.google.com", "SID", 13_700_000_000_000_000),
+ ],
+ )
+ .unwrap();
+ let reg = tempfile::tempdir().unwrap();
+ let spaces = Spaces::builder()
+ .home(reg.path())
+ .operator_display(Arc::new(cua_spaces::operator::NoDisplay))
+ .build();
+ let host: Arc<dyn HostEffects> = Arc::new(FakeHost::new().with_home(home.path()));
+ let mut registry = ExportRegistry::new();
+ registry.register(Box::new(Browser { host: host.clone() }));
+ let b = DaemonBackend::new(spaces, Arc::new(AppSessions::from_registry(registry)))
+ .with_host(host)
+ .with_platform(Platform::MacOS);
+ let inv = b.inventory("chrome", None).unwrap();
+ assert_eq!(inv.app_display, "Google Chrome");
+ let by = |d: &str| inv.domains.iter().find(|x| x.domain == d).unwrap().clone();
+ let github = by("github.com");
+ assert_eq!((github.cookies, github.session_cookies), (3, 2));
+ assert!(github.signin, "user_session is a sign-in cookie");
+ assert!(!by("doubleclick.net").signin, "a tracker keeps no sign-in");
+ assert!(by("google.com").identity_provider);
+ assert!(
+ inv.notes.iter().all(|n| !n.contains("not listed")),
+ "{:?}",
+ inv.notes
+ );
+}
diff --git a/libs/cua/crates/cua-spaces-ext/tests/site_login.rs b/libs/cua/crates/cua-spaces-ext/tests/site_login.rs
index 268a561c84..cd746f8d22 100644
--- a/libs/cua/crates/cua-spaces-ext/tests/site_login.rs
+++ b/libs/cua/crates/cua-spaces-ext/tests/site_login.rs
@@ -184,10 +184,16 @@ async fn import_decrypts_the_synthetic_profile_into_one_sealed_item() {
)
.await
.unwrap();
- assert_eq!(items.len(), 1);
- assert_eq!(items[0].site.as_deref(), Some("example.test"));
- assert_eq!(items[0].summary.passwords, 1);
- let shown = serde_json::to_string(&items).unwrap();
+ assert_eq!(items.saved, 1);
+ r.kv.broker().browse(&r.cua).await.unwrap();
+ let held = r.kv.broker().list_items(&r.cua, 0, 10).await.unwrap().items;
+ assert_eq!(held.len(), 1);
+ assert_eq!(held[0].kind, cua_keyvault::ItemKind::Password);
+ assert_eq!(
+ held[0].domain.as_deref(),
+ Some("http://login.example.test:8000")
+ );
+ let shown = serde_json::to_string(&held).unwrap();
assert!(!shown.contains(PASSWORD));
}
diff --git a/libs/cua/crates/cua-spaces-ext/tests/site_login_e2e.rs b/libs/cua/crates/cua-spaces-ext/tests/site_login_e2e.rs
index d6e5eabd47..36bf237d83 100644
--- a/libs/cua/crates/cua-spaces-ext/tests/site_login_e2e.rs
+++ b/libs/cua/crates/cua-spaces-ext/tests/site_login_e2e.rs
@@ -166,8 +166,7 @@ async fn rig() -> Option<Rig> {
)
.await
.unwrap();
- assert_eq!(items.len(), 1);
- assert_eq!(items[0].site.as_deref(), Some("example.test"));
+ assert_eq!(items.saved, 1);
let import_ms = t.elapsed().as_millis();
let mcp = McpServer::new(spaces.clone());
Some(Rig {
diff --git a/libs/cua/crates/cua-spaces-ext/tests/spaces_daemon_boundary.rs b/libs/cua/crates/cua-spaces-ext/tests/spaces_daemon_boundary.rs
index e9917d065e..64b8efa7a7 100644
--- a/libs/cua/crates/cua-spaces-ext/tests/spaces_daemon_boundary.rs
+++ b/libs/cua/crates/cua-spaces-ext/tests/spaces_daemon_boundary.rs
@@ -192,7 +192,7 @@ async fn scenario() {
)
.await
.unwrap();
- assert_eq!(items.len(), 1, "one saved login imported");
+ assert_eq!(items.saved, 1, "one saved login imported");
let sock = home.join("cua.sock");
let daemon = server::start(
runtime,
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
index c106071bc9..9279ef304b 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -1053,6 +1053,31 @@ pub fn app_picker_review(state: AppPickerState) -> Option<AppReviewView> {
core::teleport::flow::review(&state)
}
+/// The key a review's site choice is remembered under (`<app>|<space>`).
+#[uniffi::export]
+pub fn app_review_remember_key(app: String, space: String) -> String {
+ core::teleport::review::remember_key(&app, &space)
+}
+
+/// What was picked last time for `key` (an app and a Space), if anything.
+#[uniffi::export]
+pub fn app_review_remembered(
+ choices: Vec<AppRememberedChoice>,
+ key: String,
+) -> Option<Vec<String>> {
+ core::teleport::review::remembered(&choices, &key)
+}
+
+/// `choices` with the sites just sent remembered for `key`.
+#[uniffi::export]
+pub fn app_review_remember(
+ choices: Vec<AppRememberedChoice>,
+ key: String,
+ domains: Vec<String>,
+) -> Vec<AppRememberedChoice> {
+ core::teleport::review::remember(&choices, &key, &domains)
+}
+
/// The consent the confirmed review carries.
#[uniffi::export]
pub fn app_picker_consent(state: AppPickerState) -> AppTeleportConsent {
@@ -1399,37 +1424,92 @@ pub fn kv_space_access_key(
core::keyvault::view::space_access_key(&overview, now_ms, &space)
}
-/// The Passwords-style sidebar.
+/// The sidebar: All Items, Waiting, Access, Recent, and one row per app.
#[uniffi::export]
pub fn kv_sidebar(overview: KeyvaultOverview, now_ms: i64) -> KvSidebar {
core::keyvault::browse::sidebar(&overview, now_ms)
}
-/// The list for a sidebar selection.
+/// The pane for a sidebar selection (the vault list is [`kv_vault_view`]).
+#[uniffi::export]
+pub fn kv_list(overview: KeyvaultOverview, selection: KvSelection, now_ms: i64) -> KvListView {
+ core::keyvault::browse::list(&overview, &selection, now_ms)
+}
+
+/// The vault list's next state (search, selection, open groups).
#[uniffi::export]
-pub fn kv_list(
+pub fn kv_vault_reduce(
overview: KeyvaultOverview,
- selection: KvSelection,
- now_ms: i64,
- query: String,
-) -> KvListView {
- core::keyvault::browse::list(&overview, &selection, now_ms, &query)
+ state: KvVaultState,
+ action: KvVaultAction,
+) -> KvVaultState {
+ core::keyvault::vault::reduce(&overview, &state, &action)
+}
+
+/// The vault list: apps, sites and items with their locks, the selection and
+/// the batch bar.
+#[uniffi::export]
+pub fn kv_vault_view(overview: KeyvaultOverview, state: KvVaultState, now_ms: i64) -> KvVaultView {
+ core::keyvault::vault::view(&overview, &state, now_ms)
+}
+
+/// The selection without what the vault no longer holds.
+#[uniffi::export]
+pub fn kv_vault_prune(overview: KeyvaultOverview, state: KvVaultState) -> KvVaultState {
+ core::keyvault::vault::prune(&overview, &state)
+}
+
+/// What the Keyvault holds for `provider_id` that a teleport can send.
+#[uniffi::export]
+pub fn kv_vault_source(overview: KeyvaultOverview, provider_id: String) -> KvVaultSource {
+ core::keyvault::vault::vault_source(&overview, &provider_id)
+}
+
+/// The command that locks items.
+#[uniffi::export]
+pub fn kv_lock_command(ids: Vec<String>) -> KvCommand {
+ core::keyvault::vault::lock_command(&ids)
}
-/// One site's detail.
+/// The command that unlocks items (the daemon asks for Touch ID once).
#[uniffi::export]
-pub fn kv_site_detail(
+pub fn kv_unlock_command(ids: Vec<String>) -> KvCommand {
+ core::keyvault::vault::unlock_command(&ids)
+}
+
+/// The command that deletes items and wipes their copies in Spaces.
+#[uniffi::export]
+pub fn kv_delete_command(ids: Vec<String>) -> KvCommand {
+ core::keyvault::vault::delete_command(&ids)
+}
+
+/// The unlock prompt for `count` items (`name`: the one item's name). None
+/// when the user chose "Never ask again".
+#[uniffi::export]
+pub fn kv_unlock_prompt(
overview: KeyvaultOverview,
- key: String,
- now_ms: i64,
-) -> Option<KvSiteDetail> {
- core::keyvault::browse::site_detail(&overview, &key, now_ms)
+ count: u32,
+ name: Option<String>,
+) -> Option<KvUnlockPrompt> {
+ core::keyvault::vault::unlock_prompt(&overview, count, name.as_deref())
+}
+
+/// The unlock prompt whatever the setting says.
+#[uniffi::export]
+pub fn kv_unlock_prompt_always(count: u32, name: Option<String>) -> KvUnlockPrompt {
+ core::keyvault::vault::unlock_prompt_always(count, name.as_deref())
+}
+
+/// The delete confirmation.
+#[uniffi::export]
+pub fn kv_delete_confirm(count: u32, live_copies: u32) -> KvDeleteConfirm {
+ core::keyvault::vault::delete_confirm(count, live_copies)
}
-/// The site switch's command.
+/// How many Spaces hold a live copy of any of `ids`.
#[uniffi::export]
-pub fn kv_site_toggle(group: KvSiteGroup, on: bool) -> KvCommand {
- core::keyvault::view::site_toggle(&group, on)
+pub fn kv_live_copy_spaces(overview: KeyvaultOverview, ids: Vec<String>, now_ms: i64) -> u32 {
+ core::keyvault::vault::live_copy_spaces(&overview, &ids, now_ms)
}
/// Opens the approval sheet with nothing selected.
@@ -1558,6 +1638,14 @@ impl KeyvaultClient {
.unwrap_or_default()
}
+ /// Site icons the vault holds (not secret; empty while names are hidden).
+ pub async fn favicons(&self) -> Vec<KvFavicon> {
+ let inner = self.inner.clone();
+ cua_sdk::support::run(async move { Ok(inner.favicons().await) })
+ .await
+ .unwrap_or_default()
+ }
+
/// Runs one page action (a broker request).
pub async fn execute(&self, command: KvCommand) -> Result<KvOutcome> {
let inner = self.inner.clone();
@@ -1597,6 +1685,14 @@ impl KeyvaultClient {
let inner = self.inner.clone();
cua_sdk::support::run(async move { inner.lock().await.map_err(kv_error) }).await
}
+
+ /// What `app` holds, per domain with counts (the daemon asks for Touch ID
+ /// when the browse window is closed). Never a value.
+ pub async fn inventory(&self, app: String, profile: Option<String>) -> Result<KvInventory> {
+ let inner = self.inner.clone();
+ cua_sdk::support::run(async move { inner.inventory(&app, profile).await.map_err(kv_error) })
+ .await
+ }
}
// ---- Onboarding and settings ---------------------------------------------
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
index 806bfc7c61..76d881552e 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
@@ -2134,6 +2134,112 @@ pub struct AppPickerGridPrimary {
pub enabled: bool,
}
+/// Where the review sends from.
+pub type AppSendSource = core::teleport::review::SendSource;
+#[uniffi::remote(Enum)]
+pub enum AppSendSource {
+ /// Read the live app now (a browser's cookies are decrypted, so macOS asks
+ /// for Keychain access).
+ Live,
+ /// Send the items saved in the Keyvault for this app. Nothing is read from
+ /// the host.
+ Vault,
+}
+
+/// What the user picked last time for one app and Space.
+pub type AppRememberedChoice = core::teleport::review::RememberedChoice;
+#[uniffi::remote(Record)]
+pub struct AppRememberedChoice {
+ /// `<app>|<space>`.
+ pub key: String,
+ /// The sites (registrable domains) that were sent.
+ pub domains: Vec<String>,
+}
+
+/// One site of a browser, with its counts.
+pub type AppReviewDomain = core::teleport::review::ReviewDomain;
+#[uniffi::remote(Record)]
+pub struct AppReviewDomain {
+ /// The site (`github.com`).
+ pub domain: String,
+ /// "12 cookies, 2 storage values".
+ pub counts: String,
+ /// Items the site holds.
+ pub count: u32,
+ /// It looks like it keeps a sign-in.
+ pub signin: bool,
+ /// An identity provider: its session unlocks other apps.
+ pub identity_provider: bool,
+ /// Chosen to send.
+ pub selected: bool,
+ /// Can be chosen: it holds something that can be sent. A site whose
+ /// cookies are all unreadable is greyed out.
+ pub selectable: bool,
+ /// Cookies that cannot be read, shown greyed with `unavailable_note`.
+ pub unavailable: u32,
+ /// "3 cookies cannot be sent: Chrome protects them with ...", or empty.
+ pub unavailable_note: String,
+}
+
+/// A non-cookie consent line the user can turn off.
+pub type AppReviewToggle = core::teleport::review::ReviewToggle;
+#[uniffi::remote(Record)]
+pub struct AppReviewToggle {
+ /// The consent item's key.
+ pub key: String,
+ /// Label.
+ pub label: String,
+ /// Detail.
+ pub detail: String,
+ /// Bytes that leave.
+ pub bytes: u64,
+ /// A secret.
+ pub sensitive: bool,
+ /// Sent (not turned off).
+ pub selected: bool,
+}
+
+/// The saved Keyvault items of the app being teleported.
+pub type AppVaultSource = core::teleport::review::VaultSource;
+#[uniffi::remote(Record)]
+pub struct AppVaultSource {
+ /// The app has saved items that can be sent (passwords never are).
+ pub available: bool,
+ /// How many.
+ pub items: u32,
+ /// "saved 2 days ago".
+ pub saved: String,
+ /// The items chosen to send (ids).
+ pub selected: Vec<String>,
+ /// The app's saved passwords (ids), sent only when ticked.
+ pub password_ids: Vec<String>,
+}
+
+/// The review's choices.
+pub type AppReviewChoice = core::teleport::review::ReviewChoice;
+#[uniffi::remote(Record)]
+pub struct AppReviewChoice {
+ /// Where to send from.
+ pub source: AppSendSource,
+ /// The browser's sites with counts (none until read, or for an app that
+ /// is not a browser).
+ pub domains: Vec<KvDomainCount>,
+ /// The sites chosen.
+ pub selected_domains: Vec<String>,
+ /// The sites list's search text.
+ pub query: String,
+ /// Consent items (keys) turned off.
+ pub excluded: Vec<String>,
+ /// The saved items.
+ pub vault: AppVaultSource,
+ /// The sites were asked for (a failure counts: the review then sends
+ /// what the plan lists).
+ pub loaded: bool,
+ /// The saved passwords are ticked to send (off unless the user ticks
+ /// them; never remembered).
+ pub include_passwords: bool,
+}
+
/// What teleport can do with an app.
pub type AppTeleportCapability = core::teleport::flow::Capability;
#[uniffi::remote(Enum)]
@@ -2364,6 +2470,15 @@ pub struct AppTeleportConsent {
pub save_to_keyvault: bool,
/// [`Plan::relay_unsealed`]'s warning acknowledged (S1).
pub acknowledge_relay_plaintext: bool,
+ /// The sites whose cookies to send (the review's per-site choice);
+ /// `None` when the review did not list sites.
+ pub cookie_domains: Option<Vec<String>>,
+ /// Consent items (keys) the user turned off.
+ pub exclude: Vec<String>,
+ /// Send these saved Keyvault items instead of reading the live app.
+ pub from_vault: Option<Vec<String>>,
+ /// Also send the saved passwords (ticked in the review).
+ pub include_passwords: bool,
}
/// The "needs the Cua app" prompt for a Keyvault refusal.
@@ -2438,6 +2553,8 @@ pub struct AppPickerState {
pub save_to_keyvault: bool,
/// [`Plan::relay_unsealed`]'s warning acknowledged (S1).
pub acknowledged_relay_plaintext: bool,
+ /// What the review sends: which sites, which items, from where.
+ pub choice: AppReviewChoice,
/// Run events (last [`MAX_EVENTS`]).
pub events: Vec<AppTeleportRunEvent>,
/// The run's report.
@@ -2534,6 +2651,65 @@ pub enum AppPickerEvent {
/// Checked.
value: bool,
},
+ /// The browser's sites with counts arrived (and what was picked last time
+ /// for this app and Space, if anything).
+ DomainsLoaded {
+ /// The inventory.
+ inventory: KvInventory,
+ /// The sites sent last time.
+ remembered: Option<Vec<String>>,
+ },
+ /// The inventory could not be read (the review then sends what the plan
+ /// lists, as before).
+ DomainsFailed,
+ /// Pick or drop one site.
+ ToggleDomain {
+ /// The site.
+ domain: String,
+ },
+ /// Pick or drop every site the search shows.
+ SelectShownDomains {
+ /// Pick (true) or drop.
+ value: bool,
+ },
+ /// The sites list's search text.
+ DomainQuery {
+ /// Text.
+ text: String,
+ },
+ /// Turn a consent line on or off.
+ ToggleItem {
+ /// The consent item's key.
+ key: String,
+ },
+ /// Where to send from.
+ SendFrom {
+ /// The source.
+ source: AppSendSource,
+ },
+ /// The app's saved Keyvault items (what the Keyvault holds for it).
+ VaultItems {
+ /// How many can be sent.
+ count: u32,
+ /// When the newest was saved, Unix ms.
+ newest_ms: i64,
+ /// Now, Unix ms.
+ now_ms: i64,
+ /// The ones chosen to send (ids).
+ selected: Vec<String>,
+ /// The app's saved passwords (ids): sent only when ticked.
+ password_ids: Vec<String>,
+ },
+ /// Tick or untick "Also send saved passwords".
+ TogglePasswords {
+ /// Ticked.
+ value: bool,
+ },
+ /// The chosen saved items changed.
+ VaultSelection {
+ /// The ids.
+ selected: Vec<String>,
+ },
/// Confirm the review.
Confirm,
/// A run event.
@@ -2591,6 +2767,41 @@ pub struct AppReviewView {
pub leaves_text: Option<String>,
/// Caveats.
pub warnings: Vec<String>,
+ /// Lines the user can turn off (files, folders, state, secrets), each
+ /// with whether it is sent. The cookie store is the site list below.
+ pub toggles: Vec<AppReviewToggle>,
+ /// The plan sends a browser's cookies, so the sites can be chosen.
+ pub offers_domains: bool,
+ /// The sites have not been read yet (the shell asks the Keyvault for
+ /// them, which may ask for Touch ID).
+ pub needs_domains: bool,
+ /// The sites with counts, filtered by the search.
+ pub domains: Vec<AppReviewDomain>,
+ /// "3 of 12 sites".
+ pub domain_summary: String,
+ /// The sites search text.
+ pub domain_query: String,
+ /// The sites chosen (what is remembered for next time).
+ pub selected_domains: Vec<String>,
+ /// Where it sends from.
+ pub source: AppSendSource,
+ /// The app has saved Keyvault items to send instead of reading the live
+ /// app.
+ pub offers_vault: bool,
+ /// The saved items.
+ pub vault: AppVaultSource,
+ /// "Send from the Keyvault (212 items, saved 2 days ago)".
+ pub vault_label: String,
+ /// "Read Chrome now (macOS asks for Keychain access)".
+ pub live_label: String,
+ /// "Also send saved passwords" shows (there are some to send).
+ pub offers_passwords: bool,
+ /// Ticked.
+ pub include_passwords: bool,
+ /// "Also send 14 saved passwords".
+ pub passwords_label: String,
+ /// What the Keychain will do for this source, in a line.
+ pub source_note: String,
}
/// The image list's local engine.
@@ -3483,38 +3694,6 @@ pub struct AppWizardView {
pub labels: AppWizardLabels,
}
-/// A cookie's metadata (never its value).
-pub type KvCookieInfo = core::keyvault::wire::KvCookieInfo;
-#[uniffi::remote(Record)]
-pub struct KvCookieInfo {
- /// Name.
- pub name: String,
- /// Domain.
- pub domain: String,
- /// Session cookie.
- pub session: bool,
- /// Expiry.
- pub expires_ms: Option<i64>,
-}
-
-/// What an item holds, as counts and names.
-pub type KvItemSummary = core::keyvault::wire::KvItemSummary;
-#[uniffi::remote(Record)]
-pub struct KvItemSummary {
- /// Cookies.
- pub cookies: Vec<KvCookieInfo>,
- /// Storage origins.
- pub storage_origins: Vec<String>,
- /// Saved passwords.
- pub passwords: u32,
- /// Files.
- pub files: Vec<String>,
- /// Keychain services.
- pub keychain_services: Vec<String>,
- /// Bytes.
- pub bytes: u64,
-}
-
/// An item's policy.
pub type KvItemPolicy = core::keyvault::wire::KvItemPolicy;
#[uniffi::remote(Record)]
@@ -3527,37 +3706,45 @@ pub struct KvItemPolicy {
pub unattended: bool,
}
-/// One saved item (redacted).
+/// One secret item of the vault: a cookie, a localStorage value, a password
+/// or a file, in the app it came from (`cua_keyvault::ItemMeta`). Domains and
+/// keys are present only inside the browse window; a value never is.
pub type KvItem = core::keyvault::wire::KvItem;
#[uniffi::remote(Record)]
pub struct KvItem {
/// Id.
pub id: String,
- /// `browser_site`, `site_passwords`, `app_session`.
+ /// `cookie`, `local_storage`, `password` or `file`.
pub kind: String,
- /// Label.
- pub label: String,
- /// Provider.
+ /// The source app (`chrome`, `slack`).
pub provider_id: String,
- /// App.
+ /// The app's name.
pub app_display: String,
- /// Site.
- pub site: Option<String>,
- /// Account.
- pub account: Option<String>,
+ /// A cookie's host, a storage value's or password's origin; none for a
+ /// file or when the names are hidden.
+ pub domain: Option<String>,
+ /// A cookie name, storage key, username or file path; empty when the
+ /// names are hidden.
+ pub key: String,
+ /// A cookie's path.
+ pub path: Option<String>,
/// Profile.
pub source: String,
- /// Summary.
- pub summary: KvItemSummary,
- /// Warnings.
- pub warnings: Vec<String>,
- /// Identity providers always ask.
+ /// A cookie without an expiry.
+ pub session: bool,
+ /// A cookie's expiry, Unix ms.
+ pub expires_ms: Option<i64>,
+ /// Bytes.
+ pub bytes: u64,
+ /// The blob a big file's bytes live in.
+ pub blob: Option<String>,
+ /// Identity providers always ask: they cannot be unlocked.
pub identity_provider: bool,
- /// Policy.
+ /// Policy: `unattended` is the unlock.
pub policy: KvItemPolicy,
/// Created.
pub created_ms: u64,
- /// Updated.
+ /// Last saved.
pub updated_ms: u64,
/// Revision.
pub rev: u64,
@@ -3565,6 +3752,55 @@ pub struct KvItem {
pub record_digest: String,
}
+/// A site's icon, read from the source browser's own local store when its
+/// items were saved. Not secret. `png` is base64.
+pub type KvFavicon = core::keyvault::wire::KvFavicon;
+#[uniffi::remote(Record)]
+pub struct KvFavicon {
+ /// The site (registrable domain).
+ pub site: String,
+ /// PNG, base64.
+ pub png: String,
+}
+
+/// One domain a browser holds secrets for, with counts (never values).
+pub type KvDomainCount = core::keyvault::wire::KvDomainCount;
+#[uniffi::remote(Record)]
+pub struct KvDomainCount {
+ /// Registrable domain.
+ pub domain: String,
+ /// Cookies.
+ pub cookies: u32,
+ /// Cookies without an expiry.
+ pub session_cookies: u32,
+ /// localStorage values.
+ pub local_storage: u32,
+ /// Saved passwords.
+ pub passwords: u32,
+ /// Looks like it keeps a sign-in.
+ pub signin: bool,
+ /// An identity provider.
+ pub identity_provider: bool,
+ /// Cookies that cannot be read (Chrome's app-bound encryption).
+ pub unavailable: u32,
+ /// Why they cannot be read.
+ pub unavailable_reason: String,
+}
+
+/// What a host app offers, per domain (`cua_keyvault::broker::Inventory`).
+pub type KvInventory = core::keyvault::wire::KvInventory;
+#[uniffi::remote(Record)]
+pub struct KvInventory {
+ /// Provider id.
+ pub provider_id: String,
+ /// App name.
+ pub app_display: String,
+ /// Domains with counts.
+ pub domains: Vec<KvDomainCount>,
+ /// Notes.
+ pub notes: Vec<String>,
+}
+
/// How a caller is signed (`cua_keyvault::caller::Signing`: tagged by
/// `kind`, snake_case).
pub type KvSigning = core::keyvault::wire::KvSigning;
@@ -3629,8 +3865,6 @@ pub enum KvSelector {
app: String,
/// Site.
site: String,
- /// Account.
- account: Option<String>,
},
/// A whole app.
App {
@@ -3831,6 +4065,13 @@ pub struct KvStatus {
/// Protector kinds that can unlock this vault now (`macos-keychain`,
/// `windows-credential`, `passphrase`, `recovery`).
pub unlock_protectors: Vec<String>,
+ /// The browse window is open until this time, Unix ms: item names are
+ /// visible until then.
+ pub browse_until_ms: Option<u64>,
+ /// "Never ask again" on the unlock prompt is on.
+ pub skip_unlock_prompt: Option<bool>,
+ /// An earlier preview's vault was found and set aside.
+ pub reset_notice: Option<String>,
}
/// The audit chain check.
@@ -3862,8 +4103,12 @@ pub struct KeyvaultOverview {
pub status: Option<KvStatus>,
/// The daemon was checked against Cua's signature.
pub server_verified: bool,
- /// Items.
+ /// The vault's secret items, in order (app, domain, key).
pub items: Vec<KvItem>,
+ /// Domains and keys are present in `items` (the browse window is open).
+ pub names_visible: bool,
+ /// Items in the vault.
+ pub items_total: u32,
/// Pending requests.
pub pending: Vec<KvPending>,
/// Grants.
@@ -3896,13 +4141,36 @@ pub enum KvCommand {
/// On.
disabled: bool,
},
- /// Per-item unattended (turning on asks for Touch ID).
+ /// Per-item unattended (turning on asks for Touch ID): the same as
+ /// [`KvCommand::SetLocked`] with `locked` the other way round.
SetUnattended {
/// Items.
item_ids: Vec<String>,
/// On.
unattended: bool,
},
+ /// Lock or unlock items together. Unlocking allows unattended access and
+ /// asks for Touch ID once for the whole batch; locking does not.
+ SetLocked {
+ /// Items.
+ item_ids: Vec<String>,
+ /// Lock (true) or unlock.
+ locked: bool,
+ },
+ /// Delete items, wiping every live copy of them in Spaces.
+ DeleteItems {
+ /// Items.
+ item_ids: Vec<String>,
+ },
+ /// "Never ask again" on the unlock prompt (Settings turns it back on).
+ SetSkipUnlockPrompt {
+ /// On.
+ on: bool,
+ },
+ /// Show item names for a few minutes (the daemon asks for Touch ID).
+ Browse,
+ /// Hide item names again.
+ EndBrowse,
/// Revoke a grant (`*`: all).
RevokeGrant {
/// Id.
@@ -3961,48 +4229,6 @@ pub struct KvSigningBadge {
pub tone: KvTone,
}
-/// What a consent chip says.
-pub type KvConsentChipKind = core::keyvault::view::ConsentChipKind;
-#[uniffi::remote(Enum)]
-pub enum KvConsentChipKind {
- /// A request waits.
- Pending,
- /// A copy is in a Space.
- Delivered,
- /// A live grant.
- Granted,
- /// An unattended rule.
- Rule,
- /// Nothing: asks every time.
- Asks,
-}
-
-/// One consent state of an item.
-pub type KvConsentChip = core::keyvault::view::ConsentChip;
-#[uniffi::remote(Record)]
-pub struct KvConsentChip {
- /// Kind.
- pub kind: KvConsentChipKind,
- /// Text.
- pub text: String,
-}
-
-/// One account of a site.
-pub type KvItemRow = core::keyvault::view::ItemRow;
-#[uniffi::remote(Record)]
-pub struct KvItemRow {
- /// The item.
- pub item: KvItem,
- /// "[email protected]", "Whole app session", or the profile.
- pub account: String,
- /// Strongest first; `asks` when nothing else applies.
- pub consent: Vec<KvConsentChip>,
- /// The unattended switch can be changed (not an identity provider).
- pub toggle_enabled: bool,
- /// The switch's tooltip.
- pub toggle_help: String,
-}
-
/// Mixed on/off.
pub type KvTri = core::keyvault::view::Tri;
#[uniffi::remote(Enum)]
@@ -4015,24 +4241,6 @@ pub enum KvTri {
Mixed,
}
-/// A site (browsers) or app (whole-app sessions) with its accounts.
-pub type KvSiteGroup = core::keyvault::view::SiteGroup;
-#[uniffi::remote(Record)]
-pub struct KvSiteGroup {
- /// Stable key.
- pub key: String,
- /// "github.com" or "Slack".
- pub title: String,
- /// "Chrome", "Slack".
- pub app: String,
- /// Accounts.
- pub rows: Vec<KvItemRow>,
- /// Unattended across rows.
- pub unattended: KvTri,
- /// Every row is an identity provider.
- pub locked: bool,
-}
-
/// A decision's tone.
pub type KvDecisionTone = core::keyvault::view::DecisionTone;
#[uniffi::remote(Enum)]
@@ -4130,12 +4338,6 @@ pub struct KvLabels {
pub confirm_note: String,
/// "Protection".
pub protection_title: String,
- /// A site's accounts section.
- pub accounts_title: String,
- /// A site's app fact.
- pub app_label: String,
- /// A site's switch.
- pub every_account: String,
}
/// The page chrome: availability, the kill switch, banners, protection.
@@ -4172,8 +4374,12 @@ pub struct KvPage {
pub revoke_all: bool,
/// Items exist.
pub has_items: bool,
- /// Search shows (more than six items).
+ /// Search shows (any item exists).
pub search_visible: bool,
+ /// "Never ask again" on the unlock prompt is on (Settings turns it off).
+ pub skip_unlock_prompt: bool,
+ /// An earlier preview's vault was set aside: one line to show.
+ pub reset_notice: Option<String>,
/// Pending requests (the sidebar badge).
pub pending_count: u32,
/// The switch's tooltip (it reads "on" while the Keyvault works).
@@ -4184,11 +4390,291 @@ pub struct KvPage {
pub form: Option<KvCredentialForm>,
}
+/// The type of a secret, as the list draws it.
+pub type KvKind = core::keyvault::vault::KvKind;
+#[uniffi::remote(Enum)]
+pub enum KvKind {
+ /// A cookie.
+ Cookie,
+ /// A localStorage value.
+ LocalStorage,
+ /// A saved password.
+ Password,
+ /// A file.
+ File,
+}
+
+/// The lock of a row or a group.
+pub type KvLock = core::keyvault::vault::KvLock;
+#[uniffi::remote(Enum)]
+pub enum KvLock {
+ /// Every item needs approval for each use.
+ Locked,
+ /// Every item allows unattended access.
+ Unlocked,
+ /// Some of each.
+ Mixed,
+}
+
+/// The list's own state.
+pub type KvVaultState = core::keyvault::vault::VaultState;
+#[uniffi::remote(Record)]
+pub struct KvVaultState {
+ /// The search text.
+ pub query: String,
+ /// Selected item ids.
+ pub selected: Vec<String>,
+ /// Open groups (their keys); the rest are closed.
+ pub expanded: Vec<String>,
+ /// Narrowed to one app (its provider id), as the sidebar picks it.
+ pub app: Option<String>,
+}
+
+/// An input to the list.
+pub type KvVaultAction = core::keyvault::vault::VaultAction;
+#[uniffi::remote(Enum)]
+pub enum KvVaultAction {
+ /// The search text changed.
+ Query {
+ /// Text.
+ text: String,
+ },
+ /// Select or deselect one item.
+ Toggle {
+ /// Item id.
+ id: String,
+ },
+ /// Select or deselect every shown item of an app, a site or the files
+ /// of an app (all of them when any is unselected, none when all are).
+ ToggleGroup {
+ /// Group key.
+ key: String,
+ },
+ /// Select every shown item.
+ SelectAll,
+ /// Deselect everything.
+ Clear,
+ /// Open or close a group.
+ ToggleOpen {
+ /// Group key.
+ key: String,
+ },
+}
+
+/// What the list shows for an item row.
+pub type KvVaultRow = core::keyvault::vault::VaultRow;
+#[uniffi::remote(Record)]
+pub struct KvVaultRow {
+ /// Item id.
+ pub id: String,
+ /// Type.
+ pub kind: KvKind,
+ /// "Cookie".
+ pub kind_label: String,
+ /// The type's SF Symbol.
+ pub symbol: String,
+ /// The key: a cookie name, storage key, username or file name.
+ pub title: String,
+ /// Grey line: the domain, or the file's folder.
+ pub subtitle: String,
+ /// Grey time: "2 min ago".
+ pub updated: String,
+ /// Locked (needs approval for every use).
+ pub locked: bool,
+ /// The lock icon: `lock.fill` or `lock.open`.
+ pub lock_symbol: String,
+ /// The lock's tooltip and accessibility label.
+ pub lock_help: String,
+ /// Identity provider: always asks, cannot be unlocked.
+ pub identity_provider: bool,
+ /// Selected.
+ pub selected: bool,
+}
+
+/// A site inside an app: its items.
+pub type KvVaultSite = core::keyvault::vault::VaultSite;
+#[uniffi::remote(Record)]
+pub struct KvVaultSite {
+ /// Group key.
+ pub key: String,
+ /// "github.com".
+ pub site: String,
+ /// Items (all of them, even while closed).
+ pub count: u32,
+ /// "12 cookies, 2 storage values".
+ pub counts: String,
+ /// Grey time of the newest save.
+ pub updated: String,
+ /// Selection of its items.
+ pub selected: KvTri,
+ /// Lock of its items.
+ pub lock: KvLock,
+ /// Items a click on the lock unlocks (locked, not identity providers).
+ pub unlock_ids: Vec<String>,
+ /// Items a click on the lock locks (unlocked).
+ pub lock_ids: Vec<String>,
+ /// Open.
+ pub open: bool,
+ /// Its rows (empty while closed, unless searching).
+ pub rows: Vec<KvVaultRow>,
+}
+
+/// The files of an app.
+pub type KvVaultFiles = core::keyvault::vault::VaultFiles;
+#[uniffi::remote(Record)]
+pub struct KvVaultFiles {
+ /// Group key.
+ pub key: String,
+ /// Files.
+ pub count: u32,
+ /// Selection of its items.
+ pub selected: KvTri,
+ /// Lock of its items.
+ pub lock: KvLock,
+ /// Items a click on the lock unlocks (locked, not identity providers).
+ pub unlock_ids: Vec<String>,
+ /// Items a click on the lock locks (unlocked).
+ pub lock_ids: Vec<String>,
+ /// Open.
+ pub open: bool,
+ /// Its rows (empty while closed, unless searching).
+ pub rows: Vec<KvVaultRow>,
+}
+
+/// An app and everything saved from it.
+pub type KvVaultApp = core::keyvault::vault::VaultApp;
+#[uniffi::remote(Record)]
+pub struct KvVaultApp {
+ /// Group key: the provider id (`chrome`).
+ pub key: String,
+ /// The provider id, for the app's icon.
+ pub provider_id: String,
+ /// "Google Chrome".
+ pub name: String,
+ /// Items.
+ pub count: u32,
+ /// "212 items, 14 unlocked".
+ pub summary: String,
+ /// Grey time of the newest save.
+ pub updated: String,
+ /// Selection of its items.
+ pub selected: KvTri,
+ /// Lock of its items.
+ pub lock: KvLock,
+ /// Items a click on the lock unlocks (locked, not identity providers).
+ pub unlock_ids: Vec<String>,
+ /// Items a click on the lock locks (unlocked).
+ pub lock_ids: Vec<String>,
+ /// Open.
+ pub open: bool,
+ /// Sites with their items, by name.
+ pub sites: Vec<KvVaultSite>,
+ /// Files, when it has any.
+ pub files: Option<KvVaultFiles>,
+}
+
+/// What the batch bar offers for the current selection.
+pub type KvVaultSelection = core::keyvault::vault::VaultSelection;
+#[uniffi::remote(Record)]
+pub struct KvVaultSelection {
+ /// Selected items.
+ pub count: u32,
+ /// Their ids, in list order.
+ pub ids: Vec<String>,
+ /// "3 selected".
+ pub title: String,
+ /// Some selected item is locked and may be unlocked.
+ pub can_unlock: bool,
+ /// Some selected item is unlocked.
+ pub can_lock: bool,
+ /// Selected items that always ask (identity providers).
+ pub always_ask: u32,
+ /// The ids to send when unlocking (locked, not identity providers).
+ pub unlock_ids: Vec<String>,
+ /// The ids to send when locking (unlocked).
+ pub lock_ids: Vec<String>,
+}
+
+/// The list as drawn.
+pub type KvVaultView = core::keyvault::vault::VaultView;
+#[uniffi::remote(Record)]
+pub struct KvVaultView {
+ /// Apps, by name.
+ pub apps: Vec<KvVaultApp>,
+ /// Items shown (after search).
+ pub shown: u32,
+ /// Items in the vault.
+ pub total: u32,
+ /// "No items yet." and friends.
+ pub empty_text: Option<String>,
+ /// Domains and keys are hidden until the user confirms with Touch ID.
+ pub names_hidden: bool,
+ /// What to say about it.
+ pub hidden_note: Option<String>,
+ /// The button that opens the names.
+ pub show_names_label: String,
+ /// The search field's prompt.
+ pub search_prompt: String,
+ /// The selection.
+ pub selection: KvVaultSelection,
+ /// Select all is offered.
+ pub can_select_all: bool,
+}
+
+/// The unlock prompt: what the user is agreeing to before the daemon asks
+/// for Touch ID.
+pub type KvUnlockPrompt = core::keyvault::vault::UnlockPrompt;
+#[uniffi::remote(Record)]
+pub struct KvUnlockPrompt {
+ /// "Allow unattended access?"
+ pub title: String,
+ /// What it allows.
+ pub message: String,
+ /// "3 items" (a batch), or the one item's name.
+ pub subject: String,
+ /// "Deny".
+ pub deny: String,
+ /// "Allow".
+ pub allow: String,
+ /// "Never ask again".
+ pub never_ask: String,
+}
+
+/// The delete confirmation.
+pub type KvDeleteConfirm = core::keyvault::vault::KvDeleteConfirm;
+#[uniffi::remote(Record)]
+pub struct KvDeleteConfirm {
+ /// "Delete 3 items?"
+ pub title: String,
+ /// What deleting does.
+ pub message: String,
+ /// "Delete".
+ pub confirm: String,
+ /// "Cancel".
+ pub cancel: String,
+}
+
+/// What the Keyvault holds for one app that a teleport can send (passwords
+/// never are): how many, when the newest was saved, and their ids.
+pub type KvVaultSource = core::keyvault::vault::KvVaultSource;
+#[uniffi::remote(Record)]
+pub struct KvVaultSource {
+ /// Items that can be sent.
+ pub count: u32,
+ /// When the newest was saved, Unix ms (0: none).
+ pub newest_ms: i64,
+ /// Their ids, in list order.
+ pub ids: Vec<String>,
+ /// The app's saved passwords (ids), never part of `ids`: they are sent
+ /// only when ticked in the review.
+ pub password_ids: Vec<String>,
+}
+
/// A sidebar category.
pub type KvCategory = core::keyvault::browse::KvCategory;
#[uniffi::remote(Enum)]
pub enum KvCategory {
- /// Every site.
+ /// Every item, grouped by app.
All,
/// Requests waiting for approval.
Waiting,
@@ -4214,17 +4700,17 @@ pub struct KvCategoryRow {
pub badge: Option<u32>,
}
-/// A site row.
-pub type KvSiteRow = core::keyvault::browse::SiteRow;
+/// An app row: everything saved from one app.
+pub type KvAppRow = core::keyvault::browse::AppRow;
#[uniffi::remote(Record)]
-pub struct KvSiteRow {
- /// Group key.
+pub struct KvAppRow {
+ /// The provider id (`chrome`): the key, and what the icon is looked up by.
pub key: String,
- /// "github.com" or "Slack".
+ /// "Google Chrome".
pub title: String,
- /// Accounts.
- pub accounts: u32,
- /// Something waits for this site.
+ /// Items.
+ pub items: u32,
+ /// Something waits for this app.
pub waiting: bool,
}
@@ -4232,10 +4718,10 @@ pub struct KvSiteRow {
pub type KvSidebar = core::keyvault::browse::KvSidebar;
#[uniffi::remote(Record)]
pub struct KvSidebar {
- /// All, Waiting, Access, Recent.
+ /// All Items, Waiting, Access, Recent.
pub categories: Vec<KvCategoryRow>,
- /// One row per site or app.
- pub sites: Vec<KvSiteRow>,
+ /// One row per app, by name.
+ pub apps: Vec<KvAppRow>,
}
/// What the sidebar selected.
@@ -4247,9 +4733,9 @@ pub enum KvSelection {
/// Which.
category: KvCategory,
},
- /// A site.
- Site {
- /// Group key.
+ /// One app's items.
+ App {
+ /// Its provider id.
key: String,
},
}
@@ -4264,47 +4750,31 @@ pub struct KvRecentRow {
pub age: String,
}
-/// The list pane for a selection.
+/// The pane for a selection other than the vault list.
pub type KvListView = core::keyvault::browse::KvListView;
#[uniffi::remote(Record)]
pub struct KvListView {
/// Title.
pub title: String,
- /// Sites (All, or the one site).
- pub sites: Vec<KvSiteGroup>,
+ /// The vault list shows (All Items, or one app).
+ pub vault: bool,
/// Waiting.
pub pending: Vec<KvPendingRow>,
/// Access.
pub access: Vec<KvAccessRow>,
/// Recent.
pub recent: Vec<KvRecentRow>,
- /// "No items yet." and friends.
+ /// "Nothing is waiting." and friends.
pub empty_text: Option<String>,
}
-/// The detail pane of one site: the site switch and each account.
-pub type KvSiteDetail = core::keyvault::browse::SiteDetail;
-#[uniffi::remote(Record)]
-pub struct KvSiteDetail {
- /// The group.
- pub group: KvSiteGroup,
- /// The site switch shows (more than one account).
- pub site_switch: bool,
- /// The site switch's state.
- pub site_state: KvTri,
- /// The site switch can be flipped.
- pub site_switch_enabled: bool,
- /// Its tooltip.
- pub site_switch_help: String,
-}
-
/// The sheet's state: which rows are ticked.
pub type KvApprovalState = core::keyvault::approval::ApprovalState;
#[uniffi::remote(Record)]
pub struct KvApprovalState {
/// The request.
pub request_id: String,
- /// Ticked row keys (item ids, or `import:<n>` for new items).
+ /// Ticked row keys (`<app>|<site>`, or `import:<n>` for new items).
pub selected: Vec<String>,
}
@@ -4323,16 +4793,23 @@ pub enum KvApprovalAction {
Clear,
}
-/// One row of the sheet.
+/// One row of the sheet: a site (or an app's files) with how many items
+/// it carries, or an app the approval would save.
pub type KvApprovalRow = core::keyvault::approval::ApprovalRow;
#[uniffi::remote(Record)]
pub struct KvApprovalRow {
- /// Row key.
+ /// Row key: `<app>|<site>`, `<app>|files`, or `import:<n>`.
pub key: String,
- /// Site or app.
+ /// The site, or the app for files and imports.
pub title: String,
- /// Account, or "Not imported yet".
+ /// "3 cookies, 1 password", or "Not saved yet".
pub account: String,
+ /// The app's provider id (its icon), when known.
+ pub provider_id: String,
+ /// Items the row stands for.
+ pub items: u32,
+ /// The items' ids.
+ pub item_ids: Vec<String>,
/// Ticked.
pub selected: bool,
/// A new item the approval imports.
@@ -4445,10 +4922,25 @@ pub enum KvOutcome {
/// Key.
key: Option<String>,
},
- /// Items after a policy change.
- Items {
- /// Items.
- items: Vec<KvItem>,
+ /// Items locked or unlocked. Identity providers always ask: they are in
+ /// `skipped`, never changed.
+ Locked {
+ /// Items whose lock changed.
+ changed: Vec<String>,
+ /// Items left locked (identity providers).
+ skipped: Vec<String>,
+ },
+ /// Items deleted.
+ Deleted {
+ /// Items deleted.
+ count: u32,
+ /// Copies wiped in Spaces.
+ wiped: Vec<String>,
+ },
+ /// The browse window is open until then, Unix ms.
+ Browsing {
+ /// When it closes.
+ until_ms: u64,
},
/// Grants revoked.
Revoked {
@@ -5681,6 +6173,13 @@ pub struct AppSettings {
/// longer shows them, nothing is revoked or wiped
/// ([`crate::keyvault::view::prune_dismissed`] forgets the gone ones).
pub dismissed_access: Vec<String>,
+ /// Keyvault rows may load a site's icon from Google's favicon service
+ /// when the source browser had none (Settings, Keyvault; on by default).
+ /// Off, only icons read locally are shown.
+ pub keyvault_site_icons: bool,
+ /// The sites the user sent to each Space last time, per app
+ /// ([`crate::teleport::review::remember`]): the review starts from them.
+ pub teleport_choices: Vec<AppRememberedChoice>,
/// Settings, General: a running Space's desktop streams as soon as it
/// is opened (on by default); off, it waits for Connect
/// ([`crate::spaces::cover`]).
@@ -5769,6 +6268,15 @@ pub struct AppSettingsInput {
/// The Keyvault's auto-wipe, once the broker told it (none: no
/// Keyvault section).
pub keyvault_auto_wipe: Option<bool>,
+ /// The unlock prompt shows (false once the user chose "Never ask
+ /// again"); none until the broker told it.
+ pub keyvault_unlock_prompt: Option<bool>,
+ /// Load site icons from Google when the browser had none
+ /// ([`AppSettings::keyvault_site_icons`]).
+ pub keyvault_site_icons: bool,
+ /// The Keyvault's protection facts (Touch ID, the daemon's signature),
+ /// shown in the section.
+ pub keyvault_protection: Vec<AppFact>,
/// "Connect to the desktop automatically" (none: no row; a shell
/// without the preview cover leaves it out).
pub auto_connect: Option<bool>,
diff --git a/libs/cua/crates/cua-spaces-ffi/src/teleport.rs b/libs/cua/crates/cua-spaces-ffi/src/teleport.rs
index e350ff82e0..aae08f1ee8 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/teleport.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/teleport.rs
@@ -302,6 +302,8 @@ impl Teleport {
cookies: cua_keyvault::broker::CookieFilter::default(),
confirm_passwords: true,
paths: Some(paths.clone()),
+ domains: None,
+ passwords: false,
};
run(async move {
let mut client = cua_keyvault::client::KeyvaultClient::connect_default()
diff --git a/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs b/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs
index 8c27a5eafe..19ec66e7cc 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs
@@ -616,7 +616,7 @@ mod space_side {
}
/// The user's answer to the consent screen.
- #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, uniffi::Record)]
+ #[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record)]
pub struct TeleportConsent {
/// Confirmed.
pub approved: bool,
@@ -630,6 +630,20 @@ mod space_side {
/// Saw and accepted `TeleportPlan.relay_unsealed`'s warning (S1).
#[uniffi(default = false)]
pub acknowledge_relay_plaintext: bool,
+ /// The review's per-site choice: the sites whose cookies to send
+ /// (`None`: every cookie in the selection).
+ #[uniffi(default = None)]
+ pub cookie_domains: Option<Vec<String>>,
+ /// Consent items (their keys) the user turned off.
+ #[uniffi(default = [])]
+ pub exclude: Vec<String>,
+ /// Send these saved Keyvault items (ids) instead of reading the
+ /// live app: nothing is captured from the host.
+ #[uniffi(default = None)]
+ pub from_vault: Option<Vec<String>>,
+ /// Also send the saved passwords: only when ticked in the review.
+ #[uniffi(default = false)]
+ pub include_passwords: bool,
}
/// One progress event of [`Teleport::run`].
@@ -856,6 +870,10 @@ mod space_side {
acknowledge_sensitive: consent.acknowledge_sensitive,
save_to_keyvault: consent.save_to_keyvault,
acknowledge_relay_plaintext: consent.acknowledge_relay_plaintext,
+ cookie_domains: consent.cookie_domains.clone(),
+ exclude: consent.exclude.clone(),
+ from_vault: consent.from_vault.clone(),
+ include_passwords: consent.include_passwords,
})
.map_err(crate::teleport_app::ux_err)?;
let sessions = sessions(self);
diff --git a/libs/cua/crates/cua-teleport-bundle/src/cookies.rs b/libs/cua/crates/cua-teleport-bundle/src/cookies.rs
index b8fce51ecb..1143178d05 100644
--- a/libs/cua/crates/cua-teleport-bundle/src/cookies.rs
+++ b/libs/cua/crates/cua-teleport-bundle/src/cookies.rs
@@ -44,6 +44,46 @@ pub struct CookieItem {
/// Chrome's `samesite` enum (-1 unspecified, 0 none, 1 lax, 2 strict).
#[serde(default)]
pub samesite: i64,
+ /// Every other column of Chrome's current cookie schema the source had
+ /// (flattened into the same JSON object), so the destination's row is
+ /// the source's row. All optional: an older sender omits them and the
+ /// receiver fills Chrome's defaults.
+ #[serde(flatten)]
+ pub extra: CookieExtra,
+}
+
+/// The cookie columns beyond the core ones.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CookieExtra {
+ /// `creation_utc` (Chrome microseconds since 1601).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub creation_utc: Option<i64>,
+ /// `last_access_utc`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_access_utc: Option<i64>,
+ /// `last_update_utc`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_update_utc: Option<i64>,
+ /// Chrome's priority (0 low, 1 medium, 2 high).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub priority: Option<i64>,
+ /// 0 unset, 1 non-secure, 2 secure.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source_scheme: Option<i64>,
+ /// -1 unspecified.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source_port: Option<i64>,
+ /// 0 unknown, 1 http, 2 script, 3 other.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source_type: Option<i64>,
+ /// `has_cross_site_ancestor`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub has_cross_site_ancestor: Option<i64>,
+ /// The top-level site of a partitioned (CHIPS) cookie (written back as
+ /// `top_frame_site_key`, so it stays partitioned); absent or empty for an
+ /// unpartitioned cookie.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub partition_key: Option<String>,
}
impl Drop for CookieItem {
@@ -85,6 +125,7 @@ mod tests {
is_secure: true,
is_httponly: true,
samesite: 1,
+ extra: CookieExtra::default(),
},
CookieItem {
host_key: "api.github.com".into(),
@@ -95,6 +136,7 @@ mod tests {
is_secure: true,
is_httponly: false,
samesite: -1,
+ extra: CookieExtra::default(),
},
];
assert_eq!(parse(&serialize(&items)), items);
diff --git a/libs/cua/crates/cua-teleport-bundle/src/lib.rs b/libs/cua/crates/cua-teleport-bundle/src/lib.rs
index 9ea8d9af9d..dfe8ab563f 100644
--- a/libs/cua/crates/cua-teleport-bundle/src/lib.rs
+++ b/libs/cua/crates/cua-teleport-bundle/src/lib.rs
@@ -22,6 +22,10 @@
//! [`TransferManifest`], [`LaunchSpec`], …);
//! - [`keychain`]: the reserved `keychain.json` entry format (items are read
//! on the sender and installed on the receiver);
+//! - [`local_storage`]: the reserved `localstorage.json` entry (a Chromium
+//! browser's localStorage as items);
+//! - [`logins`]: the reserved `logins.json` entry (saved passwords the user
+//! ticked, re-encrypted by the receiver);
//! - [`layout`]: per-app layout descriptors — which profile files make up each
//! app's session, the canonical bundle paths, and how they remap onto each
//! destination platform -- as pure data and pure functions;
@@ -40,6 +44,8 @@ pub mod cookies;
mod error;
pub mod keychain;
pub mod layout;
+pub mod local_storage;
+pub mod logins;
mod types;
pub use error::{Result, TeleportError};
diff --git a/libs/cua/crates/cua-teleport-bundle/src/local_storage.rs b/libs/cua/crates/cua-teleport-bundle/src/local_storage.rs
new file mode 100644
index 0000000000..e436314693
--- /dev/null
+++ b/libs/cua/crates/cua-teleport-bundle/src/local_storage.rs
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The reserved `localstorage.json` bundle entry.
+//!
+//! A Chromium-family browser keeps `localStorage` in a LevelDB directory
+//! (`Local Storage/leveldb`) whose files are only valid as one consistent set.
+//! A raw copy of it works only when the source is quiet and lands on a
+//! destination that has no database of its own. This entry instead carries
+//! the values as items (`cua_chromium_storage` reads them on the sender and
+//! writes them on the receiver, while the destination browser is not
+//! running), so the Keyvault can hold, list and update them one by one.
+//!
+//! Values are text. A value whose stored bytes are not valid text (a lone
+//! UTF-16 surrogate) keeps its exact stored bytes in `value_raw`, so nothing
+//! is lost; the same for a key in `key_raw`.
+
+use serde::{Deserialize, Serialize};
+
+/// The reserved bundle entry a provider packs localStorage items into.
+pub const LOCAL_STORAGE_ENTRY: &str = "localstorage.json";
+
+/// One localStorage value.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LocalStorageItem {
+ /// The origin (`https://github.com`), exactly as the browser keyed it.
+ pub origin: String,
+ /// The storage key.
+ pub key: String,
+ /// The value.
+ pub value: String,
+ /// The exact stored key bytes (base64, format byte included), present
+ /// only when `key` cannot hold them losslessly.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub key_raw: Option<String>,
+ /// The exact stored value bytes (base64, format byte included), present
+ /// only when `value` cannot hold them losslessly.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub value_raw: Option<String>,
+}
+
+impl std::fmt::Debug for LocalStorageItem {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("LocalStorageItem")
+ .field("origin", &self.origin)
+ .field("key", &self.key)
+ .field("value", &"<redacted>")
+ .finish()
+ }
+}
+
+impl Drop for LocalStorageItem {
+ fn drop(&mut self) {
+ use zeroize::Zeroize;
+ self.value.zeroize();
+ if let Some(raw) = &mut self.value_raw {
+ raw.zeroize();
+ }
+ }
+}
+
+/// Serializes items for the [`LOCAL_STORAGE_ENTRY`] bundle entry.
+pub fn serialize(items: &[LocalStorageItem]) -> Vec<u8> {
+ serde_json::to_vec(items).unwrap_or_else(|_| b"[]".to_vec())
+}
+
+/// Parses a [`LOCAL_STORAGE_ENTRY`] payload. Malformed input yields no items.
+pub fn parse(bytes: &[u8]) -> Vec<LocalStorageItem> {
+ serde_json::from_slice(bytes).unwrap_or_default()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn round_trips_and_omits_raw_when_lossless() {
+ let items = vec![
+ LocalStorageItem {
+ origin: "https://github.com".into(),
+ key: "color_mode".into(),
+ value: "dark".into(),
+ key_raw: None,
+ value_raw: None,
+ },
+ LocalStorageItem {
+ origin: "https://a.example".into(),
+ key: "k".into(),
+ value: "\u{fffd}".into(),
+ key_raw: None,
+ value_raw: Some("AAA=".into()),
+ },
+ ];
+ let json = serialize(&items);
+ assert!(!String::from_utf8_lossy(&json).contains("key_raw"));
+ assert_eq!(parse(&json), items);
+ assert!(parse(b"nope").is_empty());
+ }
+
+ #[test]
+ fn the_entry_is_distinct_from_the_other_reserved_entries() {
+ assert_ne!(LOCAL_STORAGE_ENTRY, crate::cookies::COOKIES_ENTRY);
+ assert_ne!(LOCAL_STORAGE_ENTRY, crate::keychain::KEYCHAIN_ENTRY);
+ }
+}
diff --git a/libs/cua/crates/cua-teleport-bundle/src/logins.rs b/libs/cua/crates/cua-teleport-bundle/src/logins.rs
new file mode 100644
index 0000000000..e3230c9cdc
--- /dev/null
+++ b/libs/cua/crates/cua-teleport-bundle/src/logins.rs
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The reserved `logins.json` bundle entry.
+//!
+//! Saved passwords travel only when the user ticked them in the review. Like
+//! cookies ([`crate::cookies`]), they ride **already decrypted** by the sender
+//! inside the same integrity-checked, owner-only bundle, and the receiver
+//! re-encrypts each one under the DESTINATION browser's own Safe Storage key
+//! into its `Login Data` database. The source's key never crosses the wire.
+
+use serde::{Deserialize, Serialize};
+
+/// The reserved bundle entry a saved login rides in.
+pub const LOGINS_ENTRY: &str = "logins.json";
+
+/// One saved login, as the sender captured it.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LoginItem {
+ /// The page origin (`https://github.com`), the login's `origin_url`.
+ pub origin: String,
+ /// The username (may be empty).
+ pub username: String,
+ /// The decrypted password, base64 on the wire so any bytes survive.
+ #[serde(with = "crate::keychain::b64")]
+ pub password: Vec<u8>,
+ /// Chrome's `signon_realm` (the origin with a trailing slash for a
+ /// web form), what the browser matches a page against.
+ pub signon_realm: String,
+}
+
+impl std::fmt::Debug for LoginItem {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("LoginItem")
+ .field("origin", &self.origin)
+ .field("username", &self.username)
+ .field("password", &"<redacted>")
+ .finish()
+ }
+}
+
+impl Drop for LoginItem {
+ fn drop(&mut self) {
+ use zeroize::Zeroize;
+ self.password.zeroize();
+ }
+}
+
+/// `signon_realm` for a web login at `origin`.
+pub fn signon_realm(origin: &str) -> String {
+ format!("{}/", origin.trim_end_matches('/'))
+}
+
+/// Serializes logins for the [`LOGINS_ENTRY`] bundle entry.
+pub fn serialize(items: &[LoginItem]) -> Vec<u8> {
+ serde_json::to_vec(items).unwrap_or_else(|_| b"[]".to_vec())
+}
+
+/// Parses a [`LOGINS_ENTRY`] payload; malformed input yields no logins.
+pub fn parse(bytes: &[u8]) -> Vec<LoginItem> {
+ serde_json::from_slice(bytes).unwrap_or_default()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn round_trips_and_never_prints_the_password() {
+ let items = vec![LoginItem {
+ origin: "https://github.com".into(),
+ username: "octo".into(),
+ password: b"pw-\xff".to_vec(),
+ signon_realm: signon_realm("https://github.com"),
+ }];
+ assert_eq!(parse(&serialize(&items)), items);
+ assert!(!format!("{:?}", items[0]).contains("pw-"));
+ assert_eq!(items[0].signon_realm, "https://github.com/");
+ assert!(parse(b"nope").is_empty());
+ }
+
+ #[test]
+ fn the_entry_is_distinct_from_the_other_reserved_entries() {
+ for other in [
+ crate::cookies::COOKIES_ENTRY,
+ crate::local_storage::LOCAL_STORAGE_ENTRY,
+ crate::keychain::KEYCHAIN_ENTRY,
+ ] {
+ assert_ne!(LOGINS_ENTRY, other);
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-teleport/Cargo.toml b/libs/cua/crates/cua-teleport/Cargo.toml
index fd0aa81951..fb32e34261 100644
--- a/libs/cua/crates/cua-teleport/Cargo.toml
+++ b/libs/cua/crates/cua-teleport/Cargo.toml
@@ -13,6 +13,8 @@ publish = false
cua-icon-cache.workspace = true
cua-home.workspace = true
cua-teleport-bundle.workspace = true
+# Chromium localStorage (the Local Storage LevelDB) as items.
+cua-chromium-storage.workspace = true
cua-spacesd-client.workspace = true
# Sealed delivery to a pinned machine key (S1).
cua-machine-seal = { path = "../cua-machine-seal" }
diff --git a/libs/cua/crates/cua-teleport/src/browser_cookies.rs b/libs/cua/crates/cua-teleport/src/browser_cookies.rs
index aeb2b4e3e9..5e009c5ffa 100644
--- a/libs/cua/crates/cua-teleport/src/browser_cookies.rs
+++ b/libs/cua/crates/cua-teleport/src/browser_cookies.rs
@@ -61,11 +61,105 @@ pub struct DecryptedCookie {
pub is_httponly: bool,
/// Chrome's `samesite` enum (-1 unspecified, 0 none, 1 lax, 2 strict).
pub samesite: i64,
+ /// Every other column of Chrome's current schema, kept when the store
+ /// has it (`None`: an older Chrome without that column). They travel so
+ /// the destination's row is the source's row, not a reconstruction.
+ pub extra: CookieExtras,
/// The registrable-domain site [`host_key_in_site`] grouped this row
/// under, for a caller that filtered by site.
pub site: String,
}
+/// The cookie columns beyond the core ones, as Chrome's `cookies` table has
+/// them (names as in the schema). A partitioned (CHIPS) cookie is the one
+/// with a non-empty `top_frame_site_key`.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct CookieExtras {
+ /// `creation_utc`.
+ pub creation_utc: Option<i64>,
+ /// `last_access_utc`.
+ pub last_access_utc: Option<i64>,
+ /// `last_update_utc`.
+ pub last_update_utc: Option<i64>,
+ /// `priority` (0 low, 1 medium, 2 high).
+ pub priority: Option<i64>,
+ /// `source_scheme` (0 unset, 1 non-secure, 2 secure).
+ pub source_scheme: Option<i64>,
+ /// `source_port` (-1 unspecified).
+ pub source_port: Option<i64>,
+ /// `source_type` (0 unknown, 1 http, 2 script, 3 other).
+ pub source_type: Option<i64>,
+ /// `has_cross_site_ancestor`.
+ pub has_cross_site_ancestor: Option<i64>,
+ /// `top_frame_site_key`: the top-level site a partitioned cookie is
+ /// keyed to; empty for an unpartitioned cookie.
+ pub top_frame_site_key: Option<String>,
+}
+
+impl CookieExtras {
+ /// The partition (`top_frame_site_key`) when the cookie is partitioned.
+ pub fn partition(&self) -> Option<&str> {
+ self.top_frame_site_key.as_deref().filter(|k| !k.is_empty())
+ }
+}
+
+/// A cookie that cannot be read, and why, so a review can grey it out
+/// instead of the whole read failing.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct UnavailableCookie {
+ /// The `host_key` column.
+ pub host_key: String,
+ /// The cookie name.
+ pub name: String,
+ /// The registrable-domain site.
+ pub site: String,
+ /// Why, in a sentence.
+ pub reason: String,
+}
+
+/// The reason shown for a Chromium app-bound (`v20`) value.
+pub const APP_BOUND_REASON: &str =
+ "Chrome protects it with app-bound encryption, which only Chrome itself can unlock on this PC";
+
+/// What one read produced: the cookies that decrypted and the ones that
+/// cannot (and why).
+#[derive(Debug, Default)]
+pub struct CookieRead {
+ /// Decrypted cookies.
+ pub cookies: Vec<DecryptedCookie>,
+ /// Cookies this build cannot read.
+ pub unavailable: Vec<UnavailableCookie>,
+}
+
+impl DecryptedCookie {
+ /// The bundle's cookie row for this cookie: every column the source had,
+ /// the partition kept as `partition_key`.
+ pub fn into_item(self) -> cua_teleport_bundle::cookies::CookieItem {
+ let e = &self.extra;
+ cua_teleport_bundle::cookies::CookieItem {
+ host_key: self.host_key.clone(),
+ name: self.name.clone(),
+ value: self.value.as_bytes().to_vec(),
+ path: self.path.clone(),
+ expires_utc: self.expires_utc,
+ is_secure: self.is_secure,
+ is_httponly: self.is_httponly,
+ samesite: self.samesite,
+ extra: cua_teleport_bundle::cookies::CookieExtra {
+ creation_utc: e.creation_utc,
+ last_access_utc: e.last_access_utc,
+ last_update_utc: e.last_update_utc,
+ priority: e.priority,
+ source_scheme: e.source_scheme,
+ source_port: e.source_port,
+ source_type: e.source_type,
+ has_cross_site_ancestor: e.has_cross_site_ancestor,
+ partition_key: e.partition().map(str::to_string),
+ },
+ }
+ }
+}
+
impl std::fmt::Debug for DecryptedCookie {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DecryptedCookie")
@@ -184,6 +278,12 @@ impl ChromeCookies {
/// decrypt fails the whole read: a partial import would silently drop a
/// cookie the destination needs and still report success.
pub fn read(&self, sites: &[String]) -> Result<Vec<DecryptedCookie>, TeleportError> {
+ self.read_report(sites).map(|r| r.cookies)
+ }
+
+ /// [`Self::read`], also reporting the cookies that cannot be read (a
+ /// Chromium app-bound `v20` value) instead of failing the whole read.
+ pub fn read_report(&self, sites: &[String]) -> Result<CookieRead, TeleportError> {
let dir = self.profile_dir()?;
// `Default/Cookies` or `Default/Network/Cookies`, whichever is newer.
let db = cua_teleport_bundle::layout::chrome::cookies_store(&dir);
@@ -212,14 +312,23 @@ impl ChromeCookies {
.map(|s| s.trim().to_ascii_lowercase())
.collect();
let mut keys = SafeStorageKeys::new(self.host.as_ref(), self.platform, service);
- let mut out = Vec::new();
+ let mut out = CookieRead::default();
for r in rows {
let site = crate::passwords::site_for_host(&r.host_key);
if !wanted.is_empty() && !wanted.iter().any(|w| host_key_in_site(&r.host_key, w)) {
continue;
}
+ if is_app_bound(&r.encrypted_value) {
+ out.unavailable.push(UnavailableCookie {
+ host_key: r.host_key,
+ name: r.name,
+ site,
+ reason: APP_BOUND_REASON.into(),
+ });
+ continue;
+ }
let value = decrypt_cookie_value(&mut keys, &r.host_key, &r.encrypted_value, &r.value)?;
- out.push(DecryptedCookie {
+ out.cookies.push(DecryptedCookie {
host_key: r.host_key,
name: r.name,
value: Zeroizing::new(value),
@@ -228,6 +337,7 @@ impl ChromeCookies {
is_secure: r.is_secure,
is_httponly: r.is_httponly,
samesite: r.samesite,
+ extra: r.extra,
site,
});
}
@@ -235,6 +345,52 @@ impl ChromeCookies {
}
}
+/// Whether a stored value is Chromium's app-bound (`v20`) encryption: the key
+/// lives in Chrome's elevation service, so nobody else can unwrap it.
+pub fn is_app_bound(encrypted_value: &[u8]) -> bool {
+ encrypted_value.starts_with(b"v20")
+}
+
+/// One cookie as its store lists it, without its value: what a review
+/// shows (a domain's count and whether it keeps a sign-in) before anything
+/// is decrypted.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CookieHostRow {
+ /// The `host_key` column.
+ pub host_key: String,
+ /// The cookie name.
+ pub name: String,
+ /// Chrome's expiry (`0`: a session cookie).
+ pub expires_utc: i64,
+ /// The value is app-bound (`v20`) and cannot be read by anyone but
+ /// Chrome.
+ pub app_bound: bool,
+}
+
+impl ChromeCookies {
+ /// Every cookie's host, name and expiry (plaintext columns): nothing is
+ /// decrypted, so the Keychain is never asked.
+ pub fn host_rows(&self) -> Result<Vec<CookieHostRow>, TeleportError> {
+ let dir = self.profile_dir()?;
+ let db = cua_teleport_bundle::layout::chrome::cookies_store(&dir);
+ if !db.is_file() {
+ return Err(TeleportError::Provider(format!(
+ "no cookies: {} has no Cookies database",
+ dir.display()
+ )));
+ }
+ Ok(read_rows(&db)?
+ .into_iter()
+ .map(|r| CookieHostRow {
+ host_key: r.host_key,
+ name: r.name,
+ expires_utc: r.expires_utc,
+ app_bound: is_app_bound(&r.encrypted_value),
+ })
+ .collect())
+ }
+}
+
struct Row {
host_key: String,
name: String,
@@ -245,11 +401,13 @@ struct Row {
is_secure: bool,
is_httponly: bool,
samesite: i64,
+ extra: CookieExtras,
}
/// Reads every row of `db`'s `cookies` table. Selects columns by name (not
-/// `SELECT *`), so it tolerates extra columns a newer Chrome added; it
-/// assumes `samesite` exists, which every Chrome since ~2020 (M80) has had.
+/// `SELECT *`): the core ones must exist (`samesite` has since Chrome M80),
+/// and every other column of Chrome's current schema is read when this
+/// Chrome's table has it, so an older Chrome still reads.
fn read_rows(db: &Path) -> Result<Vec<Row>, TeleportError> {
// Chrome holds `Cookies` open; read a private copy so a running browser's
// lock never blocks the import and the original is untouched.
@@ -259,11 +417,59 @@ fn read_rows(db: &Path) -> Result<Vec<Row>, TeleportError> {
tmp.path(),
rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE,
)?;
- let mut stmt = conn.prepare(
- "SELECT host_key, name, value, encrypted_value, path, expires_utc, is_secure, \
- is_httponly, samesite FROM cookies",
- )?;
+ let have: std::collections::HashSet<String> = {
+ let mut stmt = conn.prepare("PRAGMA table_info(cookies)")?;
+ let names = stmt
+ .query_map([], |r| r.get::<_, String>(1))?
+ .collect::<rusqlite::Result<Vec<_>>>()?;
+ names.into_iter().map(|n| n.to_ascii_lowercase()).collect()
+ };
+ // Optional columns, in the order the row reads them after the core 9.
+ const OPTIONAL: [&str; 9] = [
+ "creation_utc",
+ "last_access_utc",
+ "last_update_utc",
+ "priority",
+ "source_scheme",
+ "source_port",
+ "source_type",
+ "has_cross_site_ancestor",
+ "top_frame_site_key",
+ ];
+ let optional: Vec<&str> = OPTIONAL
+ .iter()
+ .copied()
+ .filter(|c| have.contains(*c))
+ .collect();
+ let mut cols = String::from(
+ "host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite",
+ );
+ for c in &optional {
+ cols.push_str(", ");
+ cols.push_str(c);
+ }
+ let mut stmt = conn.prepare(&format!("SELECT {cols} FROM cookies"))?;
let rows = stmt.query_map([], |r| {
+ let mut extra = CookieExtras::default();
+ for (i, c) in optional.iter().enumerate() {
+ let idx = 9 + i;
+ match *c {
+ "top_frame_site_key" => extra.top_frame_site_key = r.get(idx)?,
+ other => {
+ let v: Option<i64> = r.get(idx)?;
+ match other {
+ "creation_utc" => extra.creation_utc = v,
+ "last_access_utc" => extra.last_access_utc = v,
+ "last_update_utc" => extra.last_update_utc = v,
+ "priority" => extra.priority = v,
+ "source_scheme" => extra.source_scheme = v,
+ "source_port" => extra.source_port = v,
+ "source_type" => extra.source_type = v,
+ _ => extra.has_cross_site_ancestor = v,
+ }
+ }
+ }
+ }
Ok(Row {
host_key: r.get(0)?,
name: r.get(1)?,
@@ -274,6 +480,7 @@ fn read_rows(db: &Path) -> Result<Vec<Row>, TeleportError> {
is_secure: r.get::<_, i64>(6)? != 0,
is_httponly: r.get::<_, i64>(7)? != 0,
samesite: r.get(8)?,
+ extra,
})
})?;
rows.collect()
@@ -365,6 +572,75 @@ pub fn write_network_cookies_db_for_tests(
)
}
+/// One row of Chrome's current (meta version 24) `cookies` schema, every
+/// column, for [`write_modern_cookies_db_for_tests`].
+pub struct ModernTestRow<'a> {
+ pub core: TestCookieRow<'a>,
+ pub extra: CookieExtras,
+}
+
+/// Writes `Network/Cookies` in Chrome's current schema with every column
+/// (tests and e2e fixtures), so a read proves each attribute travels.
+pub fn write_modern_cookies_db_for_tests(
+ profile_dir: &Path,
+ rows: &[ModernTestRow<'_>],
+) -> Result<(), TeleportError> {
+ let db = profile_dir.join("Network").join("Cookies");
+ std::fs::create_dir_all(db.parent().unwrap_or(profile_dir))
+ .map_err(|e| TeleportError::Provider(format!("profile dir: {e}")))?;
+ let run = || -> rusqlite::Result<()> {
+ let conn = rusqlite::Connection::open(&db)?;
+ conn.execute_batch(
+ "CREATE TABLE meta (key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR);
+ INSERT INTO meta VALUES ('version', '24'), ('last_compatible_version', '24');
+ CREATE TABLE cookies (
+ creation_utc INTEGER NOT NULL, host_key TEXT NOT NULL,
+ top_frame_site_key TEXT NOT NULL, name TEXT NOT NULL, value TEXT NOT NULL,
+ encrypted_value BLOB NOT NULL, path TEXT NOT NULL, expires_utc INTEGER NOT NULL,
+ is_secure INTEGER NOT NULL, is_httponly INTEGER NOT NULL,
+ last_access_utc INTEGER NOT NULL, has_expires INTEGER NOT NULL,
+ is_persistent INTEGER NOT NULL, priority INTEGER NOT NULL,
+ samesite INTEGER NOT NULL, source_scheme INTEGER NOT NULL,
+ source_port INTEGER NOT NULL, last_update_utc INTEGER NOT NULL,
+ source_type INTEGER NOT NULL, has_cross_site_ancestor INTEGER NOT NULL,
+ UNIQUE (host_key, top_frame_site_key, has_cross_site_ancestor, name, path,
+ source_scheme, source_port));",
+ )?;
+ for r in rows {
+ let e = &r.extra;
+ conn.execute(
+ "INSERT INTO cookies (creation_utc, host_key, top_frame_site_key, name, value, \
+ encrypted_value, path, expires_utc, is_secure, is_httponly, last_access_utc, \
+ has_expires, is_persistent, priority, samesite, source_scheme, source_port, \
+ last_update_utc, source_type, has_cross_site_ancestor) VALUES (?1, ?2, ?3, ?4, \
+ '', ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)",
+ rusqlite::params![
+ e.creation_utc.unwrap_or(1),
+ r.core.host_key,
+ e.top_frame_site_key.clone().unwrap_or_default(),
+ r.core.name,
+ r.core.encrypted_value,
+ r.core.path,
+ r.core.expires_utc,
+ r.core.is_secure as i64,
+ r.core.is_httponly as i64,
+ e.last_access_utc.unwrap_or(0),
+ (r.core.expires_utc != 0) as i64,
+ e.priority.unwrap_or(1),
+ r.core.samesite,
+ e.source_scheme.unwrap_or(0),
+ e.source_port.unwrap_or(-1),
+ e.last_update_utc.unwrap_or(0),
+ e.source_type.unwrap_or(0),
+ e.has_cross_site_ancestor.unwrap_or(0),
+ ],
+ )?;
+ }
+ Ok(())
+ };
+ run().map_err(|e| TeleportError::Provider(format!("writing the fixture Cookies: {e}")))
+}
+
fn write_cookies_db_at(
profile_dir: &Path,
db: &Path,
@@ -517,6 +793,97 @@ mod tests {
.read(&[])
}
+ fn modern_row<'a>(
+ host: &'a str,
+ name: &'a str,
+ encrypted: Vec<u8>,
+ extra: CookieExtras,
+ ) -> ModernTestRow<'a> {
+ ModernTestRow {
+ core: TestCookieRow {
+ host_key: host,
+ name,
+ encrypted_value: encrypted,
+ path: "/",
+ expires_utc: 13_400_000_000_000_000,
+ is_secure: true,
+ is_httponly: true,
+ samesite: 1,
+ },
+ extra,
+ }
+ }
+
+ /// Every column of Chrome's current schema is read, a partitioned cookie
+ /// keeps its partition, and a Windows app-bound (`v20`) value is reported
+ /// per cookie instead of failing the whole read.
+ #[test]
+ fn every_column_is_read_and_app_bound_values_are_reported_not_fatal() {
+ let dir = tempfile::tempdir().unwrap();
+ let ok = v10_row(chromium_crypto::LINUX_V10_PASSWORD, 1, "sess-value");
+ let full = CookieExtras {
+ creation_utc: Some(13_300_000_000_000_001),
+ last_access_utc: Some(13_300_000_000_000_002),
+ last_update_utc: Some(13_300_000_000_000_003),
+ priority: Some(2),
+ source_scheme: Some(2),
+ source_port: Some(443),
+ source_type: Some(1),
+ has_cross_site_ancestor: Some(1),
+ top_frame_site_key: Some("https://top.example".into()),
+ };
+ let mut v20 = b"v20".to_vec();
+ v20.extend_from_slice(&[7u8; 40]);
+ write_modern_cookies_db_for_tests(
+ dir.path(),
+ &[
+ modern_row(".example.com", "sid", ok.clone(), full.clone()),
+ modern_row(".example.com", "sid", ok, CookieExtras::default()),
+ modern_row(".bank.test", "app_bound", v20, CookieExtras::default()),
+ ],
+ )
+ .unwrap();
+ let read = ChromeCookies::new(Arc::new(FakeHost::new()))
+ .with_platform(Platform::Linux)
+ .with_profile_dir(dir.path())
+ .read_report(&[])
+ .unwrap();
+ assert_eq!(read.cookies.len(), 2);
+ let partitioned = read
+ .cookies
+ .iter()
+ .find(|c| c.extra.partition().is_some())
+ .unwrap();
+ assert_eq!(partitioned.extra, full);
+ assert_eq!(partitioned.value.as_str(), "sess-value");
+ let plain = read
+ .cookies
+ .iter()
+ .find(|c| c.extra.partition().is_none())
+ .unwrap();
+ assert_eq!(plain.extra.priority, Some(1));
+ assert_eq!(plain.extra.source_port, Some(-1));
+ // The v20 value is named, with why, and nothing else fails.
+ assert_eq!(read.unavailable.len(), 1);
+ assert_eq!(read.unavailable[0].host_key, ".bank.test");
+ assert_eq!(read.unavailable[0].site, "bank.test");
+ assert!(read.unavailable[0].reason.contains("app-bound"));
+ // The bundle row keeps the partition and every attribute.
+ let item = partitioned.clone().into_item();
+ assert_eq!(
+ item.extra.partition_key.as_deref(),
+ Some("https://top.example")
+ );
+ assert_eq!(item.extra.has_cross_site_ancestor, Some(1));
+ // The plaintext-column listing flags it too, so a review can grey it.
+ let rows = ChromeCookies::new(Arc::new(FakeHost::new()))
+ .with_platform(Platform::Linux)
+ .with_profile_dir(dir.path())
+ .host_rows()
+ .unwrap();
+ assert_eq!(rows.iter().filter(|r| r.app_bound).count(), 1);
+ }
+
/// Modern Chrome (96+): only `Network/Cookies` exists.
#[test]
fn reads_a_modern_network_cookies_only_profile() {
@@ -630,6 +997,7 @@ mod tests {
assert_eq!(cookies_store(p), p.join("Network/Cookies"));
}
+ // Reads the macOS login Keychain through `security`: only meaningful there.
#[cfg(target_os = "macos")]
#[test]
fn macos_cookies_use_the_named_browsers_safe_storage_item() {
diff --git a/libs/cua/crates/cua-teleport/src/favicons.rs b/libs/cua/crates/cua-teleport/src/favicons.rs
new file mode 100644
index 0000000000..882f356e53
--- /dev/null
+++ b/libs/cua/crates/cua-teleport/src/favicons.rs
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! A site's icon, read from the source browser's own local `Favicons`
+//! database. Never from the network: a favicon service would learn which
+//! sites the user has saved.
+//!
+//! Chromium keeps them in `<profile>/Favicons` (SQLite): `icon_mapping`
+//! links a page URL to an icon, `favicon_bitmaps` holds the PNGs. The
+//! browser holds the file open (and may have recent writes in `-wal`), so a
+//! private copy of the file and its sidecars is read, never the live file.
+//! Icons are not secret, but they are small and bounded.
+
+use std::path::{Path, PathBuf};
+
+use crate::TeleportError;
+
+/// Largest icon kept (bytes).
+pub const MAX_ICON_BYTES: usize = 16 * 1024;
+
+/// One site's icon.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Favicon {
+ /// The registrable site (`github.com`).
+ pub site: String,
+ /// PNG bytes.
+ pub png: Vec<u8>,
+}
+
+/// The `Favicons` database of a Chromium profile directory.
+pub fn favicons_db(profile_dir: &Path) -> PathBuf {
+ profile_dir.join("Favicons")
+}
+
+struct TempDir(PathBuf);
+impl Drop for TempDir {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+fn private_copy(src: &Path) -> Result<(TempDir, PathBuf), TeleportError> {
+ let dir = std::env::temp_dir().join(format!("cua-favicons-{:016x}", rand::random::<u64>()));
+ std::fs::create_dir(&dir)
+ .map_err(|e| TeleportError::Provider(format!("temp dir for Favicons: {e}")))?;
+ let guard = TempDir(dir.clone());
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
+ }
+ let dst = dir.join("Favicons");
+ std::fs::copy(src, &dst)
+ .map_err(|e| TeleportError::Provider(format!("copying Favicons failed: {e}")))?;
+ // Recent commits live in the sidecars of a WAL or journal database.
+ for ext in ["-wal", "-shm", "-journal"] {
+ let mut from = src.as_os_str().to_owned();
+ from.push(ext);
+ let mut to = dst.as_os_str().to_owned();
+ to.push(ext);
+ let _ = std::fs::copy(PathBuf::from(from), PathBuf::from(to));
+ }
+ Ok((guard, dst))
+}
+
+fn is_png(b: &[u8]) -> bool {
+ b.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a])
+}
+
+/// The icon of each of `sites` the database holds: the PNG nearest 32 px
+/// (newest on a tie), no larger than [`MAX_ICON_BYTES`]. A site without an
+/// icon is left out; a database that is missing or unreadable is an error.
+pub fn read_favicons(db: &Path, sites: &[String]) -> Result<Vec<Favicon>, TeleportError> {
+ if !db.is_file() {
+ return Err(TeleportError::Provider(format!(
+ "no Favicons database at {}",
+ db.display()
+ )));
+ }
+ let (_guard, copy) = private_copy(db)?;
+ let run = || -> rusqlite::Result<Vec<Favicon>> {
+ let conn = rusqlite::Connection::open_with_flags(
+ &copy,
+ rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
+ )?;
+ let mut stmt = conn.prepare(
+ "SELECT b.image_data FROM icon_mapping m \
+ JOIN favicon_bitmaps b ON b.icon_id = m.icon_id \
+ WHERE m.page_url LIKE ?1 ESCAPE '\\' OR m.page_url LIKE ?2 ESCAPE '\\' \
+ ORDER BY ABS(b.width - 32) ASC, b.last_updated DESC",
+ )?;
+ let mut out = Vec::new();
+ for site in sites {
+ let esc = site
+ .replace('\\', "\\\\")
+ .replace('%', "\\%")
+ .replace('_', "\\_");
+ let exact = format!("%://{esc}/%");
+ let sub = format!("%.{esc}/%");
+ let rows = stmt.query_map([exact, sub], |r| r.get::<_, Option<Vec<u8>>>(0))?;
+ for row in rows {
+ if let Some(png) = row?
+ && is_png(&png)
+ && png.len() <= MAX_ICON_BYTES
+ {
+ out.push(Favicon {
+ site: site.clone(),
+ png,
+ });
+ break;
+ }
+ }
+ }
+ Ok(out)
+ };
+ run().map_err(|e| TeleportError::Provider(format!("reading Favicons failed: {e}")))
+}
+
+/// A Chromium-shaped `Favicons` database (tests and fixtures): one row per
+/// `(page_url, width, bytes)`.
+pub fn write_favicons_db_for_tests(
+ db: &Path,
+ rows: &[(&str, u32, &[u8])],
+) -> Result<(), TeleportError> {
+ if let Some(p) = db.parent() {
+ std::fs::create_dir_all(p).map_err(|e| TeleportError::Provider(e.to_string()))?;
+ }
+ let run = || -> rusqlite::Result<()> {
+ let conn = rusqlite::Connection::open(db)?;
+ conn.execute_batch(
+ "CREATE TABLE icon_mapping (id INTEGER PRIMARY KEY, page_url LONGVARCHAR NOT NULL, \
+ icon_id INTEGER); \
+ CREATE TABLE favicon_bitmaps (id INTEGER PRIMARY KEY, icon_id INTEGER NOT NULL, \
+ last_updated INTEGER DEFAULT 0, image_data BLOB, width INTEGER DEFAULT 0, \
+ height INTEGER DEFAULT 0);",
+ )?;
+ for (n, (url, width, bytes)) in rows.iter().enumerate() {
+ let id = n as i64 + 1;
+ conn.execute(
+ "INSERT INTO icon_mapping (page_url, icon_id) VALUES (?1, ?2)",
+ rusqlite::params![url, id],
+ )?;
+ conn.execute(
+ "INSERT INTO favicon_bitmaps (icon_id, last_updated, image_data, width, height) \
+ VALUES (?1, ?2, ?3, ?4, ?4)",
+ rusqlite::params![id, id, bytes, width],
+ )?;
+ }
+ Ok(())
+ };
+ run().map_err(|e| TeleportError::Provider(format!("writing Favicons: {e}")))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn png(tag: u8) -> Vec<u8> {
+ let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
+ v.extend([tag; 8]);
+ v
+ }
+
+ #[test]
+ fn reads_the_nearest_size_per_site_from_a_private_copy() {
+ let d = tempfile::tempdir().unwrap();
+ let db = favicons_db(d.path());
+ write_favicons_db_for_tests(
+ &db,
+ &[
+ ("https://github.com/login", 16, &png(1)),
+ ("https://github.com/login", 32, &png(2)),
+ ("https://gist.github.com/x", 64, &png(3)),
+ ("https://notion.so/", 32, &png(4)),
+ ("https://evilgithub.com/", 32, &png(9)),
+ ("https://nopng.test/", 32, b"not a png"),
+ ],
+ )
+ .unwrap();
+ let before = std::fs::metadata(&db).unwrap().modified().unwrap();
+ let out = read_favicons(
+ &db,
+ &[
+ "github.com".into(),
+ "notion.so".into(),
+ "nopng.test".into(),
+ "absent.test".into(),
+ ],
+ )
+ .unwrap();
+ assert_eq!(out.len(), 2, "no icon for a site without a PNG or a row");
+ assert_eq!(out[0].site, "github.com");
+ assert_eq!(out[0].png, png(2), "32 px beats 16 and 64");
+ assert_eq!(out[1].png, png(4));
+ // A look-alike never matches, and the live file is untouched.
+ assert!(!out.iter().any(|f| f.png == png(9)));
+ assert_eq!(std::fs::metadata(&db).unwrap().modified().unwrap(), before);
+ }
+
+ #[test]
+ fn oversized_icons_and_missing_databases_are_handled() {
+ let d = tempfile::tempdir().unwrap();
+ let db = favicons_db(d.path());
+ let mut big = png(1);
+ big.extend(vec![0; MAX_ICON_BYTES]);
+ write_favicons_db_for_tests(&db, &[("https://big.test/", 32, &big)]).unwrap();
+ assert!(read_favicons(&db, &["big.test".into()]).unwrap().is_empty());
+ assert!(read_favicons(&d.path().join("none"), &["a.test".into()]).is_err());
+ }
+}
diff --git a/libs/cua/crates/cua-teleport/src/lib.rs b/libs/cua/crates/cua-teleport/src/lib.rs
index 1e974eaae7..6526bfe636 100644
--- a/libs/cua/crates/cua-teleport/src/lib.rs
+++ b/libs/cua/crates/cua-teleport/src/lib.rs
@@ -28,6 +28,7 @@
pub mod biometric;
pub mod browser_cookies;
pub mod cookies;
+pub mod favicons;
pub mod host;
pub mod keychain;
pub mod passwords;
diff --git a/libs/cua/crates/cua-teleport/src/passwords.rs b/libs/cua/crates/cua-teleport/src/passwords.rs
index 485013d533..4c07abda75 100644
--- a/libs/cua/crates/cua-teleport/src/passwords.rs
+++ b/libs/cua/crates/cua-teleport/src/passwords.rs
@@ -198,6 +198,12 @@ impl ChromePasswords {
/// to decrypt fails the read: a partial import would silently lose a
/// credential the user asked for.
pub fn read(&self, sites: &[String]) -> Result<Vec<SavedLogin>, TeleportError> {
+ self.read_report(sites).map(|r| r.logins)
+ }
+
+ /// [`Self::read`], also reporting the logins that cannot be read (a
+ /// Chromium app-bound `v20` value) instead of failing the whole read.
+ pub fn read_report(&self, sites: &[String]) -> Result<PasswordRead, TeleportError> {
let dir = self.profile_dir()?;
let db = dir.join("Login Data");
if !db.is_file() {
@@ -212,7 +218,7 @@ impl ChromePasswords {
.map(|s| s.trim().to_ascii_lowercase())
.collect();
let mut keys = SafeStorageKeys::new(self.host.as_ref(), self.platform, MAC_SAFE_STORAGE);
- let mut out = Vec::new();
+ let mut out = PasswordRead::default();
for r in rows {
let Some(origin) = origin_of(&r.origin_url) else {
continue;
@@ -224,8 +230,17 @@ impl ChromePasswords {
if r.password_value.is_empty() {
continue;
}
+ if crate::browser_cookies::is_app_bound(&r.password_value) {
+ out.unavailable.push(UnavailableLogin {
+ origin,
+ site,
+ username: r.username_value,
+ reason: crate::browser_cookies::APP_BOUND_REASON.into(),
+ });
+ continue;
+ }
let password = decrypt_password(&mut keys, &r.password_value)?;
- out.push(SavedLogin {
+ out.logins.push(SavedLogin {
origin,
site,
username: r.username_value,
@@ -236,6 +251,61 @@ impl ChromePasswords {
}
}
+/// What one read produced: the logins that decrypted and the ones that cannot
+/// (and why).
+#[derive(Debug, Default)]
+pub struct PasswordRead {
+ /// Decrypted logins.
+ pub logins: Vec<SavedLogin>,
+ /// Logins this build cannot read.
+ pub unavailable: Vec<UnavailableLogin>,
+}
+
+/// A login that cannot be read, never with its value.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct UnavailableLogin {
+ /// The page origin.
+ pub origin: String,
+ /// The registrable-domain site.
+ pub site: String,
+ /// The username.
+ pub username: String,
+ /// Why, in a sentence.
+ pub reason: String,
+}
+
+impl ChromePasswords {
+ /// How many saved logins each site holds and how many of them are
+ /// app-bound (unreadable), from the plaintext columns: nothing is
+ /// decrypted, so the Keychain is never asked.
+ pub fn count_by_site(
+ &self,
+ ) -> Result<std::collections::BTreeMap<String, (u32, u32)>, TeleportError> {
+ let dir = self.profile_dir()?;
+ let db = dir.join("Login Data");
+ let mut out: std::collections::BTreeMap<String, (u32, u32)> = Default::default();
+ if !db.is_file() {
+ return Ok(out);
+ }
+ for r in read_rows(&db)? {
+ let Some(origin) = origin_of(&r.origin_url) else {
+ continue;
+ };
+ if r.password_value.is_empty() {
+ continue;
+ }
+ let site = site_for_host(&host_of_origin(&origin));
+ let e = out.entry(site).or_default();
+ if crate::browser_cookies::is_app_bound(&r.password_value) {
+ e.1 += 1;
+ } else {
+ e.0 += 1;
+ }
+ }
+ Ok(out)
+ }
+}
+
struct Row {
origin_url: String,
username_value: String,
diff --git a/libs/cua/crates/cua-teleport/src/providers/chrome.rs b/libs/cua/crates/cua-teleport/src/providers/chrome.rs
index 76c3ab7c0b..27014e243b 100644
--- a/libs/cua/crates/cua-teleport/src/providers/chrome.rs
+++ b/libs/cua/crates/cua-teleport/src/providers/chrome.rs
@@ -454,6 +454,51 @@ fn manifest_item(
}
}
+/// `Local Storage/` as items: the LevelDB is read from a private copy and its
+/// values travel in the reserved `localstorage.json` entry, which the receiver
+/// writes into the destination browser's own store (a raw copy of LevelDB
+/// files would replace whatever the destination holds, and tear if the source
+/// is running). Anything else under `Local Storage/` stays a file. When the
+/// LevelDB cannot be read, the whole directory is copied as before.
+fn add_local_storage<W: std::io::Write>(
+ writer: &mut cua_teleport_bundle::bundle::BundleWriter<W>,
+ profile_dir: &Path,
+ disk: &Path,
+ rel: &str,
+) -> Result<()> {
+ match cua_chromium_storage::read(&cua_chromium_storage::store_dir(profile_dir)) {
+ Ok(items) => {
+ if !items.is_empty() {
+ writer.add_bytes(
+ cua_chromium_storage::LOCAL_STORAGE_ENTRY,
+ 0o600,
+ &cua_teleport_bundle::local_storage::serialize(&items),
+ )?;
+ }
+ if let Ok(entries) = std::fs::read_dir(disk) {
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if name == "leveldb" {
+ continue;
+ }
+ let child = format!("{rel}/{name}");
+ match std::fs::symlink_metadata(&path) {
+ Ok(m) if m.is_file() => add_file_best_effort(writer, &path, &child)?,
+ Ok(m) if m.is_dir() => add_dir_recursive(writer, &path, &child)?,
+ _ => {}
+ }
+ }
+ }
+ Ok(())
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "localStorage could not be read as items; copying its files");
+ add_dir_recursive(writer, disk, rel)
+ }
+ }
+}
+
/// Where curated profile file `name` lives on disk: `Cookies` resolves to
/// whichever of `Network/Cookies` and the root file is newer; every
/// other file is at the profile root.
@@ -763,16 +808,7 @@ impl ExportProvider for ChromeProvider {
if !cookies.is_empty() {
let items: Vec<cua_teleport_bundle::cookies::CookieItem> = cookies
.into_iter()
- .map(|c| cua_teleport_bundle::cookies::CookieItem {
- host_key: c.host_key,
- name: c.name,
- value: c.value.as_bytes().to_vec(),
- path: c.path,
- expires_utc: c.expires_utc,
- is_secure: c.is_secure,
- is_httponly: c.is_httponly,
- samesite: c.samesite,
- })
+ .map(crate::browser_cookies::DecryptedCookie::into_item)
.collect();
writer.add_bytes(
cua_teleport_bundle::cookies::COOKIES_ENTRY,
@@ -794,7 +830,11 @@ impl ExportProvider for ChromeProvider {
}
let disk = profile_dir.join(dir);
if disk.is_dir() {
- add_dir_recursive(&mut writer, &disk, &rel)?;
+ if *dir == "Local Storage" {
+ add_local_storage(&mut writer, &profile_dir, &disk, &rel)?;
+ } else {
+ add_dir_recursive(&mut writer, &disk, &rel)?;
+ }
}
}
}
diff --git a/libs/cua/crates/cua-teleport/src/ux/plan.rs b/libs/cua/crates/cua-teleport/src/ux/plan.rs
index 8bb3efaf39..60c63af16c 100644
--- a/libs/cua/crates/cua-teleport/src/ux/plan.rs
+++ b/libs/cua/crates/cua-teleport/src/ux/plan.rs
@@ -282,10 +282,33 @@ pub struct TeleportPlan {
/// older plan JSON (never retroactively flagged).
#[serde(default)]
pub relay_unsealed: bool,
+ /// The sites (registrable domains) whose cookies this plan sends, from
+ /// the review's per-domain choice ([`Consent::cookie_domains`]); `None`
+ /// sends every cookie in the selection.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cookie_domains: Option<Vec<String>>,
+ /// Send these saved Keyvault items (ids) instead of reading the live
+ /// app ([`Consent::from_vault`]): no fresh capture, so the host's
+ /// Keychain is never asked.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub from_vault: Option<Vec<String>>,
+ /// Also send the saved passwords ([`Consent::include_passwords`]).
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub include_passwords: bool,
+}
+
+fn is_false(b: &bool) -> bool {
+ !*b
+}
+
+/// Whether a manifest key is the browser's cookie store.
+fn is_cookie_key(key: &str) -> bool {
+ let name = key.rsplit('/').next().unwrap_or(key);
+ name.eq_ignore_ascii_case("cookies")
}
/// Consent, as a UI collects it.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Consent {
/// The user confirmed the consent screen.
pub approved: bool,
@@ -299,6 +322,25 @@ pub struct Consent {
/// (S1).
#[serde(default)]
pub acknowledge_relay_plaintext: bool,
+ /// The review's per-domain choice: the registrable domains whose cookies
+ /// to send. `None` keeps every cookie the selection holds; `Some` sends
+ /// only these (and, when empty, no cookies at all).
+ #[serde(default)]
+ pub cookie_domains: Option<Vec<String>>,
+ /// Consent items (their keys) the user turned off in the review. They
+ /// are dropped from the plan: not listed, not sent, not counted.
+ #[serde(default)]
+ pub exclude: Vec<String>,
+ /// Send these saved Keyvault items (ids) instead of reading the live
+ /// app. Only an app-state move uses it.
+ #[serde(default)]
+ pub from_vault: Option<Vec<String>>,
+ /// Also send the browser's saved passwords (of the chosen sites): only
+ /// when the user ticked them in the review, and only with
+ /// `acknowledge_sensitive`. They are re-encrypted for the destination
+ /// browser's own key.
+ #[serde(default)]
+ pub include_passwords: bool,
}
/// A plan the user approved. Only [`TeleportPlan::approve`] makes one.
@@ -333,6 +375,11 @@ impl TeleportPlan {
secrets.join(", ")
)));
}
+ if consent.include_passwords && !consent.acknowledge_sensitive {
+ return Err(UxError::NotApproved(
+ "saved passwords need an explicit acknowledgement".into(),
+ ));
+ }
if self.relay_unsealed
&& crate::RELAY_SEALING_ENFORCED
&& !consent.acknowledge_relay_plaintext
@@ -342,6 +389,35 @@ impl TeleportPlan {
crate::RELAY_UNSEALED_WARNING
)));
}
+ // What the user turned off in the review leaves the plan: first the
+ // items they excluded, then, when they chose domains, the cookie
+ // store itself if no domain was chosen (nothing to read).
+ let mut drop_keys: Vec<String> = consent.exclude.clone();
+ if consent
+ .cookie_domains
+ .as_ref()
+ .is_some_and(|d| d.is_empty())
+ {
+ drop_keys.extend(
+ self.consent
+ .iter()
+ .filter(|c| is_cookie_key(&c.key))
+ .map(|c| c.key.clone()),
+ );
+ }
+ if !drop_keys.is_empty() {
+ for step in &mut self.steps {
+ if let PlanStep::ImportState { items, .. } = step {
+ items.retain(|i| !drop_keys.contains(i));
+ }
+ }
+ self.consent.retain(|c| !drop_keys.contains(&c.key));
+ self.total_bytes = self.consent.iter().map(|c| c.bytes).sum();
+ self.sensitive = self.consent.iter().any(|c| c.sensitive);
+ }
+ self.cookie_domains = consent.cookie_domains.clone();
+ self.from_vault = consent.from_vault.clone();
+ self.include_passwords = consent.include_passwords;
self.save_to_keyvault = self.sensitive && consent.save_to_keyvault;
Ok(ApprovedPlan(self))
}
@@ -582,6 +658,9 @@ pub fn build(
warnings,
save_to_keyvault: false,
relay_unsealed: false,
+ cookie_domains: None,
+ from_vault: None,
+ include_passwords: false,
})
}
@@ -1000,6 +1079,7 @@ mod tests {
acknowledge_sensitive: true,
save_to_keyvault: true,
acknowledge_relay_plaintext: false,
+ ..Default::default()
})
.unwrap();
assert!(approved.plan().save_to_keyvault);
@@ -1019,8 +1099,91 @@ mod tests {
acknowledge_sensitive: false,
save_to_keyvault: true,
acknowledge_relay_plaintext: false,
+ ..Default::default()
})
.unwrap();
assert!(!approved.plan().save_to_keyvault);
}
+
+ /// The review's choices shape what is approved: excluded items leave the
+ /// plan (and its totals), an empty domain choice drops the cookie store,
+ /// and the domain list and the vault source ride on the approved plan.
+ #[test]
+ fn review_choices_shape_the_approved_plan() {
+ let cc = entry("Google Chrome", "com.google.Chrome");
+ let m = chrome_manifest();
+ let mac = SpaceFacts {
+ os: Platform::MacOS,
+ home: "/Users/lume".into(),
+ importers: vec!["chrome".into()],
+ ..facts("aarch64")
+ };
+ let plan = |opts: &PlanOptions| build(&cc, &mac, opts, Some(&m), &[]);
+ let mut o = PlanOptions::new(MoveKind::AppWithState);
+ o.sensitive_groups = vec![SensitiveGroup::SignIns];
+ let p = plan(&o).unwrap();
+ let keys: Vec<String> = p.consent.iter().map(|c| c.key.clone()).collect();
+ let cookie_key = keys.iter().find(|k| k.ends_with("Cookies")).cloned();
+ let ok = Consent {
+ approved: true,
+ acknowledge_sensitive: true,
+ ..Default::default()
+ };
+ // Excluding an item drops it everywhere, and the totals follow.
+ let victim = keys.last().unwrap().clone();
+ let before = p.total_bytes;
+ let a = p
+ .clone()
+ .approve(Consent {
+ exclude: vec![victim.clone()],
+ ..ok.clone()
+ })
+ .unwrap();
+ assert!(!a.plan().consent.iter().any(|c| c.key == victim));
+ assert!(a.plan().total_bytes < before);
+ for step in &a.plan().steps {
+ if let PlanStep::ImportState { items, .. } = step {
+ assert!(!items.contains(&victim));
+ }
+ }
+ // Domains ride along; an empty choice drops the cookie store itself.
+ let a = p
+ .clone()
+ .approve(Consent {
+ cookie_domains: Some(vec!["github.com".into()]),
+ ..ok.clone()
+ })
+ .unwrap();
+ assert_eq!(
+ a.plan().cookie_domains.as_deref(),
+ Some(&["github.com".to_string()][..])
+ );
+ if let Some(ck) = cookie_key {
+ let none = p
+ .clone()
+ .approve(Consent {
+ cookie_domains: Some(vec![]),
+ ..ok.clone()
+ })
+ .unwrap();
+ assert!(!none.plan().consent.iter().any(|c| c.key == ck));
+ assert!(
+ a.plan().consent.iter().any(|c| c.key == ck),
+ "a chosen domain keeps the store"
+ );
+ }
+ // The vault source is carried, never invented.
+ let v = p
+ .clone()
+ .approve(Consent {
+ from_vault: Some(vec!["i1".into()]),
+ ..ok.clone()
+ })
+ .unwrap();
+ assert_eq!(
+ v.plan().from_vault.as_deref(),
+ Some(&["i1".to_string()][..])
+ );
+ assert!(p.approve(ok).unwrap().plan().from_vault.is_none());
+ }
}
diff --git a/libs/cua/scripts/generate-app-core-ffi.py b/libs/cua/scripts/generate-app-core-ffi.py
index 50976f1ec2..d800542962 100644
--- a/libs/cua/scripts/generate-app-core-ffi.py
+++ b/libs/cua/scripts/generate-app-core-ffi.py
@@ -33,11 +33,13 @@ TYPES = [
("teleport/transfer.rs", "teleport::transfer", ["TransferPhase", "TransferOverlayState", "TransferStatus", "TransferSignal", "SentFileInfo"]),
("teleport/windows.rs", "teleport::windows", ["OpenWindow", "OpenApp", "RemoteWindow", "RemoteWindowGroup", "PickerTab", "PickerAction", "PickerPrimary"]),
("teleport/grid.rs", "teleport::grid", ["PickerTileIcon", "PickerTileThumbnail", "PickerTile", "PickerTileSection", "PickerGrid", "PickerGridTab", "PickerGridTabItem", "PickerGridPrimary"]),
+ ("teleport/review.rs", "teleport::review", ["SendSource", "RememberedChoice", "ReviewDomain", "ReviewToggle", "VaultSource", "ReviewChoice"]),
("teleport/flow.rs", "teleport::flow", ["Capability", "Move", "SensitiveGroup", "SensitiveOption", "CatalogEntry", "ConsentKind", "ConsentItem", "PlanStepView", "Plan", "RunPhase", "RunEvent", "RunReport", "Consent", "InstallCuaPrompt", "Step", "PickerState", "PickerEvent", "EntrySection", "ReviewView"]),
("wizard.rs", "wizard", ["LocalEngine", "CloudEngine", "ImageTier", "ImageDistro", "PlatformSize", "ImageSizes", "SandboxImage", "ImageGroup", "KindOption", "StorageVolume", "LocalStorage", "CloudPricing", "CloudOffer", "ConnectedCloud", "HostLimit", "SpaceHost", "PlacementOption", "GpuChoice", "WizardEnv", "WizardMode", "AddressForm", "WizardState", "WizardAction", "StepState", "StepView", "Tile", "MenuOption", "CreatePlan", "CreateSpaceArgs", "AddressView", "AddressSubmit", "ImageSuggestion", "SuggestionGroup", "ImageFieldView", "WizardField", "WizardLabels", "WizardFact", "GpuRow", "WizardView"]),
- ("keyvault/wire.rs", "keyvault::wire", ["KvCookieInfo", "KvItemSummary", "KvItemPolicy", "KvItem", "KvSigning", "KvCaller", "KvSelector", "KvAccessRequest", "KvPending", "KvGrant", "KvRuleCaller", "KvRule", "KvDelivery", "KvAuditEntry", "KvStatus", "KvVerification", "KeyvaultOverview", "KvCommand"]),
- ("keyvault/view.rs", "keyvault::view", ["Tone", "SigningBadge", "ConsentChipKind", "ConsentChip", "ItemRow", "Tri", "SiteGroup", "DecisionTone", "Decision", "PendingRow", "AccessKind", "AccessRow", "KvLabels", "KeyvaultPage"]),
- ("keyvault/browse.rs", "keyvault::browse", ["KvCategory", "CategoryRow", "SiteRow", "KvSidebar", "KvSelection", "RecentRow", "KvListView", "SiteDetail"]),
+ ("keyvault/wire.rs", "keyvault::wire", ["KvItemPolicy", "KvItem", "KvFavicon", "KvDomainCount", "KvInventory", "KvSigning", "KvCaller", "KvSelector", "KvAccessRequest", "KvPending", "KvGrant", "KvRuleCaller", "KvRule", "KvDelivery", "KvAuditEntry", "KvStatus", "KvVerification", "KeyvaultOverview", "KvCommand"]),
+ ("keyvault/view.rs", "keyvault::view", ["Tone", "SigningBadge", "Tri", "DecisionTone", "Decision", "PendingRow", "AccessKind", "AccessRow", "KvLabels", "KeyvaultPage"]),
+ ("keyvault/vault.rs", "keyvault::vault", ["KvKind", "KvLock", "VaultState", "VaultAction", "VaultRow", "VaultSite", "VaultFiles", "VaultApp", "VaultSelection", "VaultView", "UnlockPrompt", "KvDeleteConfirm", "KvVaultSource"]),
+ ("keyvault/browse.rs", "keyvault::browse", ["KvCategory", "CategoryRow", "AppRow", "KvSidebar", "KvSelection", "RecentRow", "KvListView"]),
("keyvault/approval.rs", "keyvault::approval", ["ApprovalState", "ApprovalAction", "ApprovalRow", "ApprovalView"]),
("keyvault/credential.rs", "keyvault::credential", ["KvFormMode", "KvMethod", "KvCredentialForm", "KvStrength", "KvPassphraseCheck"]),
("keyvault/client.rs", "keyvault::client", ["KvOutcome"]),
@@ -75,10 +77,16 @@ RENAME = {
"RunEvent": "AppTeleportRunEvent",
"RunReport": "AppTeleportRunReport",
"RunPhase": "AppTeleportRunPhase",
- "SiteRow": "KvSiteRow",
- "SiteGroup": "KvSiteGroup",
- "SiteDetail": "KvSiteDetail",
- "ItemRow": "KvItemRow",
+ "AppRow": "KvAppRow",
+ "VaultState": "KvVaultState",
+ "VaultAction": "KvVaultAction",
+ "VaultRow": "KvVaultRow",
+ "VaultSite": "KvVaultSite",
+ "VaultFiles": "KvVaultFiles",
+ "VaultApp": "KvVaultApp",
+ "VaultSelection": "KvVaultSelection",
+ "VaultView": "KvVaultView",
+ "UnlockPrompt": "KvUnlockPrompt",
"CategoryRow": "KvCategoryRow",
"RecentRow": "KvRecentRow",
"PendingRow": "KvPendingRow",
@@ -86,8 +94,6 @@ RENAME = {
"AccessKind": "KvAccessKind",
"Decision": "KvDecision",
"DecisionTone": "KvDecisionTone",
- "ConsentChip": "KvConsentChip",
- "ConsentChipKind": "KvConsentChipKind",
"SigningBadge": "KvSigningBadge",
"Tone": "KvTone",
"Tri": "KvTri",
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index 8536308c6a..0fca15df05 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -1089,6 +1089,17 @@ public protocol KeyvaultClientProtocol: AnyObject, Sendable {
*/
func execute(command: KvCommand) async throws -> KvOutcome
+ /**
+ * Site icons the vault holds (not secret; empty while names are hidden).
+ */
+ func favicons() async -> [KvFavicon]
+
+ /**
+ * What `app` holds, per domain with counts (the daemon asks for Touch ID
+ * when the browse window is closed). Never a value.
+ */
+ func inventory(app: String, profile: String?) async throws -> KvInventory
+
/**
* Locks the vault.
*/
@@ -1203,6 +1214,48 @@ open func execute(command: KvCommand)async throws -> KvOutcome {
)
}
+ /**
+ * Site icons the vault holds (not secret; empty while names are hidden).
+ */
+open func favicons()async -> [KvFavicon] {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_spaces_ffi_fn_method_keyvaultclient_favicons(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_cua_spaces_ffi_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_spaces_ffi_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_spaces_ffi_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeKvFavicon.lift,
+ errorHandler: nil
+
+ )
+}
+
+ /**
+ * What `app` holds, per domain with counts (the daemon asks for Touch ID
+ * when the browse window is closed). Never a value.
+ */
+open func inventory(app: String, profile: String?)async throws -> KvInventory {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cua_spaces_ffi_fn_method_keyvaultclient_inventory(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(app),FfiConverterOptionString.lower(profile)
+ )
+ },
+ pollFunc: ffi_cua_spaces_ffi_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cua_spaces_ffi_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cua_spaces_ffi_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeKvInventory_lift,
+ errorHandler: FfiConverterTypeCuaError_lift
+ )
+}
+
/**
* Locks the vault.
*/
@@ -21866,6 +21919,10 @@ public struct AppPickerState: Equatable, Hashable {
* [`Plan::relay_unsealed`]'s warning acknowledged (S1).
*/
public var acknowledgedRelayPlaintext: Bool
+ /**
+ * What the review sends: which sites, which items, from where.
+ */
+ public var choice: AppReviewChoice
/**
* Run events (last [`MAX_EVENTS`]).
*/
@@ -21933,6 +21990,9 @@ public struct AppPickerState: Equatable, Hashable {
/**
* [`Plan::relay_unsealed`]'s warning acknowledged (S1).
*/acknowledgedRelayPlaintext: Bool,
+ /**
+ * What the review sends: which sites, which items, from where.
+ */choice: AppReviewChoice,
/**
* Run events (last [`MAX_EVENTS`]).
*/events: [AppTeleportRunEvent],
@@ -21961,6 +22021,7 @@ public struct AppPickerState: Equatable, Hashable {
self.acknowledged = acknowledged
self.saveToKeyvault = saveToKeyvault
self.acknowledgedRelayPlaintext = acknowledgedRelayPlaintext
+ self.choice = choice
self.events = events
self.report = report
self.error = error
@@ -21997,6 +22058,7 @@ public struct FfiConverterTypeAppPickerState: FfiConverterRustBuffer {
acknowledged: FfiConverterBool.read(from: &buf),
saveToKeyvault: FfiConverterBool.read(from: &buf),
acknowledgedRelayPlaintext: FfiConverterBool.read(from: &buf),
+ choice: FfiConverterTypeAppReviewChoice.read(from: &buf),
events: FfiConverterSequenceTypeAppTeleportRunEvent.read(from: &buf),
report: FfiConverterOptionTypeAppTeleportRunReport.read(from: &buf),
error: FfiConverterOptionString.read(from: &buf),
@@ -22019,6 +22081,7 @@ public struct FfiConverterTypeAppPickerState: FfiConverterRustBuffer {
FfiConverterBool.write(value.acknowledged, into: &buf)
FfiConverterBool.write(value.saveToKeyvault, into: &buf)
FfiConverterBool.write(value.acknowledgedRelayPlaintext, into: &buf)
+ FfiConverterTypeAppReviewChoice.write(value.choice, into: &buf)
FfiConverterSequenceTypeAppTeleportRunEvent.write(value.events, into: &buf)
FfiConverterOptionTypeAppTeleportRunReport.write(value.report, into: &buf)
FfiConverterOptionString.write(value.error, into: &buf)
@@ -23229,6 +23292,72 @@ public func FfiConverterTypeAppRefreshReport_lower(_ value: AppRefreshReport) ->
}
+public struct AppRememberedChoice: Equatable, Hashable {
+ /**
+ * `<app>|<space>`.
+ */
+ public var key: String
+ /**
+ * The sites (registrable domains) that were sent.
+ */
+ public var domains: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * `<app>|<space>`.
+ */key: String,
+ /**
+ * The sites (registrable domains) that were sent.
+ */domains: [String]) {
+ self.key = key
+ self.domains = domains
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppRememberedChoice: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppRememberedChoice: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppRememberedChoice {
+ return
+ try AppRememberedChoice(
+ key: FfiConverterString.read(from: &buf),
+ domains: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppRememberedChoice, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterSequenceString.write(value.domains, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRememberedChoice_lift(_ buf: RustBuffer) throws -> AppRememberedChoice {
+ return try FfiConverterTypeAppRememberedChoice.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppRememberedChoice_lower(_ value: AppRememberedChoice) -> RustBuffer {
+ return FfiConverterTypeAppRememberedChoice.lower(value)
+}
+
+
public struct AppRemoteWindow: Equatable, Hashable {
/**
* Stable key.
@@ -23443,6 +23572,382 @@ public func FfiConverterTypeAppRemoteWindowGroup_lower(_ value: AppRemoteWindowG
}
+public struct AppReviewChoice: Equatable, Hashable {
+ /**
+ * Where to send from.
+ */
+ public var source: AppSendSource
+ /**
+ * The browser's sites with counts (none until read, or for an app that
+ * is not a browser).
+ */
+ public var domains: [KvDomainCount]
+ /**
+ * The sites chosen.
+ */
+ public var selectedDomains: [String]
+ /**
+ * The sites list's search text.
+ */
+ public var query: String
+ /**
+ * Consent items (keys) turned off.
+ */
+ public var excluded: [String]
+ /**
+ * The saved items.
+ */
+ public var vault: AppVaultSource
+ /**
+ * The sites were asked for (a failure counts: the review then sends
+ * what the plan lists).
+ */
+ public var loaded: Bool
+ /**
+ * The saved passwords are ticked to send (off unless the user ticks
+ * them; never remembered).
+ */
+ public var includePasswords: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Where to send from.
+ */source: AppSendSource,
+ /**
+ * The browser's sites with counts (none until read, or for an app that
+ * is not a browser).
+ */domains: [KvDomainCount],
+ /**
+ * The sites chosen.
+ */selectedDomains: [String],
+ /**
+ * The sites list's search text.
+ */query: String,
+ /**
+ * Consent items (keys) turned off.
+ */excluded: [String],
+ /**
+ * The saved items.
+ */vault: AppVaultSource,
+ /**
+ * The sites were asked for (a failure counts: the review then sends
+ * what the plan lists).
+ */loaded: Bool,
+ /**
+ * The saved passwords are ticked to send (off unless the user ticks
+ * them; never remembered).
+ */includePasswords: Bool) {
+ self.source = source
+ self.domains = domains
+ self.selectedDomains = selectedDomains
+ self.query = query
+ self.excluded = excluded
+ self.vault = vault
+ self.loaded = loaded
+ self.includePasswords = includePasswords
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppReviewChoice: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppReviewChoice: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppReviewChoice {
+ return
+ try AppReviewChoice(
+ source: FfiConverterTypeAppSendSource.read(from: &buf),
+ domains: FfiConverterSequenceTypeKvDomainCount.read(from: &buf),
+ selectedDomains: FfiConverterSequenceString.read(from: &buf),
+ query: FfiConverterString.read(from: &buf),
+ excluded: FfiConverterSequenceString.read(from: &buf),
+ vault: FfiConverterTypeAppVaultSource.read(from: &buf),
+ loaded: FfiConverterBool.read(from: &buf),
+ includePasswords: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppReviewChoice, into buf: inout [UInt8]) {
+ FfiConverterTypeAppSendSource.write(value.source, into: &buf)
+ FfiConverterSequenceTypeKvDomainCount.write(value.domains, into: &buf)
+ FfiConverterSequenceString.write(value.selectedDomains, into: &buf)
+ FfiConverterString.write(value.query, into: &buf)
+ FfiConverterSequenceString.write(value.excluded, into: &buf)
+ FfiConverterTypeAppVaultSource.write(value.vault, into: &buf)
+ FfiConverterBool.write(value.loaded, into: &buf)
+ FfiConverterBool.write(value.includePasswords, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppReviewChoice_lift(_ buf: RustBuffer) throws -> AppReviewChoice {
+ return try FfiConverterTypeAppReviewChoice.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppReviewChoice_lower(_ value: AppReviewChoice) -> RustBuffer {
+ return FfiConverterTypeAppReviewChoice.lower(value)
+}
+
+
+public struct AppReviewDomain: Equatable, Hashable {
+ /**
+ * The site (`github.com`).
+ */
+ public var domain: String
+ /**
+ * "12 cookies, 2 storage values".
+ */
+ public var counts: String
+ /**
+ * Items the site holds.
+ */
+ public var count: UInt32
+ /**
+ * It looks like it keeps a sign-in.
+ */
+ public var signin: Bool
+ /**
+ * An identity provider: its session unlocks other apps.
+ */
+ public var identityProvider: Bool
+ /**
+ * Chosen to send.
+ */
+ public var selected: Bool
+ /**
+ * Can be chosen: it holds something that can be sent. A site whose
+ * cookies are all unreadable is greyed out.
+ */
+ public var selectable: Bool
+ /**
+ * Cookies that cannot be read, shown greyed with `unavailable_note`.
+ */
+ public var unavailable: UInt32
+ /**
+ * "3 cookies cannot be sent: Chrome protects them with ...", or empty.
+ */
+ public var unavailableNote: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The site (`github.com`).
+ */domain: String,
+ /**
+ * "12 cookies, 2 storage values".
+ */counts: String,
+ /**
+ * Items the site holds.
+ */count: UInt32,
+ /**
+ * It looks like it keeps a sign-in.
+ */signin: Bool,
+ /**
+ * An identity provider: its session unlocks other apps.
+ */identityProvider: Bool,
+ /**
+ * Chosen to send.
+ */selected: Bool,
+ /**
+ * Can be chosen: it holds something that can be sent. A site whose
+ * cookies are all unreadable is greyed out.
+ */selectable: Bool,
+ /**
+ * Cookies that cannot be read, shown greyed with `unavailable_note`.
+ */unavailable: UInt32,
+ /**
+ * "3 cookies cannot be sent: Chrome protects them with ...", or empty.
+ */unavailableNote: String) {
+ self.domain = domain
+ self.counts = counts
+ self.count = count
+ self.signin = signin
+ self.identityProvider = identityProvider
+ self.selected = selected
+ self.selectable = selectable
+ self.unavailable = unavailable
+ self.unavailableNote = unavailableNote
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppReviewDomain: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppReviewDomain: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppReviewDomain {
+ return
+ try AppReviewDomain(
+ domain: FfiConverterString.read(from: &buf),
+ counts: FfiConverterString.read(from: &buf),
+ count: FfiConverterUInt32.read(from: &buf),
+ signin: FfiConverterBool.read(from: &buf),
+ identityProvider: FfiConverterBool.read(from: &buf),
+ selected: FfiConverterBool.read(from: &buf),
+ selectable: FfiConverterBool.read(from: &buf),
+ unavailable: FfiConverterUInt32.read(from: &buf),
+ unavailableNote: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppReviewDomain, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.domain, into: &buf)
+ FfiConverterString.write(value.counts, into: &buf)
+ FfiConverterUInt32.write(value.count, into: &buf)
+ FfiConverterBool.write(value.signin, into: &buf)
+ FfiConverterBool.write(value.identityProvider, into: &buf)
+ FfiConverterBool.write(value.selected, into: &buf)
+ FfiConverterBool.write(value.selectable, into: &buf)
+ FfiConverterUInt32.write(value.unavailable, into: &buf)
+ FfiConverterString.write(value.unavailableNote, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppReviewDomain_lift(_ buf: RustBuffer) throws -> AppReviewDomain {
+ return try FfiConverterTypeAppReviewDomain.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppReviewDomain_lower(_ value: AppReviewDomain) -> RustBuffer {
+ return FfiConverterTypeAppReviewDomain.lower(value)
+}
+
+
+public struct AppReviewToggle: Equatable, Hashable {
+ /**
+ * The consent item's key.
+ */
+ public var key: String
+ /**
+ * Label.
+ */
+ public var label: String
+ /**
+ * Detail.
+ */
+ public var detail: String
+ /**
+ * Bytes that leave.
+ */
+ public var bytes: UInt64
+ /**
+ * A secret.
+ */
+ public var sensitive: Bool
+ /**
+ * Sent (not turned off).
+ */
+ public var selected: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The consent item's key.
+ */key: String,
+ /**
+ * Label.
+ */label: String,
+ /**
+ * Detail.
+ */detail: String,
+ /**
+ * Bytes that leave.
+ */bytes: UInt64,
+ /**
+ * A secret.
+ */sensitive: Bool,
+ /**
+ * Sent (not turned off).
+ */selected: Bool) {
+ self.key = key
+ self.label = label
+ self.detail = detail
+ self.bytes = bytes
+ self.sensitive = sensitive
+ self.selected = selected
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppReviewToggle: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppReviewToggle: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppReviewToggle {
+ return
+ try AppReviewToggle(
+ key: FfiConverterString.read(from: &buf),
+ label: FfiConverterString.read(from: &buf),
+ detail: FfiConverterString.read(from: &buf),
+ bytes: FfiConverterUInt64.read(from: &buf),
+ sensitive: FfiConverterBool.read(from: &buf),
+ selected: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppReviewToggle, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterString.write(value.label, into: &buf)
+ FfiConverterString.write(value.detail, into: &buf)
+ FfiConverterUInt64.write(value.bytes, into: &buf)
+ FfiConverterBool.write(value.sensitive, into: &buf)
+ FfiConverterBool.write(value.selected, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppReviewToggle_lift(_ buf: RustBuffer) throws -> AppReviewToggle {
+ return try FfiConverterTypeAppReviewToggle.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppReviewToggle_lower(_ value: AppReviewToggle) -> RustBuffer {
+ return FfiConverterTypeAppReviewToggle.lower(value)
+}
+
+
public struct AppReviewView: Equatable, Hashable {
/**
* "Teleport Slack to Aurora".
@@ -23495,6 +24000,73 @@ public struct AppReviewView: Equatable, Hashable {
* Caveats.
*/
public var warnings: [String]
+ /**
+ * Lines the user can turn off (files, folders, state, secrets), each
+ * with whether it is sent. The cookie store is the site list below.
+ */
+ public var toggles: [AppReviewToggle]
+ /**
+ * The plan sends a browser's cookies, so the sites can be chosen.
+ */
+ public var offersDomains: Bool
+ /**
+ * The sites have not been read yet (the shell asks the Keyvault for
+ * them, which may ask for Touch ID).
+ */
+ public var needsDomains: Bool
+ /**
+ * The sites with counts, filtered by the search.
+ */
+ public var domains: [AppReviewDomain]
+ /**
+ * "3 of 12 sites".
+ */
+ public var domainSummary: String
+ /**
+ * The sites search text.
+ */
+ public var domainQuery: String
+ /**
+ * The sites chosen (what is remembered for next time).
+ */
+ public var selectedDomains: [String]
+ /**
+ * Where it sends from.
+ */
+ public var source: AppSendSource
+ /**
+ * The app has saved Keyvault items to send instead of reading the live
+ * app.
+ */
+ public var offersVault: Bool
+ /**
+ * The saved items.
+ */
+ public var vault: AppVaultSource
+ /**
+ * "Send from the Keyvault (212 items, saved 2 days ago)".
+ */
+ public var vaultLabel: String
+ /**
+ * "Read Chrome now (macOS asks for Keychain access)".
+ */
+ public var liveLabel: String
+ /**
+ * "Also send saved passwords" shows (there are some to send).
+ */
+ public var offersPasswords: Bool
+ /**
+ * Ticked.
+ */
+ public var includePasswords: Bool
+ /**
+ * "Also send 14 saved passwords".
+ */
+ public var passwordsLabel: String
+ /**
+ * What the Keychain will do for this source, in a line.
+ */
+ public var sourceNote: String
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -23537,7 +24109,58 @@ public struct AppReviewView: Equatable, Hashable {
*/leavesText: String?,
/**
* Caveats.
- */warnings: [String]) {
+ */warnings: [String],
+ /**
+ * Lines the user can turn off (files, folders, state, secrets), each
+ * with whether it is sent. The cookie store is the site list below.
+ */toggles: [AppReviewToggle],
+ /**
+ * The plan sends a browser's cookies, so the sites can be chosen.
+ */offersDomains: Bool,
+ /**
+ * The sites have not been read yet (the shell asks the Keyvault for
+ * them, which may ask for Touch ID).
+ */needsDomains: Bool,
+ /**
+ * The sites with counts, filtered by the search.
+ */domains: [AppReviewDomain],
+ /**
+ * "3 of 12 sites".
+ */domainSummary: String,
+ /**
+ * The sites search text.
+ */domainQuery: String,
+ /**
+ * The sites chosen (what is remembered for next time).
+ */selectedDomains: [String],
+ /**
+ * Where it sends from.
+ */source: AppSendSource,
+ /**
+ * The app has saved Keyvault items to send instead of reading the live
+ * app.
+ */offersVault: Bool,
+ /**
+ * The saved items.
+ */vault: AppVaultSource,
+ /**
+ * "Send from the Keyvault (212 items, saved 2 days ago)".
+ */vaultLabel: String,
+ /**
+ * "Read Chrome now (macOS asks for Keychain access)".
+ */liveLabel: String,
+ /**
+ * "Also send saved passwords" shows (there are some to send).
+ */offersPasswords: Bool,
+ /**
+ * Ticked.
+ */includePasswords: Bool,
+ /**
+ * "Also send 14 saved passwords".
+ */passwordsLabel: String,
+ /**
+ * What the Keychain will do for this source, in a line.
+ */sourceNote: String) {
self.title = title
self.items = items
self.steps = steps
@@ -23550,6 +24173,22 @@ public struct AppReviewView: Equatable, Hashable {
self.canConfirm = canConfirm
self.leavesText = leavesText
self.warnings = warnings
+ self.toggles = toggles
+ self.offersDomains = offersDomains
+ self.needsDomains = needsDomains
+ self.domains = domains
+ self.domainSummary = domainSummary
+ self.domainQuery = domainQuery
+ self.selectedDomains = selectedDomains
+ self.source = source
+ self.offersVault = offersVault
+ self.vault = vault
+ self.vaultLabel = vaultLabel
+ self.liveLabel = liveLabel
+ self.offersPasswords = offersPasswords
+ self.includePasswords = includePasswords
+ self.passwordsLabel = passwordsLabel
+ self.sourceNote = sourceNote
}
@@ -23579,7 +24218,23 @@ public struct FfiConverterTypeAppReviewView: FfiConverterRustBuffer {
acknowledgedRelayPlaintext: FfiConverterBool.read(from: &buf),
canConfirm: FfiConverterBool.read(from: &buf),
leavesText: FfiConverterOptionString.read(from: &buf),
- warnings: FfiConverterSequenceString.read(from: &buf)
+ warnings: FfiConverterSequenceString.read(from: &buf),
+ toggles: FfiConverterSequenceTypeAppReviewToggle.read(from: &buf),
+ offersDomains: FfiConverterBool.read(from: &buf),
+ needsDomains: FfiConverterBool.read(from: &buf),
+ domains: FfiConverterSequenceTypeAppReviewDomain.read(from: &buf),
+ domainSummary: FfiConverterString.read(from: &buf),
+ domainQuery: FfiConverterString.read(from: &buf),
+ selectedDomains: FfiConverterSequenceString.read(from: &buf),
+ source: FfiConverterTypeAppSendSource.read(from: &buf),
+ offersVault: FfiConverterBool.read(from: &buf),
+ vault: FfiConverterTypeAppVaultSource.read(from: &buf),
+ vaultLabel: FfiConverterString.read(from: &buf),
+ liveLabel: FfiConverterString.read(from: &buf),
+ offersPasswords: FfiConverterBool.read(from: &buf),
+ includePasswords: FfiConverterBool.read(from: &buf),
+ passwordsLabel: FfiConverterString.read(from: &buf),
+ sourceNote: FfiConverterString.read(from: &buf)
)
}
@@ -23596,6 +24251,22 @@ public struct FfiConverterTypeAppReviewView: FfiConverterRustBuffer {
FfiConverterBool.write(value.canConfirm, into: &buf)
FfiConverterOptionString.write(value.leavesText, into: &buf)
FfiConverterSequenceString.write(value.warnings, into: &buf)
+ FfiConverterSequenceTypeAppReviewToggle.write(value.toggles, into: &buf)
+ FfiConverterBool.write(value.offersDomains, into: &buf)
+ FfiConverterBool.write(value.needsDomains, into: &buf)
+ FfiConverterSequenceTypeAppReviewDomain.write(value.domains, into: &buf)
+ FfiConverterString.write(value.domainSummary, into: &buf)
+ FfiConverterString.write(value.domainQuery, into: &buf)
+ FfiConverterSequenceString.write(value.selectedDomains, into: &buf)
+ FfiConverterTypeAppSendSource.write(value.source, into: &buf)
+ FfiConverterBool.write(value.offersVault, into: &buf)
+ FfiConverterTypeAppVaultSource.write(value.vault, into: &buf)
+ FfiConverterString.write(value.vaultLabel, into: &buf)
+ FfiConverterString.write(value.liveLabel, into: &buf)
+ FfiConverterBool.write(value.offersPasswords, into: &buf)
+ FfiConverterBool.write(value.includePasswords, into: &buf)
+ FfiConverterString.write(value.passwordsLabel, into: &buf)
+ FfiConverterString.write(value.sourceNote, into: &buf)
}
}
@@ -24438,6 +25109,17 @@ public struct AppSettings: Equatable, Hashable {
* ([`crate::keyvault::view::prune_dismissed`] forgets the gone ones).
*/
public var dismissedAccess: [String]
+ /**
+ * Keyvault rows may load a site's icon from Google's favicon service
+ * when the source browser had none (Settings, Keyvault; on by default).
+ * Off, only icons read locally are shown.
+ */
+ public var keyvaultSiteIcons: Bool
+ /**
+ * The sites the user sent to each Space last time, per app
+ * ([`crate::teleport::review::remember`]): the review starts from them.
+ */
+ public var teleportChoices: [AppRememberedChoice]
/**
* Settings, General: a running Space's desktop streams as soon as it
* is opened (on by default); off, it waits for Connect
@@ -24487,6 +25169,15 @@ public struct AppSettings: Equatable, Hashable {
* longer shows them, nothing is revoked or wiped
* ([`crate::keyvault::view::prune_dismissed`] forgets the gone ones).
*/dismissedAccess: [String],
+ /**
+ * Keyvault rows may load a site's icon from Google's favicon service
+ * when the source browser had none (Settings, Keyvault; on by default).
+ * Off, only icons read locally are shown.
+ */keyvaultSiteIcons: Bool,
+ /**
+ * The sites the user sent to each Space last time, per app
+ * ([`crate::teleport::review::remember`]): the review starts from them.
+ */teleportChoices: [AppRememberedChoice],
/**
* Settings, General: a running Space's desktop streams as soon as it
* is opened (on by default); off, it waits for Connect
@@ -24503,6 +25194,8 @@ public struct AppSettings: Equatable, Hashable {
self.launchAtLogin = launchAtLogin
self.experiments = experiments
self.dismissedAccess = dismissedAccess
+ self.keyvaultSiteIcons = keyvaultSiteIcons
+ self.teleportChoices = teleportChoices
self.autoConnect = autoConnect
}
@@ -24533,6 +25226,8 @@ public struct FfiConverterTypeAppSettings: FfiConverterRustBuffer {
launchAtLogin: FfiConverterOptionBool.read(from: &buf),
experiments: FfiConverterTypeAppExperiments.read(from: &buf),
dismissedAccess: FfiConverterSequenceString.read(from: &buf),
+ keyvaultSiteIcons: FfiConverterBool.read(from: &buf),
+ teleportChoices: FfiConverterSequenceTypeAppRememberedChoice.read(from: &buf),
autoConnect: FfiConverterBool.read(from: &buf)
)
}
@@ -24549,6 +25244,8 @@ public struct FfiConverterTypeAppSettings: FfiConverterRustBuffer {
FfiConverterOptionBool.write(value.launchAtLogin, into: &buf)
FfiConverterTypeAppExperiments.write(value.experiments, into: &buf)
FfiConverterSequenceString.write(value.dismissedAccess, into: &buf)
+ FfiConverterBool.write(value.keyvaultSiteIcons, into: &buf)
+ FfiConverterSequenceTypeAppRememberedChoice.write(value.teleportChoices, into: &buf)
FfiConverterBool.write(value.autoConnect, into: &buf)
}
}
@@ -24632,6 +25329,21 @@ public struct AppSettingsInput: Equatable, Hashable {
* Keyvault section).
*/
public var keyvaultAutoWipe: Bool?
+ /**
+ * The unlock prompt shows (false once the user chose "Never ask
+ * again"); none until the broker told it.
+ */
+ public var keyvaultUnlockPrompt: Bool?
+ /**
+ * Load site icons from Google when the browser had none
+ * ([`AppSettings::keyvault_site_icons`]).
+ */
+ public var keyvaultSiteIcons: Bool
+ /**
+ * The Keyvault's protection facts (Touch ID, the daemon's signature),
+ * shown in the section.
+ */
+ public var keyvaultProtection: [AppFact]
/**
* "Connect to the desktop automatically" (none: no row; a shell
* without the preview cover leaves it out).
@@ -24688,6 +25400,18 @@ public struct AppSettingsInput: Equatable, Hashable {
* The Keyvault's auto-wipe, once the broker told it (none: no
* Keyvault section).
*/keyvaultAutoWipe: Bool?,
+ /**
+ * The unlock prompt shows (false once the user chose "Never ask
+ * again"); none until the broker told it.
+ */keyvaultUnlockPrompt: Bool?,
+ /**
+ * Load site icons from Google when the browser had none
+ * ([`AppSettings::keyvault_site_icons`]).
+ */keyvaultSiteIcons: Bool,
+ /**
+ * The Keyvault's protection facts (Touch ID, the daemon's signature),
+ * shown in the section.
+ */keyvaultProtection: [AppFact],
/**
* "Connect to the desktop automatically" (none: no row; a shell
* without the preview cover leaves it out).
@@ -24707,6 +25431,9 @@ public struct AppSettingsInput: Equatable, Hashable {
self.loginItem = loginItem
self.experiments = experiments
self.keyvaultAutoWipe = keyvaultAutoWipe
+ self.keyvaultUnlockPrompt = keyvaultUnlockPrompt
+ self.keyvaultSiteIcons = keyvaultSiteIcons
+ self.keyvaultProtection = keyvaultProtection
self.autoConnect = autoConnect
}
@@ -24741,6 +25468,9 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {
loginItem: FfiConverterOptionTypeAppLoginItemInput.read(from: &buf),
experiments: FfiConverterTypeAppExperiments.read(from: &buf),
keyvaultAutoWipe: FfiConverterOptionBool.read(from: &buf),
+ keyvaultUnlockPrompt: FfiConverterOptionBool.read(from: &buf),
+ keyvaultSiteIcons: FfiConverterBool.read(from: &buf),
+ keyvaultProtection: FfiConverterSequenceTypeAppFact.read(from: &buf),
autoConnect: FfiConverterOptionBool.read(from: &buf)
)
}
@@ -24761,6 +25491,9 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {
FfiConverterOptionTypeAppLoginItemInput.write(value.loginItem, into: &buf)
FfiConverterTypeAppExperiments.write(value.experiments, into: &buf)
FfiConverterOptionBool.write(value.keyvaultAutoWipe, into: &buf)
+ FfiConverterOptionBool.write(value.keyvaultUnlockPrompt, into: &buf)
+ FfiConverterBool.write(value.keyvaultSiteIcons, into: &buf)
+ FfiConverterSequenceTypeAppFact.write(value.keyvaultProtection, into: &buf)
FfiConverterOptionBool.write(value.autoConnect, into: &buf)
}
}
@@ -28816,6 +29549,23 @@ public struct AppTeleportConsent: Equatable, Hashable {
* [`Plan::relay_unsealed`]'s warning acknowledged (S1).
*/
public var acknowledgeRelayPlaintext: Bool
+ /**
+ * The sites whose cookies to send (the review's per-site choice);
+ * `None` when the review did not list sites.
+ */
+ public var cookieDomains: [String]?
+ /**
+ * Consent items (keys) the user turned off.
+ */
+ public var exclude: [String]
+ /**
+ * Send these saved Keyvault items instead of reading the live app.
+ */
+ public var fromVault: [String]?
+ /**
+ * Also send the saved passwords (ticked in the review).
+ */
+ public var includePasswords: Bool
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -28831,11 +29581,28 @@ public struct AppTeleportConsent: Equatable, Hashable {
*/saveToKeyvault: Bool,
/**
* [`Plan::relay_unsealed`]'s warning acknowledged (S1).
- */acknowledgeRelayPlaintext: Bool) {
+ */acknowledgeRelayPlaintext: Bool,
+ /**
+ * The sites whose cookies to send (the review's per-site choice);
+ * `None` when the review did not list sites.
+ */cookieDomains: [String]?,
+ /**
+ * Consent items (keys) the user turned off.
+ */exclude: [String],
+ /**
+ * Send these saved Keyvault items instead of reading the live app.
+ */fromVault: [String]?,
+ /**
+ * Also send the saved passwords (ticked in the review).
+ */includePasswords: Bool) {
self.approved = approved
self.acknowledgeSensitive = acknowledgeSensitive
self.saveToKeyvault = saveToKeyvault
self.acknowledgeRelayPlaintext = acknowledgeRelayPlaintext
+ self.cookieDomains = cookieDomains
+ self.exclude = exclude
+ self.fromVault = fromVault
+ self.includePasswords = includePasswords
}
@@ -28857,7 +29624,11 @@ public struct FfiConverterTypeAppTeleportConsent: FfiConverterRustBuffer {
approved: FfiConverterBool.read(from: &buf),
acknowledgeSensitive: FfiConverterBool.read(from: &buf),
saveToKeyvault: FfiConverterBool.read(from: &buf),
- acknowledgeRelayPlaintext: FfiConverterBool.read(from: &buf)
+ acknowledgeRelayPlaintext: FfiConverterBool.read(from: &buf),
+ cookieDomains: FfiConverterOptionSequenceString.read(from: &buf),
+ exclude: FfiConverterSequenceString.read(from: &buf),
+ fromVault: FfiConverterOptionSequenceString.read(from: &buf),
+ includePasswords: FfiConverterBool.read(from: &buf)
)
}
@@ -28866,6 +29637,10 @@ public struct FfiConverterTypeAppTeleportConsent: FfiConverterRustBuffer {
FfiConverterBool.write(value.acknowledgeSensitive, into: &buf)
FfiConverterBool.write(value.saveToKeyvault, into: &buf)
FfiConverterBool.write(value.acknowledgeRelayPlaintext, into: &buf)
+ FfiConverterOptionSequenceString.write(value.cookieDomains, into: &buf)
+ FfiConverterSequenceString.write(value.exclude, into: &buf)
+ FfiConverterOptionSequenceString.write(value.fromVault, into: &buf)
+ FfiConverterBool.write(value.includePasswords, into: &buf)
}
}
@@ -29897,6 +30672,102 @@ public func FfiConverterTypeAppUsageToggle_lower(_ value: AppUsageToggle) -> Rus
}
+public struct AppVaultSource: Equatable, Hashable {
+ /**
+ * The app has saved items that can be sent (passwords never are).
+ */
+ public var available: Bool
+ /**
+ * How many.
+ */
+ public var items: UInt32
+ /**
+ * "saved 2 days ago".
+ */
+ public var saved: String
+ /**
+ * The items chosen to send (ids).
+ */
+ public var selected: [String]
+ /**
+ * The app's saved passwords (ids), sent only when ticked.
+ */
+ public var passwordIds: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The app has saved items that can be sent (passwords never are).
+ */available: Bool,
+ /**
+ * How many.
+ */items: UInt32,
+ /**
+ * "saved 2 days ago".
+ */saved: String,
+ /**
+ * The items chosen to send (ids).
+ */selected: [String],
+ /**
+ * The app's saved passwords (ids), sent only when ticked.
+ */passwordIds: [String]) {
+ self.available = available
+ self.items = items
+ self.saved = saved
+ self.selected = selected
+ self.passwordIds = passwordIds
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppVaultSource: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppVaultSource: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppVaultSource {
+ return
+ try AppVaultSource(
+ available: FfiConverterBool.read(from: &buf),
+ items: FfiConverterUInt32.read(from: &buf),
+ saved: FfiConverterString.read(from: &buf),
+ selected: FfiConverterSequenceString.read(from: &buf),
+ passwordIds: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppVaultSource, into buf: inout [UInt8]) {
+ FfiConverterBool.write(value.available, into: &buf)
+ FfiConverterUInt32.write(value.items, into: &buf)
+ FfiConverterString.write(value.saved, into: &buf)
+ FfiConverterSequenceString.write(value.selected, into: &buf)
+ FfiConverterSequenceString.write(value.passwordIds, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppVaultSource_lift(_ buf: RustBuffer) throws -> AppVaultSource {
+ return try FfiConverterTypeAppVaultSource.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppVaultSource_lower(_ value: AppVaultSource) -> RustBuffer {
+ return FfiConverterTypeAppVaultSource.lower(value)
+}
+
+
public struct AppWizardEnv: Equatable, Hashable {
/**
* Where "Run on" starts (Settings, `cua config set default.on`).
@@ -31377,9 +32248,17 @@ public struct KeyvaultOverview: Equatable, Hashable {
*/
public var serverVerified: Bool
/**
- * Items.
+ * The vault's secret items, in order (app, domain, key).
*/
public var items: [KvItem]
+ /**
+ * Domains and keys are present in `items` (the browse window is open).
+ */
+ public var namesVisible: Bool
+ /**
+ * Items in the vault.
+ */
+ public var itemsTotal: UInt32
/**
* Pending requests.
*/
@@ -31426,8 +32305,14 @@ public struct KeyvaultOverview: Equatable, Hashable {
* The daemon was checked against Cua's signature.
*/serverVerified: Bool,
/**
- * Items.
+ * The vault's secret items, in order (app, domain, key).
*/items: [KvItem],
+ /**
+ * Domains and keys are present in `items` (the browse window is open).
+ */namesVisible: Bool,
+ /**
+ * Items in the vault.
+ */itemsTotal: UInt32,
/**
* Pending requests.
*/pending: [KvPending],
@@ -31454,6 +32339,8 @@ public struct KeyvaultOverview: Equatable, Hashable {
self.status = status
self.serverVerified = serverVerified
self.items = items
+ self.namesVisible = namesVisible
+ self.itemsTotal = itemsTotal
self.pending = pending
self.grants = grants
self.rules = rules
@@ -31484,6 +32371,8 @@ public struct FfiConverterTypeKeyvaultOverview: FfiConverterRustBuffer {
status: FfiConverterOptionTypeKvStatus.read(from: &buf),
serverVerified: FfiConverterBool.read(from: &buf),
items: FfiConverterSequenceTypeKvItem.read(from: &buf),
+ namesVisible: FfiConverterBool.read(from: &buf),
+ itemsTotal: FfiConverterUInt32.read(from: &buf),
pending: FfiConverterSequenceTypeKvPending.read(from: &buf),
grants: FfiConverterSequenceTypeKvGrant.read(from: &buf),
rules: FfiConverterSequenceTypeKvRule.read(from: &buf),
@@ -31500,6 +32389,8 @@ public struct FfiConverterTypeKeyvaultOverview: FfiConverterRustBuffer {
FfiConverterOptionTypeKvStatus.write(value.status, into: &buf)
FfiConverterBool.write(value.serverVerified, into: &buf)
FfiConverterSequenceTypeKvItem.write(value.items, into: &buf)
+ FfiConverterBool.write(value.namesVisible, into: &buf)
+ FfiConverterUInt32.write(value.itemsTotal, into: &buf)
FfiConverterSequenceTypeKvPending.write(value.pending, into: &buf)
FfiConverterSequenceTypeKvGrant.write(value.grants, into: &buf)
FfiConverterSequenceTypeKvRule.write(value.rules, into: &buf)
@@ -31770,19 +32661,117 @@ public func FfiConverterTypeKvAccessRow_lower(_ value: KvAccessRow) -> RustBuffe
}
+public struct KvAppRow: Equatable, Hashable {
+ /**
+ * The provider id (`chrome`): the key, and what the icon is looked up by.
+ */
+ public var key: String
+ /**
+ * "Google Chrome".
+ */
+ public var title: String
+ /**
+ * Items.
+ */
+ public var items: UInt32
+ /**
+ * Something waits for this app.
+ */
+ public var waiting: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The provider id (`chrome`): the key, and what the icon is looked up by.
+ */key: String,
+ /**
+ * "Google Chrome".
+ */title: String,
+ /**
+ * Items.
+ */items: UInt32,
+ /**
+ * Something waits for this app.
+ */waiting: Bool) {
+ self.key = key
+ self.title = title
+ self.items = items
+ self.waiting = waiting
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvAppRow: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvAppRow: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvAppRow {
+ return
+ try KvAppRow(
+ key: FfiConverterString.read(from: &buf),
+ title: FfiConverterString.read(from: &buf),
+ items: FfiConverterUInt32.read(from: &buf),
+ waiting: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvAppRow, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterString.write(value.title, into: &buf)
+ FfiConverterUInt32.write(value.items, into: &buf)
+ FfiConverterBool.write(value.waiting, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvAppRow_lift(_ buf: RustBuffer) throws -> KvAppRow {
+ return try FfiConverterTypeKvAppRow.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvAppRow_lower(_ value: KvAppRow) -> RustBuffer {
+ return FfiConverterTypeKvAppRow.lower(value)
+}
+
+
public struct KvApprovalRow: Equatable, Hashable {
/**
- * Row key.
+ * Row key: `<app>|<site>`, `<app>|files`, or `import:<n>`.
*/
public var key: String
/**
- * Site or app.
+ * The site, or the app for files and imports.
*/
public var title: String
/**
- * Account, or "Not imported yet".
+ * "3 cookies, 1 password", or "Not saved yet".
*/
public var account: String
+ /**
+ * The app's provider id (its icon), when known.
+ */
+ public var providerId: String
+ /**
+ * Items the row stands for.
+ */
+ public var items: UInt32
+ /**
+ * The items' ids.
+ */
+ public var itemIds: [String]
/**
* Ticked.
*/
@@ -31796,14 +32785,23 @@ public struct KvApprovalRow: Equatable, Hashable {
// declare one manually.
public init(
/**
- * Row key.
+ * Row key: `<app>|<site>`, `<app>|files`, or `import:<n>`.
*/key: String,
/**
- * Site or app.
+ * The site, or the app for files and imports.
*/title: String,
/**
- * Account, or "Not imported yet".
+ * "3 cookies, 1 password", or "Not saved yet".
*/account: String,
+ /**
+ * The app's provider id (its icon), when known.
+ */providerId: String,
+ /**
+ * Items the row stands for.
+ */items: UInt32,
+ /**
+ * The items' ids.
+ */itemIds: [String],
/**
* Ticked.
*/selected: Bool,
@@ -31813,6 +32811,9 @@ public struct KvApprovalRow: Equatable, Hashable {
self.key = key
self.title = title
self.account = account
+ self.providerId = providerId
+ self.items = items
+ self.itemIds = itemIds
self.selected = selected
self.isImport = isImport
}
@@ -31836,6 +32837,9 @@ public struct FfiConverterTypeKvApprovalRow: FfiConverterRustBuffer {
key: FfiConverterString.read(from: &buf),
title: FfiConverterString.read(from: &buf),
account: FfiConverterString.read(from: &buf),
+ providerId: FfiConverterString.read(from: &buf),
+ items: FfiConverterUInt32.read(from: &buf),
+ itemIds: FfiConverterSequenceString.read(from: &buf),
selected: FfiConverterBool.read(from: &buf),
isImport: FfiConverterBool.read(from: &buf)
)
@@ -31845,6 +32849,9 @@ public struct FfiConverterTypeKvApprovalRow: FfiConverterRustBuffer {
FfiConverterString.write(value.key, into: &buf)
FfiConverterString.write(value.title, into: &buf)
FfiConverterString.write(value.account, into: &buf)
+ FfiConverterString.write(value.providerId, into: &buf)
+ FfiConverterUInt32.write(value.items, into: &buf)
+ FfiConverterSequenceString.write(value.itemIds, into: &buf)
FfiConverterBool.write(value.selected, into: &buf)
FfiConverterBool.write(value.isImport, into: &buf)
}
@@ -31872,7 +32879,7 @@ public struct KvApprovalState: Equatable, Hashable {
*/
public var requestId: String
/**
- * Ticked row keys (item ids, or `import:<n>` for new items).
+ * Ticked row keys (`<app>|<site>`, or `import:<n>` for new items).
*/
public var selected: [String]
@@ -31883,7 +32890,7 @@ public struct KvApprovalState: Equatable, Hashable {
* The request.
*/requestId: String,
/**
- * Ticked row keys (item ids, or `import:<n>` for new items).
+ * Ticked row keys (`<app>|<site>`, or `import:<n>` for new items).
*/selected: [String]) {
self.requestId = requestId
self.selected = selected
@@ -32476,158 +33483,6 @@ public func FfiConverterTypeKvCategoryRow_lower(_ value: KvCategoryRow) -> RustB
}
-public struct KvConsentChip: Equatable, Hashable {
- /**
- * Kind.
- */
- public var kind: KvConsentChipKind
- /**
- * Text.
- */
- public var text: String
-
- // Default memberwise initializers are never public by default, so we
- // declare one manually.
- public init(
- /**
- * Kind.
- */kind: KvConsentChipKind,
- /**
- * Text.
- */text: String) {
- self.kind = kind
- self.text = text
- }
-
-
-
-
-}
-
-#if compiler(>=6)
-extension KvConsentChip: Sendable {}
-#endif
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public struct FfiConverterTypeKvConsentChip: FfiConverterRustBuffer {
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvConsentChip {
- return
- try KvConsentChip(
- kind: FfiConverterTypeKvConsentChipKind.read(from: &buf),
- text: FfiConverterString.read(from: &buf)
- )
- }
-
- public static func write(_ value: KvConsentChip, into buf: inout [UInt8]) {
- FfiConverterTypeKvConsentChipKind.write(value.kind, into: &buf)
- FfiConverterString.write(value.text, into: &buf)
- }
-}
-
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvConsentChip_lift(_ buf: RustBuffer) throws -> KvConsentChip {
- return try FfiConverterTypeKvConsentChip.lift(buf)
-}
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvConsentChip_lower(_ value: KvConsentChip) -> RustBuffer {
- return FfiConverterTypeKvConsentChip.lower(value)
-}
-
-
-public struct KvCookieInfo: Equatable, Hashable {
- /**
- * Name.
- */
- public var name: String
- /**
- * Domain.
- */
- public var domain: String
- /**
- * Session cookie.
- */
- public var session: Bool
- /**
- * Expiry.
- */
- public var expiresMs: Int64?
-
- // Default memberwise initializers are never public by default, so we
- // declare one manually.
- public init(
- /**
- * Name.
- */name: String,
- /**
- * Domain.
- */domain: String,
- /**
- * Session cookie.
- */session: Bool,
- /**
- * Expiry.
- */expiresMs: Int64?) {
- self.name = name
- self.domain = domain
- self.session = session
- self.expiresMs = expiresMs
- }
-
-
-
-
-}
-
-#if compiler(>=6)
-extension KvCookieInfo: Sendable {}
-#endif
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public struct FfiConverterTypeKvCookieInfo: FfiConverterRustBuffer {
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvCookieInfo {
- return
- try KvCookieInfo(
- name: FfiConverterString.read(from: &buf),
- domain: FfiConverterString.read(from: &buf),
- session: FfiConverterBool.read(from: &buf),
- expiresMs: FfiConverterOptionInt64.read(from: &buf)
- )
- }
-
- public static func write(_ value: KvCookieInfo, into buf: inout [UInt8]) {
- FfiConverterString.write(value.name, into: &buf)
- FfiConverterString.write(value.domain, into: &buf)
- FfiConverterBool.write(value.session, into: &buf)
- FfiConverterOptionInt64.write(value.expiresMs, into: &buf)
- }
-}
-
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvCookieInfo_lift(_ buf: RustBuffer) throws -> KvCookieInfo {
- return try FfiConverterTypeKvCookieInfo.lift(buf)
-}
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvCookieInfo_lower(_ value: KvCookieInfo) -> RustBuffer {
- return FfiConverterTypeKvCookieInfo.lower(value)
-}
-
-
public struct KvCredentialForm: Equatable, Hashable {
/**
* Setup or unlock.
@@ -32820,6 +33675,92 @@ public func FfiConverterTypeKvDecision_lower(_ value: KvDecision) -> RustBuffer
}
+public struct KvDeleteConfirm: Equatable, Hashable {
+ /**
+ * "Delete 3 items?"
+ */
+ public var title: String
+ /**
+ * What deleting does.
+ */
+ public var message: String
+ /**
+ * "Delete".
+ */
+ public var confirm: String
+ /**
+ * "Cancel".
+ */
+ public var cancel: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * "Delete 3 items?"
+ */title: String,
+ /**
+ * What deleting does.
+ */message: String,
+ /**
+ * "Delete".
+ */confirm: String,
+ /**
+ * "Cancel".
+ */cancel: String) {
+ self.title = title
+ self.message = message
+ self.confirm = confirm
+ self.cancel = cancel
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvDeleteConfirm: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvDeleteConfirm: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvDeleteConfirm {
+ return
+ try KvDeleteConfirm(
+ title: FfiConverterString.read(from: &buf),
+ message: FfiConverterString.read(from: &buf),
+ confirm: FfiConverterString.read(from: &buf),
+ cancel: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvDeleteConfirm, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.title, into: &buf)
+ FfiConverterString.write(value.message, into: &buf)
+ FfiConverterString.write(value.confirm, into: &buf)
+ FfiConverterString.write(value.cancel, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvDeleteConfirm_lift(_ buf: RustBuffer) throws -> KvDeleteConfirm {
+ return try FfiConverterTypeKvDeleteConfirm.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvDeleteConfirm_lower(_ value: KvDeleteConfirm) -> RustBuffer {
+ return FfiConverterTypeKvDeleteConfirm.lower(value)
+}
+
+
public struct KvDelivery: Equatable, Hashable {
/**
* Import id.
@@ -32946,6 +33887,208 @@ public func FfiConverterTypeKvDelivery_lower(_ value: KvDelivery) -> RustBuffer
}
+public struct KvDomainCount: Equatable, Hashable {
+ /**
+ * Registrable domain.
+ */
+ public var domain: String
+ /**
+ * Cookies.
+ */
+ public var cookies: UInt32
+ /**
+ * Cookies without an expiry.
+ */
+ public var sessionCookies: UInt32
+ /**
+ * localStorage values.
+ */
+ public var localStorage: UInt32
+ /**
+ * Saved passwords.
+ */
+ public var passwords: UInt32
+ /**
+ * Looks like it keeps a sign-in.
+ */
+ public var signin: Bool
+ /**
+ * An identity provider.
+ */
+ public var identityProvider: Bool
+ /**
+ * Cookies that cannot be read (Chrome's app-bound encryption).
+ */
+ public var unavailable: UInt32
+ /**
+ * Why they cannot be read.
+ */
+ public var unavailableReason: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Registrable domain.
+ */domain: String,
+ /**
+ * Cookies.
+ */cookies: UInt32,
+ /**
+ * Cookies without an expiry.
+ */sessionCookies: UInt32,
+ /**
+ * localStorage values.
+ */localStorage: UInt32,
+ /**
+ * Saved passwords.
+ */passwords: UInt32,
+ /**
+ * Looks like it keeps a sign-in.
+ */signin: Bool,
+ /**
+ * An identity provider.
+ */identityProvider: Bool,
+ /**
+ * Cookies that cannot be read (Chrome's app-bound encryption).
+ */unavailable: UInt32,
+ /**
+ * Why they cannot be read.
+ */unavailableReason: String) {
+ self.domain = domain
+ self.cookies = cookies
+ self.sessionCookies = sessionCookies
+ self.localStorage = localStorage
+ self.passwords = passwords
+ self.signin = signin
+ self.identityProvider = identityProvider
+ self.unavailable = unavailable
+ self.unavailableReason = unavailableReason
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvDomainCount: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvDomainCount: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvDomainCount {
+ return
+ try KvDomainCount(
+ domain: FfiConverterString.read(from: &buf),
+ cookies: FfiConverterUInt32.read(from: &buf),
+ sessionCookies: FfiConverterUInt32.read(from: &buf),
+ localStorage: FfiConverterUInt32.read(from: &buf),
+ passwords: FfiConverterUInt32.read(from: &buf),
+ signin: FfiConverterBool.read(from: &buf),
+ identityProvider: FfiConverterBool.read(from: &buf),
+ unavailable: FfiConverterUInt32.read(from: &buf),
+ unavailableReason: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvDomainCount, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.domain, into: &buf)
+ FfiConverterUInt32.write(value.cookies, into: &buf)
+ FfiConverterUInt32.write(value.sessionCookies, into: &buf)
+ FfiConverterUInt32.write(value.localStorage, into: &buf)
+ FfiConverterUInt32.write(value.passwords, into: &buf)
+ FfiConverterBool.write(value.signin, into: &buf)
+ FfiConverterBool.write(value.identityProvider, into: &buf)
+ FfiConverterUInt32.write(value.unavailable, into: &buf)
+ FfiConverterString.write(value.unavailableReason, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvDomainCount_lift(_ buf: RustBuffer) throws -> KvDomainCount {
+ return try FfiConverterTypeKvDomainCount.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvDomainCount_lower(_ value: KvDomainCount) -> RustBuffer {
+ return FfiConverterTypeKvDomainCount.lower(value)
+}
+
+
+public struct KvFavicon: Equatable, Hashable {
+ /**
+ * The site (registrable domain).
+ */
+ public var site: String
+ /**
+ * PNG, base64.
+ */
+ public var png: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The site (registrable domain).
+ */site: String,
+ /**
+ * PNG, base64.
+ */png: String) {
+ self.site = site
+ self.png = png
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvFavicon: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvFavicon: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvFavicon {
+ return
+ try KvFavicon(
+ site: FfiConverterString.read(from: &buf),
+ png: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvFavicon, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.site, into: &buf)
+ FfiConverterString.write(value.png, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvFavicon_lift(_ buf: RustBuffer) throws -> KvFavicon {
+ return try FfiConverterTypeKvFavicon.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvFavicon_lower(_ value: KvFavicon) -> RustBuffer {
+ return FfiConverterTypeKvFavicon.lower(value)
+}
+
+
public struct KvGrant: Equatable, Hashable {
/**
* Id.
@@ -33112,53 +34255,149 @@ public func FfiConverterTypeKvGrant_lower(_ value: KvGrant) -> RustBuffer {
}
+public struct KvInventory: Equatable, Hashable {
+ /**
+ * Provider id.
+ */
+ public var providerId: String
+ /**
+ * App name.
+ */
+ public var appDisplay: String
+ /**
+ * Domains with counts.
+ */
+ public var domains: [KvDomainCount]
+ /**
+ * Notes.
+ */
+ public var notes: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Provider id.
+ */providerId: String,
+ /**
+ * App name.
+ */appDisplay: String,
+ /**
+ * Domains with counts.
+ */domains: [KvDomainCount],
+ /**
+ * Notes.
+ */notes: [String]) {
+ self.providerId = providerId
+ self.appDisplay = appDisplay
+ self.domains = domains
+ self.notes = notes
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvInventory: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvInventory: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvInventory {
+ return
+ try KvInventory(
+ providerId: FfiConverterString.read(from: &buf),
+ appDisplay: FfiConverterString.read(from: &buf),
+ domains: FfiConverterSequenceTypeKvDomainCount.read(from: &buf),
+ notes: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvInventory, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.providerId, into: &buf)
+ FfiConverterString.write(value.appDisplay, into: &buf)
+ FfiConverterSequenceTypeKvDomainCount.write(value.domains, into: &buf)
+ FfiConverterSequenceString.write(value.notes, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvInventory_lift(_ buf: RustBuffer) throws -> KvInventory {
+ return try FfiConverterTypeKvInventory.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvInventory_lower(_ value: KvInventory) -> RustBuffer {
+ return FfiConverterTypeKvInventory.lower(value)
+}
+
+
public struct KvItem: Equatable, Hashable {
/**
* Id.
*/
public var id: String
/**
- * `browser_site`, `site_passwords`, `app_session`.
+ * `cookie`, `local_storage`, `password` or `file`.
*/
public var kind: String
/**
- * Label.
- */
- public var label: String
- /**
- * Provider.
+ * The source app (`chrome`, `slack`).
*/
public var providerId: String
/**
- * App.
+ * The app's name.
*/
public var appDisplay: String
/**
- * Site.
+ * A cookie's host, a storage value's or password's origin; none for a
+ * file or when the names are hidden.
*/
- public var site: String?
+ public var domain: String?
/**
- * Account.
+ * A cookie name, storage key, username or file path; empty when the
+ * names are hidden.
*/
- public var account: String?
+ public var key: String
+ /**
+ * A cookie's path.
+ */
+ public var path: String?
/**
* Profile.
*/
public var source: String
/**
- * Summary.
+ * A cookie without an expiry.
*/
- public var summary: KvItemSummary
+ public var session: Bool
/**
- * Warnings.
+ * A cookie's expiry, Unix ms.
*/
- public var warnings: [String]
+ public var expiresMs: Int64?
/**
- * Identity providers always ask.
+ * Bytes.
+ */
+ public var bytes: UInt64
+ /**
+ * The blob a big file's bytes live in.
+ */
+ public var blob: String?
+ /**
+ * Identity providers always ask: they cannot be unlocked.
*/
public var identityProvider: Bool
/**
- * Policy.
+ * Policy: `unattended` is the unlock.
*/
public var policy: KvItemPolicy
/**
@@ -33166,7 +34405,7 @@ public struct KvItem: Equatable, Hashable {
*/
public var createdMs: UInt64
/**
- * Updated.
+ * Last saved.
*/
public var updatedMs: UInt64
/**
@@ -33185,43 +34424,51 @@ public struct KvItem: Equatable, Hashable {
* Id.
*/id: String,
/**
- * `browser_site`, `site_passwords`, `app_session`.
+ * `cookie`, `local_storage`, `password` or `file`.
*/kind: String,
/**
- * Label.
- */label: String,
- /**
- * Provider.
+ * The source app (`chrome`, `slack`).
*/providerId: String,
/**
- * App.
+ * The app's name.
*/appDisplay: String,
/**
- * Site.
- */site: String?,
+ * A cookie's host, a storage value's or password's origin; none for a
+ * file or when the names are hidden.
+ */domain: String?,
/**
- * Account.
- */account: String?,
+ * A cookie name, storage key, username or file path; empty when the
+ * names are hidden.
+ */key: String,
+ /**
+ * A cookie's path.
+ */path: String?,
/**
* Profile.
*/source: String,
/**
- * Summary.
- */summary: KvItemSummary,
+ * A cookie without an expiry.
+ */session: Bool,
/**
- * Warnings.
- */warnings: [String],
+ * A cookie's expiry, Unix ms.
+ */expiresMs: Int64?,
/**
- * Identity providers always ask.
+ * Bytes.
+ */bytes: UInt64,
+ /**
+ * The blob a big file's bytes live in.
+ */blob: String?,
+ /**
+ * Identity providers always ask: they cannot be unlocked.
*/identityProvider: Bool,
/**
- * Policy.
+ * Policy: `unattended` is the unlock.
*/policy: KvItemPolicy,
/**
* Created.
*/createdMs: UInt64,
/**
- * Updated.
+ * Last saved.
*/updatedMs: UInt64,
/**
* Revision.
@@ -33231,14 +34478,16 @@ public struct KvItem: Equatable, Hashable {
*/recordDigest: String) {
self.id = id
self.kind = kind
- self.label = label
self.providerId = providerId
self.appDisplay = appDisplay
- self.site = site
- self.account = account
+ self.domain = domain
+ self.key = key
+ self.path = path
self.source = source
- self.summary = summary
- self.warnings = warnings
+ self.session = session
+ self.expiresMs = expiresMs
+ self.bytes = bytes
+ self.blob = blob
self.identityProvider = identityProvider
self.policy = policy
self.createdMs = createdMs
@@ -33265,14 +34514,16 @@ public struct FfiConverterTypeKvItem: FfiConverterRustBuffer {
try KvItem(
id: FfiConverterString.read(from: &buf),
kind: FfiConverterString.read(from: &buf),
- label: FfiConverterString.read(from: &buf),
providerId: FfiConverterString.read(from: &buf),
appDisplay: FfiConverterString.read(from: &buf),
- site: FfiConverterOptionString.read(from: &buf),
- account: FfiConverterOptionString.read(from: &buf),
+ domain: FfiConverterOptionString.read(from: &buf),
+ key: FfiConverterString.read(from: &buf),
+ path: FfiConverterOptionString.read(from: &buf),
source: FfiConverterString.read(from: &buf),
- summary: FfiConverterTypeKvItemSummary.read(from: &buf),
- warnings: FfiConverterSequenceString.read(from: &buf),
+ session: FfiConverterBool.read(from: &buf),
+ expiresMs: FfiConverterOptionInt64.read(from: &buf),
+ bytes: FfiConverterUInt64.read(from: &buf),
+ blob: FfiConverterOptionString.read(from: &buf),
identityProvider: FfiConverterBool.read(from: &buf),
policy: FfiConverterTypeKvItemPolicy.read(from: &buf),
createdMs: FfiConverterUInt64.read(from: &buf),
@@ -33285,14 +34536,16 @@ public struct FfiConverterTypeKvItem: FfiConverterRustBuffer {
public static func write(_ value: KvItem, into buf: inout [UInt8]) {
FfiConverterString.write(value.id, into: &buf)
FfiConverterString.write(value.kind, into: &buf)
- FfiConverterString.write(value.label, into: &buf)
FfiConverterString.write(value.providerId, into: &buf)
FfiConverterString.write(value.appDisplay, into: &buf)
- FfiConverterOptionString.write(value.site, into: &buf)
- FfiConverterOptionString.write(value.account, into: &buf)
+ FfiConverterOptionString.write(value.domain, into: &buf)
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterOptionString.write(value.path, into: &buf)
FfiConverterString.write(value.source, into: &buf)
- FfiConverterTypeKvItemSummary.write(value.summary, into: &buf)
- FfiConverterSequenceString.write(value.warnings, into: &buf)
+ FfiConverterBool.write(value.session, into: &buf)
+ FfiConverterOptionInt64.write(value.expiresMs, into: &buf)
+ FfiConverterUInt64.write(value.bytes, into: &buf)
+ FfiConverterOptionString.write(value.blob, into: &buf)
FfiConverterBool.write(value.identityProvider, into: &buf)
FfiConverterTypeKvItemPolicy.write(value.policy, into: &buf)
FfiConverterUInt64.write(value.createdMs, into: &buf)
@@ -33394,208 +34647,6 @@ public func FfiConverterTypeKvItemPolicy_lower(_ value: KvItemPolicy) -> RustBuf
}
-public struct KvItemRow: Equatable, Hashable {
- /**
- * The item.
- */
- public var item: KvItem
- /**
- * "[email protected]", "Whole app session", or the profile.
- */
- public var account: String
- /**
- * Strongest first; `asks` when nothing else applies.
- */
- public var consent: [KvConsentChip]
- /**
- * The unattended switch can be changed (not an identity provider).
- */
- public var toggleEnabled: Bool
- /**
- * The switch's tooltip.
- */
- public var toggleHelp: String
-
- // Default memberwise initializers are never public by default, so we
- // declare one manually.
- public init(
- /**
- * The item.
- */item: KvItem,
- /**
- * "[email protected]", "Whole app session", or the profile.
- */account: String,
- /**
- * Strongest first; `asks` when nothing else applies.
- */consent: [KvConsentChip],
- /**
- * The unattended switch can be changed (not an identity provider).
- */toggleEnabled: Bool,
- /**
- * The switch's tooltip.
- */toggleHelp: String) {
- self.item = item
- self.account = account
- self.consent = consent
- self.toggleEnabled = toggleEnabled
- self.toggleHelp = toggleHelp
- }
-
-
-
-
-}
-
-#if compiler(>=6)
-extension KvItemRow: Sendable {}
-#endif
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public struct FfiConverterTypeKvItemRow: FfiConverterRustBuffer {
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvItemRow {
- return
- try KvItemRow(
- item: FfiConverterTypeKvItem.read(from: &buf),
- account: FfiConverterString.read(from: &buf),
- consent: FfiConverterSequenceTypeKvConsentChip.read(from: &buf),
- toggleEnabled: FfiConverterBool.read(from: &buf),
- toggleHelp: FfiConverterString.read(from: &buf)
- )
- }
-
- public static func write(_ value: KvItemRow, into buf: inout [UInt8]) {
- FfiConverterTypeKvItem.write(value.item, into: &buf)
- FfiConverterString.write(value.account, into: &buf)
- FfiConverterSequenceTypeKvConsentChip.write(value.consent, into: &buf)
- FfiConverterBool.write(value.toggleEnabled, into: &buf)
- FfiConverterString.write(value.toggleHelp, into: &buf)
- }
-}
-
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvItemRow_lift(_ buf: RustBuffer) throws -> KvItemRow {
- return try FfiConverterTypeKvItemRow.lift(buf)
-}
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvItemRow_lower(_ value: KvItemRow) -> RustBuffer {
- return FfiConverterTypeKvItemRow.lower(value)
-}
-
-
-public struct KvItemSummary: Equatable, Hashable {
- /**
- * Cookies.
- */
- public var cookies: [KvCookieInfo]
- /**
- * Storage origins.
- */
- public var storageOrigins: [String]
- /**
- * Saved passwords.
- */
- public var passwords: UInt32
- /**
- * Files.
- */
- public var files: [String]
- /**
- * Keychain services.
- */
- public var keychainServices: [String]
- /**
- * Bytes.
- */
- public var bytes: UInt64
-
- // Default memberwise initializers are never public by default, so we
- // declare one manually.
- public init(
- /**
- * Cookies.
- */cookies: [KvCookieInfo],
- /**
- * Storage origins.
- */storageOrigins: [String],
- /**
- * Saved passwords.
- */passwords: UInt32,
- /**
- * Files.
- */files: [String],
- /**
- * Keychain services.
- */keychainServices: [String],
- /**
- * Bytes.
- */bytes: UInt64) {
- self.cookies = cookies
- self.storageOrigins = storageOrigins
- self.passwords = passwords
- self.files = files
- self.keychainServices = keychainServices
- self.bytes = bytes
- }
-
-
-
-
-}
-
-#if compiler(>=6)
-extension KvItemSummary: Sendable {}
-#endif
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public struct FfiConverterTypeKvItemSummary: FfiConverterRustBuffer {
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvItemSummary {
- return
- try KvItemSummary(
- cookies: FfiConverterSequenceTypeKvCookieInfo.read(from: &buf),
- storageOrigins: FfiConverterSequenceString.read(from: &buf),
- passwords: FfiConverterUInt32.read(from: &buf),
- files: FfiConverterSequenceString.read(from: &buf),
- keychainServices: FfiConverterSequenceString.read(from: &buf),
- bytes: FfiConverterUInt64.read(from: &buf)
- )
- }
-
- public static func write(_ value: KvItemSummary, into buf: inout [UInt8]) {
- FfiConverterSequenceTypeKvCookieInfo.write(value.cookies, into: &buf)
- FfiConverterSequenceString.write(value.storageOrigins, into: &buf)
- FfiConverterUInt32.write(value.passwords, into: &buf)
- FfiConverterSequenceString.write(value.files, into: &buf)
- FfiConverterSequenceString.write(value.keychainServices, into: &buf)
- FfiConverterUInt64.write(value.bytes, into: &buf)
- }
-}
-
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvItemSummary_lift(_ buf: RustBuffer) throws -> KvItemSummary {
- return try FfiConverterTypeKvItemSummary.lift(buf)
-}
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvItemSummary_lower(_ value: KvItemSummary) -> RustBuffer {
- return FfiConverterTypeKvItemSummary.lower(value)
-}
-
-
public struct KvLabels: Equatable, Hashable {
/**
* "Deny".
@@ -33629,18 +34680,6 @@ public struct KvLabels: Equatable, Hashable {
* "Protection".
*/
public var protectionTitle: String
- /**
- * A site's accounts section.
- */
- public var accountsTitle: String
- /**
- * A site's app fact.
- */
- public var appLabel: String
- /**
- * A site's switch.
- */
- public var everyAccount: String
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -33668,16 +34707,7 @@ public struct KvLabels: Equatable, Hashable {
*/confirmNote: String,
/**
* "Protection".
- */protectionTitle: String,
- /**
- * A site's accounts section.
- */accountsTitle: String,
- /**
- * A site's app fact.
- */appLabel: String,
- /**
- * A site's switch.
- */everyAccount: String) {
+ */protectionTitle: String) {
self.deny = deny
self.review = review
self.cancel = cancel
@@ -33686,9 +34716,6 @@ public struct KvLabels: Equatable, Hashable {
self.revokeAll = revokeAll
self.confirmNote = confirmNote
self.protectionTitle = protectionTitle
- self.accountsTitle = accountsTitle
- self.appLabel = appLabel
- self.everyAccount = everyAccount
}
@@ -33714,10 +34741,7 @@ public struct FfiConverterTypeKvLabels: FfiConverterRustBuffer {
unlock: FfiConverterString.read(from: &buf),
revokeAll: FfiConverterString.read(from: &buf),
confirmNote: FfiConverterString.read(from: &buf),
- protectionTitle: FfiConverterString.read(from: &buf),
- accountsTitle: FfiConverterString.read(from: &buf),
- appLabel: FfiConverterString.read(from: &buf),
- everyAccount: FfiConverterString.read(from: &buf)
+ protectionTitle: FfiConverterString.read(from: &buf)
)
}
@@ -33730,9 +34754,6 @@ public struct FfiConverterTypeKvLabels: FfiConverterRustBuffer {
FfiConverterString.write(value.revokeAll, into: &buf)
FfiConverterString.write(value.confirmNote, into: &buf)
FfiConverterString.write(value.protectionTitle, into: &buf)
- FfiConverterString.write(value.accountsTitle, into: &buf)
- FfiConverterString.write(value.appLabel, into: &buf)
- FfiConverterString.write(value.everyAccount, into: &buf)
}
}
@@ -33758,9 +34779,9 @@ public struct KvListView: Equatable, Hashable {
*/
public var title: String
/**
- * Sites (All, or the one site).
+ * The vault list shows (All Items, or one app).
*/
- public var sites: [KvSiteGroup]
+ public var vault: Bool
/**
* Waiting.
*/
@@ -33774,7 +34795,7 @@ public struct KvListView: Equatable, Hashable {
*/
public var recent: [KvRecentRow]
/**
- * "No items yet." and friends.
+ * "Nothing is waiting." and friends.
*/
public var emptyText: String?
@@ -33785,8 +34806,8 @@ public struct KvListView: Equatable, Hashable {
* Title.
*/title: String,
/**
- * Sites (All, or the one site).
- */sites: [KvSiteGroup],
+ * The vault list shows (All Items, or one app).
+ */vault: Bool,
/**
* Waiting.
*/pending: [KvPendingRow],
@@ -33797,10 +34818,10 @@ public struct KvListView: Equatable, Hashable {
* Recent.
*/recent: [KvRecentRow],
/**
- * "No items yet." and friends.
+ * "Nothing is waiting." and friends.
*/emptyText: String?) {
self.title = title
- self.sites = sites
+ self.vault = vault
self.pending = pending
self.access = access
self.recent = recent
@@ -33824,7 +34845,7 @@ public struct FfiConverterTypeKvListView: FfiConverterRustBuffer {
return
try KvListView(
title: FfiConverterString.read(from: &buf),
- sites: FfiConverterSequenceTypeKvSiteGroup.read(from: &buf),
+ vault: FfiConverterBool.read(from: &buf),
pending: FfiConverterSequenceTypeKvPendingRow.read(from: &buf),
access: FfiConverterSequenceTypeKvAccessRow.read(from: &buf),
recent: FfiConverterSequenceTypeKvRecentRow.read(from: &buf),
@@ -33834,7 +34855,7 @@ public struct FfiConverterTypeKvListView: FfiConverterRustBuffer {
public static func write(_ value: KvListView, into buf: inout [UInt8]) {
FfiConverterString.write(value.title, into: &buf)
- FfiConverterSequenceTypeKvSiteGroup.write(value.sites, into: &buf)
+ FfiConverterBool.write(value.vault, into: &buf)
FfiConverterSequenceTypeKvPendingRow.write(value.pending, into: &buf)
FfiConverterSequenceTypeKvAccessRow.write(value.access, into: &buf)
FfiConverterSequenceTypeKvRecentRow.write(value.recent, into: &buf)
@@ -33920,9 +34941,17 @@ public struct KvPage: Equatable, Hashable {
*/
public var hasItems: Bool
/**
- * Search shows (more than six items).
+ * Search shows (any item exists).
*/
public var searchVisible: Bool
+ /**
+ * "Never ask again" on the unlock prompt is on (Settings turns it off).
+ */
+ public var skipUnlockPrompt: Bool
+ /**
+ * An earlier preview's vault was set aside: one line to show.
+ */
+ public var resetNotice: String?
/**
* Pending requests (the sidebar badge).
*/
@@ -33989,8 +35018,14 @@ public struct KvPage: Equatable, Hashable {
* Items exist.
*/hasItems: Bool,
/**
- * Search shows (more than six items).
+ * Search shows (any item exists).
*/searchVisible: Bool,
+ /**
+ * "Never ask again" on the unlock prompt is on (Settings turns it off).
+ */skipUnlockPrompt: Bool,
+ /**
+ * An earlier preview's vault was set aside: one line to show.
+ */resetNotice: String?,
/**
* Pending requests (the sidebar badge).
*/pendingCount: UInt32,
@@ -34019,6 +35054,8 @@ public struct KvPage: Equatable, Hashable {
self.revokeAll = revokeAll
self.hasItems = hasItems
self.searchVisible = searchVisible
+ self.skipUnlockPrompt = skipUnlockPrompt
+ self.resetNotice = resetNotice
self.pendingCount = pendingCount
self.killSwitchHelp = killSwitchHelp
self.labels = labels
@@ -34057,6 +35094,8 @@ public struct FfiConverterTypeKvPage: FfiConverterRustBuffer {
revokeAll: FfiConverterBool.read(from: &buf),
hasItems: FfiConverterBool.read(from: &buf),
searchVisible: FfiConverterBool.read(from: &buf),
+ skipUnlockPrompt: FfiConverterBool.read(from: &buf),
+ resetNotice: FfiConverterOptionString.read(from: &buf),
pendingCount: FfiConverterUInt32.read(from: &buf),
killSwitchHelp: FfiConverterString.read(from: &buf),
labels: FfiConverterTypeKvLabels.read(from: &buf),
@@ -34081,6 +35120,8 @@ public struct FfiConverterTypeKvPage: FfiConverterRustBuffer {
FfiConverterBool.write(value.revokeAll, into: &buf)
FfiConverterBool.write(value.hasItems, into: &buf)
FfiConverterBool.write(value.searchVisible, into: &buf)
+ FfiConverterBool.write(value.skipUnlockPrompt, into: &buf)
+ FfiConverterOptionString.write(value.resetNotice, into: &buf)
FfiConverterUInt32.write(value.pendingCount, into: &buf)
FfiConverterString.write(value.killSwitchHelp, into: &buf)
FfiConverterTypeKvLabels.write(value.labels, into: &buf)
@@ -34672,25 +35713,25 @@ public func FfiConverterTypeKvRuleCaller_lower(_ value: KvRuleCaller) -> RustBuf
public struct KvSidebar: Equatable, Hashable {
/**
- * All, Waiting, Access, Recent.
+ * All Items, Waiting, Access, Recent.
*/
public var categories: [KvCategoryRow]
/**
- * One row per site or app.
+ * One row per app, by name.
*/
- public var sites: [KvSiteRow]
+ public var apps: [KvAppRow]
// Default memberwise initializers are never public by default, so we
// declare one manually.
public init(
/**
- * All, Waiting, Access, Recent.
+ * All Items, Waiting, Access, Recent.
*/categories: [KvCategoryRow],
/**
- * One row per site or app.
- */sites: [KvSiteRow]) {
+ * One row per app, by name.
+ */apps: [KvAppRow]) {
self.categories = categories
- self.sites = sites
+ self.apps = apps
}
@@ -34710,13 +35751,13 @@ public struct FfiConverterTypeKvSidebar: FfiConverterRustBuffer {
return
try KvSidebar(
categories: FfiConverterSequenceTypeKvCategoryRow.read(from: &buf),
- sites: FfiConverterSequenceTypeKvSiteRow.read(from: &buf)
+ apps: FfiConverterSequenceTypeKvAppRow.read(from: &buf)
)
}
public static func write(_ value: KvSidebar, into buf: inout [UInt8]) {
FfiConverterSequenceTypeKvCategoryRow.write(value.categories, into: &buf)
- FfiConverterSequenceTypeKvSiteRow.write(value.sites, into: &buf)
+ FfiConverterSequenceTypeKvAppRow.write(value.apps, into: &buf)
}
}
@@ -34802,51 +35843,1115 @@ public func FfiConverterTypeKvSigningBadge_lower(_ value: KvSigningBadge) -> Rus
}
-public struct KvSiteDetail: Equatable, Hashable {
+public struct KvStatus: Equatable, Hashable {
/**
- * The group.
+ * Version.
*/
- public var group: KvSiteGroup
+ public var version: String
/**
- * The site switch shows (more than one account).
+ * A vault exists.
*/
- public var siteSwitch: Bool
+ public var initialized: Bool
/**
- * The site switch's state.
+ * Unlocked.
*/
- public var siteState: KvTri
+ public var unlocked: Bool
/**
- * The site switch can be flipped.
+ * The kill switch is on.
*/
- public var siteSwitchEnabled: Bool
+ public var disabled: Bool
/**
- * Its tooltip.
+ * This app is first party.
+ */
+ public var callerFirstParty: Bool
+ /**
+ * How the broker sees this app.
+ */
+ public var callerDisplay: String
+ /**
+ * Items.
+ */
+ public var items: UInt32
+ /**
+ * Pending requests.
+ */
+ public var pending: UInt32
+ /**
+ * `auto` or `presence`.
+ */
+ public var unlockPolicy: String?
+ /**
+ * Delivered copies wipe themselves after their TTL (off by default;
+ * none: not told, a broker before the setting or a third party).
+ */
+ public var autoWipe: Bool?
+ /**
+ * The daemon can create the OS key store protector (setup offers Touch
+ * ID); false for a development daemon, which is passphrase-only.
*/
- public var siteSwitchHelp: String
+ public var osProtectorAvailable: Bool
+ /**
+ * A passphrase can always be chosen.
+ */
+ public var passphraseAvailable: Bool
+ /**
+ * Protector kinds that can unlock this vault now (`macos-keychain`,
+ * `windows-credential`, `passphrase`, `recovery`).
+ */
+ public var unlockProtectors: [String]
+ /**
+ * The browse window is open until this time, Unix ms: item names are
+ * visible until then.
+ */
+ public var browseUntilMs: UInt64?
+ /**
+ * "Never ask again" on the unlock prompt is on.
+ */
+ public var skipUnlockPrompt: Bool?
+ /**
+ * An earlier preview's vault was found and set aside.
+ */
+ public var resetNotice: String?
// Default memberwise initializers are never public by default, so we
// declare one manually.
public init(
/**
- * The group.
- */group: KvSiteGroup,
+ * Version.
+ */version: String,
/**
- * The site switch shows (more than one account).
- */siteSwitch: Bool,
+ * A vault exists.
+ */initialized: Bool,
/**
- * The site switch's state.
- */siteState: KvTri,
+ * Unlocked.
+ */unlocked: Bool,
/**
- * The site switch can be flipped.
- */siteSwitchEnabled: Bool,
+ * The kill switch is on.
+ */disabled: Bool,
/**
- * Its tooltip.
- */siteSwitchHelp: String) {
- self.group = group
- self.siteSwitch = siteSwitch
- self.siteState = siteState
- self.siteSwitchEnabled = siteSwitchEnabled
- self.siteSwitchHelp = siteSwitchHelp
+ * This app is first party.
+ */callerFirstParty: Bool,
+ /**
+ * How the broker sees this app.
+ */callerDisplay: String,
+ /**
+ * Items.
+ */items: UInt32,
+ /**
+ * Pending requests.
+ */pending: UInt32,
+ /**
+ * `auto` or `presence`.
+ */unlockPolicy: String?,
+ /**
+ * Delivered copies wipe themselves after their TTL (off by default;
+ * none: not told, a broker before the setting or a third party).
+ */autoWipe: Bool?,
+ /**
+ * The daemon can create the OS key store protector (setup offers Touch
+ * ID); false for a development daemon, which is passphrase-only.
+ */osProtectorAvailable: Bool,
+ /**
+ * A passphrase can always be chosen.
+ */passphraseAvailable: Bool,
+ /**
+ * Protector kinds that can unlock this vault now (`macos-keychain`,
+ * `windows-credential`, `passphrase`, `recovery`).
+ */unlockProtectors: [String],
+ /**
+ * The browse window is open until this time, Unix ms: item names are
+ * visible until then.
+ */browseUntilMs: UInt64?,
+ /**
+ * "Never ask again" on the unlock prompt is on.
+ */skipUnlockPrompt: Bool?,
+ /**
+ * An earlier preview's vault was found and set aside.
+ */resetNotice: String?) {
+ self.version = version
+ self.initialized = initialized
+ self.unlocked = unlocked
+ self.disabled = disabled
+ self.callerFirstParty = callerFirstParty
+ self.callerDisplay = callerDisplay
+ self.items = items
+ self.pending = pending
+ self.unlockPolicy = unlockPolicy
+ self.autoWipe = autoWipe
+ self.osProtectorAvailable = osProtectorAvailable
+ self.passphraseAvailable = passphraseAvailable
+ self.unlockProtectors = unlockProtectors
+ self.browseUntilMs = browseUntilMs
+ self.skipUnlockPrompt = skipUnlockPrompt
+ self.resetNotice = resetNotice
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvStatus: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvStatus: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvStatus {
+ return
+ try KvStatus(
+ version: FfiConverterString.read(from: &buf),
+ initialized: FfiConverterBool.read(from: &buf),
+ unlocked: FfiConverterBool.read(from: &buf),
+ disabled: FfiConverterBool.read(from: &buf),
+ callerFirstParty: FfiConverterBool.read(from: &buf),
+ callerDisplay: FfiConverterString.read(from: &buf),
+ items: FfiConverterUInt32.read(from: &buf),
+ pending: FfiConverterUInt32.read(from: &buf),
+ unlockPolicy: FfiConverterOptionString.read(from: &buf),
+ autoWipe: FfiConverterOptionBool.read(from: &buf),
+ osProtectorAvailable: FfiConverterBool.read(from: &buf),
+ passphraseAvailable: FfiConverterBool.read(from: &buf),
+ unlockProtectors: FfiConverterSequenceString.read(from: &buf),
+ browseUntilMs: FfiConverterOptionUInt64.read(from: &buf),
+ skipUnlockPrompt: FfiConverterOptionBool.read(from: &buf),
+ resetNotice: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvStatus, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.version, into: &buf)
+ FfiConverterBool.write(value.initialized, into: &buf)
+ FfiConverterBool.write(value.unlocked, into: &buf)
+ FfiConverterBool.write(value.disabled, into: &buf)
+ FfiConverterBool.write(value.callerFirstParty, into: &buf)
+ FfiConverterString.write(value.callerDisplay, into: &buf)
+ FfiConverterUInt32.write(value.items, into: &buf)
+ FfiConverterUInt32.write(value.pending, into: &buf)
+ FfiConverterOptionString.write(value.unlockPolicy, into: &buf)
+ FfiConverterOptionBool.write(value.autoWipe, into: &buf)
+ FfiConverterBool.write(value.osProtectorAvailable, into: &buf)
+ FfiConverterBool.write(value.passphraseAvailable, into: &buf)
+ FfiConverterSequenceString.write(value.unlockProtectors, into: &buf)
+ FfiConverterOptionUInt64.write(value.browseUntilMs, into: &buf)
+ FfiConverterOptionBool.write(value.skipUnlockPrompt, into: &buf)
+ FfiConverterOptionString.write(value.resetNotice, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvStatus_lift(_ buf: RustBuffer) throws -> KvStatus {
+ return try FfiConverterTypeKvStatus.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvStatus_lower(_ value: KvStatus) -> RustBuffer {
+ return FfiConverterTypeKvStatus.lower(value)
+}
+
+
+public struct KvUnlockPrompt: Equatable, Hashable {
+ /**
+ * "Allow unattended access?"
+ */
+ public var title: String
+ /**
+ * What it allows.
+ */
+ public var message: String
+ /**
+ * "3 items" (a batch), or the one item's name.
+ */
+ public var subject: String
+ /**
+ * "Deny".
+ */
+ public var deny: String
+ /**
+ * "Allow".
+ */
+ public var allow: String
+ /**
+ * "Never ask again".
+ */
+ public var neverAsk: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * "Allow unattended access?"
+ */title: String,
+ /**
+ * What it allows.
+ */message: String,
+ /**
+ * "3 items" (a batch), or the one item's name.
+ */subject: String,
+ /**
+ * "Deny".
+ */deny: String,
+ /**
+ * "Allow".
+ */allow: String,
+ /**
+ * "Never ask again".
+ */neverAsk: String) {
+ self.title = title
+ self.message = message
+ self.subject = subject
+ self.deny = deny
+ self.allow = allow
+ self.neverAsk = neverAsk
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvUnlockPrompt: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvUnlockPrompt: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvUnlockPrompt {
+ return
+ try KvUnlockPrompt(
+ title: FfiConverterString.read(from: &buf),
+ message: FfiConverterString.read(from: &buf),
+ subject: FfiConverterString.read(from: &buf),
+ deny: FfiConverterString.read(from: &buf),
+ allow: FfiConverterString.read(from: &buf),
+ neverAsk: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvUnlockPrompt, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.title, into: &buf)
+ FfiConverterString.write(value.message, into: &buf)
+ FfiConverterString.write(value.subject, into: &buf)
+ FfiConverterString.write(value.deny, into: &buf)
+ FfiConverterString.write(value.allow, into: &buf)
+ FfiConverterString.write(value.neverAsk, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvUnlockPrompt_lift(_ buf: RustBuffer) throws -> KvUnlockPrompt {
+ return try FfiConverterTypeKvUnlockPrompt.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvUnlockPrompt_lower(_ value: KvUnlockPrompt) -> RustBuffer {
+ return FfiConverterTypeKvUnlockPrompt.lower(value)
+}
+
+
+public struct KvVaultApp: Equatable, Hashable {
+ /**
+ * Group key: the provider id (`chrome`).
+ */
+ public var key: String
+ /**
+ * The provider id, for the app's icon.
+ */
+ public var providerId: String
+ /**
+ * "Google Chrome".
+ */
+ public var name: String
+ /**
+ * Items.
+ */
+ public var count: UInt32
+ /**
+ * "212 items, 14 unlocked".
+ */
+ public var summary: String
+ /**
+ * Grey time of the newest save.
+ */
+ public var updated: String
+ /**
+ * Selection of its items.
+ */
+ public var selected: KvTri
+ /**
+ * Lock of its items.
+ */
+ public var lock: KvLock
+ /**
+ * Items a click on the lock unlocks (locked, not identity providers).
+ */
+ public var unlockIds: [String]
+ /**
+ * Items a click on the lock locks (unlocked).
+ */
+ public var lockIds: [String]
+ /**
+ * Open.
+ */
+ public var `open`: Bool
+ /**
+ * Sites with their items, by name.
+ */
+ public var sites: [KvVaultSite]
+ /**
+ * Files, when it has any.
+ */
+ public var files: KvVaultFiles?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Group key: the provider id (`chrome`).
+ */key: String,
+ /**
+ * The provider id, for the app's icon.
+ */providerId: String,
+ /**
+ * "Google Chrome".
+ */name: String,
+ /**
+ * Items.
+ */count: UInt32,
+ /**
+ * "212 items, 14 unlocked".
+ */summary: String,
+ /**
+ * Grey time of the newest save.
+ */updated: String,
+ /**
+ * Selection of its items.
+ */selected: KvTri,
+ /**
+ * Lock of its items.
+ */lock: KvLock,
+ /**
+ * Items a click on the lock unlocks (locked, not identity providers).
+ */unlockIds: [String],
+ /**
+ * Items a click on the lock locks (unlocked).
+ */lockIds: [String],
+ /**
+ * Open.
+ */`open`: Bool,
+ /**
+ * Sites with their items, by name.
+ */sites: [KvVaultSite],
+ /**
+ * Files, when it has any.
+ */files: KvVaultFiles?) {
+ self.key = key
+ self.providerId = providerId
+ self.name = name
+ self.count = count
+ self.summary = summary
+ self.updated = updated
+ self.selected = selected
+ self.lock = lock
+ self.unlockIds = unlockIds
+ self.lockIds = lockIds
+ self.`open` = `open`
+ self.sites = sites
+ self.files = files
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvVaultApp: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvVaultApp: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvVaultApp {
+ return
+ try KvVaultApp(
+ key: FfiConverterString.read(from: &buf),
+ providerId: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ count: FfiConverterUInt32.read(from: &buf),
+ summary: FfiConverterString.read(from: &buf),
+ updated: FfiConverterString.read(from: &buf),
+ selected: FfiConverterTypeKvTri.read(from: &buf),
+ lock: FfiConverterTypeKvLock.read(from: &buf),
+ unlockIds: FfiConverterSequenceString.read(from: &buf),
+ lockIds: FfiConverterSequenceString.read(from: &buf),
+ open: FfiConverterBool.read(from: &buf),
+ sites: FfiConverterSequenceTypeKvVaultSite.read(from: &buf),
+ files: FfiConverterOptionTypeKvVaultFiles.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvVaultApp, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterString.write(value.providerId, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterUInt32.write(value.count, into: &buf)
+ FfiConverterString.write(value.summary, into: &buf)
+ FfiConverterString.write(value.updated, into: &buf)
+ FfiConverterTypeKvTri.write(value.selected, into: &buf)
+ FfiConverterTypeKvLock.write(value.lock, into: &buf)
+ FfiConverterSequenceString.write(value.unlockIds, into: &buf)
+ FfiConverterSequenceString.write(value.lockIds, into: &buf)
+ FfiConverterBool.write(value.`open`, into: &buf)
+ FfiConverterSequenceTypeKvVaultSite.write(value.sites, into: &buf)
+ FfiConverterOptionTypeKvVaultFiles.write(value.files, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultApp_lift(_ buf: RustBuffer) throws -> KvVaultApp {
+ return try FfiConverterTypeKvVaultApp.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultApp_lower(_ value: KvVaultApp) -> RustBuffer {
+ return FfiConverterTypeKvVaultApp.lower(value)
+}
+
+
+public struct KvVaultFiles: Equatable, Hashable {
+ /**
+ * Group key.
+ */
+ public var key: String
+ /**
+ * Files.
+ */
+ public var count: UInt32
+ /**
+ * Selection of its items.
+ */
+ public var selected: KvTri
+ /**
+ * Lock of its items.
+ */
+ public var lock: KvLock
+ /**
+ * Items a click on the lock unlocks (locked, not identity providers).
+ */
+ public var unlockIds: [String]
+ /**
+ * Items a click on the lock locks (unlocked).
+ */
+ public var lockIds: [String]
+ /**
+ * Open.
+ */
+ public var `open`: Bool
+ /**
+ * Its rows (empty while closed, unless searching).
+ */
+ public var rows: [KvVaultRow]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Group key.
+ */key: String,
+ /**
+ * Files.
+ */count: UInt32,
+ /**
+ * Selection of its items.
+ */selected: KvTri,
+ /**
+ * Lock of its items.
+ */lock: KvLock,
+ /**
+ * Items a click on the lock unlocks (locked, not identity providers).
+ */unlockIds: [String],
+ /**
+ * Items a click on the lock locks (unlocked).
+ */lockIds: [String],
+ /**
+ * Open.
+ */`open`: Bool,
+ /**
+ * Its rows (empty while closed, unless searching).
+ */rows: [KvVaultRow]) {
+ self.key = key
+ self.count = count
+ self.selected = selected
+ self.lock = lock
+ self.unlockIds = unlockIds
+ self.lockIds = lockIds
+ self.`open` = `open`
+ self.rows = rows
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvVaultFiles: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvVaultFiles: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvVaultFiles {
+ return
+ try KvVaultFiles(
+ key: FfiConverterString.read(from: &buf),
+ count: FfiConverterUInt32.read(from: &buf),
+ selected: FfiConverterTypeKvTri.read(from: &buf),
+ lock: FfiConverterTypeKvLock.read(from: &buf),
+ unlockIds: FfiConverterSequenceString.read(from: &buf),
+ lockIds: FfiConverterSequenceString.read(from: &buf),
+ open: FfiConverterBool.read(from: &buf),
+ rows: FfiConverterSequenceTypeKvVaultRow.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvVaultFiles, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterUInt32.write(value.count, into: &buf)
+ FfiConverterTypeKvTri.write(value.selected, into: &buf)
+ FfiConverterTypeKvLock.write(value.lock, into: &buf)
+ FfiConverterSequenceString.write(value.unlockIds, into: &buf)
+ FfiConverterSequenceString.write(value.lockIds, into: &buf)
+ FfiConverterBool.write(value.`open`, into: &buf)
+ FfiConverterSequenceTypeKvVaultRow.write(value.rows, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultFiles_lift(_ buf: RustBuffer) throws -> KvVaultFiles {
+ return try FfiConverterTypeKvVaultFiles.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultFiles_lower(_ value: KvVaultFiles) -> RustBuffer {
+ return FfiConverterTypeKvVaultFiles.lower(value)
+}
+
+
+public struct KvVaultRow: Equatable, Hashable {
+ /**
+ * Item id.
+ */
+ public var id: String
+ /**
+ * Type.
+ */
+ public var kind: KvKind
+ /**
+ * "Cookie".
+ */
+ public var kindLabel: String
+ /**
+ * The type's SF Symbol.
+ */
+ public var symbol: String
+ /**
+ * The key: a cookie name, storage key, username or file name.
+ */
+ public var title: String
+ /**
+ * Grey line: the domain, or the file's folder.
+ */
+ public var subtitle: String
+ /**
+ * Grey time: "2 min ago".
+ */
+ public var updated: String
+ /**
+ * Locked (needs approval for every use).
+ */
+ public var locked: Bool
+ /**
+ * The lock icon: `lock.fill` or `lock.open`.
+ */
+ public var lockSymbol: String
+ /**
+ * The lock's tooltip and accessibility label.
+ */
+ public var lockHelp: String
+ /**
+ * Identity provider: always asks, cannot be unlocked.
+ */
+ public var identityProvider: Bool
+ /**
+ * Selected.
+ */
+ public var selected: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Item id.
+ */id: String,
+ /**
+ * Type.
+ */kind: KvKind,
+ /**
+ * "Cookie".
+ */kindLabel: String,
+ /**
+ * The type's SF Symbol.
+ */symbol: String,
+ /**
+ * The key: a cookie name, storage key, username or file name.
+ */title: String,
+ /**
+ * Grey line: the domain, or the file's folder.
+ */subtitle: String,
+ /**
+ * Grey time: "2 min ago".
+ */updated: String,
+ /**
+ * Locked (needs approval for every use).
+ */locked: Bool,
+ /**
+ * The lock icon: `lock.fill` or `lock.open`.
+ */lockSymbol: String,
+ /**
+ * The lock's tooltip and accessibility label.
+ */lockHelp: String,
+ /**
+ * Identity provider: always asks, cannot be unlocked.
+ */identityProvider: Bool,
+ /**
+ * Selected.
+ */selected: Bool) {
+ self.id = id
+ self.kind = kind
+ self.kindLabel = kindLabel
+ self.symbol = symbol
+ self.title = title
+ self.subtitle = subtitle
+ self.updated = updated
+ self.locked = locked
+ self.lockSymbol = lockSymbol
+ self.lockHelp = lockHelp
+ self.identityProvider = identityProvider
+ self.selected = selected
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvVaultRow: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvVaultRow: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvVaultRow {
+ return
+ try KvVaultRow(
+ id: FfiConverterString.read(from: &buf),
+ kind: FfiConverterTypeKvKind.read(from: &buf),
+ kindLabel: FfiConverterString.read(from: &buf),
+ symbol: FfiConverterString.read(from: &buf),
+ title: FfiConverterString.read(from: &buf),
+ subtitle: FfiConverterString.read(from: &buf),
+ updated: FfiConverterString.read(from: &buf),
+ locked: FfiConverterBool.read(from: &buf),
+ lockSymbol: FfiConverterString.read(from: &buf),
+ lockHelp: FfiConverterString.read(from: &buf),
+ identityProvider: FfiConverterBool.read(from: &buf),
+ selected: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvVaultRow, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.id, into: &buf)
+ FfiConverterTypeKvKind.write(value.kind, into: &buf)
+ FfiConverterString.write(value.kindLabel, into: &buf)
+ FfiConverterString.write(value.symbol, into: &buf)
+ FfiConverterString.write(value.title, into: &buf)
+ FfiConverterString.write(value.subtitle, into: &buf)
+ FfiConverterString.write(value.updated, into: &buf)
+ FfiConverterBool.write(value.locked, into: &buf)
+ FfiConverterString.write(value.lockSymbol, into: &buf)
+ FfiConverterString.write(value.lockHelp, into: &buf)
+ FfiConverterBool.write(value.identityProvider, into: &buf)
+ FfiConverterBool.write(value.selected, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultRow_lift(_ buf: RustBuffer) throws -> KvVaultRow {
+ return try FfiConverterTypeKvVaultRow.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultRow_lower(_ value: KvVaultRow) -> RustBuffer {
+ return FfiConverterTypeKvVaultRow.lower(value)
+}
+
+
+public struct KvVaultSelection: Equatable, Hashable {
+ /**
+ * Selected items.
+ */
+ public var count: UInt32
+ /**
+ * Their ids, in list order.
+ */
+ public var ids: [String]
+ /**
+ * "3 selected".
+ */
+ public var title: String
+ /**
+ * Some selected item is locked and may be unlocked.
+ */
+ public var canUnlock: Bool
+ /**
+ * Some selected item is unlocked.
+ */
+ public var canLock: Bool
+ /**
+ * Selected items that always ask (identity providers).
+ */
+ public var alwaysAsk: UInt32
+ /**
+ * The ids to send when unlocking (locked, not identity providers).
+ */
+ public var unlockIds: [String]
+ /**
+ * The ids to send when locking (unlocked).
+ */
+ public var lockIds: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Selected items.
+ */count: UInt32,
+ /**
+ * Their ids, in list order.
+ */ids: [String],
+ /**
+ * "3 selected".
+ */title: String,
+ /**
+ * Some selected item is locked and may be unlocked.
+ */canUnlock: Bool,
+ /**
+ * Some selected item is unlocked.
+ */canLock: Bool,
+ /**
+ * Selected items that always ask (identity providers).
+ */alwaysAsk: UInt32,
+ /**
+ * The ids to send when unlocking (locked, not identity providers).
+ */unlockIds: [String],
+ /**
+ * The ids to send when locking (unlocked).
+ */lockIds: [String]) {
+ self.count = count
+ self.ids = ids
+ self.title = title
+ self.canUnlock = canUnlock
+ self.canLock = canLock
+ self.alwaysAsk = alwaysAsk
+ self.unlockIds = unlockIds
+ self.lockIds = lockIds
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvVaultSelection: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvVaultSelection: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvVaultSelection {
+ return
+ try KvVaultSelection(
+ count: FfiConverterUInt32.read(from: &buf),
+ ids: FfiConverterSequenceString.read(from: &buf),
+ title: FfiConverterString.read(from: &buf),
+ canUnlock: FfiConverterBool.read(from: &buf),
+ canLock: FfiConverterBool.read(from: &buf),
+ alwaysAsk: FfiConverterUInt32.read(from: &buf),
+ unlockIds: FfiConverterSequenceString.read(from: &buf),
+ lockIds: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvVaultSelection, into buf: inout [UInt8]) {
+ FfiConverterUInt32.write(value.count, into: &buf)
+ FfiConverterSequenceString.write(value.ids, into: &buf)
+ FfiConverterString.write(value.title, into: &buf)
+ FfiConverterBool.write(value.canUnlock, into: &buf)
+ FfiConverterBool.write(value.canLock, into: &buf)
+ FfiConverterUInt32.write(value.alwaysAsk, into: &buf)
+ FfiConverterSequenceString.write(value.unlockIds, into: &buf)
+ FfiConverterSequenceString.write(value.lockIds, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultSelection_lift(_ buf: RustBuffer) throws -> KvVaultSelection {
+ return try FfiConverterTypeKvVaultSelection.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultSelection_lower(_ value: KvVaultSelection) -> RustBuffer {
+ return FfiConverterTypeKvVaultSelection.lower(value)
+}
+
+
+public struct KvVaultSite: Equatable, Hashable {
+ /**
+ * Group key.
+ */
+ public var key: String
+ /**
+ * "github.com".
+ */
+ public var site: String
+ /**
+ * Items (all of them, even while closed).
+ */
+ public var count: UInt32
+ /**
+ * "12 cookies, 2 storage values".
+ */
+ public var counts: String
+ /**
+ * Grey time of the newest save.
+ */
+ public var updated: String
+ /**
+ * Selection of its items.
+ */
+ public var selected: KvTri
+ /**
+ * Lock of its items.
+ */
+ public var lock: KvLock
+ /**
+ * Items a click on the lock unlocks (locked, not identity providers).
+ */
+ public var unlockIds: [String]
+ /**
+ * Items a click on the lock locks (unlocked).
+ */
+ public var lockIds: [String]
+ /**
+ * Open.
+ */
+ public var `open`: Bool
+ /**
+ * Its rows (empty while closed, unless searching).
+ */
+ public var rows: [KvVaultRow]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Group key.
+ */key: String,
+ /**
+ * "github.com".
+ */site: String,
+ /**
+ * Items (all of them, even while closed).
+ */count: UInt32,
+ /**
+ * "12 cookies, 2 storage values".
+ */counts: String,
+ /**
+ * Grey time of the newest save.
+ */updated: String,
+ /**
+ * Selection of its items.
+ */selected: KvTri,
+ /**
+ * Lock of its items.
+ */lock: KvLock,
+ /**
+ * Items a click on the lock unlocks (locked, not identity providers).
+ */unlockIds: [String],
+ /**
+ * Items a click on the lock locks (unlocked).
+ */lockIds: [String],
+ /**
+ * Open.
+ */`open`: Bool,
+ /**
+ * Its rows (empty while closed, unless searching).
+ */rows: [KvVaultRow]) {
+ self.key = key
+ self.site = site
+ self.count = count
+ self.counts = counts
+ self.updated = updated
+ self.selected = selected
+ self.lock = lock
+ self.unlockIds = unlockIds
+ self.lockIds = lockIds
+ self.`open` = `open`
+ self.rows = rows
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvVaultSite: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvVaultSite: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvVaultSite {
+ return
+ try KvVaultSite(
+ key: FfiConverterString.read(from: &buf),
+ site: FfiConverterString.read(from: &buf),
+ count: FfiConverterUInt32.read(from: &buf),
+ counts: FfiConverterString.read(from: &buf),
+ updated: FfiConverterString.read(from: &buf),
+ selected: FfiConverterTypeKvTri.read(from: &buf),
+ lock: FfiConverterTypeKvLock.read(from: &buf),
+ unlockIds: FfiConverterSequenceString.read(from: &buf),
+ lockIds: FfiConverterSequenceString.read(from: &buf),
+ open: FfiConverterBool.read(from: &buf),
+ rows: FfiConverterSequenceTypeKvVaultRow.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: KvVaultSite, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterString.write(value.site, into: &buf)
+ FfiConverterUInt32.write(value.count, into: &buf)
+ FfiConverterString.write(value.counts, into: &buf)
+ FfiConverterString.write(value.updated, into: &buf)
+ FfiConverterTypeKvTri.write(value.selected, into: &buf)
+ FfiConverterTypeKvLock.write(value.lock, into: &buf)
+ FfiConverterSequenceString.write(value.unlockIds, into: &buf)
+ FfiConverterSequenceString.write(value.lockIds, into: &buf)
+ FfiConverterBool.write(value.`open`, into: &buf)
+ FfiConverterSequenceTypeKvVaultRow.write(value.rows, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultSite_lift(_ buf: RustBuffer) throws -> KvVaultSite {
+ return try FfiConverterTypeKvVaultSite.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultSite_lower(_ value: KvVaultSite) -> RustBuffer {
+ return FfiConverterTypeKvVaultSite.lower(value)
+}
+
+
+public struct KvVaultSource: Equatable, Hashable {
+ /**
+ * Items that can be sent.
+ */
+ public var count: UInt32
+ /**
+ * When the newest was saved, Unix ms (0: none).
+ */
+ public var newestMs: Int64
+ /**
+ * Their ids, in list order.
+ */
+ public var ids: [String]
+ /**
+ * The app's saved passwords (ids), never part of `ids`: they are sent
+ * only when ticked in the review.
+ */
+ public var passwordIds: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Items that can be sent.
+ */count: UInt32,
+ /**
+ * When the newest was saved, Unix ms (0: none).
+ */newestMs: Int64,
+ /**
+ * Their ids, in list order.
+ */ids: [String],
+ /**
+ * The app's saved passwords (ids), never part of `ids`: they are sent
+ * only when ticked in the review.
+ */passwordIds: [String]) {
+ self.count = count
+ self.newestMs = newestMs
+ self.ids = ids
+ self.passwordIds = passwordIds
}
@@ -34855,30 +36960,28 @@ public struct KvSiteDetail: Equatable, Hashable {
}
#if compiler(>=6)
-extension KvSiteDetail: Sendable {}
+extension KvVaultSource: Sendable {}
#endif
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public struct FfiConverterTypeKvSiteDetail: FfiConverterRustBuffer {
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvSiteDetail {
+public struct FfiConverterTypeKvVaultSource: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvVaultSource {
return
- try KvSiteDetail(
- group: FfiConverterTypeKvSiteGroup.read(from: &buf),
- siteSwitch: FfiConverterBool.read(from: &buf),
- siteState: FfiConverterTypeKvTri.read(from: &buf),
- siteSwitchEnabled: FfiConverterBool.read(from: &buf),
- siteSwitchHelp: FfiConverterString.read(from: &buf)
+ try KvVaultSource(
+ count: FfiConverterUInt32.read(from: &buf),
+ newestMs: FfiConverterInt64.read(from: &buf),
+ ids: FfiConverterSequenceString.read(from: &buf),
+ passwordIds: FfiConverterSequenceString.read(from: &buf)
)
}
- public static func write(_ value: KvSiteDetail, into buf: inout [UInt8]) {
- FfiConverterTypeKvSiteGroup.write(value.group, into: &buf)
- FfiConverterBool.write(value.siteSwitch, into: &buf)
- FfiConverterTypeKvTri.write(value.siteState, into: &buf)
- FfiConverterBool.write(value.siteSwitchEnabled, into: &buf)
- FfiConverterString.write(value.siteSwitchHelp, into: &buf)
+ public static func write(_ value: KvVaultSource, into buf: inout [UInt8]) {
+ FfiConverterUInt32.write(value.count, into: &buf)
+ FfiConverterInt64.write(value.newestMs, into: &buf)
+ FfiConverterSequenceString.write(value.ids, into: &buf)
+ FfiConverterSequenceString.write(value.passwordIds, into: &buf)
}
}
@@ -34886,161 +36989,55 @@ public struct FfiConverterTypeKvSiteDetail: FfiConverterRustBuffer {
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public func FfiConverterTypeKvSiteDetail_lift(_ buf: RustBuffer) throws -> KvSiteDetail {
- return try FfiConverterTypeKvSiteDetail.lift(buf)
+public func FfiConverterTypeKvVaultSource_lift(_ buf: RustBuffer) throws -> KvVaultSource {
+ return try FfiConverterTypeKvVaultSource.lift(buf)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public func FfiConverterTypeKvSiteDetail_lower(_ value: KvSiteDetail) -> RustBuffer {
- return FfiConverterTypeKvSiteDetail.lower(value)
+public func FfiConverterTypeKvVaultSource_lower(_ value: KvVaultSource) -> RustBuffer {
+ return FfiConverterTypeKvVaultSource.lower(value)
}
-public struct KvSiteGroup: Equatable, Hashable {
+public struct KvVaultState: Equatable, Hashable {
/**
- * Stable key.
- */
- public var key: String
- /**
- * "github.com" or "Slack".
- */
- public var title: String
- /**
- * "Chrome", "Slack".
+ * The search text.
*/
- public var app: String
+ public var query: String
/**
- * Accounts.
+ * Selected item ids.
*/
- public var rows: [KvItemRow]
+ public var selected: [String]
/**
- * Unattended across rows.
+ * Open groups (their keys); the rest are closed.
*/
- public var unattended: KvTri
+ public var expanded: [String]
/**
- * Every row is an identity provider.
+ * Narrowed to one app (its provider id), as the sidebar picks it.
*/
- public var locked: Bool
+ public var app: String?
// Default memberwise initializers are never public by default, so we
// declare one manually.
public init(
/**
- * Stable key.
- */key: String,
- /**
- * "github.com" or "Slack".
- */title: String,
- /**
- * "Chrome", "Slack".
- */app: String,
+ * The search text.
+ */query: String,
/**
- * Accounts.
- */rows: [KvItemRow],
+ * Selected item ids.
+ */selected: [String],
/**
- * Unattended across rows.
- */unattended: KvTri,
+ * Open groups (their keys); the rest are closed.
+ */expanded: [String],
/**
- * Every row is an identity provider.
- */locked: Bool) {
- self.key = key
- self.title = title
+ * Narrowed to one app (its provider id), as the sidebar picks it.
+ */app: String?) {
+ self.query = query
+ self.selected = selected
+ self.expanded = expanded
self.app = app
- self.rows = rows
- self.unattended = unattended
- self.locked = locked
- }
-
-
-
-
-}
-
-#if compiler(>=6)
-extension KvSiteGroup: Sendable {}
-#endif
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public struct FfiConverterTypeKvSiteGroup: FfiConverterRustBuffer {
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvSiteGroup {
- return
- try KvSiteGroup(
- key: FfiConverterString.read(from: &buf),
- title: FfiConverterString.read(from: &buf),
- app: FfiConverterString.read(from: &buf),
- rows: FfiConverterSequenceTypeKvItemRow.read(from: &buf),
- unattended: FfiConverterTypeKvTri.read(from: &buf),
- locked: FfiConverterBool.read(from: &buf)
- )
- }
-
- public static func write(_ value: KvSiteGroup, into buf: inout [UInt8]) {
- FfiConverterString.write(value.key, into: &buf)
- FfiConverterString.write(value.title, into: &buf)
- FfiConverterString.write(value.app, into: &buf)
- FfiConverterSequenceTypeKvItemRow.write(value.rows, into: &buf)
- FfiConverterTypeKvTri.write(value.unattended, into: &buf)
- FfiConverterBool.write(value.locked, into: &buf)
- }
-}
-
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvSiteGroup_lift(_ buf: RustBuffer) throws -> KvSiteGroup {
- return try FfiConverterTypeKvSiteGroup.lift(buf)
-}
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvSiteGroup_lower(_ value: KvSiteGroup) -> RustBuffer {
- return FfiConverterTypeKvSiteGroup.lower(value)
-}
-
-
-public struct KvSiteRow: Equatable, Hashable {
- /**
- * Group key.
- */
- public var key: String
- /**
- * "github.com" or "Slack".
- */
- public var title: String
- /**
- * Accounts.
- */
- public var accounts: UInt32
- /**
- * Something waits for this site.
- */
- public var waiting: Bool
-
- // Default memberwise initializers are never public by default, so we
- // declare one manually.
- public init(
- /**
- * Group key.
- */key: String,
- /**
- * "github.com" or "Slack".
- */title: String,
- /**
- * Accounts.
- */accounts: UInt32,
- /**
- * Something waits for this site.
- */waiting: Bool) {
- self.key = key
- self.title = title
- self.accounts = accounts
- self.waiting = waiting
}
@@ -35049,28 +37046,28 @@ public struct KvSiteRow: Equatable, Hashable {
}
#if compiler(>=6)
-extension KvSiteRow: Sendable {}
+extension KvVaultState: Sendable {}
#endif
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public struct FfiConverterTypeKvSiteRow: FfiConverterRustBuffer {
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvSiteRow {
+public struct FfiConverterTypeKvVaultState: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvVaultState {
return
- try KvSiteRow(
- key: FfiConverterString.read(from: &buf),
- title: FfiConverterString.read(from: &buf),
- accounts: FfiConverterUInt32.read(from: &buf),
- waiting: FfiConverterBool.read(from: &buf)
+ try KvVaultState(
+ query: FfiConverterString.read(from: &buf),
+ selected: FfiConverterSequenceString.read(from: &buf),
+ expanded: FfiConverterSequenceString.read(from: &buf),
+ app: FfiConverterOptionString.read(from: &buf)
)
}
- public static func write(_ value: KvSiteRow, into buf: inout [UInt8]) {
- FfiConverterString.write(value.key, into: &buf)
- FfiConverterString.write(value.title, into: &buf)
- FfiConverterUInt32.write(value.accounts, into: &buf)
- FfiConverterBool.write(value.waiting, into: &buf)
+ public static func write(_ value: KvVaultState, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.query, into: &buf)
+ FfiConverterSequenceString.write(value.selected, into: &buf)
+ FfiConverterSequenceString.write(value.expanded, into: &buf)
+ FfiConverterOptionString.write(value.app, into: &buf)
}
}
@@ -35078,133 +37075,103 @@ public struct FfiConverterTypeKvSiteRow: FfiConverterRustBuffer {
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public func FfiConverterTypeKvSiteRow_lift(_ buf: RustBuffer) throws -> KvSiteRow {
- return try FfiConverterTypeKvSiteRow.lift(buf)
+public func FfiConverterTypeKvVaultState_lift(_ buf: RustBuffer) throws -> KvVaultState {
+ return try FfiConverterTypeKvVaultState.lift(buf)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public func FfiConverterTypeKvSiteRow_lower(_ value: KvSiteRow) -> RustBuffer {
- return FfiConverterTypeKvSiteRow.lower(value)
+public func FfiConverterTypeKvVaultState_lower(_ value: KvVaultState) -> RustBuffer {
+ return FfiConverterTypeKvVaultState.lower(value)
}
-public struct KvStatus: Equatable, Hashable {
+public struct KvVaultView: Equatable, Hashable {
/**
- * Version.
+ * Apps, by name.
*/
- public var version: String
+ public var apps: [KvVaultApp]
/**
- * A vault exists.
+ * Items shown (after search).
*/
- public var initialized: Bool
+ public var shown: UInt32
/**
- * Unlocked.
+ * Items in the vault.
*/
- public var unlocked: Bool
+ public var total: UInt32
/**
- * The kill switch is on.
+ * "No items yet." and friends.
*/
- public var disabled: Bool
+ public var emptyText: String?
/**
- * This app is first party.
+ * Domains and keys are hidden until the user confirms with Touch ID.
*/
- public var callerFirstParty: Bool
+ public var namesHidden: Bool
/**
- * How the broker sees this app.
+ * What to say about it.
*/
- public var callerDisplay: String
+ public var hiddenNote: String?
/**
- * Items.
+ * The button that opens the names.
*/
- public var items: UInt32
+ public var showNamesLabel: String
/**
- * Pending requests.
+ * The search field's prompt.
*/
- public var pending: UInt32
+ public var searchPrompt: String
/**
- * `auto` or `presence`.
+ * The selection.
*/
- public var unlockPolicy: String?
+ public var selection: KvVaultSelection
/**
- * Delivered copies wipe themselves after their TTL (off by default;
- * none: not told, a broker before the setting or a third party).
+ * Select all is offered.
*/
- public var autoWipe: Bool?
- /**
- * The daemon can create the OS key store protector (setup offers Touch
- * ID); false for a development daemon, which is passphrase-only.
- */
- public var osProtectorAvailable: Bool
- /**
- * A passphrase can always be chosen.
- */
- public var passphraseAvailable: Bool
- /**
- * Protector kinds that can unlock this vault now (`macos-keychain`,
- * `windows-credential`, `passphrase`, `recovery`).
- */
- public var unlockProtectors: [String]
+ public var canSelectAll: Bool
// Default memberwise initializers are never public by default, so we
// declare one manually.
public init(
/**
- * Version.
- */version: String,
+ * Apps, by name.
+ */apps: [KvVaultApp],
/**
- * A vault exists.
- */initialized: Bool,
+ * Items shown (after search).
+ */shown: UInt32,
/**
- * Unlocked.
- */unlocked: Bool,
- /**
- * The kill switch is on.
- */disabled: Bool,
- /**
- * This app is first party.
- */callerFirstParty: Bool,
- /**
- * How the broker sees this app.
- */callerDisplay: String,
+ * Items in the vault.
+ */total: UInt32,
/**
- * Items.
- */items: UInt32,
+ * "No items yet." and friends.
+ */emptyText: String?,
/**
- * Pending requests.
- */pending: UInt32,
+ * Domains and keys are hidden until the user confirms with Touch ID.
+ */namesHidden: Bool,
/**
- * `auto` or `presence`.
- */unlockPolicy: String?,
+ * What to say about it.
+ */hiddenNote: String?,
/**
- * Delivered copies wipe themselves after their TTL (off by default;
- * none: not told, a broker before the setting or a third party).
- */autoWipe: Bool?,
+ * The button that opens the names.
+ */showNamesLabel: String,
/**
- * The daemon can create the OS key store protector (setup offers Touch
- * ID); false for a development daemon, which is passphrase-only.
- */osProtectorAvailable: Bool,
+ * The search field's prompt.
+ */searchPrompt: String,
/**
- * A passphrase can always be chosen.
- */passphraseAvailable: Bool,
+ * The selection.
+ */selection: KvVaultSelection,
/**
- * Protector kinds that can unlock this vault now (`macos-keychain`,
- * `windows-credential`, `passphrase`, `recovery`).
- */unlockProtectors: [String]) {
- self.version = version
- self.initialized = initialized
- self.unlocked = unlocked
- self.disabled = disabled
- self.callerFirstParty = callerFirstParty
- self.callerDisplay = callerDisplay
- self.items = items
- self.pending = pending
- self.unlockPolicy = unlockPolicy
- self.autoWipe = autoWipe
- self.osProtectorAvailable = osProtectorAvailable
- self.passphraseAvailable = passphraseAvailable
- self.unlockProtectors = unlockProtectors
+ * Select all is offered.
+ */canSelectAll: Bool) {
+ self.apps = apps
+ self.shown = shown
+ self.total = total
+ self.emptyText = emptyText
+ self.namesHidden = namesHidden
+ self.hiddenNote = hiddenNote
+ self.showNamesLabel = showNamesLabel
+ self.searchPrompt = searchPrompt
+ self.selection = selection
+ self.canSelectAll = canSelectAll
}
@@ -35213,46 +37180,40 @@ public struct KvStatus: Equatable, Hashable {
}
#if compiler(>=6)
-extension KvStatus: Sendable {}
+extension KvVaultView: Sendable {}
#endif
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public struct FfiConverterTypeKvStatus: FfiConverterRustBuffer {
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvStatus {
+public struct FfiConverterTypeKvVaultView: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvVaultView {
return
- try KvStatus(
- version: FfiConverterString.read(from: &buf),
- initialized: FfiConverterBool.read(from: &buf),
- unlocked: FfiConverterBool.read(from: &buf),
- disabled: FfiConverterBool.read(from: &buf),
- callerFirstParty: FfiConverterBool.read(from: &buf),
- callerDisplay: FfiConverterString.read(from: &buf),
- items: FfiConverterUInt32.read(from: &buf),
- pending: FfiConverterUInt32.read(from: &buf),
- unlockPolicy: FfiConverterOptionString.read(from: &buf),
- autoWipe: FfiConverterOptionBool.read(from: &buf),
- osProtectorAvailable: FfiConverterBool.read(from: &buf),
- passphraseAvailable: FfiConverterBool.read(from: &buf),
- unlockProtectors: FfiConverterSequenceString.read(from: &buf)
+ try KvVaultView(
+ apps: FfiConverterSequenceTypeKvVaultApp.read(from: &buf),
+ shown: FfiConverterUInt32.read(from: &buf),
+ total: FfiConverterUInt32.read(from: &buf),
+ emptyText: FfiConverterOptionString.read(from: &buf),
+ namesHidden: FfiConverterBool.read(from: &buf),
+ hiddenNote: FfiConverterOptionString.read(from: &buf),
+ showNamesLabel: FfiConverterString.read(from: &buf),
+ searchPrompt: FfiConverterString.read(from: &buf),
+ selection: FfiConverterTypeKvVaultSelection.read(from: &buf),
+ canSelectAll: FfiConverterBool.read(from: &buf)
)
}
- public static func write(_ value: KvStatus, into buf: inout [UInt8]) {
- FfiConverterString.write(value.version, into: &buf)
- FfiConverterBool.write(value.initialized, into: &buf)
- FfiConverterBool.write(value.unlocked, into: &buf)
- FfiConverterBool.write(value.disabled, into: &buf)
- FfiConverterBool.write(value.callerFirstParty, into: &buf)
- FfiConverterString.write(value.callerDisplay, into: &buf)
- FfiConverterUInt32.write(value.items, into: &buf)
- FfiConverterUInt32.write(value.pending, into: &buf)
- FfiConverterOptionString.write(value.unlockPolicy, into: &buf)
- FfiConverterOptionBool.write(value.autoWipe, into: &buf)
- FfiConverterBool.write(value.osProtectorAvailable, into: &buf)
- FfiConverterBool.write(value.passphraseAvailable, into: &buf)
- FfiConverterSequenceString.write(value.unlockProtectors, into: &buf)
+ public static func write(_ value: KvVaultView, into buf: inout [UInt8]) {
+ FfiConverterSequenceTypeKvVaultApp.write(value.apps, into: &buf)
+ FfiConverterUInt32.write(value.shown, into: &buf)
+ FfiConverterUInt32.write(value.total, into: &buf)
+ FfiConverterOptionString.write(value.emptyText, into: &buf)
+ FfiConverterBool.write(value.namesHidden, into: &buf)
+ FfiConverterOptionString.write(value.hiddenNote, into: &buf)
+ FfiConverterString.write(value.showNamesLabel, into: &buf)
+ FfiConverterString.write(value.searchPrompt, into: &buf)
+ FfiConverterTypeKvVaultSelection.write(value.selection, into: &buf)
+ FfiConverterBool.write(value.canSelectAll, into: &buf)
}
}
@@ -35260,15 +37221,15 @@ public struct FfiConverterTypeKvStatus: FfiConverterRustBuffer {
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public func FfiConverterTypeKvStatus_lift(_ buf: RustBuffer) throws -> KvStatus {
- return try FfiConverterTypeKvStatus.lift(buf)
+public func FfiConverterTypeKvVaultView_lift(_ buf: RustBuffer) throws -> KvVaultView {
+ return try FfiConverterTypeKvVaultView.lift(buf)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public func FfiConverterTypeKvStatus_lower(_ value: KvStatus) -> RustBuffer {
- return FfiConverterTypeKvStatus.lower(value)
+public func FfiConverterTypeKvVaultView_lower(_ value: KvVaultView) -> RustBuffer {
+ return FfiConverterTypeKvVaultView.lower(value)
}
@@ -35939,6 +37900,24 @@ public struct TeleportConsent: Equatable, Hashable {
* Saw and accepted `TeleportPlan.relay_unsealed`'s warning (S1).
*/
public var acknowledgeRelayPlaintext: Bool
+ /**
+ * The review's per-site choice: the sites whose cookies to send
+ * (`None`: every cookie in the selection).
+ */
+ public var cookieDomains: [String]?
+ /**
+ * Consent items (their keys) the user turned off.
+ */
+ public var exclude: [String]
+ /**
+ * Send these saved Keyvault items (ids) instead of reading the
+ * live app: nothing is captured from the host.
+ */
+ public var fromVault: [String]?
+ /**
+ * Also send the saved passwords: only when ticked in the review.
+ */
+ public var includePasswords: Bool
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -35955,11 +37934,29 @@ public struct TeleportConsent: Equatable, Hashable {
*/saveToKeyvault: Bool = false,
/**
* Saw and accepted `TeleportPlan.relay_unsealed`'s warning (S1).
- */acknowledgeRelayPlaintext: Bool = false) {
+ */acknowledgeRelayPlaintext: Bool = false,
+ /**
+ * The review's per-site choice: the sites whose cookies to send
+ * (`None`: every cookie in the selection).
+ */cookieDomains: [String]? = nil,
+ /**
+ * Consent items (their keys) the user turned off.
+ */exclude: [String] = [],
+ /**
+ * Send these saved Keyvault items (ids) instead of reading the
+ * live app: nothing is captured from the host.
+ */fromVault: [String]? = nil,
+ /**
+ * Also send the saved passwords: only when ticked in the review.
+ */includePasswords: Bool = false) {
self.approved = approved
self.acknowledgeSensitive = acknowledgeSensitive
self.saveToKeyvault = saveToKeyvault
self.acknowledgeRelayPlaintext = acknowledgeRelayPlaintext
+ self.cookieDomains = cookieDomains
+ self.exclude = exclude
+ self.fromVault = fromVault
+ self.includePasswords = includePasswords
}
@@ -35981,7 +37978,11 @@ public struct FfiConverterTypeTeleportConsent: FfiConverterRustBuffer {
approved: FfiConverterBool.read(from: &buf),
acknowledgeSensitive: FfiConverterBool.read(from: &buf),
saveToKeyvault: FfiConverterBool.read(from: &buf),
- acknowledgeRelayPlaintext: FfiConverterBool.read(from: &buf)
+ acknowledgeRelayPlaintext: FfiConverterBool.read(from: &buf),
+ cookieDomains: FfiConverterOptionSequenceString.read(from: &buf),
+ exclude: FfiConverterSequenceString.read(from: &buf),
+ fromVault: FfiConverterOptionSequenceString.read(from: &buf),
+ includePasswords: FfiConverterBool.read(from: &buf)
)
}
@@ -35990,6 +37991,10 @@ public struct FfiConverterTypeTeleportConsent: FfiConverterRustBuffer {
FfiConverterBool.write(value.acknowledgeSensitive, into: &buf)
FfiConverterBool.write(value.saveToKeyvault, into: &buf)
FfiConverterBool.write(value.acknowledgeRelayPlaintext, into: &buf)
+ FfiConverterOptionSequenceString.write(value.cookieDomains, into: &buf)
+ FfiConverterSequenceString.write(value.exclude, into: &buf)
+ FfiConverterOptionSequenceString.write(value.fromVault, into: &buf)
+ FfiConverterBool.write(value.includePasswords, into: &buf)
}
}
@@ -43200,6 +45205,99 @@ public enum AppPickerEvent: Equatable, Hashable {
* Checked.
*/value: Bool
)
+ /**
+ * The browser's sites with counts arrived (and what was picked last time
+ * for this app and Space, if anything).
+ */
+ case domainsLoaded(
+ /**
+ * The inventory.
+ */inventory: KvInventory,
+ /**
+ * The sites sent last time.
+ */remembered: [String]?
+ )
+ /**
+ * The inventory could not be read (the review then sends what the plan
+ * lists, as before).
+ */
+ case domainsFailed
+ /**
+ * Pick or drop one site.
+ */
+ case toggleDomain(
+ /**
+ * The site.
+ */domain: String
+ )
+ /**
+ * Pick or drop every site the search shows.
+ */
+ case selectShownDomains(
+ /**
+ * Pick (true) or drop.
+ */value: Bool
+ )
+ /**
+ * The sites list's search text.
+ */
+ case domainQuery(
+ /**
+ * Text.
+ */text: String
+ )
+ /**
+ * Turn a consent line on or off.
+ */
+ case toggleItem(
+ /**
+ * The consent item's key.
+ */key: String
+ )
+ /**
+ * Where to send from.
+ */
+ case sendFrom(
+ /**
+ * The source.
+ */source: AppSendSource
+ )
+ /**
+ * The app's saved Keyvault items (what the Keyvault holds for it).
+ */
+ case vaultItems(
+ /**
+ * How many can be sent.
+ */count: UInt32,
+ /**
+ * When the newest was saved, Unix ms.
+ */newestMs: Int64,
+ /**
+ * Now, Unix ms.
+ */nowMs: Int64,
+ /**
+ * The ones chosen to send (ids).
+ */selected: [String],
+ /**
+ * The app's saved passwords (ids): sent only when ticked.
+ */passwordIds: [String]
+ )
+ /**
+ * Tick or untick "Also send saved passwords".
+ */
+ case togglePasswords(
+ /**
+ * Ticked.
+ */value: Bool
+ )
+ /**
+ * The chosen saved items changed.
+ */
+ case vaultSelection(
+ /**
+ * The ids.
+ */selected: [String]
+ )
/**
* Confirm the review.
*/
@@ -43289,15 +45387,44 @@ public struct FfiConverterTypeAppPickerEvent: FfiConverterRustBuffer {
case 15: return .acknowledgeRelayPlaintext(value: try FfiConverterBool.read(from: &buf)
)
- case 16: return .confirm
+ case 16: return .domainsLoaded(inventory: try FfiConverterTypeKvInventory.read(from: &buf), remembered: try FfiConverterOptionSequenceString.read(from: &buf)
+ )
+
+ case 17: return .domainsFailed
- case 17: return .progress(event: try FfiConverterTypeAppTeleportRunEvent.read(from: &buf)
+ case 18: return .toggleDomain(domain: try FfiConverterString.read(from: &buf)
)
- case 18: return .finished(report: try FfiConverterTypeAppTeleportRunReport.read(from: &buf)
+ case 19: return .selectShownDomains(value: try FfiConverterBool.read(from: &buf)
)
- case 19: return .back
+ case 20: return .domainQuery(text: try FfiConverterString.read(from: &buf)
+ )
+
+ case 21: return .toggleItem(key: try FfiConverterString.read(from: &buf)
+ )
+
+ case 22: return .sendFrom(source: try FfiConverterTypeAppSendSource.read(from: &buf)
+ )
+
+ case 23: return .vaultItems(count: try FfiConverterUInt32.read(from: &buf), newestMs: try FfiConverterInt64.read(from: &buf), nowMs: try FfiConverterInt64.read(from: &buf), selected: try FfiConverterSequenceString.read(from: &buf), passwordIds: try FfiConverterSequenceString.read(from: &buf)
+ )
+
+ case 24: return .togglePasswords(value: try FfiConverterBool.read(from: &buf)
+ )
+
+ case 25: return .vaultSelection(selected: try FfiConverterSequenceString.read(from: &buf)
+ )
+
+ case 26: return .confirm
+
+ case 27: return .progress(event: try FfiConverterTypeAppTeleportRunEvent.read(from: &buf)
+ )
+
+ case 28: return .finished(report: try FfiConverterTypeAppTeleportRunReport.read(from: &buf)
+ )
+
+ case 29: return .back
default: throw UniffiInternalError.unexpectedEnumCase
}
@@ -43385,22 +45512,76 @@ public struct FfiConverterTypeAppPickerEvent: FfiConverterRustBuffer {
FfiConverterBool.write(value, into: &buf)
- case .confirm:
+ case let .domainsLoaded(inventory,remembered):
writeInt(&buf, Int32(16))
+ FfiConverterTypeKvInventory.write(inventory, into: &buf)
+ FfiConverterOptionSequenceString.write(remembered, into: &buf)
- case let .progress(event):
+ case .domainsFailed:
writeInt(&buf, Int32(17))
+
+
+ case let .toggleDomain(domain):
+ writeInt(&buf, Int32(18))
+ FfiConverterString.write(domain, into: &buf)
+
+
+ case let .selectShownDomains(value):
+ writeInt(&buf, Int32(19))
+ FfiConverterBool.write(value, into: &buf)
+
+
+ case let .domainQuery(text):
+ writeInt(&buf, Int32(20))
+ FfiConverterString.write(text, into: &buf)
+
+
+ case let .toggleItem(key):
+ writeInt(&buf, Int32(21))
+ FfiConverterString.write(key, into: &buf)
+
+
+ case let .sendFrom(source):
+ writeInt(&buf, Int32(22))
+ FfiConverterTypeAppSendSource.write(source, into: &buf)
+
+
+ case let .vaultItems(count,newestMs,nowMs,selected,passwordIds):
+ writeInt(&buf, Int32(23))
+ FfiConverterUInt32.write(count, into: &buf)
+ FfiConverterInt64.write(newestMs, into: &buf)
+ FfiConverterInt64.write(nowMs, into: &buf)
+ FfiConverterSequenceString.write(selected, into: &buf)
+ FfiConverterSequenceString.write(passwordIds, into: &buf)
+
+
+ case let .togglePasswords(value):
+ writeInt(&buf, Int32(24))
+ FfiConverterBool.write(value, into: &buf)
+
+
+ case let .vaultSelection(selected):
+ writeInt(&buf, Int32(25))
+ FfiConverterSequenceString.write(selected, into: &buf)
+
+
+ case .confirm:
+ writeInt(&buf, Int32(26))
+
+
+ case let .progress(event):
+ writeInt(&buf, Int32(27))
FfiConverterTypeAppTeleportRunEvent.write(event, into: &buf)
case let .finished(report):
- writeInt(&buf, Int32(18))
+ writeInt(&buf, Int32(28))
FfiConverterTypeAppTeleportRunReport.write(report, into: &buf)
case .back:
- writeInt(&buf, Int32(19))
+ writeInt(&buf, Int32(29))
}
}
@@ -44557,6 +46738,81 @@ public func FfiConverterTypeAppRuntime_lower(_ value: AppRuntime) -> RustBuffer
}
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum AppSendSource: Equatable, Hashable {
+
+ /**
+ * Read the live app now (a browser's cookies are decrypted, so macOS asks
+ * for Keychain access).
+ */
+ case live
+ /**
+ * Send the items saved in the Keyvault for this app. Nothing is read from
+ * the host.
+ */
+ case vault
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppSendSource: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppSendSource: FfiConverterRustBuffer {
+ typealias SwiftType = AppSendSource
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppSendSource {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .live
+
+ case 2: return .vault
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: AppSendSource, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .live:
+ writeInt(&buf, Int32(1))
+
+
+ case .vault:
+ writeInt(&buf, Int32(2))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSendSource_lift(_ buf: RustBuffer) throws -> AppSendSource {
+ return try FfiConverterTypeAppSendSource.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSendSource_lower(_ value: AppSendSource) -> RustBuffer {
+ return FfiConverterTypeAppSendSource.lower(value)
+}
+
+
// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
@@ -48443,7 +50699,7 @@ public func FfiConverterTypeKvApprovalAction_lower(_ value: KvApprovalAction) ->
public enum KvCategory: Equatable, Hashable {
/**
- * Every site.
+ * Every item, grouped by app.
*/
case all
/**
@@ -48555,7 +50811,8 @@ public enum KvCommand: Equatable, Hashable {
*/disabled: Bool
)
/**
- * Per-item unattended (turning on asks for Touch ID).
+ * Per-item unattended (turning on asks for Touch ID): the same as
+ * [`KvCommand::SetLocked`] with `locked` the other way round.
*/
case setUnattended(
/**
@@ -48565,6 +50822,42 @@ public enum KvCommand: Equatable, Hashable {
* On.
*/unattended: Bool
)
+ /**
+ * Lock or unlock items together. Unlocking allows unattended access and
+ * asks for Touch ID once for the whole batch; locking does not.
+ */
+ case setLocked(
+ /**
+ * Items.
+ */itemIds: [String],
+ /**
+ * Lock (true) or unlock.
+ */locked: Bool
+ )
+ /**
+ * Delete items, wiping every live copy of them in Spaces.
+ */
+ case deleteItems(
+ /**
+ * Items.
+ */itemIds: [String]
+ )
+ /**
+ * "Never ask again" on the unlock prompt (Settings turns it back on).
+ */
+ case setSkipUnlockPrompt(
+ /**
+ * On.
+ */on: Bool
+ )
+ /**
+ * Show item names for a few minutes (the daemon asks for Touch ID).
+ */
+ case browse
+ /**
+ * Hide item names again.
+ */
+ case endBrowse
/**
* Revoke a grant (`*`: all).
*/
@@ -48649,22 +50942,35 @@ public struct FfiConverterTypeKvCommand: FfiConverterRustBuffer {
case 4: return .setUnattended(itemIds: try FfiConverterSequenceString.read(from: &buf), unattended: try FfiConverterBool.read(from: &buf)
)
- case 5: return .revokeGrant(id: try FfiConverterString.read(from: &buf)
+ case 5: return .setLocked(itemIds: try FfiConverterSequenceString.read(from: &buf), locked: try FfiConverterBool.read(from: &buf)
+ )
+
+ case 6: return .deleteItems(itemIds: try FfiConverterSequenceString.read(from: &buf)
+ )
+
+ case 7: return .setSkipUnlockPrompt(on: try FfiConverterBool.read(from: &buf)
+ )
+
+ case 8: return .browse
+
+ case 9: return .endBrowse
+
+ case 10: return .revokeGrant(id: try FfiConverterString.read(from: &buf)
)
- case 6: return .removeRule(id: try FfiConverterString.read(from: &buf)
+ case 11: return .removeRule(id: try FfiConverterString.read(from: &buf)
)
- case 7: return .setAutoWipe(on: try FfiConverterBool.read(from: &buf)
+ case 12: return .setAutoWipe(on: try FfiConverterBool.read(from: &buf)
)
- case 8: return .release(target: try FfiConverterString.read(from: &buf)
+ case 13: return .release(target: try FfiConverterString.read(from: &buf)
)
- case 9: return .approve(requestId: try FfiConverterString.read(from: &buf), items: try FfiConverterOptionSequenceString.read(from: &buf)
+ case 14: return .approve(requestId: try FfiConverterString.read(from: &buf), items: try FfiConverterOptionSequenceString.read(from: &buf)
)
- case 10: return .deny(requestId: try FfiConverterString.read(from: &buf)
+ case 15: return .deny(requestId: try FfiConverterString.read(from: &buf)
)
default: throw UniffiInternalError.unexpectedEnumCase
@@ -48694,138 +51000,59 @@ public struct FfiConverterTypeKvCommand: FfiConverterRustBuffer {
FfiConverterBool.write(unattended, into: &buf)
- case let .revokeGrant(id):
+ case let .setLocked(itemIds,locked):
writeInt(&buf, Int32(5))
- FfiConverterString.write(id, into: &buf)
+ FfiConverterSequenceString.write(itemIds, into: &buf)
+ FfiConverterBool.write(locked, into: &buf)
- case let .removeRule(id):
+ case let .deleteItems(itemIds):
writeInt(&buf, Int32(6))
- FfiConverterString.write(id, into: &buf)
+ FfiConverterSequenceString.write(itemIds, into: &buf)
- case let .setAutoWipe(on):
+ case let .setSkipUnlockPrompt(on):
writeInt(&buf, Int32(7))
FfiConverterBool.write(on, into: &buf)
- case let .release(target):
+ case .browse:
writeInt(&buf, Int32(8))
- FfiConverterString.write(target, into: &buf)
- case let .approve(requestId,items):
+ case .endBrowse:
writeInt(&buf, Int32(9))
- FfiConverterString.write(requestId, into: &buf)
- FfiConverterOptionSequenceString.write(items, into: &buf)
- case let .deny(requestId):
+ case let .revokeGrant(id):
writeInt(&buf, Int32(10))
- FfiConverterString.write(requestId, into: &buf)
-
- }
- }
-}
-
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvCommand_lift(_ buf: RustBuffer) throws -> KvCommand {
- return try FfiConverterTypeKvCommand.lift(buf)
-}
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public func FfiConverterTypeKvCommand_lower(_ value: KvCommand) -> RustBuffer {
- return FfiConverterTypeKvCommand.lower(value)
-}
-
-
-// Note that we don't yet support `indirect` for enums.
-// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
-
-public enum KvConsentChipKind: Equatable, Hashable {
-
- /**
- * A request waits.
- */
- case pending
- /**
- * A copy is in a Space.
- */
- case delivered
- /**
- * A live grant.
- */
- case granted
- /**
- * An unattended rule.
- */
- case rule
- /**
- * Nothing: asks every time.
- */
- case asks
-
-
-
-
-
-}
-
-#if compiler(>=6)
-extension KvConsentChipKind: Sendable {}
-#endif
-
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-public struct FfiConverterTypeKvConsentChipKind: FfiConverterRustBuffer {
- typealias SwiftType = KvConsentChipKind
-
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvConsentChipKind {
- let variant: Int32 = try readInt(&buf)
- switch variant {
-
- case 1: return .pending
-
- case 2: return .delivered
-
- case 3: return .granted
-
- case 4: return .rule
-
- case 5: return .asks
-
- default: throw UniffiInternalError.unexpectedEnumCase
- }
- }
-
- public static func write(_ value: KvConsentChipKind, into buf: inout [UInt8]) {
- switch value {
+ FfiConverterString.write(id, into: &buf)
- case .pending:
- writeInt(&buf, Int32(1))
+ case let .removeRule(id):
+ writeInt(&buf, Int32(11))
+ FfiConverterString.write(id, into: &buf)
- case .delivered:
- writeInt(&buf, Int32(2))
+ case let .setAutoWipe(on):
+ writeInt(&buf, Int32(12))
+ FfiConverterBool.write(on, into: &buf)
- case .granted:
- writeInt(&buf, Int32(3))
+ case let .release(target):
+ writeInt(&buf, Int32(13))
+ FfiConverterString.write(target, into: &buf)
- case .rule:
- writeInt(&buf, Int32(4))
+ case let .approve(requestId,items):
+ writeInt(&buf, Int32(14))
+ FfiConverterString.write(requestId, into: &buf)
+ FfiConverterOptionSequenceString.write(items, into: &buf)
- case .asks:
- writeInt(&buf, Int32(5))
+ case let .deny(requestId):
+ writeInt(&buf, Int32(15))
+ FfiConverterString.write(requestId, into: &buf)
}
}
@@ -48835,15 +51062,15 @@ public struct FfiConverterTypeKvConsentChipKind: FfiConverterRustBuffer {
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public func FfiConverterTypeKvConsentChipKind_lift(_ buf: RustBuffer) throws -> KvConsentChipKind {
- return try FfiConverterTypeKvConsentChipKind.lift(buf)
+public func FfiConverterTypeKvCommand_lift(_ buf: RustBuffer) throws -> KvCommand {
+ return try FfiConverterTypeKvCommand.lift(buf)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-public func FfiConverterTypeKvConsentChipKind_lower(_ value: KvConsentChipKind) -> RustBuffer {
- return FfiConverterTypeKvConsentChipKind.lower(value)
+public func FfiConverterTypeKvCommand_lower(_ value: KvCommand) -> RustBuffer {
+ return FfiConverterTypeKvCommand.lower(value)
}
@@ -49003,6 +51230,182 @@ public func FfiConverterTypeKvFormMode_lower(_ value: KvFormMode) -> RustBuffer
}
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum KvKind: Equatable, Hashable {
+
+ /**
+ * A cookie.
+ */
+ case cookie
+ /**
+ * A localStorage value.
+ */
+ case localStorage
+ /**
+ * A saved password.
+ */
+ case password
+ /**
+ * A file.
+ */
+ case file
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvKind: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvKind: FfiConverterRustBuffer {
+ typealias SwiftType = KvKind
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvKind {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .cookie
+
+ case 2: return .localStorage
+
+ case 3: return .password
+
+ case 4: return .file
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: KvKind, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .cookie:
+ writeInt(&buf, Int32(1))
+
+
+ case .localStorage:
+ writeInt(&buf, Int32(2))
+
+
+ case .password:
+ writeInt(&buf, Int32(3))
+
+
+ case .file:
+ writeInt(&buf, Int32(4))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvKind_lift(_ buf: RustBuffer) throws -> KvKind {
+ return try FfiConverterTypeKvKind.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvKind_lower(_ value: KvKind) -> RustBuffer {
+ return FfiConverterTypeKvKind.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum KvLock: Equatable, Hashable {
+
+ /**
+ * Every item needs approval for each use.
+ */
+ case locked
+ /**
+ * Every item allows unattended access.
+ */
+ case unlocked
+ /**
+ * Some of each.
+ */
+ case mixed
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvLock: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvLock: FfiConverterRustBuffer {
+ typealias SwiftType = KvLock
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvLock {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .locked
+
+ case 2: return .unlocked
+
+ case 3: return .mixed
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: KvLock, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .locked:
+ writeInt(&buf, Int32(1))
+
+
+ case .unlocked:
+ writeInt(&buf, Int32(2))
+
+
+ case .mixed:
+ writeInt(&buf, Int32(3))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvLock_lift(_ buf: RustBuffer) throws -> KvLock {
+ return try FfiConverterTypeKvLock.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvLock_lower(_ value: KvLock) -> RustBuffer {
+ return FfiConverterTypeKvLock.lower(value)
+}
+
+
// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
@@ -49094,12 +51497,35 @@ public enum KvOutcome: Equatable, Hashable {
*/key: String?
)
/**
- * Items after a policy change.
+ * Items locked or unlocked. Identity providers always ask: they are in
+ * `skipped`, never changed.
*/
- case items(
+ case locked(
/**
- * Items.
- */items: [KvItem]
+ * Items whose lock changed.
+ */changed: [String],
+ /**
+ * Items left locked (identity providers).
+ */skipped: [String]
+ )
+ /**
+ * Items deleted.
+ */
+ case deleted(
+ /**
+ * Items deleted.
+ */count: UInt32,
+ /**
+ * Copies wiped in Spaces.
+ */wiped: [String]
+ )
+ /**
+ * The browse window is open until then, Unix ms.
+ */
+ case browsing(
+ /**
+ * When it closes.
+ */untilMs: UInt64
)
/**
* Grants revoked.
@@ -49151,16 +51577,22 @@ public struct FfiConverterTypeKvOutcome: FfiConverterRustBuffer {
case 2: return .recoveryKey(key: try FfiConverterOptionString.read(from: &buf)
)
- case 3: return .items(items: try FfiConverterSequenceTypeKvItem.read(from: &buf)
+ case 3: return .locked(changed: try FfiConverterSequenceString.read(from: &buf), skipped: try FfiConverterSequenceString.read(from: &buf)
+ )
+
+ case 4: return .deleted(count: try FfiConverterUInt32.read(from: &buf), wiped: try FfiConverterSequenceString.read(from: &buf)
+ )
+
+ case 5: return .browsing(untilMs: try FfiConverterUInt64.read(from: &buf)
)
- case 4: return .revoked(count: try FfiConverterUInt32.read(from: &buf)
+ case 6: return .revoked(count: try FfiConverterUInt32.read(from: &buf)
)
- case 5: return .wiped(imports: try FfiConverterSequenceString.read(from: &buf)
+ case 7: return .wiped(imports: try FfiConverterSequenceString.read(from: &buf)
)
- case 6: return .granted(grant: try FfiConverterTypeKvGrant.read(from: &buf)
+ case 8: return .granted(grant: try FfiConverterTypeKvGrant.read(from: &buf)
)
default: throw UniffiInternalError.unexpectedEnumCase
@@ -49180,23 +51612,35 @@ public struct FfiConverterTypeKvOutcome: FfiConverterRustBuffer {
FfiConverterOptionString.write(key, into: &buf)
- case let .items(items):
+ case let .locked(changed,skipped):
writeInt(&buf, Int32(3))
- FfiConverterSequenceTypeKvItem.write(items, into: &buf)
+ FfiConverterSequenceString.write(changed, into: &buf)
+ FfiConverterSequenceString.write(skipped, into: &buf)
- case let .revoked(count):
+ case let .deleted(count,wiped):
writeInt(&buf, Int32(4))
FfiConverterUInt32.write(count, into: &buf)
+ FfiConverterSequenceString.write(wiped, into: &buf)
- case let .wiped(imports):
+ case let .browsing(untilMs):
writeInt(&buf, Int32(5))
+ FfiConverterUInt64.write(untilMs, into: &buf)
+
+
+ case let .revoked(count):
+ writeInt(&buf, Int32(6))
+ FfiConverterUInt32.write(count, into: &buf)
+
+
+ case let .wiped(imports):
+ writeInt(&buf, Int32(7))
FfiConverterSequenceString.write(imports, into: &buf)
case let .granted(grant):
- writeInt(&buf, Int32(6))
+ writeInt(&buf, Int32(8))
FfiConverterTypeKvGrant.write(grant, into: &buf)
}
@@ -49233,11 +51677,11 @@ public enum KvSelection: Equatable, Hashable {
*/category: KvCategory
)
/**
- * A site.
+ * One app's items.
*/
- case site(
+ case app(
/**
- * Group key.
+ * Its provider id.
*/key: String
)
@@ -49264,7 +51708,7 @@ public struct FfiConverterTypeKvSelection: FfiConverterRustBuffer {
case 1: return .category(category: try FfiConverterTypeKvCategory.read(from: &buf)
)
- case 2: return .site(key: try FfiConverterString.read(from: &buf)
+ case 2: return .app(key: try FfiConverterString.read(from: &buf)
)
default: throw UniffiInternalError.unexpectedEnumCase
@@ -49280,7 +51724,7 @@ public struct FfiConverterTypeKvSelection: FfiConverterRustBuffer {
FfiConverterTypeKvCategory.write(category, into: &buf)
- case let .site(key):
+ case let .app(key):
writeInt(&buf, Int32(2))
FfiConverterString.write(key, into: &buf)
@@ -49326,10 +51770,7 @@ public enum KvSelector: Equatable, Hashable {
*/app: String,
/**
* Site.
- */site: String,
- /**
- * Account.
- */account: String?
+ */site: String
)
/**
* A whole app.
@@ -49371,7 +51812,7 @@ public struct FfiConverterTypeKvSelector: FfiConverterRustBuffer {
case 1: return .item(id: try FfiConverterString.read(from: &buf)
)
- case 2: return .site(app: try FfiConverterString.read(from: &buf), site: try FfiConverterString.read(from: &buf), account: try FfiConverterOptionString.read(from: &buf)
+ case 2: return .site(app: try FfiConverterString.read(from: &buf), site: try FfiConverterString.read(from: &buf)
)
case 3: return .app(app: try FfiConverterString.read(from: &buf)
@@ -49393,11 +51834,10 @@ public struct FfiConverterTypeKvSelector: FfiConverterRustBuffer {
FfiConverterString.write(id, into: &buf)
- case let .site(app,site,account):
+ case let .site(app,site):
writeInt(&buf, Int32(2))
FfiConverterString.write(app, into: &buf)
FfiConverterString.write(site, into: &buf)
- FfiConverterOptionString.write(account, into: &buf)
case let .app(app):
@@ -49795,6 +52235,144 @@ public func FfiConverterTypeKvTri_lower(_ value: KvTri) -> RustBuffer {
}
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum KvVaultAction: Equatable, Hashable {
+
+ /**
+ * The search text changed.
+ */
+ case query(
+ /**
+ * Text.
+ */text: String
+ )
+ /**
+ * Select or deselect one item.
+ */
+ case toggle(
+ /**
+ * Item id.
+ */id: String
+ )
+ /**
+ * Select or deselect every shown item of an app, a site or the files
+ * of an app (all of them when any is unselected, none when all are).
+ */
+ case toggleGroup(
+ /**
+ * Group key.
+ */key: String
+ )
+ /**
+ * Select every shown item.
+ */
+ case selectAll
+ /**
+ * Deselect everything.
+ */
+ case clear
+ /**
+ * Open or close a group.
+ */
+ case toggleOpen(
+ /**
+ * Group key.
+ */key: String
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension KvVaultAction: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKvVaultAction: FfiConverterRustBuffer {
+ typealias SwiftType = KvVaultAction
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KvVaultAction {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .query(text: try FfiConverterString.read(from: &buf)
+ )
+
+ case 2: return .toggle(id: try FfiConverterString.read(from: &buf)
+ )
+
+ case 3: return .toggleGroup(key: try FfiConverterString.read(from: &buf)
+ )
+
+ case 4: return .selectAll
+
+ case 5: return .clear
+
+ case 6: return .toggleOpen(key: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: KvVaultAction, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case let .query(text):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(text, into: &buf)
+
+
+ case let .toggle(id):
+ writeInt(&buf, Int32(2))
+ FfiConverterString.write(id, into: &buf)
+
+
+ case let .toggleGroup(key):
+ writeInt(&buf, Int32(3))
+ FfiConverterString.write(key, into: &buf)
+
+
+ case .selectAll:
+ writeInt(&buf, Int32(4))
+
+
+ case .clear:
+ writeInt(&buf, Int32(5))
+
+
+ case let .toggleOpen(key):
+ writeInt(&buf, Int32(6))
+ FfiConverterString.write(key, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultAction_lift(_ buf: RustBuffer) throws -> KvVaultAction {
+ return try FfiConverterTypeKvVaultAction.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKvVaultAction_lower(_ value: KvVaultAction) -> RustBuffer {
+ return FfiConverterTypeKvVaultAction.lower(value)
+}
+
+
// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/**
@@ -51969,8 +54547,8 @@ fileprivate struct FfiConverterOptionTypeKvCredentialForm: FfiConverterRustBuffe
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-fileprivate struct FfiConverterOptionTypeKvSiteDetail: FfiConverterRustBuffer {
- typealias SwiftType = KvSiteDetail?
+fileprivate struct FfiConverterOptionTypeKvStatus: FfiConverterRustBuffer {
+ typealias SwiftType = KvStatus?
public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
guard let value = value else {
@@ -51978,13 +54556,13 @@ fileprivate struct FfiConverterOptionTypeKvSiteDetail: FfiConverterRustBuffer {
return
}
writeInt(&buf, Int8(1))
- FfiConverterTypeKvSiteDetail.write(value, into: &buf)
+ FfiConverterTypeKvStatus.write(value, into: &buf)
}
public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
switch try readInt(&buf) as Int8 {
case 0: return nil
- case 1: return try FfiConverterTypeKvSiteDetail.read(from: &buf)
+ case 1: return try FfiConverterTypeKvStatus.read(from: &buf)
default: throw UniffiInternalError.unexpectedOptionalTag
}
}
@@ -51993,8 +54571,8 @@ fileprivate struct FfiConverterOptionTypeKvSiteDetail: FfiConverterRustBuffer {
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-fileprivate struct FfiConverterOptionTypeKvStatus: FfiConverterRustBuffer {
- typealias SwiftType = KvStatus?
+fileprivate struct FfiConverterOptionTypeKvUnlockPrompt: FfiConverterRustBuffer {
+ typealias SwiftType = KvUnlockPrompt?
public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
guard let value = value else {
@@ -52002,13 +54580,37 @@ fileprivate struct FfiConverterOptionTypeKvStatus: FfiConverterRustBuffer {
return
}
writeInt(&buf, Int8(1))
- FfiConverterTypeKvStatus.write(value, into: &buf)
+ FfiConverterTypeKvUnlockPrompt.write(value, into: &buf)
}
public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
switch try readInt(&buf) as Int8 {
case 0: return nil
- case 1: return try FfiConverterTypeKvStatus.read(from: &buf)
+ case 1: return try FfiConverterTypeKvUnlockPrompt.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeKvVaultFiles: FfiConverterRustBuffer {
+ typealias SwiftType = KvVaultFiles?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeKvVaultFiles.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeKvVaultFiles.read(from: &buf)
default: throw UniffiInternalError.unexpectedOptionalTag
}
}
@@ -54707,6 +57309,31 @@ fileprivate struct FfiConverterSequenceTypeAppPreviewSegment: FfiConverterRustBu
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeAppRememberedChoice: FfiConverterRustBuffer {
+ typealias SwiftType = [AppRememberedChoice]
+
+ public static func write(_ value: [AppRememberedChoice], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeAppRememberedChoice.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [AppRememberedChoice] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [AppRememberedChoice]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeAppRememberedChoice.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -54757,6 +57384,56 @@ fileprivate struct FfiConverterSequenceTypeAppRemoteWindowGroup: FfiConverterRus
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeAppReviewDomain: FfiConverterRustBuffer {
+ typealias SwiftType = [AppReviewDomain]
+
+ public static func write(_ value: [AppReviewDomain], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeAppReviewDomain.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [AppReviewDomain] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [AppReviewDomain]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeAppReviewDomain.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeAppReviewToggle: FfiConverterRustBuffer {
+ typealias SwiftType = [AppReviewToggle]
+
+ public static func write(_ value: [AppReviewToggle], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeAppReviewToggle.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [AppReviewToggle] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [AppReviewToggle]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeAppReviewToggle.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -55507,6 +58184,31 @@ fileprivate struct FfiConverterSequenceTypeKvAccessRow: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeKvAppRow: FfiConverterRustBuffer {
+ typealias SwiftType = [KvAppRow]
+
+ public static func write(_ value: [KvAppRow], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeKvAppRow.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvAppRow] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [KvAppRow]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeKvAppRow.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -55585,23 +58287,23 @@ fileprivate struct FfiConverterSequenceTypeKvCategoryRow: FfiConverterRustBuffer
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-fileprivate struct FfiConverterSequenceTypeKvConsentChip: FfiConverterRustBuffer {
- typealias SwiftType = [KvConsentChip]
+fileprivate struct FfiConverterSequenceTypeKvDelivery: FfiConverterRustBuffer {
+ typealias SwiftType = [KvDelivery]
- public static func write(_ value: [KvConsentChip], into buf: inout [UInt8]) {
+ public static func write(_ value: [KvDelivery], into buf: inout [UInt8]) {
let len = Int32(value.count)
writeInt(&buf, len)
for item in value {
- FfiConverterTypeKvConsentChip.write(item, into: &buf)
+ FfiConverterTypeKvDelivery.write(item, into: &buf)
}
}
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvConsentChip] {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvDelivery] {
let len: Int32 = try readInt(&buf)
- var seq = [KvConsentChip]()
+ var seq = [KvDelivery]()
seq.reserveCapacity(Int(len))
for _ in 0 ..< len {
- seq.append(try FfiConverterTypeKvConsentChip.read(from: &buf))
+ seq.append(try FfiConverterTypeKvDelivery.read(from: &buf))
}
return seq
}
@@ -55610,23 +58312,23 @@ fileprivate struct FfiConverterSequenceTypeKvConsentChip: FfiConverterRustBuffer
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-fileprivate struct FfiConverterSequenceTypeKvCookieInfo: FfiConverterRustBuffer {
- typealias SwiftType = [KvCookieInfo]
+fileprivate struct FfiConverterSequenceTypeKvDomainCount: FfiConverterRustBuffer {
+ typealias SwiftType = [KvDomainCount]
- public static func write(_ value: [KvCookieInfo], into buf: inout [UInt8]) {
+ public static func write(_ value: [KvDomainCount], into buf: inout [UInt8]) {
let len = Int32(value.count)
writeInt(&buf, len)
for item in value {
- FfiConverterTypeKvCookieInfo.write(item, into: &buf)
+ FfiConverterTypeKvDomainCount.write(item, into: &buf)
}
}
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvCookieInfo] {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvDomainCount] {
let len: Int32 = try readInt(&buf)
- var seq = [KvCookieInfo]()
+ var seq = [KvDomainCount]()
seq.reserveCapacity(Int(len))
for _ in 0 ..< len {
- seq.append(try FfiConverterTypeKvCookieInfo.read(from: &buf))
+ seq.append(try FfiConverterTypeKvDomainCount.read(from: &buf))
}
return seq
}
@@ -55635,23 +58337,23 @@ fileprivate struct FfiConverterSequenceTypeKvCookieInfo: FfiConverterRustBuffer
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-fileprivate struct FfiConverterSequenceTypeKvDelivery: FfiConverterRustBuffer {
- typealias SwiftType = [KvDelivery]
+fileprivate struct FfiConverterSequenceTypeKvFavicon: FfiConverterRustBuffer {
+ typealias SwiftType = [KvFavicon]
- public static func write(_ value: [KvDelivery], into buf: inout [UInt8]) {
+ public static func write(_ value: [KvFavicon], into buf: inout [UInt8]) {
let len = Int32(value.count)
writeInt(&buf, len)
for item in value {
- FfiConverterTypeKvDelivery.write(item, into: &buf)
+ FfiConverterTypeKvFavicon.write(item, into: &buf)
}
}
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvDelivery] {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvFavicon] {
let len: Int32 = try readInt(&buf)
- var seq = [KvDelivery]()
+ var seq = [KvFavicon]()
seq.reserveCapacity(Int(len))
for _ in 0 ..< len {
- seq.append(try FfiConverterTypeKvDelivery.read(from: &buf))
+ seq.append(try FfiConverterTypeKvFavicon.read(from: &buf))
}
return seq
}
@@ -55707,31 +58409,6 @@ fileprivate struct FfiConverterSequenceTypeKvItem: FfiConverterRustBuffer {
}
}
-#if swift(>=5.8)
-@_documentation(visibility: private)
-#endif
-fileprivate struct FfiConverterSequenceTypeKvItemRow: FfiConverterRustBuffer {
- typealias SwiftType = [KvItemRow]
-
- public static func write(_ value: [KvItemRow], into buf: inout [UInt8]) {
- let len = Int32(value.count)
- writeInt(&buf, len)
- for item in value {
- FfiConverterTypeKvItemRow.write(item, into: &buf)
- }
- }
-
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvItemRow] {
- let len: Int32 = try readInt(&buf)
- var seq = [KvItemRow]()
- seq.reserveCapacity(Int(len))
- for _ in 0 ..< len {
- seq.append(try FfiConverterTypeKvItemRow.read(from: &buf))
- }
- return seq
- }
-}
-
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -55860,23 +58537,23 @@ fileprivate struct FfiConverterSequenceTypeKvRuleCaller: FfiConverterRustBuffer
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-fileprivate struct FfiConverterSequenceTypeKvSiteGroup: FfiConverterRustBuffer {
- typealias SwiftType = [KvSiteGroup]
+fileprivate struct FfiConverterSequenceTypeKvVaultApp: FfiConverterRustBuffer {
+ typealias SwiftType = [KvVaultApp]
- public static func write(_ value: [KvSiteGroup], into buf: inout [UInt8]) {
+ public static func write(_ value: [KvVaultApp], into buf: inout [UInt8]) {
let len = Int32(value.count)
writeInt(&buf, len)
for item in value {
- FfiConverterTypeKvSiteGroup.write(item, into: &buf)
+ FfiConverterTypeKvVaultApp.write(item, into: &buf)
}
}
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvSiteGroup] {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvVaultApp] {
let len: Int32 = try readInt(&buf)
- var seq = [KvSiteGroup]()
+ var seq = [KvVaultApp]()
seq.reserveCapacity(Int(len))
for _ in 0 ..< len {
- seq.append(try FfiConverterTypeKvSiteGroup.read(from: &buf))
+ seq.append(try FfiConverterTypeKvVaultApp.read(from: &buf))
}
return seq
}
@@ -55885,23 +58562,48 @@ fileprivate struct FfiConverterSequenceTypeKvSiteGroup: FfiConverterRustBuffer {
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
-fileprivate struct FfiConverterSequenceTypeKvSiteRow: FfiConverterRustBuffer {
- typealias SwiftType = [KvSiteRow]
+fileprivate struct FfiConverterSequenceTypeKvVaultRow: FfiConverterRustBuffer {
+ typealias SwiftType = [KvVaultRow]
- public static func write(_ value: [KvSiteRow], into buf: inout [UInt8]) {
+ public static func write(_ value: [KvVaultRow], into buf: inout [UInt8]) {
let len = Int32(value.count)
writeInt(&buf, len)
for item in value {
- FfiConverterTypeKvSiteRow.write(item, into: &buf)
+ FfiConverterTypeKvVaultRow.write(item, into: &buf)
}
}
- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvSiteRow] {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvVaultRow] {
let len: Int32 = try readInt(&buf)
- var seq = [KvSiteRow]()
+ var seq = [KvVaultRow]()
seq.reserveCapacity(Int(len))
for _ in 0 ..< len {
- seq.append(try FfiConverterTypeKvSiteRow.read(from: &buf))
+ seq.append(try FfiConverterTypeKvVaultRow.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeKvVaultSite: FfiConverterRustBuffer {
+ typealias SwiftType = [KvVaultSite]
+
+ public static func write(_ value: [KvVaultSite], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeKvVaultSite.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [KvVaultSite] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [KvVaultSite]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeKvVaultSite.read(from: &buf))
}
return seq
}
@@ -58025,6 +60727,40 @@ public func appRefreshReportFromJson(json: String)throws -> AppRefreshReport {
)
})
}
+/**
+ * `choices` with the sites just sent remembered for `key`.
+ */
+public func appReviewRemember(choices: [AppRememberedChoice], key: String, domains: [String]) -> [AppRememberedChoice] {
+ return try! FfiConverterSequenceTypeAppRememberedChoice.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_review_remember(
+ FfiConverterSequenceTypeAppRememberedChoice.lower(choices),
+ FfiConverterString.lower(key),
+ FfiConverterSequenceString.lower(domains),$0
+ )
+})
+}
+/**
+ * The key a review's site choice is remembered under (`<app>|<space>`).
+ */
+public func appReviewRememberKey(app: String, space: String) -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_review_remember_key(
+ FfiConverterString.lower(app),
+ FfiConverterString.lower(space),$0
+ )
+})
+}
+/**
+ * What was picked last time for `key` (an app and a Space), if anything.
+ */
+public func appReviewRemembered(choices: [AppRememberedChoice], key: String) -> [String]? {
+ return try! FfiConverterOptionSequenceString.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_review_remembered(
+ FfiConverterSequenceTypeAppRememberedChoice.lower(choices),
+ FfiConverterString.lower(key),$0
+ )
+})
+}
/**
* The Space list's first state.
*/
@@ -58900,6 +61636,27 @@ public func kvCredentialForm(overview: KeyvaultOverview) -> KvCredentialForm? {
)
})
}
+/**
+ * The command that deletes items and wipes their copies in Spaces.
+ */
+public func kvDeleteCommand(ids: [String]) -> KvCommand {
+ return try! FfiConverterTypeKvCommand_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_delete_command(
+ FfiConverterSequenceString.lower(ids),$0
+ )
+})
+}
+/**
+ * The delete confirmation.
+ */
+public func kvDeleteConfirm(count: UInt32, liveCopies: UInt32) -> KvDeleteConfirm {
+ return try! FfiConverterTypeKvDeleteConfirm_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_delete_confirm(
+ FfiConverterUInt32.lower(count),
+ FfiConverterUInt32.lower(liveCopies),$0
+ )
+})
+}
/**
* A duration in words ("5 min").
*/
@@ -58920,15 +61677,36 @@ public func kvLabels() -> KvLabels {
})
}
/**
- * The list for a sidebar selection.
+ * The pane for a sidebar selection (the vault list is [`kv_vault_view`]).
*/
-public func kvList(overview: KeyvaultOverview, selection: KvSelection, nowMs: Int64, query: String) -> KvListView {
+public func kvList(overview: KeyvaultOverview, selection: KvSelection, nowMs: Int64) -> KvListView {
return try! FfiConverterTypeKvListView_lift(try! rustCall() {
uniffi_cua_spaces_ffi_fn_func_kv_list(
FfiConverterTypeKeyvaultOverview_lower(overview),
FfiConverterTypeKvSelection_lower(selection),
- FfiConverterInt64.lower(nowMs),
- FfiConverterString.lower(query),$0
+ FfiConverterInt64.lower(nowMs),$0
+ )
+})
+}
+/**
+ * How many Spaces hold a live copy of any of `ids`.
+ */
+public func kvLiveCopySpaces(overview: KeyvaultOverview, ids: [String], nowMs: Int64) -> UInt32 {
+ return try! FfiConverterUInt32.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_live_copy_spaces(
+ FfiConverterTypeKeyvaultOverview_lower(overview),
+ FfiConverterSequenceString.lower(ids),
+ FfiConverterInt64.lower(nowMs),$0
+ )
+})
+}
+/**
+ * The command that locks items.
+ */
+public func kvLockCommand(ids: [String]) -> KvCommand {
+ return try! FfiConverterTypeKvCommand_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_lock_command(
+ FfiConverterSequenceString.lower(ids),$0
)
})
}
@@ -59002,7 +61780,7 @@ public func kvSharingLabel(overview: KeyvaultOverview, nowMs: Int64) -> String?
})
}
/**
- * The Passwords-style sidebar.
+ * The sidebar: All Items, Waiting, Access, Recent, and one row per app.
*/
public func kvSidebar(overview: KeyvaultOverview, nowMs: Int64) -> KvSidebar {
return try! FfiConverterTypeKvSidebar_lift(try! rustCall() {
@@ -59028,37 +61806,95 @@ public func kvSignedInSpaces(overview: KeyvaultOverview, nowMs: Int64, dismissed
})
}
/**
- * One site's detail.
+ * The Access row of `space`'s copies, to focus from its "Signed in" badge.
*/
-public func kvSiteDetail(overview: KeyvaultOverview, key: String, nowMs: Int64) -> KvSiteDetail? {
- return try! FfiConverterOptionTypeKvSiteDetail.lift(try! rustCall() {
- uniffi_cua_spaces_ffi_fn_func_kv_site_detail(
+public func kvSpaceAccessKey(overview: KeyvaultOverview, nowMs: Int64, space: AppSpace) -> String? {
+ return try! FfiConverterOptionString.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_space_access_key(
FfiConverterTypeKeyvaultOverview_lower(overview),
- FfiConverterString.lower(key),
- FfiConverterInt64.lower(nowMs),$0
+ FfiConverterInt64.lower(nowMs),
+ FfiConverterTypeAppSpace_lower(space),$0
)
})
}
/**
- * The site switch's command.
+ * The command that unlocks items (the daemon asks for Touch ID once).
*/
-public func kvSiteToggle(group: KvSiteGroup, on: Bool) -> KvCommand {
+public func kvUnlockCommand(ids: [String]) -> KvCommand {
return try! FfiConverterTypeKvCommand_lift(try! rustCall() {
- uniffi_cua_spaces_ffi_fn_func_kv_site_toggle(
- FfiConverterTypeKvSiteGroup_lower(group),
- FfiConverterBool.lower(on),$0
+ uniffi_cua_spaces_ffi_fn_func_kv_unlock_command(
+ FfiConverterSequenceString.lower(ids),$0
)
})
}
/**
- * The Access row of `space`'s copies, to focus from its "Signed in" badge.
+ * The unlock prompt for `count` items (`name`: the one item's name). None
+ * when the user chose "Never ask again".
*/
-public func kvSpaceAccessKey(overview: KeyvaultOverview, nowMs: Int64, space: AppSpace) -> String? {
- return try! FfiConverterOptionString.lift(try! rustCall() {
- uniffi_cua_spaces_ffi_fn_func_kv_space_access_key(
+public func kvUnlockPrompt(overview: KeyvaultOverview, count: UInt32, name: String?) -> KvUnlockPrompt? {
+ return try! FfiConverterOptionTypeKvUnlockPrompt.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_unlock_prompt(
FfiConverterTypeKeyvaultOverview_lower(overview),
- FfiConverterInt64.lower(nowMs),
- FfiConverterTypeAppSpace_lower(space),$0
+ FfiConverterUInt32.lower(count),
+ FfiConverterOptionString.lower(name),$0
+ )
+})
+}
+/**
+ * The unlock prompt whatever the setting says.
+ */
+public func kvUnlockPromptAlways(count: UInt32, name: String?) -> KvUnlockPrompt {
+ return try! FfiConverterTypeKvUnlockPrompt_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_unlock_prompt_always(
+ FfiConverterUInt32.lower(count),
+ FfiConverterOptionString.lower(name),$0
+ )
+})
+}
+/**
+ * The selection without what the vault no longer holds.
+ */
+public func kvVaultPrune(overview: KeyvaultOverview, state: KvVaultState) -> KvVaultState {
+ return try! FfiConverterTypeKvVaultState_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_vault_prune(
+ FfiConverterTypeKeyvaultOverview_lower(overview),
+ FfiConverterTypeKvVaultState_lower(state),$0
+ )
+})
+}
+/**
+ * The vault list's next state (search, selection, open groups).
+ */
+public func kvVaultReduce(overview: KeyvaultOverview, state: KvVaultState, action: KvVaultAction) -> KvVaultState {
+ return try! FfiConverterTypeKvVaultState_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_vault_reduce(
+ FfiConverterTypeKeyvaultOverview_lower(overview),
+ FfiConverterTypeKvVaultState_lower(state),
+ FfiConverterTypeKvVaultAction_lower(action),$0
+ )
+})
+}
+/**
+ * What the Keyvault holds for `provider_id` that a teleport can send.
+ */
+public func kvVaultSource(overview: KeyvaultOverview, providerId: String) -> KvVaultSource {
+ return try! FfiConverterTypeKvVaultSource_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_vault_source(
+ FfiConverterTypeKeyvaultOverview_lower(overview),
+ FfiConverterString.lower(providerId),$0
+ )
+})
+}
+/**
+ * The vault list: apps, sites and items with their locks, the selection and
+ * the batch bar.
+ */
+public func kvVaultView(overview: KeyvaultOverview, state: KvVaultState, nowMs: Int64) -> KvVaultView {
+ return try! FfiConverterTypeKvVaultView_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_kv_vault_view(
+ FfiConverterTypeKeyvaultOverview_lower(overview),
+ FfiConverterTypeKvVaultState_lower(state),
+ FfiConverterInt64.lower(nowMs),$0
)
})
}
@@ -59604,6 +62440,15 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_app_refresh_report_from_json() != 63623) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_spaces_ffi_checksum_func_app_review_remember() != 9631) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_app_review_remember_key() != 37113) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_app_review_remembered() != 62742) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_spaces_ffi_checksum_func_app_roster_initial() != 64316) {
return InitializationResult.apiChecksumMismatch
}
@@ -59850,13 +62695,25 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_kv_credential_form() != 40935) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_delete_command() != 38222) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_delete_confirm() != 319) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_spaces_ffi_checksum_func_kv_duration() != 51253) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_spaces_ffi_checksum_func_kv_labels() != 10991) {
return InitializationResult.apiChecksumMismatch
}
- if (uniffi_cua_spaces_ffi_checksum_func_kv_list() != 17849) {
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_list() != 17291) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_live_copy_spaces() != 53230) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_lock_command() != 45339) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_spaces_ffi_checksum_func_kv_overview_from_json() != 48866) {
@@ -59877,19 +62734,34 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_kv_sharing_label() != 21406) {
return InitializationResult.apiChecksumMismatch
}
- if (uniffi_cua_spaces_ffi_checksum_func_kv_sidebar() != 64808) {
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_sidebar() != 55835) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_spaces_ffi_checksum_func_kv_signed_in_spaces() != 26065) {
return InitializationResult.apiChecksumMismatch
}
- if (uniffi_cua_spaces_ffi_checksum_func_kv_site_detail() != 19420) {
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_space_access_key() != 62359) {
return InitializationResult.apiChecksumMismatch
}
- if (uniffi_cua_spaces_ffi_checksum_func_kv_site_toggle() != 62757) {
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_unlock_command() != 15701) {
return InitializationResult.apiChecksumMismatch
}
- if (uniffi_cua_spaces_ffi_checksum_func_kv_space_access_key() != 62359) {
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_unlock_prompt() != 36334) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_unlock_prompt_always() != 11194) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_vault_prune() != 34533) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_vault_reduce() != 45396) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_vault_source() != 38295) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_kv_vault_view() != 26773) {
return InitializationResult.apiChecksumMismatch
}
if (uniffi_cua_spaces_ffi_checksum_func_kv_visible_sharing_label() != 41274) {
@@ -59913,6 +62785,12 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_method_keyvaultclient_execute() != 54541) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_spaces_ffi_checksum_method_keyvaultclient_favicons() != 17072) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_method_keyvaultclient_inventory() != 27868) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_spaces_ffi_checksum_method_keyvaultclient_lock() != 58127) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
index cde6c6b034..e8bfb12f07 100644
--- a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
+++ b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
@@ -384,6 +384,16 @@ uint64_t uniffi_cua_spaces_ffi_fn_constructor_keyvaultclient_new(RustBuffer cua_
uint64_t uniffi_cua_spaces_ffi_fn_method_keyvaultclient_execute(uint64_t ptr, RustBuffer command
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_METHOD_KEYVAULTCLIENT_FAVICONS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_METHOD_KEYVAULTCLIENT_FAVICONS
+uint64_t uniffi_cua_spaces_ffi_fn_method_keyvaultclient_favicons(uint64_t ptr
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_METHOD_KEYVAULTCLIENT_INVENTORY
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_METHOD_KEYVAULTCLIENT_INVENTORY
+uint64_t uniffi_cua_spaces_ffi_fn_method_keyvaultclient_inventory(uint64_t ptr, RustBuffer app, RustBuffer profile
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_METHOD_KEYVAULTCLIENT_LOCK
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_METHOD_KEYVAULTCLIENT_LOCK
uint64_t uniffi_cua_spaces_ffi_fn_method_keyvaultclient_lock(uint64_t ptr
@@ -1435,6 +1445,21 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_app_presentation_preview_still(int8_t m
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_refresh_report_from_json(RustBuffer json, RustCallStatus *_Nonnull out_status
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_REVIEW_REMEMBER
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_REVIEW_REMEMBER
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_review_remember(RustBuffer choices, RustBuffer key, RustBuffer domains, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_REVIEW_REMEMBER_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_REVIEW_REMEMBER_KEY
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_review_remember_key(RustBuffer app, RustBuffer space, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_REVIEW_REMEMBERED
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_REVIEW_REMEMBERED
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_review_remembered(RustBuffer choices, RustBuffer key, RustCallStatus *_Nonnull out_status
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_ROSTER_INITIAL
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_ROSTER_INITIAL
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_roster_initial(RustBuffer spaces, RustCallStatus *_Nonnull out_status
@@ -1852,6 +1877,16 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_approval_view(RustBuffer overview, R
RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_credential_form(RustBuffer overview, RustCallStatus *_Nonnull out_status
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_DELETE_COMMAND
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_DELETE_COMMAND
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_delete_command(RustBuffer ids, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_DELETE_CONFIRM
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_DELETE_CONFIRM
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_delete_confirm(uint32_t count, uint32_t live_copies, RustCallStatus *_Nonnull out_status
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_DURATION
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_DURATION
RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_duration(int64_t ms, RustCallStatus *_Nonnull out_status
@@ -1865,7 +1900,17 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_labels(RustCallStatus *_Nonnull out_
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_LIST
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_LIST
-RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_list(RustBuffer overview, RustBuffer selection, int64_t now_ms, RustBuffer query, RustCallStatus *_Nonnull out_status
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_list(RustBuffer overview, RustBuffer selection, int64_t now_ms, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_LIVE_COPY_SPACES
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_LIVE_COPY_SPACES
+uint32_t uniffi_cua_spaces_ffi_fn_func_kv_live_copy_spaces(RustBuffer overview, RustBuffer ids, int64_t now_ms, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_LOCK_COMMAND
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_LOCK_COMMAND
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_lock_command(RustBuffer ids, RustCallStatus *_Nonnull out_status
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_OVERVIEW_FROM_JSON
@@ -1908,19 +1953,44 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_sidebar(RustBuffer overview, int64_t
RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_signed_in_spaces(RustBuffer overview, int64_t now_ms, RustBuffer dismissed, RustBuffer spaces, RustCallStatus *_Nonnull out_status
);
#endif
-#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_SITE_DETAIL
-#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_SITE_DETAIL
-RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_site_detail(RustBuffer overview, RustBuffer key, int64_t now_ms, RustCallStatus *_Nonnull out_status
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_SPACE_ACCESS_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_SPACE_ACCESS_KEY
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_space_access_key(RustBuffer overview, int64_t now_ms, RustBuffer space, RustCallStatus *_Nonnull out_status
);
#endif
-#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_SITE_TOGGLE
-#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_SITE_TOGGLE
-RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_site_toggle(RustBuffer group, int8_t on, RustCallStatus *_Nonnull out_status
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_UNLOCK_COMMAND
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_UNLOCK_COMMAND
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_unlock_command(RustBuffer ids, RustCallStatus *_Nonnull out_status
);
#endif
-#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_SPACE_ACCESS_KEY
-#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_SPACE_ACCESS_KEY
-RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_space_access_key(RustBuffer overview, int64_t now_ms, RustBuffer space, RustCallStatus *_Nonnull out_status
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_UNLOCK_PROMPT
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_UNLOCK_PROMPT
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_unlock_prompt(RustBuffer overview, uint32_t count, RustBuffer name, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_UNLOCK_PROMPT_ALWAYS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_UNLOCK_PROMPT_ALWAYS
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_unlock_prompt_always(uint32_t count, RustBuffer name, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_VAULT_PRUNE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_VAULT_PRUNE
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_vault_prune(RustBuffer overview, RustBuffer state, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_VAULT_REDUCE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_VAULT_REDUCE
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_vault_reduce(RustBuffer overview, RustBuffer state, RustBuffer action, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_VAULT_SOURCE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_VAULT_SOURCE
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_vault_source(RustBuffer overview, RustBuffer provider_id, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_VAULT_VIEW
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_VAULT_VIEW
+RustBuffer uniffi_cua_spaces_ffi_fn_func_kv_vault_view(RustBuffer overview, RustBuffer state, int64_t now_ms, RustCallStatus *_Nonnull out_status
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_KV_VISIBLE_SHARING_LABEL
@@ -3131,6 +3201,24 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_presentation_preview_still(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_REFRESH_REPORT_FROM_JSON
uint16_t uniffi_cua_spaces_ffi_checksum_func_app_refresh_report_from_json(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_REVIEW_REMEMBER
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_REVIEW_REMEMBER
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_review_remember(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_REVIEW_REMEMBER_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_REVIEW_REMEMBER_KEY
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_review_remember_key(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_REVIEW_REMEMBERED
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_REVIEW_REMEMBERED
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_review_remembered(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_ROSTER_INITIAL
@@ -3623,6 +3711,18 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_approval_view(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_CREDENTIAL_FORM
uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_credential_form(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_DELETE_COMMAND
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_DELETE_COMMAND
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_delete_command(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_DELETE_CONFIRM
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_DELETE_CONFIRM
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_delete_confirm(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_DURATION
@@ -3641,6 +3741,18 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_labels(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_LIST
uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_list(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_LIVE_COPY_SPACES
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_LIVE_COPY_SPACES
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_live_copy_spaces(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_LOCK_COMMAND
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_LOCK_COMMAND
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_lock_command(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_OVERVIEW_FROM_JSON
@@ -3691,21 +3803,51 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_signed_in_spaces(void
);
#endif
-#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_SITE_DETAIL
-#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_SITE_DETAIL
-uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_site_detail(void
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_SPACE_ACCESS_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_SPACE_ACCESS_KEY
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_space_access_key(void
);
#endif
-#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_SITE_TOGGLE
-#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_SITE_TOGGLE
-uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_site_toggle(void
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_UNLOCK_COMMAND
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_UNLOCK_COMMAND
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_unlock_command(void
);
#endif
-#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_SPACE_ACCESS_KEY
-#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_SPACE_ACCESS_KEY
-uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_space_access_key(void
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_UNLOCK_PROMPT
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_UNLOCK_PROMPT
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_unlock_prompt(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_UNLOCK_PROMPT_ALWAYS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_UNLOCK_PROMPT_ALWAYS
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_unlock_prompt_always(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_VAULT_PRUNE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_VAULT_PRUNE
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_vault_prune(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_VAULT_REDUCE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_VAULT_REDUCE
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_vault_reduce(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_VAULT_SOURCE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_VAULT_SOURCE
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_vault_source(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_VAULT_VIEW
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_KV_VAULT_VIEW
+uint16_t uniffi_cua_spaces_ffi_checksum_func_kv_vault_view(void
);
#endif
@@ -3749,6 +3891,18 @@ uint16_t uniffi_cua_spaces_ffi_checksum_method_appcliinstaller_plan(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_METHOD_KEYVAULTCLIENT_EXECUTE
uint16_t uniffi_cua_spaces_ffi_checksum_method_keyvaultclient_execute(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_METHOD_KEYVAULTCLIENT_FAVICONS
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_METHOD_KEYVAULTCLIENT_FAVICONS
+uint16_t uniffi_cua_spaces_ffi_checksum_method_keyvaultclient_favicons(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_METHOD_KEYVAULTCLIENT_INVENTORY
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_METHOD_KEYVAULTCLIENT_INVENTORY
+uint16_t uniffi_cua_spaces_ffi_checksum_method_keyvaultclient_inventory(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_METHOD_KEYVAULTCLIENT_LOCK
diff --git a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
index 7b3e45ca08..3084abd2a4 100644
--- a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
+++ b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
@@ -875,6 +875,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crc32c"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
+dependencies = [
+ "rustc_version",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.1"
@@ -1039,6 +1048,18 @@ dependencies = [
"url",
]
+[[package]]
+name = "cua-chromium-storage"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "cua-teleport-bundle",
+ "rusty-leveldb",
+ "tempfile",
+ "thiserror 2.0.20",
+ "tracing",
+]
+
[[package]]
name = "cua-daemon"
version = "0.1.0"
@@ -1369,6 +1390,7 @@ dependencies = [
"chrono",
"cua-agents",
"cua-auth",
+ "cua-chromium-storage",
"cua-daemon",
"cua-fleet",
"cua-home",
@@ -1457,6 +1479,7 @@ dependencies = [
"core-foundation 0.10.1",
"core-graphics",
"cua-agents",
+ "cua-chromium-storage",
"cua-home",
"cua-icon-cache",
"cua-machine-seal",
@@ -2008,6 +2031,17 @@ dependencies = [
"typeid",
]
+[[package]]
+name = "errno"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1"
+dependencies = [
+ "errno-dragonfly",
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -2018,6 +2052,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "errno-dragonfly"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
+dependencies = [
+ "cc",
+ "libc",
+]
+
[[package]]
name = "fallible-iterator"
version = "0.3.0"
@@ -2157,6 +2201,16 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "fs2"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
+dependencies = [
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -3103,6 +3157,12 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "integer-encoding"
+version = "3.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -5019,7 +5079,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags 2.13.1",
- "errno",
+ "errno 0.3.14",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
@@ -5108,6 +5168,21 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+[[package]]
+name = "rusty-leveldb"
+version = "4.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43ddda8f34100fca4bf1b0bbf743d12d27b5d84c35c74a52f392aac26f54e82d"
+dependencies = [
+ "bytes",
+ "crc32c",
+ "errno 0.2.8",
+ "fs2",
+ "integer-encoding",
+ "rand 0.8.8",
+ "snap",
+]
+
[[package]]
name = "ryu"
version = "1.0.23"
@@ -5561,7 +5636,7 @@ version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
- "errno",
+ "errno 0.3.14",
"libc",
]
@@ -5611,6 +5686,12 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100"
+[[package]]
+name = "snap"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886"
+
[[package]]
name = "socket2"
version = "0.6.5"
diff --git a/scripts/docs-generators/cua-sdk.ts b/scripts/docs-generators/cua-sdk.ts
index 1cef31cd4f..4b5012f1d1 100644
--- a/scripts/docs-generators/cua-sdk.ts
+++ b/scripts/docs-generators/cua-sdk.ts
@@ -822,10 +822,10 @@ export const PAGES: PageSpec[] = [
{
slug: 'spaces/app-core/teleport',
title: 'Teleport picker',
- description: 'The teleport picker and review, and consent.',
- intro: 'The picker lists `Teleport.catalog` entries, reviews a `Teleport.plan` with its consent items, and follows the run. The overlays that show a teleport in progress are on [Teleport transfer and drag](/cua-sdk/reference/spaces/app-core/teleport-transfer).',
- items: ['AppEntrySection', 'AppReviewView', 'AppPlanStepView', 'AppInstallCuaPrompt'],
- prefixes: ['AppPicker', 'app_picker_', 'AppTeleport', 'app_teleport_', 'AppCatalog', 'app_catalog_', 'AppConsent'],
+ description: 'The teleport picker and its catalog.',
+ intro: 'The picker lists `Teleport.catalog` entries and drives the steps up to the review. The overlays that show a teleport in progress are on [Teleport transfer and drag](/cua-sdk/reference/spaces/app-core/teleport-transfer).',
+ items: ['AppEntrySection'],
+ prefixes: ['AppPicker', 'app_picker_', 'AppCatalog', 'app_catalog_'],
spaces: true,
},
{
@@ -837,6 +837,24 @@ export const PAGES: PageSpec[] = [
prefixes: ['AppTransfer', 'app_transfer_', 'AppDragOverlay'],
spaces: true,
},
+ {
+ slug: 'spaces/app-core/teleport-run',
+ title: 'Teleport plan and run',
+ description: 'The teleport plan, its consent and capabilities, and the run\'s steps.',
+ intro: '`app_teleport_plan` turns a `Teleport.plan` into the consent the user sees; `AppTeleportRunEvent` and `AppTeleportRunReport` follow the run.',
+ items: [],
+ prefixes: ['AppTeleport', 'app_teleport_'],
+ spaces: true,
+ },
+ {
+ slug: 'spaces/app-core/teleport-review',
+ title: 'Teleport review',
+ description: 'The review and consent before a teleport: what to send per site, from the app or from the Keyvault, and the choice remembered for next time.',
+ intro: '`AppReviewView` is the review sheet. `AppReviewToggle` and `AppReviewChoice` change what is sent, per site or per part; `app_review_remember` keeps the choice for the next teleport of the same app to the same Space, and `AppVaultSource` offers the items the Keyvault already holds, which need no Keychain prompt.',
+ items: ['AppReviewView', 'AppSendSource', 'AppVaultSource', 'AppRememberedChoice', 'AppPlanStepView', 'AppInstallCuaPrompt'],
+ prefixes: ['AppReview', 'app_review_', 'AppConsent'],
+ spaces: true,
+ },
{
slug: 'spaces/app-core/teleport-grid',
title: 'Teleport picker grid',
@@ -949,10 +967,10 @@ export const PAGES: PageSpec[] = [
{
slug: 'spaces/app-core/keyvault-screens',
title: 'Keyvault screens',
- description: 'The Keyvault page, sidebar, list, site detail and the approval prompt.',
- intro: 'The `kv_*` functions derive each Keyvault screen from a `KeyvaultOverview`. `kv_approval_open`, `kv_approval_reduce` and `kv_approval_view` drive the approval prompt; the `*_command` functions return the `KvCommand` to send.',
+ description: 'The Keyvault page, sidebar, the vault list (apps, sites and items with their locks), the unlock prompt and the approval prompt.',
+ intro: 'The `kv_*` functions derive each Keyvault screen from a `KeyvaultOverview`. `kv_vault_view` groups the vault by source app and site, with a lock on each row; `kv_vault_reduce` applies search, selection and open groups; `kv_unlock_prompt` is the "Allow unattended access?" prompt. `kv_approval_open`, `kv_approval_reduce` and `kv_approval_view` drive the approval prompt; the `*_command` functions return the `KvCommand` to send.',
items: ['KvAccessRow', 'KvAccessKind', 'KvRecentRow', 'KvDecision', 'KvDecisionTone', 'KvTri', 'KvSelection', 'KvSigningBadge', 'KvTone'],
- prefixes: ['kv_page', 'KvPage', 'kv_sidebar', 'KvSidebar', 'KvCategory', 'kv_list', 'KvListView', 'kv_site_', 'KvSite', 'KvItemRow', 'KvConsentChip', 'KvPendingRow', 'kv_approval_', 'KvApproval'],
+ prefixes: ['kv_page', 'KvPage', 'kv_sidebar', 'KvSidebar', 'KvCategory', 'kv_list', 'KvListView', 'kv_vault_', 'KvVault', 'KvLock', 'KvKind', 'KvAppRow', 'kv_unlock_', 'KvUnlockPrompt', 'kv_delete_', 'KvDeleteConfirm', 'kv_lock_', 'kv_live_', 'KvPendingRow', 'kv_approval_', 'KvApproval'],
spaces: true,
},
{