diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index d283f8730..55b95c23f 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-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 - The simlock lease is the only clock; an agent-device lease never outlives it. 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 new file mode 100644 index 000000000..e4da5bb48 --- /dev/null +++ b/src/agent-device/local-profile.test.ts @@ -0,0 +1,383 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { createConnection, 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 { seedTokensDatabase } from "../auth/testing.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 logs: MemoryLogSink; + readonly profilePath: string; + readonly port: number; + readonly restart: (options?: Switches & { readonly port?: number }) => Promise; +} + +interface Switches { + readonly http?: boolean; + readonly agentDevice?: boolean; + readonly role?: "gateway"; +} + +interface LaunchOptions extends Switches { + readonly refuseWrite?: boolean; + readonly host?: string; + readonly seed?: Parameters[1]; + readonly port?: number; + 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, filesystem } = await dataDirectoryFor(options); + const clock = new FakeClock(1_000); + const logs = new MemoryLogSink(); + 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: { + 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: [ + 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: logs }), + optionalModules: [agentDeviceModuleWith({ upstream: new FakeAgentDevice() })], + version: "1.2.3", + } as StartDaemonOptions); + runningDaemons.push(daemon); + return { + daemon, + filesystem, + logs, + port, + profilePath: join(directory, "agent-device-profile.json"), + restart: async (restartOptions = {}) => { + await daemon.stop("test"); + return launch({ + host, + ...restartOptions, + port: restartOptions.port ?? port, + resume: { directory, filesystem }, + }); + }, + }; +} + +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", + }); +} + +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 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); + 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"); + expect(labelled[0]?.id).not.toBe("tok_operator"); + + 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", + { kind: "leases" }, + adminSession, + )) as never as { + 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`); + } + }); + + 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 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(); + 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, + ); + } + }); + + 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); + }); + + 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); + }); +}); 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/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..f5013282e 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 }, }; } @@ -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/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/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/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..0ff6a9a63 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -1,5 +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, @@ -8,13 +10,88 @@ import type { ModuleHost, ModuleHostOptions, ModuleLeaseEndParticipant, + ModuleLocalProfile, ModuleMount, ModuleRelayTarget, + ModuleTokens, MountDeps, OptionalModuleDefinition, 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)}`; +} + +// why: a missing, unreadable or malformed file all mean "make a new token". +async function readStoredProfile( + filesystem: Filesystem, + path: string, +): Promise<{ readonly text: string; readonly secret: string } | undefined> { + try { + 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, text } : undefined; + } catch { + return undefined; + } +} + +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 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 { filesystem } = options.context; + const stored = await readStoredProfile(filesystem, path); + 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), + token.secret, + ); + if (token.reused && stored?.text === contents) return; + 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; interface Started { @@ -260,6 +337,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 prepareLocalProfile(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..be8d1d8fd 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -16,6 +16,8 @@ export type { 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">; } 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..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`. @@ -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.