From 7f8c9b2b77e5dc66b6e2141b81093f0d3e791777 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 21:56:16 +0200 Subject: [PATCH 01/13] test: a worker with HTTP and agent-device on writes the profile before HTTP listens (#956) --- src/agent-device/local-profile.test.ts | 144 +++++++++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 src/agent-device/local-profile.test.ts diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts new file mode 100644 index 000000000..ce012478b --- /dev/null +++ b/src/agent-device/local-profile.test.ts @@ -0,0 +1,144 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; +import { startDaemon, type StartDaemonOptions } from "../daemon/main.js"; +import type { DaemonServer } from "../daemon/server.js"; +import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import { agentDeviceModuleWith, FakeAgentDevice } from "./testing.js"; + +const runningDaemons: DaemonServer[] = []; +const temporaryDirectories: string[] = []; + +afterEach(async () => { + await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test"))); + await Promise.all( + temporaryDirectories.splice(0).map((path) => rm(path, { force: true, recursive: true })), + ); +}); + +const LABEL = "agent-device on this Mac"; +const adminSession = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "admin", + role: "admin", +} as const; + +async function freeLoopbackPort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (typeof address !== "object" || address === null) throw new Error("no port bound"); + return address.port; +} + +interface Rig { + readonly daemon: DaemonServer; + readonly filesystem: MemoryFilesystem; + readonly profilePath: string; + readonly port: number; +} + +async function launch(host = "127.0.0.1"): Promise { + const directory = await mkdtemp(join(tmpdir(), "simlock-local-profile-")); + temporaryDirectories.push(directory); + const clock = new FakeClock(1_000); + const filesystem = new MemoryFilesystem(); + const port = await freeLoopbackPort(); + const daemon = await startDaemon({ + clock, + configOverrides: { + capabilities: { "agent-device": { enabled: true } }, + http: { enabled: true, host, port }, + }, + dataDirectory: directory, + deviceDataTables: fakeDeviceDataTables, + drivers: [ + new FakeDriver({ + availableOsVersions: ["26.5"], + clock, + defaultModels: { phone: ["iPhone 16"] }, + knownModels: ["iPhone 16"], + modelClasses: { "iPhone 16": "phone" }, + platform: "ios", + }), + ], + filesystem, + logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), + optionalModules: [agentDeviceModuleWith({ upstream: new FakeAgentDevice() })], + version: "1.2.3", + } as StartDaemonOptions); + runningDaemons.push(daemon); + return { daemon, filesystem, port, profilePath: join(directory, "agent-device-profile.json") }; +} + +async function tokens(rig: Rig) { + return (await rig.daemon.dispatch("token.list", {}, adminSession)).tokens; +} + +describe("the local agent-device profile", () => { + it("is written before HTTP listens, and its token leases for a local agent", async () => { + const rig = await launch(); + + const text = await rig.filesystem.readFile(rig.profilePath); + const profile = JSON.parse(text) as Record; + expect((await rig.filesystem.stat(rig.profilePath)).mode).toBe(0o600); + expect(Object.keys(profile)).toEqual([ + "daemonAuthToken", + "daemonBaseUrl", + "daemonTransport", + "leaseProvider", + "runId", + "sessionIsolation", + "tenant", + ]); + expect(text).toBe(`${JSON.stringify(profile, null, 2)}\n`); + expect(profile).toMatchObject({ + daemonBaseUrl: `http://127.0.0.1:${rig.port}/v1/agent-device`, + daemonTransport: "http", + leaseProvider: "proxy", + runId: "simlock-local", + sessionIsolation: "tenant", + tenant: "local", + }); + const labelled = (await tokens(rig)).filter((token) => token.label === LABEL); + expect(labelled).toHaveLength(1); + expect(labelled[0]?.role).toBe("agent"); + + const response = await fetch(`http://127.0.0.1:${rig.port}/v1/agent-device/rpc`, { + body: JSON.stringify({ + id: 1, + jsonrpc: "2.0", + method: "agent_device.lease.allocate", + params: { + clientId: "c", + leaseId: "1".padStart(32, "0"), + leaseProvider: "proxy", + platform: "ios", + runId: "r", + ttlMs: 120_000, + }, + }), + headers: { + authorization: `Bearer ${profile.daemonAuthToken}`, + connection: "close", + "content-type": "application/json", + }, + method: "POST", + }); + expect(((await response.json()) as { result: unknown }).result).toMatchObject({ ok: true }); + const leases = (await rig.daemon.dispatch( + "list.get", + { kind: "leases" }, + adminSession, + )) as never as { + ownerId: string; + }[]; + expect(leases.map((lease) => lease.ownerId)).toEqual([labelled[0]?.id]); + }); +}); From 342b94b969bfd7c16706097a9552835bc42b8f1c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 21:58:01 +0200 Subject: [PATCH 02/13] feat(modules): a worker writes a private agent-device profile (#956) --- src/agent-device/definition.ts | 18 +++++++++++++++ src/agent-device/local-profile.test.ts | 12 ++++++++-- src/auth/index.ts | 1 + src/auth/testing.ts | 2 +- src/auth/tokens.ts | 1 + src/daemon/main.ts | 4 +++- src/daemon/module-shapes.test.ts | 4 ++++ src/gateway/dispatcher.test.ts | 4 ++++ src/modules/conformance.test.ts | 3 ++- src/modules/host.ts | 31 ++++++++++++++++++++++++++ src/modules/index.ts | 3 +++ src/modules/testing.ts | 30 +++++++++++++++++++++++++ src/modules/types.ts | 29 ++++++++++++++++++++++++ 13 files changed, 137 insertions(+), 5 deletions(-) diff --git a/src/agent-device/definition.ts b/src/agent-device/definition.ts index 82d6fef13..94364b488 100644 --- a/src/agent-device/definition.ts +++ b/src/agent-device/definition.ts @@ -36,6 +36,24 @@ export const agentDeviceModule: OptionalModuleDefinition + `${JSON.stringify( + { + daemonAuthToken: secret, + daemonBaseUrl: `${origin}/v1/agent-device`, + daemonTransport: "http", + leaseProvider: "proxy", + runId: "simlock-local", + sessionIsolation: "tenant", + tenant: "local", + }, + null, + 2, + )}\n`, + tokenLabel: "agent-device on this Mac", + }, loadGateway: () => import("./gateway.js"), loadWorker: () => import("./worker.js"), name: "agent-device", diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts index ce012478b..4abf63880 100644 --- a/src/agent-device/local-profile.test.ts +++ b/src/agent-device/local-profile.test.ts @@ -40,6 +40,7 @@ async function freeLoopbackPort(): Promise { interface Rig { readonly daemon: DaemonServer; readonly filesystem: MemoryFilesystem; + readonly logs: MemoryLogSink; readonly profilePath: string; readonly port: number; } @@ -49,6 +50,7 @@ async function launch(host = "127.0.0.1"): Promise { temporaryDirectories.push(directory); const clock = new FakeClock(1_000); const filesystem = new MemoryFilesystem(); + const logs = new MemoryLogSink(); const port = await freeLoopbackPort(); const daemon = await startDaemon({ clock, @@ -69,12 +71,18 @@ async function launch(host = "127.0.0.1"): Promise { }), ], filesystem, - logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), + logger: new JsonLinesLogger({ clock, level: "debug", sink: logs }), optionalModules: [agentDeviceModuleWith({ upstream: new FakeAgentDevice() })], version: "1.2.3", } as StartDaemonOptions); runningDaemons.push(daemon); - return { daemon, filesystem, port, profilePath: join(directory, "agent-device-profile.json") }; + return { + daemon, + filesystem, + logs, + port, + profilePath: join(directory, "agent-device-profile.json"), + }; } async function tokens(rig: Rig) { diff --git a/src/auth/index.ts b/src/auth/index.ts index b6be8399e..3b5cc2830 100644 --- a/src/auth/index.ts +++ b/src/auth/index.ts @@ -110,6 +110,7 @@ export function createAuthFrom( create: (role, label) => store.create(role, label), list: () => store.list(), revoke: (id) => store.revoke(id), + verify: (secret) => store.verify(secret), }, adminSecret: { persist: () => adminSecret.persist(), diff --git a/src/auth/testing.ts b/src/auth/testing.ts index 4f5a89985..fcdd8c5ba 100644 --- a/src/auth/testing.ts +++ b/src/auth/testing.ts @@ -37,7 +37,7 @@ export function fakeAuth(identities: ReadonlyMap): Auth { }, resolveHelloRole: unused, authenticateUplink: unused, - tokens: { create: unused, list: unused, revoke: unused }, + tokens: { create: unused, list: unused, revoke: unused, verify: unused }, adminSecret: { persist: unused, remove: unused }, }; } diff --git a/src/auth/tokens.ts b/src/auth/tokens.ts index d8021569e..ad2de7d6a 100644 --- a/src/auth/tokens.ts +++ b/src/auth/tokens.ts @@ -12,4 +12,5 @@ export interface TokenOperations { create(role: TokenRole, label?: string): Promise<{ record: TokenRecord; secret: string }>; list(): Promise; revoke(id: string): Promise; + verify(secret: string): Promise; } diff --git a/src/daemon/main.ts b/src/daemon/main.ts index ec91fbf7e..a197e7b96 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -518,6 +518,7 @@ async function composeDaemon( }, definitions: moduleDefinitions, logger, + tokens: auth.tokens, role: "worker", }); // Builds leasing on top of core (ADR 0018 §2). @@ -766,8 +767,9 @@ async function composeDaemon( if (gatewayUplink !== undefined) { void (hostLoad?.firstReading() ?? Promise.resolve()).then(() => gatewayUplink.start()); } + const profilesPrepared = moduleHost.prepareLocalProfiles(); if (!config.http.enabled) return; - void startHttpGateway().then( + void profilesPrepared.then(startHttpGateway).then( () => resolveGatewayStarted?.(), (error: unknown) => { logger.error("HTTP frontend failed to start", { message: errorMessage(error) }); diff --git a/src/daemon/module-shapes.test.ts b/src/daemon/module-shapes.test.ts index 9241f4d13..f04ea85bc 100644 --- a/src/daemon/module-shapes.test.ts +++ b/src/daemon/module-shapes.test.ts @@ -1,5 +1,6 @@ import { describe, expectTypeOf, it } from "vitest"; +import type { TokenOperations } from "../auth/index.js"; import type { EndedLease, LeaseEndParticipant } from "../leasing/index.js"; import type { HttpMount } from "../http/app.js"; import type { HttpDispatch } from "../http/dispatcher-session.js"; @@ -10,6 +11,7 @@ import type { ModuleLeaseEndParticipant, ModuleMount, ModuleRelayTarget, + ModuleTokens, } from "../modules/index.js"; import type { CapabilitySource } from "./dispatcher.js"; import type { RelayTarget } from "./relay.js"; @@ -18,6 +20,8 @@ describe("the shapes src/modules declares by shape", () => { it("each by-shape type in src/modules and its original are assignable both ways", () => { expectTypeOf().toExtend(); expectTypeOf().toExtend(); + expectTypeOf().toExtend(); + expectTypeOf().toExtend(); expectTypeOf().toExtend(); expectTypeOf().toExtend(); expectTypeOf().toExtend(); diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 1f7189ccf..fe8d1a3d7 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -125,6 +125,10 @@ class FakeTokens implements TokenOperations { }; } + async verify(): Promise { + return undefined; + } + async list() { return [ { createdAt: 1, hash: "unused", id: "tok_1", role: "worker" as const }, diff --git a/src/modules/conformance.test.ts b/src/modules/conformance.test.ts index 466be9df7..85be96841 100644 --- a/src/modules/conformance.test.ts +++ b/src/modules/conformance.test.ts @@ -9,7 +9,7 @@ import { type OptionalModuleDefinition, type WorkerView, } from "./index.js"; -import { fakeGatewayContext, fakeModule, fakeWorkerContext } from "./testing.js"; +import { fakeGatewayContext, fakeModule, fakeModuleTokens, fakeWorkerContext } from "./testing.js"; const HOOK_DEADLINE_MS = 30_000; @@ -76,6 +76,7 @@ describe("every optional module's contract", () => { definitions: [definition], logger: new NoopLogger(), role: "worker", + tokens: fakeModuleTokens(), }); expect(loadWorker).not.toHaveBeenCalled(); diff --git a/src/modules/host.ts b/src/modules/host.ts index 5e2ab80b2..e11d4688a 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -1,3 +1,5 @@ +import { join } from "node:path"; + import { CORE_ROUTE_SEGMENTS, MAX_CAPABILITIES, capabilityNameSchema } from "../contract/index.js"; import type { Clock, Logger } from "../ports/index.js"; import type { @@ -15,6 +17,26 @@ import type { WorkerModule, } from "./types.js"; +function profileOrigin(host: string, port: number): string { + const reachable = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host; + return `http://${reachable.includes(":") ? `[${reachable}]` : reachable}:${String(port)}`; +} + +async function writeLocalProfile( + definition: OptionalModuleDefinition, + options: ModuleHostOptions, +): Promise { + const { localProfile } = definition; + if (localProfile === undefined) return; + const { tokens } = options; + const { secret } = await tokens.create("agent", localProfile.tokenLabel); + await options.context.filesystem.writeFileAtomic( + join(options.context.dataDirectory, localProfile.fileName), + localProfile.render(profileOrigin(options.config.http.host, options.config.http.port), secret), + { mode: 0o600 }, + ); +} + const HOOK_DEADLINE_MS = 30_000; interface Started { @@ -260,6 +282,15 @@ async function createWorkerHost(options: ModuleHostOptions): Promise if (call !== undefined) void runHook(logger, name, "afterSocketClaimed", () => call()); } }, + async prepareLocalProfiles(): Promise { + for (const definition of definitions) { + try { + await writeLocalProfile(definition, options); + } catch (error: unknown) { + logger.warn(`Could not prepare the ${definition.name} profile: ${messageOf(error)}`); + } + } + }, beforeDrain: () => runStopStep("beforeDrain"), beforeDriversDispose: () => runStopStep("beforeDriversDispose"), capabilitySources, diff --git a/src/modules/index.ts b/src/modules/index.ts index 4e3e7b5a1..2aaaad379 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -13,9 +13,12 @@ export type { ModuleFinding, ModuleHttpResponse, ModuleLeaseEndParticipant, + ModuleLocalProfile, ModuleMount, ModuleRegistryView, ModuleRelayTarget, + ModuleTokenRecord, + ModuleTokens, OptionalModuleDefinition, WorkerContext, WorkerHooks, diff --git a/src/modules/testing.ts b/src/modules/testing.ts index 17974619b..08ad8bc50 100644 --- a/src/modules/testing.ts +++ b/src/modules/testing.ts @@ -15,6 +15,8 @@ import type { GatewayContext, GatewayModule, ModuleFinding, + ModuleTokenRecord, + ModuleTokens, OptionalModuleDefinition, WorkerContext, WorkerHooks, @@ -121,6 +123,34 @@ export function fakeModule(options: FakeModuleOptions): FakeModule { return fake; } +// why: secrets are `secret-`, and a revoked one stops verifying, as in the real store. +export function fakeModuleTokens(): ModuleTokens { + const records = new Map(); + let next = 1; + return { + create: (role, label) => { + const id = `tok_${String(next)}`; + const entry = { + record: { + createdAt: 1, + hash: "unused", + id, + role, + ...(label === undefined ? {} : { label }), + }, + secret: `secret-${String(next)}`, + }; + next += 1; + records.set(id, entry); + return Promise.resolve(entry); + }, + list: () => Promise.resolve([...records.values()].map(({ record }) => record)), + revoke: (id) => Promise.resolve(records.delete(id)), + verify: (secret) => + Promise.resolve([...records.values()].find((entry) => entry.secret === secret)?.record), + }; +} + export interface FakeWorkerContext { readonly ctx: WorkerContext; readonly clock: FakeClock; diff --git a/src/modules/types.ts b/src/modules/types.ts index 77e950807..e3336690b 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -216,9 +216,36 @@ export interface ModuleHttpRoute { readonly statuses: Readonly>; } +// why: a by-shape copy of the auth module's token operations, so a module host mints and checks tokens without importing auth. +export interface ModuleTokenRecord { + readonly id: string; + readonly hash: string; + readonly role: "agent" | "operator" | "worker"; + readonly label?: string; + readonly createdAt: number; +} + +export interface ModuleTokens { + create( + role: ModuleTokenRecord["role"], + label?: string, + ): Promise<{ record: ModuleTokenRecord; secret: string }>; + list(): Promise; + revoke(id: string): Promise; + verify(secret: string): Promise; +} + +// why: plain data in a `definition.ts`: the host keeps this file for local agents, loading none of the module's code. +export interface ModuleLocalProfile { + readonly fileName: string; + readonly tokenLabel: string; + render(origin: string, secret: string): string; +} + export interface OptionalModuleDefinition { readonly name: string; readonly config: ModuleConfig; + readonly localProfile?: ModuleLocalProfile; readonly http?: { readonly routes: readonly ModuleHttpRoute[] }; loadWorker(): Promise<{ createWorker(ctx: WorkerContext): WorkerModule }>; loadGateway?(): Promise<{ createGateway(ctx: GatewayContext): GatewayModule }>; @@ -236,6 +263,7 @@ export interface ModuleHost { readonly remedy: string; }[]; afterSocketClaimed(): void; + prepareLocalProfiles(): Promise; beforeDrain(): Promise; beforeDriversDispose(): Promise; } @@ -279,5 +307,6 @@ export interface ModuleHostOptions { readonly definitions: readonly OptionalModuleDefinition[]; readonly config: Config; readonly logger: Logger; + readonly tokens: ModuleTokens; readonly context: Omit, "name" | "config" | "daemonConfig" | "logger">; } From 5090b39b093c5f6eef5e8b2334739dce7f299e79 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 21:59:04 +0200 Subject: [PATCH 03/13] feat(modules): the profile host table and operator labelled tokens (#956) --- src/agent-device/local-profile.test.ts | 23 +++++++++++++++++++++-- src/auth/testing.ts | 8 ++++---- src/modules/host.ts | 7 ++++++- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts index 4abf63880..d92a8c4f3 100644 --- a/src/agent-device/local-profile.test.ts +++ b/src/agent-device/local-profile.test.ts @@ -8,6 +8,7 @@ import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; import { startDaemon, type StartDaemonOptions } from "../daemon/main.js"; import type { DaemonServer } from "../daemon/server.js"; import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import { seedTokensDatabase } from "../auth/testing.js"; import { agentDeviceModuleWith, FakeAgentDevice } from "./testing.js"; const runningDaemons: DaemonServer[] = []; @@ -45,12 +46,16 @@ interface Rig { readonly port: number; } -async function launch(host = "127.0.0.1"): Promise { +async function launch( + host = "127.0.0.1", + seed: Parameters[1] = [], +): Promise { const directory = await mkdtemp(join(tmpdir(), "simlock-local-profile-")); temporaryDirectories.push(directory); const clock = new FakeClock(1_000); const filesystem = new MemoryFilesystem(); const logs = new MemoryLogSink(); + await seedTokensDatabase(directory, seed); const port = await freeLoopbackPort(); const daemon = await startDaemon({ clock, @@ -91,7 +96,7 @@ async function tokens(rig: Rig) { describe("the local agent-device profile", () => { it("is written before HTTP listens, and its token leases for a local agent", async () => { - const rig = await launch(); + const rig = await launch("127.0.0.1", [["tok_operator", "slk_operator", "operator", LABEL]]); const text = await rig.filesystem.readFile(rig.profilePath); const profile = JSON.parse(text) as Record; @@ -117,6 +122,7 @@ describe("the local agent-device profile", () => { const labelled = (await tokens(rig)).filter((token) => token.label === LABEL); expect(labelled).toHaveLength(1); expect(labelled[0]?.role).toBe("agent"); + expect(labelled[0]?.id).not.toBe("tok_operator"); const response = await fetch(`http://127.0.0.1:${rig.port}/v1/agent-device/rpc`, { body: JSON.stringify({ @@ -148,5 +154,18 @@ describe("the local agent-device profile", () => { ownerId: string; }[]; expect(leases.map((lease) => lease.ownerId)).toEqual([labelled[0]?.id]); + + const bases = [ + ["0.0.0.0", "http://127.0.0.1"], + ["::", "http://127.0.0.1"], + ["::1", "http://[::1]"], + ] as const; + for (const [host, origin] of bases) { + const other = await launch(host); + const written = JSON.parse(await other.filesystem.readFile(other.profilePath)) as { + daemonBaseUrl: string; + }; + expect(written.daemonBaseUrl, host).toBe(`${origin}:${other.port}/v1/agent-device`); + } }); }); diff --git a/src/auth/testing.ts b/src/auth/testing.ts index fcdd8c5ba..f5013282e 100644 --- a/src/auth/testing.ts +++ b/src/auth/testing.ts @@ -142,7 +142,7 @@ export function openMemoryStateDatabase( /** why: the daemon opens `state.db` itself, so a test that starts one with known tokens writes them to the file first. */ export async function seedTokensDatabase( directory: string, - records: readonly (readonly [id: string, secret: string, role: TokenRole])[], + records: readonly (readonly [id: string, secret: string, role: TokenRole, label?: string])[], ): Promise { const hasher = new CryptoTokenSecrets(); const state = await openStateDatabase({ @@ -155,12 +155,12 @@ export async function seedTokensDatabase( upgradeStep: "", }); try { - for (const [id, secret, role] of records) { + for (const [id, secret, role, label] of records) { state.database .prepare( - "INSERT OR REPLACE INTO tokens (id, hash, role, label, created_at) VALUES (?, ?, ?, NULL, 0)", + "INSERT OR REPLACE INTO tokens (id, hash, role, label, created_at) VALUES (?, ?, ?, ?, 0)", ) - .run(id, hasher.hash(secret), role); + .run(id, hasher.hash(secret), role, label ?? null); } } finally { state.close(); diff --git a/src/modules/host.ts b/src/modules/host.ts index e11d4688a..c5e985944 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -29,7 +29,12 @@ async function writeLocalProfile( const { localProfile } = definition; if (localProfile === undefined) return; const { tokens } = options; - const { secret } = await tokens.create("agent", localProfile.tokenLabel); + const { record, secret } = await tokens.create("agent", localProfile.tokenLabel); + for (const other of await tokens.list()) { + if (other.label === localProfile.tokenLabel && other.id !== record.id) { + await tokens.revoke(other.id); + } + } await options.context.filesystem.writeFileAtomic( join(options.context.dataDirectory, localProfile.fileName), localProfile.render(profileOrigin(options.config.http.host, options.config.http.port), secret), From e6dc7b3e7108870410b41db7e235b0ced23cb155 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:00:04 +0200 Subject: [PATCH 04/13] test: a restart keeps the profile, and a token that no longer verifies is replaced (#956) --- src/agent-device/local-profile.test.ts | 150 +++++++++++++++++++------ 1 file changed, 118 insertions(+), 32 deletions(-) diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts index d92a8c4f3..24c3ac4d9 100644 --- a/src/agent-device/local-profile.test.ts +++ b/src/agent-device/local-profile.test.ts @@ -44,19 +44,28 @@ interface Rig { readonly logs: MemoryLogSink; readonly profilePath: string; readonly port: number; + readonly restart: (options?: { readonly port?: number }) => Promise; } -async function launch( - host = "127.0.0.1", - seed: Parameters[1] = [], -): Promise { - const directory = await mkdtemp(join(tmpdir(), "simlock-local-profile-")); - temporaryDirectories.push(directory); +interface LaunchOptions { + readonly host?: string; + readonly seed?: Parameters[1]; + readonly port?: number; + readonly resume?: { readonly directory: string; readonly filesystem: MemoryFilesystem }; +} + +async function launch(options: LaunchOptions = {}): Promise { + const host = options.host ?? "127.0.0.1"; + const directory = + options.resume?.directory ?? (await mkdtemp(join(tmpdir(), "simlock-local-profile-"))); const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); + const filesystem = options.resume?.filesystem ?? new MemoryFilesystem(); const logs = new MemoryLogSink(); - await seedTokensDatabase(directory, seed); - const port = await freeLoopbackPort(); + if (options.resume === undefined) { + temporaryDirectories.push(directory); + await seedTokensDatabase(directory, options.seed ?? []); + } + const port = options.port ?? (await freeLoopbackPort()); const daemon = await startDaemon({ clock, configOverrides: { @@ -87,6 +96,14 @@ async function launch( logs, port, profilePath: join(directory, "agent-device-profile.json"), + restart: async (restartOptions = {}) => { + await daemon.stop("test"); + return launch({ + host, + port: restartOptions.port ?? port, + resume: { directory, filesystem }, + }); + }, }; } @@ -94,9 +111,33 @@ async function tokens(rig: Rig) { return (await rig.daemon.dispatch("token.list", {}, adminSession)).tokens; } +function allocateWith(rig: Rig, secret: string, n: number): Promise { + return fetch(`http://127.0.0.1:${rig.port}/v1/agent-device/rpc`, { + body: JSON.stringify({ + id: 1, + jsonrpc: "2.0", + method: "agent_device.lease.allocate", + params: { + clientId: "c", + leaseId: n.toString(16).padStart(32, "0"), + leaseProvider: "proxy", + platform: "ios", + runId: "r", + ttlMs: 120_000, + }, + }), + headers: { + authorization: `Bearer ${secret}`, + connection: "close", + "content-type": "application/json", + }, + method: "POST", + }); +} + describe("the local agent-device profile", () => { it("is written before HTTP listens, and its token leases for a local agent", async () => { - const rig = await launch("127.0.0.1", [["tok_operator", "slk_operator", "operator", LABEL]]); + const rig = await launch({ seed: [["tok_operator", "slk_operator", "operator", LABEL]] }); const text = await rig.filesystem.readFile(rig.profilePath); const profile = JSON.parse(text) as Record; @@ -124,27 +165,7 @@ describe("the local agent-device profile", () => { expect(labelled[0]?.role).toBe("agent"); expect(labelled[0]?.id).not.toBe("tok_operator"); - const response = await fetch(`http://127.0.0.1:${rig.port}/v1/agent-device/rpc`, { - body: JSON.stringify({ - id: 1, - jsonrpc: "2.0", - method: "agent_device.lease.allocate", - params: { - clientId: "c", - leaseId: "1".padStart(32, "0"), - leaseProvider: "proxy", - platform: "ios", - runId: "r", - ttlMs: 120_000, - }, - }), - headers: { - authorization: `Bearer ${profile.daemonAuthToken}`, - connection: "close", - "content-type": "application/json", - }, - method: "POST", - }); + const response = await allocateWith(rig, profile.daemonAuthToken ?? "", 1); expect(((await response.json()) as { result: unknown }).result).toMatchObject({ ok: true }); const leases = (await rig.daemon.dispatch( "list.get", @@ -161,11 +182,76 @@ describe("the local agent-device profile", () => { ["::1", "http://[::1]"], ] as const; for (const [host, origin] of bases) { - const other = await launch(host); + const other = await launch({ host }); const written = JSON.parse(await other.filesystem.readFile(other.profilePath)) as { daemonBaseUrl: string; }; expect(written.daemonBaseUrl, host).toBe(`${origin}:${other.port}/v1/agent-device`); } }); + + it("keeps the profile across a restart, and replaces a token that no longer verifies", async () => { + const readProfile = async (rig: Rig) => { + const text = await rig.filesystem.readFile(rig.profilePath); + return { + profile: JSON.parse(text) as { daemonAuthToken: string; daemonBaseUrl: string }, + text, + }; + }; + const labelledIds = async (rig: Rig) => + (await tokens(rig)).filter((token) => token.label === LABEL).map((token) => token.id); + + const first = await launch(); + const before = await readProfile(first); + const [tokenId] = await labelledIds(first); + await first.daemon.dispatch("token.create", { label: LABEL, role: "operator" }, adminSession); + expect(await labelledIds(first)).toHaveLength(2); + + const same = await first.restart(); + expect((await readProfile(same)).text).toBe(before.text); + expect(await labelledIds(same)).toEqual([tokenId]); + + const port = await freeLoopbackPort(); + const moved = await same.restart({ port }); + const after = await readProfile(moved); + expect(after.profile.daemonBaseUrl).toBe(`http://127.0.0.1:${port}/v1/agent-device`); + expect(after.profile.daemonAuthToken).toBe(before.profile.daemonAuthToken); + expect(await labelledIds(moved)).toEqual([tokenId]); + + const breakers: [string, (rig: Rig) => Promise][] = [ + [ + "revoked", + async (rig) => { + await rig.daemon.dispatch("token.revoke", { id: tokenId ?? "" }, adminSession); + }, + ], + ["deleted", (rig) => rig.filesystem.rm(rig.profilePath)], + ["not JSON", (rig) => rig.filesystem.writeFileAtomic(rig.profilePath, "not json")], + [ + "unlabelled", + async (rig) => { + const made = await rig.daemon.dispatch("token.create", { role: "agent" }, adminSession); + await rig.filesystem.writeFileAtomic( + rig.profilePath, + JSON.stringify({ daemonAuthToken: made.secret }), + ); + }, + ], + ]; + let current = moved; + for (const [name, breakIt] of breakers) { + const lastToken = (await readProfile(current)).profile.daemonAuthToken; + await current.daemon.dispatch("token.create", { label: LABEL, role: "agent" }, adminSession); + await breakIt(current); + current = await current.restart(); + const replaced = await readProfile(current); + const ids = await labelledIds(current); + expect(ids, name).toHaveLength(1); + expect(replaced.profile.daemonAuthToken, name).not.toBe(lastToken); + expect(ids[0], name).not.toBe(tokenId); + expect((await allocateWith(current, replaced.profile.daemonAuthToken, 2)).status, name).toBe( + 200, + ); + } + }); }); From fc8093d63e2e3fe8a9906e5653b25d8ce199170c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:00:20 +0200 Subject: [PATCH 05/13] feat(modules): the profile token is kept across restarts (#956) --- src/modules/host.ts | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/src/modules/host.ts b/src/modules/host.ts index c5e985944..c4f82a1c1 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -1,7 +1,7 @@ import { join } from "node:path"; import { CORE_ROUTE_SEGMENTS, MAX_CAPABILITIES, capabilityNameSchema } from "../contract/index.js"; -import type { Clock, Logger } from "../ports/index.js"; +import type { Clock, Filesystem, Logger } from "../ports/index.js"; import type { GatewayHostOptions, GatewayModule, @@ -22,6 +22,22 @@ function profileOrigin(host: string, port: number): string { return `http://${reachable.includes(":") ? `[${reachable}]` : reachable}:${String(port)}`; } +async function readProfileSecret( + filesystem: Filesystem, + path: string, +): Promise { + try { + const parsed: unknown = JSON.parse(await filesystem.readFile(path)); + const secret = + typeof parsed === "object" && parsed !== null + ? (parsed as { daemonAuthToken?: unknown }).daemonAuthToken + : undefined; + return typeof secret === "string" ? secret : undefined; + } catch { + return undefined; + } +} + async function writeLocalProfile( definition: OptionalModuleDefinition, options: ModuleHostOptions, @@ -29,17 +45,24 @@ async function writeLocalProfile( const { localProfile } = definition; if (localProfile === undefined) return; const { tokens } = options; - const { record, secret } = await tokens.create("agent", localProfile.tokenLabel); + const { filesystem } = options.context; + const path = join(options.context.dataDirectory, localProfile.fileName); + const stored = await readProfileSecret(filesystem, path); + const verified = stored === undefined ? undefined : await tokens.verify(stored); + const kept = verified?.label === localProfile.tokenLabel ? verified : undefined; + const made = + kept === undefined ? await tokens.create("agent", localProfile.tokenLabel) : undefined; + const id = kept?.id ?? made?.record.id; + const secret = made?.secret ?? stored ?? ""; for (const other of await tokens.list()) { - if (other.label === localProfile.tokenLabel && other.id !== record.id) { - await tokens.revoke(other.id); - } + if (other.label === localProfile.tokenLabel && other.id !== id) await tokens.revoke(other.id); } - await options.context.filesystem.writeFileAtomic( - join(options.context.dataDirectory, localProfile.fileName), - localProfile.render(profileOrigin(options.config.http.host, options.config.http.port), secret), - { mode: 0o600 }, + const contents = localProfile.render( + profileOrigin(options.config.http.host, options.config.http.port), + secret, ); + if (kept !== undefined && (await filesystem.readFile(path)) === contents) return; + await filesystem.writeFileAtomic(path, contents, { mode: 0o600 }); } const HOOK_DEADLINE_MS = 30_000; From a9188cd3e6697a2c5ea10e0a25de47ee997fe4b8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:00:44 +0200 Subject: [PATCH 06/13] test: the profile is withdrawn where HTTP or agent-device is off (#956) --- src/agent-device/local-profile.test.ts | 38 +++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts index 24c3ac4d9..20b167f59 100644 --- a/src/agent-device/local-profile.test.ts +++ b/src/agent-device/local-profile.test.ts @@ -44,10 +44,16 @@ interface Rig { readonly logs: MemoryLogSink; readonly profilePath: string; readonly port: number; - readonly restart: (options?: { readonly port?: number }) => Promise; + readonly restart: (options?: Switches & { readonly port?: number }) => Promise; } -interface LaunchOptions { +interface Switches { + readonly http?: boolean; + readonly agentDevice?: boolean; + readonly role?: "gateway"; +} + +interface LaunchOptions extends Switches { readonly host?: string; readonly seed?: Parameters[1]; readonly port?: number; @@ -69,9 +75,10 @@ async function launch(options: LaunchOptions = {}): Promise { const daemon = await startDaemon({ clock, configOverrides: { - capabilities: { "agent-device": { enabled: true } }, - http: { enabled: true, host, port }, + capabilities: { "agent-device": { enabled: options.agentDevice ?? true } }, + http: { enabled: options.http ?? true, host, port }, }, + ...(options.role === undefined ? {} : { role: options.role }), dataDirectory: directory, deviceDataTables: fakeDeviceDataTables, drivers: [ @@ -100,6 +107,7 @@ async function launch(options: LaunchOptions = {}): Promise { await daemon.stop("test"); return launch({ host, + ...restartOptions, port: restartOptions.port ?? port, resume: { directory, filesystem }, }); @@ -254,4 +262,26 @@ describe("the local agent-device profile", () => { ); } }); + + it("is withdrawn where it does not apply: HTTP off, agent-device off, a gateway", async () => { + const withdrawals: [string, Switches][] = [ + ["HTTP off", { http: false }], + ["agent-device off", { agentDevice: false }], + ]; + for (const [name, off] of withdrawals) { + const on = await launch(); + expect(await on.filesystem.exists(on.profilePath), name).toBe(true); + + const withdrawn = await on.restart(off); + + expect(await withdrawn.filesystem.exists(withdrawn.profilePath), name).toBe(false); + expect( + (await tokens(withdrawn)).filter((token) => token.label === LABEL), + name, + ).toEqual([]); + } + + const gateway = await launch({ role: "gateway" }); + expect(await gateway.filesystem.exists(gateway.profilePath)).toBe(false); + }); }); From 293bf4e2b6b7bff0df48c48ea4b72f510c69c753 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:00:59 +0200 Subject: [PATCH 07/13] feat(modules): withdraw the profile where it does not apply (#956) --- src/modules/host.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/modules/host.ts b/src/modules/host.ts index c4f82a1c1..322c8d16b 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -38,7 +38,7 @@ async function readProfileSecret( } } -async function writeLocalProfile( +async function prepareLocalProfile( definition: OptionalModuleDefinition, options: ModuleHostOptions, ): Promise { @@ -47,6 +47,16 @@ async function writeLocalProfile( const { tokens } = options; const { filesystem } = options.context; const path = join(options.context.dataDirectory, localProfile.fileName); + if ( + options.config.capabilities[definition.name]?.enabled !== true || + !options.config.http.enabled + ) { + if (await filesystem.exists(path)) await filesystem.rm(path); + for (const other of await tokens.list()) { + if (other.label === localProfile.tokenLabel) await tokens.revoke(other.id); + } + return; + } const stored = await readProfileSecret(filesystem, path); const verified = stored === undefined ? undefined : await tokens.verify(stored); const kept = verified?.label === localProfile.tokenLabel ? verified : undefined; @@ -313,7 +323,7 @@ async function createWorkerHost(options: ModuleHostOptions): Promise async prepareLocalProfiles(): Promise { for (const definition of definitions) { try { - await writeLocalProfile(definition, options); + await prepareLocalProfile(definition, options); } catch (error: unknown) { logger.warn(`Could not prepare the ${definition.name} profile: ${messageOf(error)}`); } From 6e1dfdb69061ccec84438867bc0961b308306326 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:01:32 +0200 Subject: [PATCH 08/13] test: a failure preparing the profile does not stop the worker (#956) --- src/agent-device/local-profile.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts index 20b167f59..ac0b707d7 100644 --- a/src/agent-device/local-profile.test.ts +++ b/src/agent-device/local-profile.test.ts @@ -54,6 +54,7 @@ interface Switches { } interface LaunchOptions extends Switches { + readonly refuseWrite?: boolean; readonly host?: string; readonly seed?: Parameters[1]; readonly port?: number; @@ -72,6 +73,9 @@ async function launch(options: LaunchOptions = {}): Promise { await seedTokensDatabase(directory, options.seed ?? []); } const port = options.port ?? (await freeLoopbackPort()); + if (options.refuseWrite === true) { + filesystem.defineFailure(join(directory, "agent-device-profile.json"), "EACCES"); + } const daemon = await startDaemon({ clock, configOverrides: { @@ -284,4 +288,20 @@ describe("the local agent-device profile", () => { const gateway = await launch({ role: "gateway" }); expect(await gateway.filesystem.exists(gateway.profilePath)).toBe(false); }); + + it("does not stop the worker when the profile cannot be written, and logs one warning", async () => { + const rig = await launch({ refuseWrite: true }); + + const warnings = rig.logs.records.filter((record) => + record.message.startsWith("Could not prepare"), + ); + expect(warnings.map((record) => [record.level, record.message])).toEqual([ + [ + "warn", + `Could not prepare the agent-device profile: Injected EACCES failure: ${rig.profilePath}`, + ], + ]); + const made = await rig.daemon.dispatch("token.create", { role: "agent" }, adminSession); + expect((await allocateWith(rig, made.secret, 1)).status).toBe(200); + }); }); From ae685f3a1e3106c85c698dc7ecf1898a63efdf8b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:02:21 +0200 Subject: [PATCH 09/13] docs: the local agent-device profile (#956) --- src/agent-device/AGENTS.md | 4 +++- src/auth/AGENTS.md | 2 +- src/modules/AGENTS.md | 11 ++++++----- .../docs/docs/using-devices/agent-device.mdx | 15 +++++++++++++++ 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index d283f8730..4c4a2215c 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -10,7 +10,7 @@ Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no | File | Role | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `definition.ts` | `agentDeviceModule`: config, defaults, cap check; loads `worker.ts` only when on | +| `definition.ts` | `agentDeviceModule`: config, defaults, cap check, `localProfile` (file name, token label, `render`); loads `worker.ts` only when on | | `worker.ts` | `createWorker`: both supervisors, edge parts, capability, relay target, mount, hooks | | `host/agent-device-supervisor.ts` | Reap, start, watch, stop one role's daemon (`simulators` or `phones`); availability state | | `host/install.ts` | `findAgentDevice`: command → install root → daemon entry | @@ -133,6 +133,8 @@ under leasing's signal (`lease.endWaitMs`). Disk: `/agent-device/` and `/agent-device-phones/` (agent-device's own files) and the two pid records. Front map, renewals and release scopes: memory only. +Local profile: a standalone worker with HTTP and this module on keeps `/agent-device-profile.json` (0600) so an agent on the same Mac connects with `agent-device connect --remote-config ` and no token of its own ([ADR 0046](../../docs/internal/adr/0046-a-local-agent-reaches-agent-device-without-a-token.md)). `definition.ts` declares the file as plain data; the module host writes it at each start, reuses the one `agent`-role token labelled `agent-device on this Mac` (so an agent's saved connection stays valid), revokes other tokens with that label, and deletes the file and revokes the token when HTTP or the module is off. No worker code runs for it. + ## Rules - The simlock lease is the only clock; an agent-device lease never outlives it. diff --git a/src/auth/AGENTS.md b/src/auth/AGENTS.md index 00193b210..c7358e58f 100644 --- a/src/auth/AGENTS.md +++ b/src/auth/AGENTS.md @@ -31,7 +31,7 @@ Decision: [ADR 0033](../../docs/internal/adr/0033-a-sign-in-proxy-is-a-second-wa | `authenticateRequest` | Asks the enabled strategies in registry order; returns `Identity` or throws `AuthError` | | `resolveHelloRole` | No credential → `agent`; operator token or admin secret → `admin`; else `AdminAuthenticationFailedError` | | `authenticateUplink` | None or unknown → `unauthenticated`; not a `worker` token → `forbidden`; else accept with the token id | -| `tokens` | `create`, `list`, `revoke` (both dispatchers) | +| `tokens` | `create`, `list`, `revoke` (both dispatchers); `verify` (the module host, for a local profile) | | `adminSecret` | `persist`, `remove` (`DaemonServer`) | ## Strategies diff --git a/src/modules/AGENTS.md b/src/modules/AGENTS.md index fc03ad010..435e1ad45 100644 --- a/src/modules/AGENTS.md +++ b/src/modules/AGENTS.md @@ -7,11 +7,11 @@ Imported by: `daemon/main.ts` (the factory and types); on a gateway it is handed ## Files -| File | Role | -| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `types.ts` | `OptionalModuleDefinition` (with optional `http` route data, read only by the OpenAPI document), `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `WorkerContext`, the by-shape copies | -| `host.ts` | `createModuleHost`: checks names, loads turned-on modules (`role: "worker"` or `"gateway"`), runs hooks; a gateway host runs `beforeDrain` under the same 30 s deadline | -| `testing.ts` | Fake module and context for tests and the conformance suite | +| File | Role | +| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `types.ts` | `OptionalModuleDefinition` (with optional `http` route data, read only by the OpenAPI document, and optional `localProfile` data), `ModuleTokens`, `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `WorkerContext`, the by-shape copies | +| `host.ts` | `createModuleHost`: checks names, loads turned-on modules (`role: "worker"` or `"gateway"`), runs hooks, and on a worker `prepareLocalProfiles` (below); a gateway host runs `beforeDrain` under the same 30 s deadline | +| `testing.ts` | Fake module and context for tests and the conformance suite | ## Rules @@ -19,4 +19,5 @@ Imported by: `daemon/main.ts` (the factory and types); on a gateway it is handed - Names: the capability name pattern, unique, not a core route segment, at most 16 capabilities. - Creating starts nothing. A start that fails before the socket is claimed drops created modules; after it, the normal stop runs their stop hooks. - Hooks are direct calls. `afterSocketClaimed` is not awaited; `beforeDrain` and `beforeDriversDispose` share one 30 s budget per step; a throw is logged and the step goes on. +- A definition with `localProfile` has a file in the data directory that the worker host keeps for local agents: `prepareLocalProfiles` (awaited by `daemon/main.ts` after the socket claim and before HTTP starts) writes it with one `agent` token labelled `localProfile.tokenLabel` when `http.enabled` and the module are on, and deletes it and revokes labelled tokens otherwise, for an off module too. A failure logs one `warn` and the start goes on. - Each by-shape type (`Module*`) has a type test in `src/daemon/module-shapes.test.ts` against its original. diff --git a/website/src/content/docs/docs/using-devices/agent-device.mdx b/website/src/content/docs/docs/using-devices/agent-device.mdx index b038eb8f3..bfad4836e 100644 --- a/website/src/content/docs/docs/using-devices/agent-device.mdx +++ b/website/src/content/docs/docs/using-devices/agent-device.mdx @@ -98,6 +98,21 @@ The URL is the worker's HTTP address, or the gateway's (port 4700 by default), f - **`install` sends the app from your machine.** The path is on the agent's machine, and agent-device uploads it. A path on the worker is refused with `refused: send the app from your machine as an upload`. - **`devices` lists only your devices**, and an empty list before `open`. +## On the same Mac + +On a standalone worker with HTTP and agent-device turned on, an agent on the same Mac, running as the same user, needs no token of its own. At each start the worker writes `agent-device-profile.json` in its data directory (`~/.simlock/` for a user session), readable only by its user. It holds the worker's agent-device URL and one agent token, labelled `agent-device on this Mac`. Connect with that file: + +```sh +agent-device connect --remote-config ~/.simlock/agent-device-profile.json --session s1 +agent-device open --platform ios --session s1 +agent-device snapshot --session s1 +agent-device close --session s1 +``` + +Pass `--session` on every command. All local agents share the profile's one token, so they share one Simlock identity: give each agent its own `--session` name, or two agents will see each other's devices. + +The worker keeps the same token across restarts, so a saved connection keeps working. If the file changes anyway (you changed `http.port`, or revoked the token with `simlock token revoke`), agent-device refuses the saved connection with `Active remote connection config changed`. Run `agent-device connect --remote-config ~/.simlock/agent-device-profile.json --session s1 --force` to refresh it. The worker removes the file and revokes the token when HTTP or agent-device is turned off. A worker that joins a gateway writes none. Do not give your own tokens the label `agent-device on this Mac`: the worker revokes them at the next start. + ## Through a gateway Point `connect proxy` at the gateway and use a token created on the gateway. `open` lands on a worker whose agent-device is available, and every later command for that device goes to the same worker. You never name a worker. From d730b42d301d6fb9f8203319b1dfb5b76438d121 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:03:18 +0200 Subject: [PATCH 10/13] refactor(modules): split the local profile step (#956) --- src/agent-device/AGENTS.md | 2 +- src/agent-device/local-profile.test.ts | 18 +++-- src/modules/host.ts | 72 +++++++++++-------- src/modules/index.ts | 1 - .../docs/docs/using-devices/agent-device.mdx | 2 +- 5 files changed, 54 insertions(+), 41 deletions(-) diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index 4c4a2215c..55b95c23f 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -133,7 +133,7 @@ under leasing's signal (`lease.endWaitMs`). Disk: `/agent-device/` and `/agent-device-phones/` (agent-device's own files) and the two pid records. Front map, renewals and release scopes: memory only. -Local profile: a standalone worker with HTTP and this module on keeps `/agent-device-profile.json` (0600) so an agent on the same Mac connects with `agent-device connect --remote-config ` and no token of its own ([ADR 0046](../../docs/internal/adr/0046-a-local-agent-reaches-agent-device-without-a-token.md)). `definition.ts` declares the file as plain data; the module host writes it at each start, reuses the one `agent`-role token labelled `agent-device on this Mac` (so an agent's saved connection stays valid), revokes other tokens with that label, and deletes the file and revokes the token when HTTP or the module is off. No worker code runs for it. +Local profile: a standalone worker with HTTP and this module on keeps `/agent-device-profile.json` (0600) so an agent on the same Mac connects with `agent-device connect --remote-config ` and no token of its own ([ADR 0046](../../docs/internal/adr/0046-a-standalone-worker-serves-agent-device-by-default-with-a-private-profile.md)). `definition.ts` declares the file as plain data; the module host writes it at each start, reuses the one `agent`-role token labelled `agent-device on this Mac` (so an agent's saved connection stays valid), revokes other tokens with that label, and deletes the file and revokes the token when HTTP or the module is off. No worker code runs for it. ## Rules diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts index ac0b707d7..8484b2db2 100644 --- a/src/agent-device/local-profile.test.ts +++ b/src/agent-device/local-profile.test.ts @@ -61,17 +61,21 @@ interface LaunchOptions extends Switches { readonly resume?: { readonly directory: string; readonly filesystem: MemoryFilesystem }; } +async function dataDirectoryFor( + options: LaunchOptions, +): Promise<{ directory: string; filesystem: MemoryFilesystem }> { + if (options.resume !== undefined) return options.resume; + const directory = await mkdtemp(join(tmpdir(), "simlock-local-profile-")); + temporaryDirectories.push(directory); + await seedTokensDatabase(directory, options.seed ?? []); + return { directory, filesystem: new MemoryFilesystem() }; +} + async function launch(options: LaunchOptions = {}): Promise { const host = options.host ?? "127.0.0.1"; - const directory = - options.resume?.directory ?? (await mkdtemp(join(tmpdir(), "simlock-local-profile-"))); + const { directory, filesystem } = await dataDirectoryFor(options); const clock = new FakeClock(1_000); - const filesystem = options.resume?.filesystem ?? new MemoryFilesystem(); const logs = new MemoryLogSink(); - if (options.resume === undefined) { - temporaryDirectories.push(directory); - await seedTokensDatabase(directory, options.seed ?? []); - } const port = options.port ?? (await freeLoopbackPort()); if (options.refuseWrite === true) { filesystem.defineFailure(join(directory, "agent-device-profile.json"), "EACCES"); diff --git a/src/modules/host.ts b/src/modules/host.ts index 322c8d16b..ba647d5a8 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -10,8 +10,10 @@ import type { ModuleHost, ModuleHostOptions, ModuleLeaseEndParticipant, + ModuleLocalProfile, ModuleMount, ModuleRelayTarget, + ModuleTokens, MountDeps, OptionalModuleDefinition, WorkerModule, @@ -22,57 +24,65 @@ function profileOrigin(host: string, port: number): string { return `http://${reachable.includes(":") ? `[${reachable}]` : reachable}:${String(port)}`; } -async function readProfileSecret( +// why: a missing, unreadable or malformed file all mean "make a new token". +async function readStoredProfile( filesystem: Filesystem, path: string, -): Promise { +): Promise<{ readonly text: string; readonly secret: string } | undefined> { try { - const parsed: unknown = JSON.parse(await filesystem.readFile(path)); + const text = await filesystem.readFile(path); + const parsed: unknown = JSON.parse(text); const secret = typeof parsed === "object" && parsed !== null ? (parsed as { daemonAuthToken?: unknown }).daemonAuthToken : undefined; - return typeof secret === "string" ? secret : undefined; + return typeof secret === "string" ? { secret, text } : undefined; } catch { return undefined; } } -async function prepareLocalProfile( - definition: OptionalModuleDefinition, +async function revokeLabelled(tokens: ModuleTokens, label: string, keep?: string): Promise { + for (const other of await tokens.list()) { + if (other.label === label && other.id !== keep) await tokens.revoke(other.id); + } +} + +async function publishLocalProfile( + localProfile: ModuleLocalProfile, + path: string, options: ModuleHostOptions, ): Promise { - const { localProfile } = definition; - if (localProfile === undefined) return; const { tokens } = options; const { filesystem } = options.context; - const path = join(options.context.dataDirectory, localProfile.fileName); - if ( - options.config.capabilities[definition.name]?.enabled !== true || - !options.config.http.enabled - ) { - if (await filesystem.exists(path)) await filesystem.rm(path); - for (const other of await tokens.list()) { - if (other.label === localProfile.tokenLabel) await tokens.revoke(other.id); - } - return; - } - const stored = await readProfileSecret(filesystem, path); - const verified = stored === undefined ? undefined : await tokens.verify(stored); - const kept = verified?.label === localProfile.tokenLabel ? verified : undefined; + const stored = await readStoredProfile(filesystem, path); + const verified = stored === undefined ? undefined : await tokens.verify(stored.secret); + const live = verified?.label === localProfile.tokenLabel ? verified : undefined; const made = - kept === undefined ? await tokens.create("agent", localProfile.tokenLabel) : undefined; - const id = kept?.id ?? made?.record.id; - const secret = made?.secret ?? stored ?? ""; - for (const other of await tokens.list()) { - if (other.label === localProfile.tokenLabel && other.id !== id) await tokens.revoke(other.id); - } + live === undefined ? await tokens.create("agent", localProfile.tokenLabel) : undefined; + const id = live?.id ?? made?.record.id; + await revokeLabelled(tokens, localProfile.tokenLabel, id); const contents = localProfile.render( profileOrigin(options.config.http.host, options.config.http.port), - secret, + made?.secret ?? stored?.secret ?? "", ); - if (kept !== undefined && (await filesystem.readFile(path)) === contents) return; - await filesystem.writeFileAtomic(path, contents, { mode: 0o600 }); + if (live === undefined || stored?.text !== contents) { + await filesystem.writeFileAtomic(path, contents, { mode: 0o600 }); + } +} + +async function prepareLocalProfile( + definition: OptionalModuleDefinition, + options: ModuleHostOptions, +): Promise { + const { localProfile } = definition; + if (localProfile === undefined) return; + const path = join(options.context.dataDirectory, localProfile.fileName); + const applies = + options.config.capabilities[definition.name]?.enabled === true && options.config.http.enabled; + if (applies) return publishLocalProfile(localProfile, path, options); + if (await options.context.filesystem.exists(path)) await options.context.filesystem.rm(path); + await revokeLabelled(options.tokens, localProfile.tokenLabel); } const HOOK_DEADLINE_MS = 30_000; diff --git a/src/modules/index.ts b/src/modules/index.ts index 2aaaad379..be8d1d8fd 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -13,7 +13,6 @@ export type { ModuleFinding, ModuleHttpResponse, ModuleLeaseEndParticipant, - ModuleLocalProfile, ModuleMount, ModuleRegistryView, ModuleRelayTarget, diff --git a/website/src/content/docs/docs/using-devices/agent-device.mdx b/website/src/content/docs/docs/using-devices/agent-device.mdx index bfad4836e..1a4e7ca8e 100644 --- a/website/src/content/docs/docs/using-devices/agent-device.mdx +++ b/website/src/content/docs/docs/using-devices/agent-device.mdx @@ -19,7 +19,7 @@ On each worker: On each agent's machine: - agent-device 0.21.28 or later. An older CLI is refused with `refused: this agent-device is too old for simlock; upgrade it`. -- Its own Simlock agent token. Simlock tells agents apart by token: two agents that share a token share one agent-device session and see each other's devices. +- Its own Simlock agent token, unless it runs on the worker's Mac (see [On the same Mac](#on-the-same-mac)). Simlock tells agents apart by token: two agents that share a token share one agent-device session and see each other's devices. agent-device through Simlock drives simulators, emulators and, with `--physical`, phones enrolled in Simlock (see [Physical devices](/simlock/docs/using-devices/physical-devices)). `open --physical` leases an enrolled phone: the command goes to the phone daemon and the reply names the device with `physical: true`. Simlock picks the phone, so name no `--udid` or `--serial`. From 6323c67dce062d442f13722d1d7452c38e831276 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:03:41 +0200 Subject: [PATCH 11/13] refactor(modules): simplify the local profile step (#956) --- src/modules/host.ts | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/modules/host.ts b/src/modules/host.ts index ba647d5a8..0ff6a9a63 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -48,27 +48,34 @@ async function revokeLabelled(tokens: ModuleTokens, label: string, keep?: string } } +async function liveProfileToken( + tokens: ModuleTokens, + label: string, + stored: { readonly secret: string } | undefined, +): Promise<{ readonly id: string; readonly secret: string; readonly reused: boolean }> { + const verified = stored === undefined ? undefined : await tokens.verify(stored.secret); + if (stored !== undefined && verified?.label === label) { + return { id: verified.id, reused: true, secret: stored.secret }; + } + const made = await tokens.create("agent", label); + return { id: made.record.id, reused: false, secret: made.secret }; +} + async function publishLocalProfile( localProfile: ModuleLocalProfile, path: string, options: ModuleHostOptions, ): Promise { - const { tokens } = options; const { filesystem } = options.context; const stored = await readStoredProfile(filesystem, path); - const verified = stored === undefined ? undefined : await tokens.verify(stored.secret); - const live = verified?.label === localProfile.tokenLabel ? verified : undefined; - const made = - live === undefined ? await tokens.create("agent", localProfile.tokenLabel) : undefined; - const id = live?.id ?? made?.record.id; - await revokeLabelled(tokens, localProfile.tokenLabel, id); + const token = await liveProfileToken(options.tokens, localProfile.tokenLabel, stored); + await revokeLabelled(options.tokens, localProfile.tokenLabel, token.id); const contents = localProfile.render( profileOrigin(options.config.http.host, options.config.http.port), - made?.secret ?? stored?.secret ?? "", + token.secret, ); - if (live === undefined || stored?.text !== contents) { - await filesystem.writeFileAtomic(path, contents, { mode: 0o600 }); - } + if (token.reused && stored?.text === contents) return; + await filesystem.writeFileAtomic(path, contents, { mode: 0o600 }); } async function prepareLocalProfile( From 318c014768f05f25afb357356cb969d29856d6f7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:08:03 +0200 Subject: [PATCH 12/13] test: the local profile test proves a restart does not rewrite an unchanged file (#956) --- src/agent-device/local-profile.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts index 8484b2db2..dd7630cd7 100644 --- a/src/agent-device/local-profile.test.ts +++ b/src/agent-device/local-profile.test.ts @@ -223,8 +223,10 @@ describe("the local agent-device profile", () => { await first.daemon.dispatch("token.create", { label: LABEL, role: "operator" }, adminSession); expect(await labelledIds(first)).toHaveLength(2); + const identity = (await first.filesystem.stat(first.profilePath)).identity; const same = await first.restart(); expect((await readProfile(same)).text).toBe(before.text); + expect((await same.filesystem.stat(same.profilePath)).identity).toBe(identity); expect(await labelledIds(same)).toEqual([tokenId]); const port = await freeLoopbackPort(); From baea24d6c566e3c206adee0d7b238e513c8916e9 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 22:10:28 +0200 Subject: [PATCH 13/13] test: the local profile is on disk before HTTP accepts a connection (#956) --- src/agent-device/local-profile.test.ts | 74 +++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts index dd7630cd7..e4da5bb48 100644 --- a/src/agent-device/local-profile.test.ts +++ b/src/agent-device/local-profile.test.ts @@ -1,5 +1,5 @@ import { mkdtemp, rm } from "node:fs/promises"; -import { createServer } from "node:net"; +import { createConnection, createServer } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -151,8 +151,78 @@ function allocateWith(rig: Rig, secret: string, n: number): Promise { }); } +function listens(port: number): Promise { + return new Promise((resolve) => { + const socket = createConnection({ host: "127.0.0.1", port }); + socket.once("connect", () => { + socket.destroy(); + resolve(true); + }); + socket.once("error", () => resolve(false)); + }); +} + +// why: holds the profile write open so a test can look at the HTTP port while the profile is not yet on disk. +class HoldingFilesystem extends MemoryFilesystem { + readonly reached: Promise; + release: () => void = () => undefined; + private markReached: () => void = () => undefined; + private readonly released = new Promise((resolve) => { + this.release = resolve; + }); + + constructor() { + super(); + this.reached = new Promise((resolve) => { + this.markReached = resolve; + }); + } + + override async writeFileAtomic( + ...args: Parameters + ): Promise { + if (args[0].endsWith("agent-device-profile.json")) { + this.markReached(); + await this.released; + } + return super.writeFileAtomic(...args); + } + + override async writeFileExclusive( + ...args: Parameters + ): Promise { + if (args[0].endsWith("agent-device-profile.json")) { + this.markReached(); + await this.released; + } + return super.writeFileExclusive(...args); + } +} + describe("the local agent-device profile", () => { - it("is written before HTTP listens, and its token leases for a local agent", async () => { + it("is on disk before the HTTP listener accepts a connection", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-local-profile-")); + temporaryDirectories.push(directory); + await seedTokensDatabase(directory, []); + const filesystem = new HoldingFilesystem(); + const port = await freeLoopbackPort(); + + const starting = launch({ port, resume: { directory, filesystem } }); + await filesystem.reached; + for (let attempt = 0; attempt < 5; attempt++) { + expect(await listens(port), "HTTP listens while the profile is still being written").toBe( + false, + ); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + filesystem.release(); + const rig = await starting; + + expect(await filesystem.readFile(rig.profilePath)).toContain("daemonAuthToken"); + expect(await listens(port)).toBe(true); + }); + + it("is written with the contract keys, and its token leases for a local agent", async () => { const rig = await launch({ seed: [["tok_operator", "slk_operator", "operator", LABEL]] }); const text = await rig.filesystem.readFile(rig.profilePath);