Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(remote-desktop): 修复多屏 Mac 解锁并隔离手机指纹影响 (#4896)

Dash5ac26ed2bd4b
diff --git a/apps/mobile/fingerprint.config.cjs b/apps/mobile/fingerprint.config.cjs
index 6f20c95cfa..608ed85f6d 100644
--- a/apps/mobile/fingerprint.config.cjs
+++ b/apps/mobile/fingerprint.config.cjs
@@ -17,6 +17,28 @@ const sourceSkips = [
module.exports = {
sourceSkips,
+ // These entry points are outside the iOS podspec's source glob, and these
+ // six core files are wholly guarded by #if os(macOS). Keep this an explicit
+ // list: new/shared Swift files and Resources must still change the runtime.
+ // fingerprintConfig.test.ts checks the platform guards and real hash effects.
+ // Adopting this boundary changes legacy hashes once; ship with a planned
+ // native release, never label old installations compatible by overriding it.
+ ignorePaths: [
+ "../../packages/remote-credentials-native/Sources/CredentialHost/**/*",
+ "../../packages/remote-credentials-native/Sources/UnlockInspect/**/*",
+ "../../packages/remote-credentials-native/Sources/DesktopNativeCaller/**/*",
+ ...[
+ "CredentialPipeInput",
+ "HostCredentialServer",
+ "MacCredentialPasswordForm",
+ "MacCredentialSecret",
+ "MacScreenUnlock",
+ "MacSystemAccount",
+ ].map(
+ (name) =>
+ `../../packages/remote-credentials-native/Sources/CindyRemoteCredentials/${name}.swift`,
+ ),
+ ],
// These images are compiled into the native catalog, not delivered by Metro.
extraSources: [
"cindy-message-square-plus",
diff --git a/apps/mobile/src/__tests__/fingerprintConfig.test.ts b/apps/mobile/src/__tests__/fingerprintConfig.test.ts
index 190f27eee2..a02f2360fc 100644
--- a/apps/mobile/src/__tests__/fingerprintConfig.test.ts
+++ b/apps/mobile/src/__tests__/fingerprintConfig.test.ts
@@ -1,8 +1,17 @@
-import { describe, expect, it } from 'vitest';
-import { resolve } from 'node:path';
-import { execFileSync } from 'node:child_process';
+import { describe, expect, it } from "vitest";
+import { dirname, join, resolve } from "node:path";
+import { execFileSync } from "node:child_process";
+import {
+ cpSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
-const CONFIG_PATH = resolve(__dirname, '../../fingerprint.config.cjs');
+const CONFIG_PATH = resolve(__dirname, "../../fingerprint.config.cjs");
function loadConfigSourceSkips(env: Record<string, string> = {}): string[] {
const script = `
@@ -14,34 +23,167 @@ function loadConfigSourceSkips(env: Record<string, string> = {}): string[] {
const cfg = require(${JSON.stringify(CONFIG_PATH)});
process.stdout.write(JSON.stringify(cfg.sourceSkips));
`;
- const out = execFileSync(process.execPath, ['-e', script, JSON.stringify(env)], {
- encoding: 'utf8',
- env: { ...process.env, ...env },
- });
+ const out = execFileSync(
+ process.execPath,
+ ["-e", script, JSON.stringify(env)],
+ {
+ encoding: "utf8",
+ env: { ...process.env, ...env },
+ },
+ );
return JSON.parse(out);
}
-describe('fingerprint.config.cjs sourceSkips', () => {
- it('includes ExpoConfigVersions when EXPO_PUBLIC_XDT_OTA_SELFHOST=1', () => {
- const skips = loadConfigSourceSkips({ EXPO_PUBLIC_XDT_OTA_SELFHOST: '1' });
- expect(skips).toContain('ExpoConfigVersions');
- expect(skips).toContain('PackageJsonAndroidAndIosScriptsIfNotContainRun');
+describe("fingerprint.config.cjs sourceSkips", () => {
+ it("includes ExpoConfigVersions when EXPO_PUBLIC_XDT_OTA_SELFHOST=1", () => {
+ const skips = loadConfigSourceSkips({ EXPO_PUBLIC_XDT_OTA_SELFHOST: "1" });
+ expect(skips).toContain("ExpoConfigVersions");
+ expect(skips).toContain("PackageJsonAndroidAndIosScriptsIfNotContainRun");
});
- it('does not include ExpoConfigVersions without the self-host env', () => {
+ it("does not include ExpoConfigVersions without the self-host env", () => {
const skips = loadConfigSourceSkips({});
- expect(skips).not.toContain('ExpoConfigVersions');
- expect(skips).toContain('PackageJsonAndroidAndIosScriptsIfNotContainRun');
+ expect(skips).not.toContain("ExpoConfigVersions");
+ expect(skips).toContain("PackageJsonAndroidAndIosScriptsIfNotContainRun");
});
- it('ExpoConfigVersions is a valid @expo/fingerprint source skip', () => {
+ it("ExpoConfigVersions is a valid @expo/fingerprint source skip", () => {
let SourceSkips: Record<string, unknown>;
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
- SourceSkips = require('@expo/fingerprint').SourceSkips;
+ SourceSkips = require("@expo/fingerprint").SourceSkips;
} catch {
return; // @expo/fingerprint not installed in test env — skip gracefully
}
- expect(SourceSkips).toHaveProperty('ExpoConfigVersions');
+ expect(SourceSkips).toHaveProperty("ExpoConfigVersions");
});
});
+
+describe("remote credentials fingerprint boundary", () => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const config = require(CONFIG_PATH);
+ const projectRoot = dirname(CONFIG_PATH);
+ const core =
+ "../../packages/remote-credentials-native/Sources/CindyRemoteCredentials/";
+
+ it.each(["\n", "\r\n"])(
+ "only excludes core files wholly guarded for macOS (%j)",
+ (eol) => {
+ const files: string[] = config.ignorePaths.filter((path: string) =>
+ path.endsWith(".swift"),
+ );
+ expect(files).toHaveLength(6);
+ for (const file of files) {
+ const lines = readFileSync(resolve(projectRoot, file), "utf8")
+ .trim()
+ .replace(/\r?\n/g, eol)
+ .split(/\r?\n/);
+ expect(lines[0], file).toBe("#if os(macOS)");
+ let depth = 0;
+ for (const [index, line] of lines.entries()) {
+ if (/^\s*#if\b/.test(line)) depth++;
+ if (/^\s*#(?:else|elseif)\b/.test(line))
+ expect(depth, file).toBeGreaterThan(1);
+ if (/^\s*#endif\b/.test(line)) depth--;
+ if (index < lines.length - 1) expect(depth, file).toBeGreaterThan(0);
+ }
+ expect(depth, file).toBe(0);
+ }
+ const podspec = readFileSync(
+ resolve(
+ projectRoot,
+ "../../packages/remote-credentials-native/CindyRemoteCredentials.podspec",
+ ),
+ "utf8",
+ );
+ expect(podspec).toContain(
+ "s.source_files = 'Sources/CindyRemoteCredentials/**/*.swift'",
+ );
+ },
+ );
+
+ it.each(["ios", "android"])(
+ "%s ignores desktop changes but detects mobile inputs",
+ (platform) => {
+ const fixture = mkdtempSync(
+ join(tmpdir(), "cindy-fingerprint-boundary-"),
+ );
+ try {
+ const mobile = join(fixture, "apps/mobile");
+ mkdirSync(mobile, { recursive: true });
+ const nativePath = "../../packages/remote-credentials-native";
+ const native = resolve(mobile, nativePath);
+ mkdirSync(native, { recursive: true });
+ cpSync(
+ resolve(projectRoot, nativePath, "Sources"),
+ join(native, "Sources"),
+ { recursive: true },
+ );
+ cpSync(
+ resolve(projectRoot, nativePath, "CindyRemoteCredentials.podspec"),
+ join(native, "CindyRemoteCredentials.podspec"),
+ );
+ // Exercise Expo's actual directory hashing and ignore rules, without
+ // spawning autolinking or modifying any working-tree/native source.
+ const sources = config.extraSources.filter(
+ (source: { filePath: string }) =>
+ source.filePath.startsWith(nativePath),
+ );
+ writeFileSync(
+ join(mobile, "fingerprint.config.cjs"),
+ `module.exports = ${JSON.stringify({ ignorePaths: config.ignorePaths })}`,
+ );
+ const script = `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const { normalizeOptionsAsync } = require('@expo/fingerprint/build/Options');
+ const { createFingerprintFromSourcesAsync } = require('@expo/fingerprint/build/hash/Hash');
+ (async () => {
+ const root = process.argv[1];
+ const options = await normalizeOptionsAsync(root, { platforms: [process.argv[2]], silent: true });
+ const sources = ${JSON.stringify(sources)};
+ const hash = async () => (await createFingerprintFromSourcesAsync(sources, root, options)).hash;
+ const baseline = await hash();
+ const results = {};
+ for (const relative of ${JSON.stringify([
+ ...config.ignorePaths.filter((path: string) =>
+ path.endsWith(".swift"),
+ ),
+ `${nativePath}/Sources/CredentialHost/main.swift`,
+ `${nativePath}/Sources/UnlockInspect/main.swift`,
+ `${nativePath}/Sources/DesktopNativeCaller/DesktopNativeCaller.swift`,
+ `${core}MobileCredentialClient.swift`,
+ `${core}CredentialError.swift`,
+ `${core}Resources/credentials.json`,
+ `${core}NewSharedInput.swift`,
+ `${nativePath}/CindyRemoteCredentials.podspec`,
+ ])}) {
+ const file = path.resolve(root, relative);
+ const original = fs.existsSync(file) ? fs.readFileSync(file) : null;
+ fs.appendFileSync(file, '\\n// fingerprint mutation probe\\n');
+ results[relative] = (await hash()) === baseline;
+ if (original) fs.writeFileSync(file, original); else fs.unlinkSync(file);
+ }
+ process.stdout.write(JSON.stringify(results));
+ })().catch(error => { console.error(error); process.exitCode = 1; });
+ `;
+ const result = JSON.parse(
+ execFileSync(process.execPath, ["-e", script, mobile, platform], {
+ cwd: projectRoot,
+ encoding: "utf8",
+ }),
+ ) as Record<string, boolean>;
+ for (const [path, unchanged] of Object.entries(result)) {
+ const desktopOnly =
+ config.ignorePaths.includes(path) ||
+ /Sources\/(CredentialHost|UnlockInspect|DesktopNativeCaller)\//.test(
+ path,
+ );
+ expect(unchanged, path).toBe(desktopOnly);
+ }
+ } finally {
+ rmSync(fixture, { recursive: true, force: true });
+ }
+ },
+ );
+});
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 08d4325708..6d23742893 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -168,6 +168,13 @@ Mobile 用 `runtimeVersion.policy: "fingerprint"`:OTA 热更只在**指纹一致
### 判断哪些改动会动指纹
+- 远控凭证共享目录默认参与指纹,但 `fingerprint.config.cjs` 明确列出的六个
+ `#if os(macOS)` 文件及三个桌面入口目录不参与。共享 Swift、手机密码表单、资源、
+ podspec 和未列出的新文件仍参与;不要按 `Mac*` 文件名通配排除。
+ `fingerprintConfig.test.ts` 校验排除文件的完整 macOS 编译保护,并使用 Expo 哈希器
+ 验证两端的排除项与保留项。移除平台保护或让手机依赖这些文件前,必须同步移除排除项。
+ **首次采用此边界仍改变旧指纹**,须随计划内原生发版迁移;它只避免迁移后桌面专用
+ 修改反复触发手机冷更,不为旧安装包伪造兼容 runtime,也不豁免上面的冷更确认门。
- 改 `app.json` / `app.config.js` 前先判断是否会动指纹。被哈希的是**解析后的
ExpoConfig**(app.config.js 的输出),不是源文件本身:凡进入 resolved config 的字段,
改了值就会变指纹;只有被 app.config.js **覆写 / 剥离、传不到 resolved config** 的值才指纹
diff --git a/docs/remote-desktop-credentials.md b/docs/remote-desktop-credentials.md
index 1ceb1dfc6f..932257a585 100644
--- a/docs/remote-desktop-credentials.md
+++ b/docs/remote-desktop-credentials.md
@@ -138,6 +138,34 @@ Submission still requires the same signed process, console account, window and
secure field, plus an enabled same-parent submit button; the button is revalidated
immediately before one AXPress. Recovery dialogs, user-selection and unknown password fields fail closed.
+Multiple displays may expose empty `login` windows alongside the interactive
+surface. The Mac helper inspects all windows within the existing shared time/node
+budget and selects exactly one recognized password-field or own-account
+presentation surface. Empty login windows are allowed; unknown siblings and
+multiple actionable surfaces fail closed. Revalidation follows the original
+window and secure field even if the window list is reordered. See
+`MacScreenUnlock.swift` and `MacUnlockProfileTests.swift` for selection and regressions.
+Abort cleanup revalidates only the original window's subtree, retaining the
+console account, signed process and exact secure-field identity checks. A sibling
+becoming actionable or unreadable still prevents submission, but cannot by itself
+prevent clearing the password already written to the original field. Cleanup never
+falls back to a replacement window. `MacUnlockWindowCollectorTests.swift` covers
+these sibling transitions alongside traversal budgets and object mapping.
+On a two-display Mac, the old preparation probe failed with
+`CREDENTIAL_UNLOCK_UNAVAILABLE` while the updated probe returned `fieldReady: true`
+on the same locked session. This checks field preparation only, not password
+submission or successful system unlock.
+
+Mobile fingerprints exclude the explicit macOS-only source files and desktop
+entry-point directories listed in `apps/mobile/fingerprint.config.cjs`. Shared
+Swift, mobile forms, resources and the podspec remain fingerprint inputs, including
+new files unless explicitly excluded. Regression tests verify both directions.
+Adopting this narrower boundary changes existing fingerprints once and must be
+coordinated with a planned native mobile release; it does not make legacy runtime
+hashes interchangeable. Subsequent changes confined to the excluded Mac sources
+do not require another mobile runtime. Existing phones can use the updated Mac
+helper over the unchanged protocol without installing a new phone build.
+
The `cindy-remote-unlock-inspect --prepare` diagnostic exercises wake and field
preparation without accepting any password or submitting login. On the test Mac,
this probe reaches `fieldReady: true`; a separately cleared, never-submitted test
diff --git a/packages/remote-credentials-native/Sources/CindyRemoteCredentials/MacScreenUnlock.swift b/packages/remote-credentials-native/Sources/CindyRemoteCredentials/MacScreenUnlock.swift
index 73eb2b3084..2c17d55f68 100644
--- a/packages/remote-credentials-native/Sources/CindyRemoteCredentials/MacScreenUnlock.swift
+++ b/packages/remote-credentials-native/Sources/CindyRemoteCredentials/MacScreenUnlock.swift
@@ -36,6 +36,21 @@ struct MacUnlockProfile {
}
struct Selection: Equatable { let field: Int; let submit: Int; let label: Int? }
struct FieldSelection: Equatable { let field: Int; let label: Int? }
+ /// Secondary displays can expose empty login windows. Never pick the first
+ /// window: accept exactly one actionable surface and reject unknown siblings.
+ static func selectWindow(_ windows: [[Node]]) throws -> Int {
+ var candidates: [Int] = []
+ for (index, nodes) in windows.enumerated() {
+ _ = try accountLabel(nodes)
+ if nodes.count == 1 { continue }
+ guard (try? selectField(nodes)) != nil || (try? presentationLabel(nodes)) != nil else {
+ throw CredentialError.unlockUnavailable
+ }
+ candidates.append(index)
+ }
+ guard candidates.count == 1, let selected = candidates.first else { throw CredentialError.unlockUnavailable }
+ return selected
+ }
private static func accountLabel(_ nodes: [Node]) throws -> Int? {
guard nodes.first?.identifier == "login", nodes.first?.role == kAXWindowRole,
!nodes.contains(where: { [kAXSheetRole, kAXListRole, kAXTableRole, kAXOutlineRole, kAXComboBoxRole, kAXPopUpButtonRole].contains($0.role)
@@ -80,6 +95,42 @@ struct MacUnlockProfile {
}
}
+/// The production traversal, with AX reads and the monotonic clock injectable
+/// so budget and object-mapping regressions can be tested without a real login.
+enum MacUnlockWindowCollector {
+ static func collect<Element>(windows: [Element], cleanupWindow: Element? = nil,
+ now: () -> TimeInterval = { ProcessInfo.processInfo.systemUptime },
+ equal: (Element, Element) -> Bool,
+ read: (Element, Int?) throws -> MacUnlockProfile.Node,
+ children: (Element) throws -> [Element]) throws -> (elements: [Element], nodes: [MacUnlockProfile.Node]) {
+ // Cleanup may inspect only the original window. It must never fall back to
+ // another candidate, and unrelated sibling changes cannot suppress clearing.
+ let windows = cleanupWindow.map { original in windows.filter { equal($0, original) } } ?? windows
+ guard !windows.isEmpty, windows.count <= 16,
+ cleanupWindow == nil || windows.count == 1 else { throw CredentialError.unlockUnavailable }
+ let deadline = now() + 2
+ var elements: [Element] = [], nodes: [MacUnlockProfile.Node] = []
+ var visited: [Element] = []
+ func visit(_ element: Element, parent: Int?, depth: Int) throws {
+ guard now() < deadline, depth <= 12, visited.count < 256,
+ !visited.contains(where: { equal($0, element) }) else { throw CredentialError.unlockUnavailable }
+ visited.append(element)
+ let index = nodes.count
+ elements.append(element)
+ nodes.append(try read(element, parent))
+ for child in try children(element) { try visit(child, parent: index, depth: depth + 1) }
+ }
+ var surfaces: [(elements: [Element], nodes: [MacUnlockProfile.Node])] = []
+ for window in windows {
+ elements = []; nodes = []
+ try visit(window, parent: nil, depth: 0)
+ surfaces.append((elements, nodes))
+ }
+ guard now() < deadline else { throw CredentialError.unlockUnavailable }
+ return surfaces[try MacUnlockProfile.selectWindow(surfaces.map { $0.nodes })]
+ }
+}
+
/// Kernel start time is available for loginwindow even when NSWorkspace has no
/// launchDate. Bind PID reuse checks to the same OS process and owning user.
struct MacUnlockProcessIdentity: Equatable {
@@ -128,7 +179,7 @@ final class MacScreenUnlocker {
var wrote = false
defer {
// Clear only the same still-verified secure object; never chase new focus.
- if wrote, (try? validate(target, account: account)) != nil {
+ if wrote, (try? validate(target, account: account, forCleanup: true)) != nil {
_ = AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, "" as CFString)
}
}
@@ -237,7 +288,7 @@ final class MacScreenUnlocker {
}
throw CredentialError.unlockUnavailable
}
- private func collect(account: MacSystemAccount) throws -> Snapshot {
+ private func collect(account: MacSystemAccount, cleanupWindow: AXUIElement? = nil) throws -> Snapshot {
guard AXIsProcessTrusted() else { throw CredentialError.accessibilityRequired }
guard try MacConsoleState.read(account: account).locked else { throw CredentialError.unlockUnavailable }
let apps = NSWorkspace.shared.runningApplications.filter { $0.bundleIdentifier == "com.apple.loginwindow" && $0.executableURL?.path == path }
@@ -249,13 +300,9 @@ final class MacScreenUnlocker {
let code, SecCodeCheckValidity(code, [], requirement) == errSecSuccess else { throw CredentialError.invalidIdentity }
let root = AXUIElementCreateApplication(app.processIdentifier)
AXUIElementSetMessagingTimeout(root, 0.25)
- guard let windows = try value(root, kAXWindowsAttribute) as? [AXUIElement], windows.count == 1 else { throw CredentialError.unlockUnavailable }
+ guard let windows = try value(root, kAXWindowsAttribute) as? [AXUIElement] else { throw CredentialError.unlockUnavailable }
let names = try account.unambiguousDisplayNames()
- let deadline = ProcessInfo.processInfo.systemUptime + 2
- var elements: [AXUIElement] = [], nodes: [MacUnlockProfile.Node] = []
- func visit(_ element: AXUIElement, parent: Int?, depth: Int) throws {
- guard ProcessInfo.processInfo.systemUptime < deadline, depth <= 12, nodes.count < 256,
- !elements.contains(where: { CFEqual($0, element) }) else { throw CredentialError.unlockUnavailable }
+ let selected = try MacUnlockWindowCollector.collect(windows: windows, cleanupWindow: cleanupWindow, equal: { CFEqual($0, $1) }, read: { element, parent in
AXUIElementSetMessagingTimeout(element, 0.1)
guard let role = try value(element, kAXRoleAttribute) as? String, !role.isEmpty else { throw CredentialError.unlockUnavailable }
let subrole = try value(element, kAXSubroleAttribute) as? String ?? ""
@@ -275,24 +322,19 @@ final class MacScreenUnlocker {
if identifier == "FocusedUser", role == kAXStaticTextRole {
matches = names.contains(try value(element, kAXValueAttribute) as? String ?? "")
}
- let index = nodes.count
- elements.append(element)
- nodes.append(.init(parent: parent, role: role, subrole: subrole, identifier: identifier,
+ return .init(parent: parent, role: role, subrole: subrole, identifier: identifier,
enabled: try value(element, kAXEnabledAttribute) as? Bool == true, writable: writable.boolValue,
- press: (actions as? [String])?.contains(kAXPressAction) == true, matchesAccount: matches))
- if let children = try value(element, kAXChildrenAttribute) as? [AXUIElement] {
- for child in children { try visit(child, parent: index, depth: depth + 1) }
- }
- }
- try visit(windows[0], parent: nil, depth: 0)
- guard ProcessInfo.processInfo.systemUptime < deadline else { throw CredentialError.unlockUnavailable }
- return (app, launch, code, elements, nodes)
+ press: (actions as? [String])?.contains(kAXPressAction) == true, matchesAccount: matches)
+ }, children: { element in
+ try value(element, kAXChildrenAttribute) as? [AXUIElement] ?? []
+ })
+ return (app, launch, code, selected.elements, selected.nodes)
}
- private func validate(_ target: Target, account: MacSystemAccount) throws -> Snapshot {
+ private func validate(_ target: Target, account: MacSystemAccount, forCleanup: Bool = false) throws -> Snapshot {
guard !target.application.isTerminated,
try MacUnlockProcessIdentity.read(pid: target.application.processIdentifier, uid: account.uid) == target.launch,
SecCodeCheckValidity(target.code, [], nil) == errSecSuccess else { throw CredentialError.invalidIdentity }
- let next = try collect(account: account)
+ let next = try collect(account: account, cleanupWindow: forCleanup ? target.elements[0] : nil)
let selection = try MacUnlockProfile.selectField(next.nodes)
guard next.application.processIdentifier == target.application.processIdentifier, next.launch == target.launch,
CFEqual(next.elements[0], target.elements[0]),
diff --git a/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/MacUnlockProfileTests.swift b/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/MacUnlockProfileTests.swift
index ad69af9a5a..4bc7a6b6c9 100644
--- a/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/MacUnlockProfileTests.swift
+++ b/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/MacUnlockProfileTests.swift
@@ -17,6 +17,35 @@ final class MacUnlockProfileTests: XCTestCase {
func testSelectsOnlyKnownSecureProfile() throws {
XCTAssertEqual(try MacUnlockProfile.select(valid), .init(field: 3, submit: 4, label: 2))
}
+ func testSelectsUniqueSurfaceAcrossDisplaysRegardlessOfOrder() throws {
+ let empty = [node(nil, "AXWindow", "login")]
+ XCTAssertEqual(try MacUnlockProfile.selectWindow([valid]), 0)
+ XCTAssertEqual(try MacUnlockProfile.selectWindow([empty, valid]), 1)
+ XCTAssertEqual(try MacUnlockProfile.selectWindow([valid, empty]), 0)
+ let collapsed = [node(nil, "AXWindow", "login"), node(0, "AXStaticText", "FocusedUser", matches: true)]
+ XCTAssertEqual(try MacUnlockProfile.selectWindow([empty, collapsed]), 1)
+ // A button need not exist yet; selection must survive its later appearance.
+ XCTAssertEqual(try MacUnlockProfile.selectWindow([empty, Array(valid.dropLast())]), 1)
+ }
+ func testRejectsAmbiguousOrUnavailableDisplaySurfaces() {
+ let empty = [node(nil, "AXWindow", "login")]
+ let collapsed = [node(nil, "AXWindow", "login"), node(0, "AXStaticText", "FocusedUser", matches: true)]
+ for windows in [[], [empty], [empty, empty], [valid, valid], [collapsed, collapsed], [valid, collapsed]] {
+ XCTAssertThrowsError(try MacUnlockProfile.selectWindow(windows))
+ }
+ }
+ func testOtherWindowsCannotHideUnsafeFlows() {
+ var otherAccount = valid
+ otherAccount[2] = node(1, "AXStaticText", "FocusedUser", matches: false)
+ let unsafe = [otherAccount, [node(nil, "AXWindow", "keychain")],
+ [node(nil, "AXWindow", "login", subrole: "AXDialog")],
+ [node(nil, "AXWindow", "login"), node(0, "AXTextField", "unknown")],
+ [node(nil, "AXWindow", "login"), node(0, "AXList")]]
+ for sibling in unsafe {
+ XCTAssertThrowsError(try MacUnlockProfile.selectWindow([valid, sibling]))
+ XCTAssertThrowsError(try MacUnlockProfile.selectWindow([sibling, valid]))
+ }
+ }
func testFlatLayoutDoesNotRequireSubmitBeforeWriting() throws {
let field = [node(nil, "AXWindow", "login"),
node(0, "AXStaticText", "FocusedUser", matches: true),
diff --git a/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/MacUnlockWindowCollectorTests.swift b/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/MacUnlockWindowCollectorTests.swift
new file mode 100644
index 0000000000..0e26d7cae9
--- /dev/null
+++ b/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/MacUnlockWindowCollectorTests.swift
@@ -0,0 +1,108 @@
+#if os(macOS)
+import XCTest
+@testable import CindyRemoteCredentials
+
+final class MacUnlockWindowCollectorTests: XCTestCase {
+ private func node(_ id: Int, _ parent: Int?) -> MacUnlockProfile.Node {
+ let window = parent == nil
+ let field = id == 12
+ return .init(parent: parent, role: window ? "AXWindow" : field ? "AXTextField" : "AXGroup",
+ subrole: field ? "AXSecureTextField" : "", identifier: window ? "login" : field ? "UserPasswordTextField" : "",
+ enabled: true, writable: field, press: false, matchesAccount: false)
+ }
+ private func children(_ id: Int) -> [Int] {
+ id == 10 ? [11] : id == 11 ? [12] : []
+ }
+ func testMapsSelectedObjectsAndResetsParentIndicesAcrossWindowOrder() throws {
+ for windows in [[0, 10], [10, 0]] {
+ let result = try MacUnlockWindowCollector.collect(windows: windows, equal: ==, read: node, children: children)
+ XCTAssertEqual(result.elements, [10, 11, 12])
+ XCTAssertEqual(result.nodes.map { $0.parent }, [nil, 0, 1])
+ let selection = try MacUnlockProfile.selectField(result.nodes)
+ XCTAssertEqual(result.elements[selection.field], 12)
+ }
+ }
+ func testNodeBudgetIsSharedAcrossWindows() {
+ var reads = 0
+ func wideChildren(_ id: Int) -> [Int] {
+ if id == 0 { return Array(1...150) }
+ if id == 1000 { return Array(1001...1150) }
+ return []
+ }
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [0, 1000], equal: ==,
+ read: { id, parent in reads += 1; return self.node(id, parent) },
+ children: wideChildren))
+ XCTAssertEqual(reads, 256)
+ }
+ func testCleanupRetainsOriginalObjectsWhenSiblingBecomesActionable() throws {
+ func read(_ id: Int, _ parent: Int?) -> MacUnlockProfile.Node {
+ node(id == 22 ? 12 : id, parent)
+ }
+ func expandedChildren(_ id: Int) -> [Int] {
+ if id == 20 { return [22] }
+ return children(id)
+ }
+ let original = try MacUnlockWindowCollector.collect(windows: [0, 10], equal: ==, read: read, children: children)
+ let originalField = original.elements[try MacUnlockProfile.selectField(original.nodes).field]
+ // Submission must abort once a second actionable surface appears.
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [20, 10], equal: ==,
+ read: read, children: expandedChildren))
+ let cleanup = try MacUnlockWindowCollector.collect(windows: [20, 10], cleanupWindow: original.elements[0],
+ equal: ==, read: read, children: expandedChildren)
+ XCTAssertEqual(cleanup.elements[try MacUnlockProfile.selectField(cleanup.nodes).field], originalField)
+ XCTAssertEqual(cleanup.elements, [10, 11, 12])
+ }
+ func testCleanupDoesNotReadBrokenSiblingOrFallBackToReplacementWindow() throws {
+ let cleanup = try MacUnlockWindowCollector.collect(windows: [0, 10], cleanupWindow: 10, equal: ==,
+ read: { id, parent in
+ if id == 0 { throw CredentialError.unlockUnavailable }
+ return self.node(id, parent)
+ }, children: children)
+ XCTAssertEqual(cleanup.elements, [10, 11, 12])
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [10], cleanupWindow: 99,
+ equal: ==, read: node, children: children))
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [10, 10], cleanupWindow: 10,
+ equal: ==, read: node, children: children))
+ }
+ func testCleanupStillRejectsAnInvalidOriginalSecureField() {
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [0, 10], cleanupWindow: 10,
+ equal: ==, read: { id, parent in self.node(id == 12 ? 99 : id, parent) }, children: children))
+ }
+ func testTimeBudgetIsNotResetForSecondWindow() {
+ var time = 0.0
+ var reads: [Int] = []
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [0, 10], now: { time }, equal: ==,
+ read: { id, parent in
+ reads.append(id)
+ time += 1.1
+ return self.node(id, parent)
+ }, children: children))
+ XCTAssertEqual(reads, [0, 10]) // The second window's children never get a fresh budget.
+ }
+ func testFinalReadCannotOverrunDeadlineUnnoticed() {
+ var time = 0.0
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [0, 10], now: { time }, equal: ==,
+ read: node, children: { id in
+ if id == 12 { time = 2 }
+ return self.children(id)
+ }))
+ }
+ func testDuplicateObjectsAndReadFailuresInSiblingsFailClosed() {
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [10, 10], equal: ==, read: node, children: children))
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [10, 0], equal: ==,
+ read: { id, parent in
+ if id == 0 { throw CredentialError.unlockUnavailable }
+ return self.node(id, parent)
+ }, children: children))
+ }
+ func testWindowAndDepthLimitsRemainBounded() {
+ var reads = 0
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: Array(0...16), equal: ==,
+ read: { id, parent in reads += 1; return self.node(id, parent) }, children: children))
+ XCTAssertEqual(reads, 0)
+ XCTAssertThrowsError(try MacUnlockWindowCollector.collect(windows: [0], equal: ==,
+ read: { id, parent in reads += 1; return self.node(id, parent) }, children: { [$0 + 1] }))
+ XCTAssertEqual(reads, 13)
+ }
+}
+#endif