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(ios-simulator): harden device control consent

JiangJiahao493915e73a11
diff --git a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
index 3149faa86a..bbb2b767d3 100644
--- a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
@@ -129,14 +129,14 @@ describe('desktop MCP approval policy', () => {
expect(getDesktopMcpToolApprovalPolicy({ serverName: 'third_party' })).toBe('prompt');
});
- it('prompts for simulator build, URL, and device creation while device-gated actions stay trusted', () => {
+ it('prompts for simulator setup actions while device-gated actions stay trusted', () => {
expect(
getDesktopMcpToolApprovalPolicy({
serverName: 'cindy_ios_simulator',
toolName: 'list_tools',
}),
).toBe('auto-approve');
- for (const name of ['build_app', 'create_instance', 'open_url']) {
+ for (const name of ['attach_device', 'build_app', 'create_instance', 'open_url']) {
expect(
getDesktopMcpToolApprovalPolicy({
serverName: 'cindy_ios_simulator',
diff --git a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
index 4bd6d2445c..33a68bd86a 100644
--- a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
+++ b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
@@ -116,9 +116,12 @@ export function getDesktopMcpToolApprovalPolicy(
if (toolName === 'call_tool') {
const innerName =
toolParams && typeof toolParams === 'object'
- ? (toolParams as { name?: unknown }).name
+ ? (toolParams as { name?: unknown }).name
: undefined;
- return innerName === 'build_app' || innerName === 'open_url' || innerName === 'create_instance'
+ return innerName === 'build_app' ||
+ innerName === 'open_url' ||
+ innerName === 'create_instance' ||
+ innerName === 'attach_device'
? 'prompt-each-time'
: 'auto-approve';
}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index 9e1a9fe595..c78f586b9b 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
@@ -9,6 +9,7 @@ import { describe, expect, it, vi } from 'vitest';
import {
createIOSSimulatorNativeDevelopmentAdmissionPolicy,
evaluateIOSSimulatorNativeCapabilityAdmission,
+ IOSSimulatorDeviceGrantStore,
IOSSimulatorInstanceActor,
IOSSimulatorInstanceError,
IOSSimulatorOwnershipStore,
@@ -31,6 +32,7 @@ import {
cancelIOSSimulatorSessionOperations,
cleanupIOSSimulatorRemovedSession,
createIOSSimulatorHost,
+ createRegistryBackedIOSSimulatorDeviceGrantStore,
createRegistryBackedIOSSimulatorActor,
disposeIOSSimulatorHost,
flushIOSSimulatorOwnershipRegistry,
@@ -126,6 +128,49 @@ describe('iOS Simulator host', () => {
}
});
+ itMac(
+ 'persists device grants in the active Cindy profile and restores them after restart',
+ async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-grants-'));
+ const ownershipRegistry = new IOSSimulatorOwnershipRegistryFile(
+ path.join(root, 'ios-simulator', 'ownership-registry.json'),
+ );
+ try {
+ expect(ownershipRegistry.acquireWriterSync()).toBe(true);
+ const firstStore = createRegistryBackedIOSSimulatorDeviceGrantStore(ownershipRegistry);
+ firstStore.set(READY_REPORT.devices[0]!.udid, { agentControl: 'allowed' });
+
+ const restoredStore = createRegistryBackedIOSSimulatorDeviceGrantStore(ownershipRegistry);
+ expect(restoredStore.get(READY_REPORT.devices[0]!.udid)).toMatchObject({
+ agentControl: 'allowed',
+ policySource: 'user',
+ });
+ restoredStore.set(READY_REPORT.devices[0]!.udid, { agentControl: 'denied' });
+ const deniedAfterRestart =
+ createRegistryBackedIOSSimulatorDeviceGrantStore(ownershipRegistry);
+ expect(deniedAfterRestart.get(READY_REPORT.devices[0]!.udid).agentControl).toBe('denied');
+ expect(
+ JSON.parse(
+ await readFile(path.join(root, 'ios-simulator', 'device-grants.json'), 'utf8'),
+ ),
+ ).toMatchObject({
+ version: 1,
+ grants: [{ simulatorUdid: READY_REPORT.devices[0]!.udid }],
+ });
+
+ await writeFile(
+ path.join(root, 'ios-simulator', 'device-grants.json'),
+ '{"version":1,"grants":[',
+ );
+ const failClosedStore = createRegistryBackedIOSSimulatorDeviceGrantStore(ownershipRegistry);
+ expect(failClosedStore.get(READY_REPORT.devices[0]!.udid).agentControl).toBe('unknown');
+ } finally {
+ ownershipRegistry.releaseWriterSync();
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
itMac(
'recovers pending creates with an empty registry before releasing its writer lease',
async () => {
@@ -4648,6 +4693,74 @@ describe('iOS Simulator host', () => {
);
});
+ it('revokes an attached agent lease even when persisting the denial fails', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const grantStore = new IOSSimulatorDeviceGrantStore({
+ initialGrants: [
+ {
+ simulatorUdid: READY_REPORT.devices[0]!.udid,
+ agentControl: 'allowed',
+ screenshotCapture: 'unknown',
+ policySource: 'user',
+ updatedAt: '2026-08-07T00:00:00.000Z',
+ },
+ ],
+ onChange: () => {
+ throw new Error('disk unavailable');
+ },
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ grantStore,
+ runtime: {
+ inspect: vi.fn(async () => ({
+ ...READY_REPORT,
+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],
+ })),
+ },
+ getSession: vi.fn(async (id) => localSession(id)),
+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),
+ resourceScheduler: testResourceScheduler(),
+ });
+
+ await expect(
+ host.callTool(
+ 'attach_device',
+ { udid: READY_REPORT.devices[0]!.udid },
+ { sessionId: 'session-agent', origin: 'agent' },
+ ),
+ ).resolves.toMatchObject({ ok: true });
+ const instance = actor.list('session-agent')[0]!;
+ const route = {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ };
+
+ await expect(
+ host.setAgentControlGrant('session-agent', instance.instanceId, 'denied'),
+ ).resolves.toMatchObject({ ok: false });
+ expect(grantStore.get(instance.simulatorUdid).agentControl).toBe('denied');
+ await expect(
+ host.callTool('stop_instance', route, {
+ sessionId: 'session-agent',
+ origin: 'agent',
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'DEVICE_CONTROL_NOT_GRANTED' });
+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();
+ });
+
it('renews the lease after a slow driver start and opens the embedded viewer', async () => {
let now = 1_000;
const lifecycle: IOSSimulatorSimctlLifecycle = {
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index cb66ea5f15..8ee5264038 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -12,6 +12,7 @@ import {
IOSSimulatorAppLifecycle,
auditIOSSimulatorScreenMap,
diffIOSSimulatorScreenMaps,
+ IOSSimulatorDeviceGrantRegistryFile,
IOSSimulatorDeviceGrantStore,
IOSSimulatorDiagnosticsStore,
IOSSimulatorFramePump,
@@ -33,6 +34,7 @@ import {
WdaProcessManager,
type IOSSimulatorEnvironmentReport,
type IOSSimulatorDriverCapabilityReport,
+ type IOSSimulatorDeviceGrant,
type IOSSimulatorAdmissionPolicy,
type IOSSimulatorNativeCapabilityAdmissionPolicy,
type IOSSimulatorNativeSidecarDiagnostics,
@@ -375,6 +377,39 @@ function createDefaultOwnershipRegistry(): IOSSimulatorOwnershipRegistryFile {
);
}
+/**
+ * Device consent is profile-scoped but independent from task ownership. Reuse
+ * the ownership registry's process-wide writer lease while keeping a corrupt
+ * consent snapshot from blocking lifecycle recovery: invalid data restores as
+ * all-unknown, and the next explicit decision must persist before it succeeds.
+ */
+export function createRegistryBackedIOSSimulatorDeviceGrantStore(
+ ownershipRegistry: IOSSimulatorOwnershipRegistryFile,
+): IOSSimulatorDeviceGrantStore {
+ const grantRegistry = new IOSSimulatorDeviceGrantRegistryFile(
+ path.join(path.dirname(ownershipRegistry.filePath), 'device-grants.json'),
+ { assertMutationAllowed: () => ownershipRegistry.assertWriter() },
+ );
+ let initialGrants: IOSSimulatorDeviceGrant[];
+ try {
+ initialGrants = grantRegistry.loadSync();
+ } catch (error) {
+ if (error instanceof IOSSimulatorInstanceError && error.code === 'DEVICE_BUSY') {
+ throw error;
+ }
+ logger.warn('Ignoring invalid persisted iOS Simulator device grants', {
+ filePath: redact(grantRegistry.filePath),
+ error: error instanceof Error ? error.message : String(error),
+ });
+ initialGrants = [];
+ }
+ return new IOSSimulatorDeviceGrantStore({
+ initialGrants,
+ assertMutationAllowed: () => ownershipRegistry.assertWriter(),
+ onChange: (grants) => grantRegistry.saveSync(grants),
+ });
+}
+
function createProfileScopedIOSSimulatorLifecycle(
registry: IOSSimulatorOwnershipRegistryFile,
): IOSSimulatorSimctlLifecycle {
@@ -6060,6 +6095,7 @@ let defaultIOSSimulatorRuntimeDisposePromise: Promise<void> | null = null;
function installDefaultIOSSimulatorHost(
lifecycle: IOSSimulatorSimctlLifecycle,
persistedActor: ReturnType<typeof createDefaultActor>,
+ registry: IOSSimulatorOwnershipRegistryFile,
): IOSSimulatorHost {
if (defaultIOSSimulatorRuntime) {
persistedActor.release();
@@ -6075,6 +6111,7 @@ function installDefaultIOSSimulatorHost(
const host = createIOSSimulatorHost({
lifecycle,
actor: persistedActor.actor,
+ grantStore: createRegistryBackedIOSSimulatorDeviceGrantStore(registry),
canReconcilePendingCreates: persistedActor.canReconcilePendingCreates,
driverManager: createDefaultDriverManager(),
});
@@ -6116,7 +6153,7 @@ export function initializeIOSSimulatorHost(): IOSSimulatorHost {
const registry = createDefaultOwnershipRegistry();
const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry);
const persistedActor = createDefaultActor(lifecycle, registry);
- return installDefaultIOSSimulatorHost(lifecycle, persistedActor);
+ return installDefaultIOSSimulatorHost(lifecycle, persistedActor, registry);
}
function currentIOSSimulatorHost(): IOSSimulatorHost | null {
@@ -6232,7 +6269,7 @@ export async function reconcilePersistedIOSSimulatorOwnership(
return;
}
const persistedActor = createDefaultActor(lifecycle, registry);
- const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor);
+ const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor, registry);
registryTransferred = true;
await host.reconcileOwnership();
} catch (error) {
@@ -6296,7 +6333,7 @@ export function cleanupIOSSimulatorRemovedSession(sessionId: string): Promise<vo
// another Cindy process attaching this task while it is being removed.
const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry);
const persistedActor = createDefaultActor(lifecycle, registry);
- const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor);
+ const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor, registry);
registryTransferred = true;
return host.cleanupRemovedSession(normalizedSessionId);
} catch (error) {
diff --git a/packages/ios-simulator-runtime/src/device-grant-registry-file.test.ts b/packages/ios-simulator-runtime/src/device-grant-registry-file.test.ts
new file mode 100644
index 0000000000..1be96f2d52
--- /dev/null
+++ b/packages/ios-simulator-runtime/src/device-grant-registry-file.test.ts
@@ -0,0 +1,97 @@
+import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { IOSSimulatorDeviceGrantRegistryFile } from "./device-grant-registry-file.js";
+import type { IOSSimulatorDeviceGrant } from "./device-grant-store.js";
+
+const GRANT: IOSSimulatorDeviceGrant = {
+ simulatorUdid: "1A9D41E0-E031-4AD0-A8B5-847480802E8E",
+ agentControl: "allowed",
+ screenshotCapture: "denied",
+ policySource: "user",
+ updatedAt: "2026-08-07T00:00:00.000Z",
+};
+
+describe("IOSSimulatorDeviceGrantRegistryFile", () => {
+ it("treats a missing file as empty and round-trips grants atomically", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-grants-"));
+ try {
+ const registry = new IOSSimulatorDeviceGrantRegistryFile(
+ path.join(root, "device-grants.json"),
+ );
+ expect(registry.loadSync()).toEqual([]);
+
+ registry.saveSync([GRANT]);
+ expect(registry.loadSync()).toEqual([GRANT]);
+ expect(
+ JSON.parse(await readFile(registry.filePath, "utf8")),
+ ).toMatchObject({
+ version: 1,
+ grants: [
+ { simulatorUdid: GRANT.simulatorUdid, agentControl: "allowed" },
+ ],
+ });
+ expect((await stat(registry.filePath)).mode & 0o777).toBe(0o600);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it("canonicalizes device IDs and rejects malformed or duplicate snapshots", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-grants-"));
+ const filePath = path.join(root, "device-grants.json");
+ const registry = new IOSSimulatorDeviceGrantRegistryFile(filePath);
+ try {
+ registry.saveSync([
+ { ...GRANT, simulatorUdid: GRANT.simulatorUdid.toLowerCase() },
+ ]);
+ expect(registry.loadSync()[0]?.simulatorUdid).toBe(GRANT.simulatorUdid);
+
+ await writeFile(filePath, JSON.stringify({ version: 999, grants: [] }));
+ expect(() => registry.loadSync()).toThrowError(
+ expect.objectContaining({ code: "INVALID_ARGUMENT" }),
+ );
+
+ await writeFile(
+ filePath,
+ JSON.stringify({
+ version: 1,
+ savedAt: "2026-08-07T00:00:00.000Z",
+ grants: [
+ GRANT,
+ { ...GRANT, simulatorUdid: GRANT.simulatorUdid.toLowerCase() },
+ ],
+ }),
+ );
+ expect(() => registry.loadSync()).toThrowError(
+ expect.objectContaining({ code: "INVALID_ARGUMENT" }),
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it("checks the profile writer before reading and before replacing a snapshot", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-grants-"));
+ let writerHeld = true;
+ const registry = new IOSSimulatorDeviceGrantRegistryFile(
+ path.join(root, "device-grants.json"),
+ {
+ assertMutationAllowed: () => {
+ if (!writerHeld) throw new Error("writer lease lost");
+ },
+ },
+ );
+ try {
+ registry.saveSync([GRANT]);
+ writerHeld = false;
+ expect(() => registry.loadSync()).toThrow("writer lease lost");
+ expect(() => registry.saveSync([])).toThrow("writer lease lost");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/ios-simulator-runtime/src/device-grant-registry-file.ts b/packages/ios-simulator-runtime/src/device-grant-registry-file.ts
new file mode 100644
index 0000000000..8ee3269970
--- /dev/null
+++ b/packages/ios-simulator-runtime/src/device-grant-registry-file.ts
@@ -0,0 +1,175 @@
+import { randomUUID } from "node:crypto";
+import {
+ mkdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import path from "node:path";
+
+import type { IOSSimulatorDeviceGrant } from "./device-grant-store.js";
+import { IOSSimulatorInstanceError } from "./instance-errors.js";
+
+const REGISTRY_VERSION = 1;
+const MAX_REGISTRY_BYTES = 256 * 1024;
+const MAX_GRANTS = 512;
+const SIMULATOR_UDID_PATTERN =
+ /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/;
+
+export interface IOSSimulatorDeviceGrantRegistrySnapshot {
+ version: 1;
+ savedAt: string;
+ grants: IOSSimulatorDeviceGrant[];
+}
+
+export interface IOSSimulatorDeviceGrantRegistryFileOptions {
+ /** Reuses the profile ownership registry's process-wide writer lease. */
+ assertMutationAllowed?: () => void;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+function canonicalUdid(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const normalized = value.trim().toUpperCase();
+ return SIMULATOR_UDID_PATTERN.test(normalized) ? normalized : null;
+}
+
+function isIsoDate(value: unknown): value is string {
+ if (typeof value !== "string") return false;
+ const timestamp = Date.parse(value);
+ return (
+ Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value
+ );
+}
+
+function isDecision(value: unknown): boolean {
+ return value === "unknown" || value === "allowed" || value === "denied";
+}
+
+function parseGrant(value: unknown): IOSSimulatorDeviceGrant | null {
+ if (!isRecord(value)) return null;
+ const simulatorUdid = canonicalUdid(value.simulatorUdid);
+ if (
+ !simulatorUdid ||
+ !isDecision(value.agentControl) ||
+ !isDecision(value.screenshotCapture) ||
+ (value.policySource !== "user" &&
+ value.policySource !== "managed-policy") ||
+ !isIsoDate(value.updatedAt)
+ ) {
+ return null;
+ }
+ return {
+ simulatorUdid,
+ agentControl: value.agentControl as IOSSimulatorDeviceGrant["agentControl"],
+ screenshotCapture:
+ value.screenshotCapture as IOSSimulatorDeviceGrant["screenshotCapture"],
+ policySource: value.policySource,
+ updatedAt: value.updatedAt,
+ };
+}
+
+function parseSnapshot(value: unknown): IOSSimulatorDeviceGrant[] | null {
+ if (
+ !isRecord(value) ||
+ value.version !== REGISTRY_VERSION ||
+ !isIsoDate(value.savedAt) ||
+ !Array.isArray(value.grants) ||
+ value.grants.length > MAX_GRANTS
+ ) {
+ return null;
+ }
+ const grants: IOSSimulatorDeviceGrant[] = [];
+ const seenUdids = new Set<string>();
+ for (const valueGrant of value.grants) {
+ const grant = parseGrant(valueGrant);
+ if (!grant || seenUdids.has(grant.simulatorUdid)) return null;
+ seenUdids.add(grant.simulatorUdid);
+ grants.push(grant);
+ }
+ return grants;
+}
+
+function invalidRegistryError(): IOSSimulatorInstanceError {
+ return new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "The persisted iOS Simulator device grants are invalid.",
+ );
+}
+
+/** Profile-scoped, schema-bounded device consent snapshot. */
+export class IOSSimulatorDeviceGrantRegistryFile {
+ readonly #filePath: string;
+ readonly #assertMutationAllowed: (() => void) | null;
+
+ constructor(
+ filePath: string,
+ options: IOSSimulatorDeviceGrantRegistryFileOptions = {},
+ ) {
+ this.#filePath = filePath;
+ this.#assertMutationAllowed = options.assertMutationAllowed ?? null;
+ }
+
+ get filePath(): string {
+ return this.#filePath;
+ }
+
+ loadSync(): IOSSimulatorDeviceGrant[] {
+ this.#assertMutationAllowed?.();
+ let serialized: Buffer;
+ try {
+ serialized = readFileSync(this.#filePath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException | null)?.code === "ENOENT") return [];
+ throw invalidRegistryError();
+ }
+ if (serialized.byteLength > MAX_REGISTRY_BYTES)
+ throw invalidRegistryError();
+ let value: unknown;
+ try {
+ value = JSON.parse(serialized.toString("utf8")) as unknown;
+ } catch {
+ throw invalidRegistryError();
+ }
+ const grants = parseSnapshot(value);
+ if (!grants) throw invalidRegistryError();
+ return grants;
+ }
+
+ saveSync(grants: readonly IOSSimulatorDeviceGrant[]): void {
+ this.#assertMutationAllowed?.();
+ const snapshot: IOSSimulatorDeviceGrantRegistrySnapshot = {
+ version: REGISTRY_VERSION,
+ savedAt: new Date().toISOString(),
+ grants: grants.map((grant) => ({ ...grant })),
+ };
+ const validated = parseSnapshot(snapshot);
+ if (!validated) throw invalidRegistryError();
+ const serialized = JSON.stringify({ ...snapshot, grants: validated });
+ if (Buffer.byteLength(serialized, "utf8") > MAX_REGISTRY_BYTES) {
+ throw invalidRegistryError();
+ }
+
+ mkdirSync(path.dirname(this.#filePath), { recursive: true });
+ const tempPath = `${this.#filePath}.${process.pid}.${randomUUID()}.tmp`;
+ try {
+ writeFileSync(tempPath, serialized, {
+ encoding: "utf8",
+ mode: 0o600,
+ flag: "wx",
+ });
+ this.#assertMutationAllowed?.();
+ renameSync(tempPath, this.#filePath);
+ } finally {
+ try {
+ rmSync(tempPath, { force: true });
+ } catch {
+ // The write error remains authoritative; cleanup is best effort.
+ }
+ }
+ }
+}
diff --git a/packages/ios-simulator-runtime/src/device-grant-store.test.ts b/packages/ios-simulator-runtime/src/device-grant-store.test.ts
index f3e526384f..e98bc4aaf0 100644
--- a/packages/ios-simulator-runtime/src/device-grant-store.test.ts
+++ b/packages/ios-simulator-runtime/src/device-grant-store.test.ts
@@ -29,4 +29,92 @@ describe("IOSSimulatorDeviceGrantStore", () => {
policySource: "managed-policy",
});
});
+
+ it("restores persisted grants with canonical device identities", () => {
+ const store = new IOSSimulatorDeviceGrantStore({
+ initialGrants: [
+ {
+ simulatorUdid: UDID.toLowerCase(),
+ agentControl: "allowed",
+ screenshotCapture: "denied",
+ policySource: "user",
+ updatedAt: "2026-08-07T00:00:00.000Z",
+ },
+ ],
+ });
+
+ expect(store.get(UDID)).toEqual({
+ simulatorUdid: UDID,
+ agentControl: "allowed",
+ screenshotCapture: "denied",
+ policySource: "user",
+ updatedAt: "2026-08-07T00:00:00.000Z",
+ });
+ expect(store.listAll()).toEqual([store.get(UDID)]);
+ });
+
+ it("persists complete snapshots, rolls elevations back, and keeps revocations fail-closed", () => {
+ let failPersistence = false;
+ const snapshots: unknown[] = [];
+ const store = new IOSSimulatorDeviceGrantStore({
+ now: () => 2_000,
+ onChange: (grants) => {
+ snapshots.push(grants);
+ if (failPersistence) throw new Error("disk unavailable");
+ },
+ });
+
+ store.set(UDID, { agentControl: "allowed" });
+ expect(snapshots).toEqual([
+ [expect.objectContaining({ agentControl: "allowed" })],
+ ]);
+
+ failPersistence = true;
+ expect(() => store.set(UDID, { agentControl: "denied" })).toThrow(
+ "disk unavailable",
+ );
+ expect(store.get(UDID).agentControl).toBe("denied");
+
+ const elevationStore = new IOSSimulatorDeviceGrantStore({
+ onChange: () => {
+ throw new Error("disk unavailable");
+ },
+ });
+ expect(() => elevationStore.set(UDID, { agentControl: "allowed" })).toThrow(
+ "disk unavailable",
+ );
+ expect(elevationStore.get(UDID).agentControl).toBe("unknown");
+ });
+
+ it("checks the profile writer before changing a grant", () => {
+ const store = new IOSSimulatorDeviceGrantStore({
+ assertMutationAllowed: () => {
+ throw new Error("writer lease lost");
+ },
+ });
+
+ expect(() => store.set(UDID, { agentControl: "allowed" })).toThrow(
+ "writer lease lost",
+ );
+ expect(store.get(UDID).agentControl).toBe("unknown");
+
+ const revocationStore = new IOSSimulatorDeviceGrantStore({
+ initialGrants: [
+ {
+ simulatorUdid: UDID,
+ agentControl: "allowed",
+ screenshotCapture: "unknown",
+ policySource: "user",
+ updatedAt: "2026-08-07T00:00:00.000Z",
+ },
+ ],
+ assertMutationAllowed: () => {
+ throw new Error("writer lease lost");
+ },
+ });
+ expect(() => revocationStore.set(UDID, { agentControl: "denied" })).toThrow(
+ "writer lease lost",
+ );
+ expect(revocationStore.get(UDID).agentControl).toBe("denied");
+ });
});
diff --git a/packages/ios-simulator-runtime/src/device-grant-store.ts b/packages/ios-simulator-runtime/src/device-grant-store.ts
index 55f5f9a4b0..fd531417f4 100644
--- a/packages/ios-simulator-runtime/src/device-grant-store.ts
+++ b/packages/ios-simulator-runtime/src/device-grant-store.ts
@@ -12,6 +12,12 @@ export interface IOSSimulatorDeviceGrant {
}
export interface IOSSimulatorDeviceGrantStoreOptions {
now?: () => number;
+ /** Previously persisted per-device decisions restored at Host startup. */
+ initialGrants?: readonly IOSSimulatorDeviceGrant[];
+ /** Synchronous persistence hook; failed elevations roll back and revocations stay fail-closed. */
+ onChange?: (grants: IOSSimulatorDeviceGrant[]) => void;
+ /** Fail-closed gate supplied by the profile-scoped registry owner. */
+ assertMutationAllowed?: () => void;
}
function requireUdid(value: string): string {
@@ -25,28 +31,94 @@ function requireUdid(value: string): string {
return normalized;
}
+function requireDecision(value: unknown): IOSSimulatorGrantDecision {
+ if (value !== "unknown" && value !== "allowed" && value !== "denied") {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "Simulator grant decisions must be unknown, allowed, or denied",
+ );
+ }
+ return value;
+}
+
+function requirePolicySource(value: unknown): IOSSimulatorGrantPolicySource {
+ if (value !== "user" && value !== "managed-policy") {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "Simulator grant policy source is invalid",
+ );
+ }
+ return value;
+}
+
+function requireIsoDate(value: unknown): string {
+ if (
+ typeof value !== "string" ||
+ !Number.isFinite(Date.parse(value)) ||
+ new Date(Date.parse(value)).toISOString() !== value
+ ) {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "Simulator grant updatedAt must be an ISO date",
+ );
+ }
+ return value;
+}
+
+function copyGrant(grant: IOSSimulatorDeviceGrant): IOSSimulatorDeviceGrant {
+ return { ...grant };
+}
+
+function restoreGrant(grant: IOSSimulatorDeviceGrant): IOSSimulatorDeviceGrant {
+ return {
+ simulatorUdid: requireUdid(grant.simulatorUdid),
+ agentControl: requireDecision(grant.agentControl),
+ screenshotCapture: requireDecision(grant.screenshotCapture),
+ policySource: requirePolicySource(grant.policySource),
+ updatedAt: requireIsoDate(grant.updatedAt),
+ };
+}
+
/** Per-device consent registry, deliberately independent from Session ownership. */
export class IOSSimulatorDeviceGrantStore {
readonly #now: () => number;
+ readonly #onChange: ((grants: IOSSimulatorDeviceGrant[]) => void) | null;
+ readonly #assertMutationAllowed: (() => void) | null;
readonly #grants = new Map<string, IOSSimulatorDeviceGrant>();
constructor(options: IOSSimulatorDeviceGrantStoreOptions = {}) {
this.#now = options.now ?? Date.now;
+ this.#onChange = options.onChange ?? null;
+ this.#assertMutationAllowed = options.assertMutationAllowed ?? null;
+ for (const persisted of options.initialGrants ?? []) {
+ const grant = restoreGrant(persisted);
+ if (this.#grants.has(grant.simulatorUdid)) {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "Persisted simulator grants contain duplicate devices",
+ );
+ }
+ this.#grants.set(grant.simulatorUdid, grant);
+ }
}
get(simulatorUdid: string): IOSSimulatorDeviceGrant {
const udid = requireUdid(simulatorUdid);
- return (
+ return copyGrant(
this.#grants.get(udid) ?? {
simulatorUdid: udid,
agentControl: "unknown",
screenshotCapture: "unknown",
policySource: "user",
updatedAt: new Date(0).toISOString(),
- }
+ },
);
}
+ listAll(): IOSSimulatorDeviceGrant[] {
+ return Array.from(this.#grants.values(), copyGrant);
+ }
+
set(
simulatorUdid: string,
patch: Partial<
@@ -58,14 +130,54 @@ export class IOSSimulatorDeviceGrantStore {
if (current.policySource === "managed-policy" && policySource === "user") {
return current;
}
+ const previous = this.#grants.get(current.simulatorUdid);
const next: IOSSimulatorDeviceGrant = {
...current,
- ...patch,
- policySource,
+ agentControl:
+ patch.agentControl === undefined
+ ? current.agentControl
+ : requireDecision(patch.agentControl),
+ screenshotCapture:
+ patch.screenshotCapture === undefined
+ ? current.screenshotCapture
+ : requireDecision(patch.screenshotCapture),
+ policySource: requirePolicySource(policySource),
updatedAt: new Date(this.#now()).toISOString(),
};
- this.#grants.set(current.simulatorUdid, next);
- return { ...next };
+ try {
+ this.#assertMutationAllowed?.();
+ this.#grants.set(current.simulatorUdid, next);
+ this.#onChange?.(this.listAll());
+ } catch (error) {
+ // A persistence failure must never grant a capability. Roll elevations
+ // back, but retain explicitly non-allowed decisions in memory so a user
+ // revocation takes effect for the rest of this Host lifetime even when
+ // the profile file is temporarily unwritable.
+ const failClosed = copyGrant(current);
+ let retainedRestriction = false;
+ if (patch.agentControl !== undefined && next.agentControl !== "allowed") {
+ failClosed.agentControl = next.agentControl;
+ retainedRestriction = true;
+ }
+ if (
+ patch.screenshotCapture !== undefined &&
+ next.screenshotCapture !== "allowed"
+ ) {
+ failClosed.screenshotCapture = next.screenshotCapture;
+ retainedRestriction = true;
+ }
+ if (retainedRestriction) {
+ failClosed.policySource = next.policySource;
+ failClosed.updatedAt = next.updatedAt;
+ this.#grants.set(current.simulatorUdid, failClosed);
+ } else if (previous) {
+ this.#grants.set(current.simulatorUdid, previous);
+ } else {
+ this.#grants.delete(current.simulatorUdid);
+ }
+ throw error;
+ }
+ return copyGrant(next);
}
requireAgentControl(simulatorUdid: string): IOSSimulatorDeviceGrant {
diff --git a/packages/ios-simulator-runtime/src/index.ts b/packages/ios-simulator-runtime/src/index.ts
index 1ed1a7d03d..f585674628 100644
--- a/packages/ios-simulator-runtime/src/index.ts
+++ b/packages/ios-simulator-runtime/src/index.ts
@@ -4,6 +4,7 @@ export * from "./compatibility.js";
export * from "./compatibility-matrix.js";
export * from "./app-lifecycle.js";
export * from "./device-grant-store.js";
+export * from "./device-grant-registry-file.js";
export * from "./diagnostics-store.js";
export * from "./driver.js";
export * from "./driver-router.js";