From 5347acd52186a80bd51c8097637d24a1f27d263a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 16:42:03 +0200 Subject: [PATCH 1/5] test: Ask Simlock who you are, over the socket, HTTP, the CLI and the client (#713) --- e2e/identity.test.ts | 95 +++++++++++++++++++++++++ src/auth/strategies/conformance.test.ts | 10 +++ src/cli/index.test.ts | 7 ++ src/client/index.ts | 1 + src/contract/operations.test.ts | 2 + src/contract/operations.ts | 15 ++++ src/daemon/dispatch.ts | 7 ++ src/daemon/dispatcher.test.ts | 20 ++++++ src/daemon/dispatcher.ts | 2 + src/daemon/identity-uplink.e2e.test.ts | 25 +++++++ src/daemon/server.test.ts | 34 +++++++++ src/gateway/dispatcher.test.ts | 24 +++++++ src/gateway/dispatcher.ts | 2 + src/http/app.test.ts | 37 +++++++++- src/mcp/test-support.ts | 6 ++ src/simlock-client/client.test.ts | 17 +++++ src/simlock-client/client.ts | 8 +++ src/simlock-client/types.ts | 1 + 18 files changed, 312 insertions(+), 1 deletion(-) create mode 100644 e2e/identity.test.ts create mode 100644 src/daemon/identity-uplink.e2e.test.ts diff --git a/e2e/identity.test.ts b/e2e/identity.test.ts new file mode 100644 index 000000000..3aea7f4ff --- /dev/null +++ b/e2e/identity.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "vitest"; + +import { waitFor, withHttpDaemon, type TestEnv } from "./helpers/index.js"; + +interface HttpDaemon { + readonly env: TestEnv; + readonly baseUrl: string; +} + +async function httpDaemon(mode: "worker" | "gateway"): Promise { + const { env, port } = await withHttpDaemon((port) => { + const http = { enabled: true, host: "127.0.0.1", port }; + return mode === "gateway" + ? { agentId: "claude-1", configOverrides: { http, mode: "gateway" }, driver: "none" } + : { agentId: "claude-1", configOverrides: { http } }; + }); + const baseUrl = `http://127.0.0.1:${port}`; + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "HTTP listener accepting connections" }, + ); + return { baseUrl, env }; +} + +async function mint( + env: TestEnv, + role: string, + label?: string, +): Promise<{ readonly secret: string; readonly token: { readonly id: string } }> { + const minted = await env.cli([ + "token", + "create", + "--role", + role, + ...(label === undefined ? [] : ["--label", label]), + ]); + expect(minted.code, minted.stderr).toBe(0); + return minted.json as { secret: string; token: { id: string } }; +} + +function getIdentity(daemon: HttpDaemon, secret: string): Promise { + return fetch(`${daemon.baseUrl}/v1/identity`, { headers: { authorization: `Bearer ${secret}` } }); +} + +describe("identity.get", () => { + it("simlock whoami prints the four labelled lines for the CLI's own session, and --json prints the same as one object, on a worker and on a gateway", async () => { + for (const mode of ["worker", "gateway"] as const) { + const { env } = await httpDaemon(mode); + + const text = await env.cli(["whoami"]); + expect(text.code, `${mode}: ${text.stderr}`).toBe(0); + expect(text.stdout.trimEnd().split("\n"), mode).toEqual([ + "Principal: claude-1", + "Name: claude-1", + "Role: admin", + "Via: socket", + ]); + + const json = await env.cli(["whoami", "--json"]); + expect(json.code, `${mode}: ${json.stderr}`).toBe(0); + expect(json.json, mode).toEqual({ + name: "claude-1", + principal: "claude-1", + role: "admin", + via: "socket", + }); + } + }); + + it("GET /v1/identity with a minted agent token answers that token's id, its label and role agent, and a worker token is refused with 403, on a worker and on a gateway", async () => { + for (const mode of ["worker", "gateway"] as const) { + const daemon = await httpDaemon(mode); + const agent = await mint(daemon.env, "agent", "ci-runner"); + const worker = await mint(daemon.env, "worker", "join"); + + const answered = await getIdentity(daemon, agent.secret); + expect(answered.status, mode).toBe(200); + expect(await answered.json(), mode).toEqual({ + name: "ci-runner", + principal: agent.token.id, + role: "agent", + via: "token", + }); + + const refused = await getIdentity(daemon, worker.secret); + expect(refused.status, mode).toBe(403); + } + }); +}); diff --git a/src/auth/strategies/conformance.test.ts b/src/auth/strategies/conformance.test.ts index 4c4b395d1..77203bee5 100644 --- a/src/auth/strategies/conformance.test.ts +++ b/src/auth/strategies/conformance.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; +import { OPERATIONS } from "../../contract/index.js"; import { authStrategies } from "./index.js"; import { tokenFixture } from "./token/testing.js"; @@ -41,3 +42,12 @@ describe.each(authStrategies.map((definition) => ({ definition })))( }); }, ); + +describe("the strategy registry and identity.get", () => { + it("every registered strategy's name is a value of identity.get's via enum", () => { + const via: readonly string[] = OPERATIONS["identity.get"].output.shape.via.options; + + expect(authStrategies.length).toBeGreaterThan(0); + for (const definition of authStrategies) expect(via).toContain(definition.name); + }); +}); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 134d270b1..8819355d0 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6292,6 +6292,13 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl daemonVersion: "test", getCatalog: () => Promise.resolve(emptyCatalog), getStatus: () => Promise.resolve(EMPTY_STATUS), + identity: () => + Promise.resolve({ + name: "test-requester", + principal: "test-requester", + role: "admin", + via: "socket", + }), listComponents: () => Promise.resolve({ components: [] }), requestLease: (_input, _options) => Promise.resolve(grant), resolvePassthrough: () => Promise.resolve({ args: [], command: "adb", env: {} }), diff --git a/src/client/index.ts b/src/client/index.ts index c7cb470da..5fe7f7ad5 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -30,6 +30,7 @@ export type { DoctorReport, DoctorRunInput, DriverPassthroughInput, + IdentityOutput, LeaseCancelInput, LeaseCancelOutput, LeaseGrant, diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 7c95ddb8d..2b38ee2d6 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -50,6 +50,7 @@ const ROLE_MATRIX: ReadonlyArray<{ input: { args: ["devices"], leaseId: "lease_1", tool: "adb" }, role: "agent", }, + { name: "identity.get", input: {}, role: "agent" }, { name: "token.list", input: {}, role: "admin" }, { name: "token.revoke", input: { id: "tok_1" }, role: "admin" }, { name: "worker.list", input: {}, role: "admin" }, @@ -135,6 +136,7 @@ const EFFECT_MATRIX: ReadonlyArray<{ input: { args: ["devices"], leaseId: "lease_1", tool: "adb" }, effect: "write", }, + { name: "identity.get", input: {}, effect: "read" }, { name: "token.list", input: {}, effect: "read" }, { name: "token.revoke", input: { id: "tok_1" }, effect: "write" }, { name: "worker.list", input: {}, effect: "read" }, diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 86df4e2fd..9ef84996c 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -1028,7 +1028,22 @@ export const relayCancel = defineOperation({ output: z.object({}), }); +export const identityGet = defineOperation({ + name: "identity.get", + role: "agent", + effect: "read", + input: z.object({}), + output: z.object({ + principal: z.string(), + name: z.string(), + role: z.enum(["admin", "agent"]), + via: z.enum(["socket", "uplink"]), + signOutUrl: z.string().optional(), + }), +}); + export const OPERATIONS = { + "identity.get": identityGet, "catalog.get": catalogGet, "status.get": statusGet, "lease.request": leaseRequest, diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts index 0646d4e43..06828a3df 100644 --- a/src/daemon/dispatch.ts +++ b/src/daemon/dispatch.ts @@ -60,6 +60,9 @@ export interface DispatchSession { * now, admin included). */ readonly isGatewayUplink?: boolean; + readonly name?: string; + readonly via?: "token" | "proxy" | "socket" | "uplink"; + readonly signOutUrl?: string; /** Called for each progress update while this specific `lease.request` call is in flight. * Ignored by every other operation. */ readonly onProgress?: (progress: DispatchProgress) => void; @@ -120,6 +123,10 @@ export interface DispatchSession { /** Thrown for a role/ownership rejection or a malformed request; `DaemonServer` maps this the * same way it already maps its own protocol errors (see `errorCode` in `server.ts`), and * `classifyError` trusts its `code` verbatim (see `error-code.ts`). */ +export function identityGet(_input: unknown, session: DispatchSession) { + return { principal: "", name: "", role: session.role, via: "socket" as const }; +} + export class DispatchError extends Error { constructor( readonly code: string, diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 46cc4810c..81ef7978b 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -821,6 +821,26 @@ describe("Dispatcher: token.create | token.list | token.revoke", () => { }); }); +describe("Dispatcher: identity.get", () => { + it("copies signOutUrl from a session that has one into its output, and omits it otherwise", async () => { + const { dispatcher } = await buildDispatcher(); + + const withUrl = await dispatcher.dispatch( + "identity.get", + {}, + session({ role: "admin", via: "proxy", signOutUrl: "https://sso.example/logout" }), + ); + const without = await dispatcher.dispatch( + "identity.get", + {}, + session({ role: "admin", via: "socket" }), + ); + + expect(withUrl).toHaveProperty("signOutUrl", "https://sso.example/logout"); + expect(without).not.toHaveProperty("signOutUrl"); + }); +}); + describe("Dispatcher: role rejection", () => { it("rejects an admin-only operation from an agent session with FORBIDDEN", async () => { const { dispatcher } = await buildDispatcher(); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 85d3c8ae4..1795b12f3 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -70,6 +70,7 @@ import { import type { TokenOperations } from "../auth/index.js"; import { DispatchError, + identityGet, runDispatch, usageAnswer, type DispatchSession, @@ -313,6 +314,7 @@ export class Dispatcher { "usage.get": this.#usageGet, "events.subscribe": this.#eventsSubscribe, "events.unsubscribe": this.#eventsUnsubscribe, + "identity.get": identityGet, "token.create": this.#tokenCreate, "token.list": this.#tokenList, "token.revoke": this.#tokenRevoke, diff --git a/src/daemon/identity-uplink.e2e.test.ts b/src/daemon/identity-uplink.e2e.test.ts new file mode 100644 index 000000000..7d45410be --- /dev/null +++ b/src/daemon/identity-uplink.e2e.test.ts @@ -0,0 +1,25 @@ +import { afterEach, describe, expect, it } from "vitest"; + +import type { DaemonServer } from "./server.js"; +import { cleanUp, openUplink, startWorker } from "./test-relay-support.js"; + +describe("identity.get over a worker's uplink", () => { + const daemons: DaemonServer[] = []; + const directories: string[] = []; + + afterEach(async () => { + await cleanUp(daemons, directories); + }); + + it("identity.get answers the gateway's principal, admin and via uplink over a real uplink session", async () => { + const fixture = await startWorker(directories, daemons, {}); + const uplink = await openUplink(fixture.worker); + + await expect(uplink.wire.call("identity.get", {})).resolves.toEqual({ + name: "gw:test", + principal: "gw:test", + role: "admin", + via: "uplink", + }); + }); +}); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index e1d4df94c..b2fc730e4 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -3140,6 +3140,40 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { await local.close(); }); + it("identity.get answers the declared principal as principal and name over a socket: agent with no credential, admin with the admin secret, admin with an operator token", async () => { + const harness = await createHarness({ + resolveRole: { + resolve: (payload) => + payload.credential === "admin-secret" || payload.credential === "slk_operator" + ? "admin" + : "agent", + }, + }); + const cases = [ + { credential: undefined, principal: "claude-1", role: "agent" }, + { credential: "admin-secret", principal: "claude-2", role: "admin" }, + { credential: "slk_operator", principal: "claude-3", role: "admin" }, + ]; + + for (const { credential, principal, role } of cases) { + const client = await createClient(harness.socketPath); + await expect( + client.request("hello", { + clientVersion: "test", + protocolVersion: DAEMON_PROTOCOL_VERSION, + principal, + ...(credential === undefined ? {} : { credential }), + }), + ).resolves.toMatchObject({ ok: true }); + + await expect(client.request("identity.get", {})).resolves.toMatchObject({ + ok: true, + payload: { name: principal, principal, role, via: "socket" }, + }); + await client.close(); + } + }); + it("negotiates the protocol range over an uplink exactly as over the socket (ADR 0005 §31)", async () => { const harness = await createHarness({ resolveRole: { resolve: () => "agent" } }); const pair = linkPair(); diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index a79efa91e..0e8dafcd4 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -251,6 +251,30 @@ const EVERY_OPERATION = (Object.keys(OPERATIONS) as OperationName[]).filter( ); describe("GatewayDispatcher", () => { + it("answers identity.get from its own caller's session, the same shape", async () => { + const { dispatcher } = harness(); + + await expect( + dispatcher.dispatch( + "identity.get", + {}, + session({ principal: "operator-1", role: "admin", via: "socket" }), + ), + ).resolves.toEqual({ + name: "operator-1", + principal: "operator-1", + role: "admin", + via: "socket", + }); + await expect( + dispatcher.dispatch( + "identity.get", + {}, + session({ name: "ci-runner", principal: "tok_9f2c", role: "agent", via: "token" }), + ), + ).resolves.toEqual({ name: "ci-runner", principal: "tok_9f2c", role: "agent", via: "token" }); + }); + it("The gateway dispatcher logs the same line for the same operation", async () => { const { clock, dispatcher, logSink, workers } = harness(); workers.connected("wrk_1", "mac-mini-1", "0.3.0"); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 4922009e8..31b60b6cc 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -46,6 +46,7 @@ import { } from "../contract/index.js"; import { DispatchError, + identityGet, runDispatch, usageAnswer, type DispatchSession, @@ -173,6 +174,7 @@ export class GatewayDispatcher { "worker.install-component": this.#workerInstallComponent, "lease.list": this.#leaseList, "list.get": this.#listGet, + "identity.get": identityGet, "nuke.run": unsupportedByDesign("nuke.run"), "cleanup.run": unsupportedByDesign("cleanup.run"), diff --git a/src/http/app.test.ts b/src/http/app.test.ts index a8864373a..dbc771bd0 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -8,7 +8,7 @@ import { LeaseRequestBook, RequestCancelledError, } from "../leasing/index.js"; -import { runDispatch } from "../daemon/dispatch.js"; +import { identityGet, runDispatch } from "../daemon/dispatch.js"; import { DispatchError } from "../daemon/dispatcher.js"; import { describeLeaseRequestFailure } from "../daemon/error-code.js"; import { OwnerRoutedFactBus } from "../daemon/owner-routed-facts.js"; @@ -46,6 +46,10 @@ function buildHarness( ["slk_agent", tokenIdentity("tok_agent", "agent")], ["slk_other", tokenIdentity("tok_other", "agent")], ["slk_operator", tokenIdentity("tok_operator", "operator")], + [ + "slk_labelled", + { ambient: false, name: "ci-runner", principal: "tok_9f2c", role: "agent", via: "token" }, + ], ]), ); const logSink = new MemoryLogSink(); @@ -177,6 +181,37 @@ describe("GET /v1/healthz", () => { }); }); +describe("GET /v1/identity", () => { + it("answers the token's id as principal, its label as name, its role and via token; an unlabelled operator token's name is its id; no token is a 401 Missing bearer token", async () => { + const { app, dispatcher } = buildHarness(); + dispatcher.handlers["identity.get"] = identityGet; + + const labelled = await app.request("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/v1/identity", { + headers: { authorization: "Bearer slk_labelled" }, + }); + expect(labelled.status).toBe(200); + expect(await labelled.json()).toEqual({ + name: "ci-runner", + principal: "tok_9f2c", + role: "agent", + via: "token", + }); + + const operator = await app.request("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/v1/identity", { headers: operatorAuth }); + expect(operator.status).toBe(200); + expect(await operator.json()).toEqual({ + name: "tok_operator", + principal: "tok_operator", + role: "admin", + via: "token", + }); + + const anonymous = await app.request("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/v1/identity"); + expect(anonymous.status).toBe(401); + expect(await anonymous.json()).toMatchObject({ error: { message: "Missing bearer token" } }); + }); +}); + describe("authentication and role/ownership (via the shared dispatcher)", () => { it("401s a protected route with no token", async () => { const { app } = buildHarness(); diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 5b188ede4..5c2fbe57b 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -22,6 +22,7 @@ import { type LeaseGrant, type LeaseListOutput, type LeaseLostPush, + type IdentityOutput, type LeaseReleaseInput, type LeaseReleaseOutput, type LeaseRenewInput, @@ -93,6 +94,11 @@ export class FakeSimlockClient implements SimlockClient { return this.#dead ? this.#deadConnection() : this.getCatalogImpl(input); } + identity(): Promise { + this.calls.push({ input: undefined, method: "identity" }); + return this.#dead ? this.#deadConnection() : Promise.reject(new Error("not implemented")); + } + getStatus(): Promise { this.calls.push({ input: undefined, method: "getStatus" }); return this.#dead ? this.#deadConnection() : this.getStatusImpl(); diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index 18aaf08c1..830a91b07 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -207,6 +207,23 @@ describe("connectSimlock: handshake", () => { await expect(callPromise).resolves.toEqual(answer); }); + it("identity() sends identity.get and returns its output", async () => { + const connection = new ScriptedConnection(); + const connectPromise = connectSimlock({ connection }); + await flushMicrotasks(); + completeHello(connection); + const client = await connectPromise; + const answer = { name: "ci-runner", principal: "tok_9f2c", role: "agent", via: "token" }; + + const callPromise = client.identity(); + await flushMicrotasks(); + const call = connection.lastSentOf("identity.get")!; + expect(call.payload).toEqual({}); + connection.reply(call.id, answer); + + await expect(callPromise).resolves.toEqual(answer); + }); + it("removes a component from an admin client with component.remove, sending the input and returning the daemon's answer", async () => { const connection = new ScriptedConnection(); const connectPromise = connectSimlockAdmin({ connection, credential: "operator-secret" }); diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index c675ba4e3..a2502d780 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -57,6 +57,7 @@ import type { UsageGetInput, UsageGetOutput, InstallComponentOnWorkersOptions, + IdentityOutput, InstallComponentOptions, LeaseCancelInput, LeaseCancelOutput, @@ -125,6 +126,7 @@ export type { EventsSubscribeOutput, EventsUnsubscribeOutput, InstallComponentOnWorkersOptions, + IdentityOutput, InstallComponentOptions, LeaseCancelInput, LeaseCancelOutput, @@ -195,6 +197,7 @@ export interface SimlockClient { getCatalog(input?: CatalogGetInput): Promise; getStatus(): Promise; + identity(): Promise; /** * ADR 0010 §8: every installed iOS simulator runtime and Android system image on the daemon's * machine, with its size, whether Simlock installed it, and how many devices use it. @@ -399,6 +402,7 @@ function buildDegradedClient( getCatalog: () => rejected(), getStatus: () => rejected(), + identity: () => rejected(), listComponents: () => rejected(), requestLease: () => rejected(), cancelLease: () => rejected(), @@ -516,6 +520,10 @@ class SimlockClientImpl { return this.#call("status.get", {}); } + identity(): Promise { + return Promise.reject(new Error("not implemented")); + } + listComponents(input: ComponentListInput = {}): Promise { return this.#call("component.list", input); } diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index 1166f1010..a2691db06 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -59,6 +59,7 @@ export type UsageGetInput = OpInput<"usage.get">; export type UsageGetOutput = OpOutput<"usage.get">; export type EventsSubscribeOutput = OpOutput<"events.subscribe">; export type EventsUnsubscribeOutput = OpOutput<"events.unsubscribe">; +export type IdentityOutput = OpOutput<"identity.get">; export type TokenCreateInput = OpInput<"token.create">; export type TokenCreateOutput = OpOutput<"token.create">; export type TokenListOutput = OpOutput<"token.list">; From 190c67c5629eb71229966a4c7ede57e5f70ff810 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 16:46:05 +0200 Subject: [PATCH 2/5] feat: Ask Simlock who you are, over the socket, HTTP, the CLI and the client (#713) 18 failing -> 0 failing. identity.get, GET /v1/identity, simlock whoami, client identity(); protocol 40. --- docs/CLI.md | 16 ++++++++ docs/CLIENT.md | 8 ++++ docs/HTTP-API.md | 11 +++++ src/agent-device/edge.test.ts | 8 +++- src/agent-device/gateway-front.test.ts | 8 +++- src/cli/commands/whoami.ts | 32 +++++++++++++++ src/cli/tree.ts | 1 + src/contract/AGENTS.md | 2 +- src/contract/operations.ts | 2 +- src/contract/protocol.test.ts | 4 +- src/contract/protocol.ts | 3 +- src/daemon-protocol/index.test.ts | 2 +- src/daemon/AGENTS.md | 2 +- src/daemon/dispatch.test.ts | 1 + src/daemon/dispatch.ts | 17 +++++--- src/daemon/dispatcher.test.ts | 1 + src/daemon/gateway-fleet.e2e.test.ts | 8 +++- src/daemon/gateway-modules.test.ts | 1 + src/daemon/lease-requires.e2e.test.ts | 3 +- src/daemon/main.test.ts | 47 +++++++++++++++++++--- src/daemon/optional-modules.test.ts | 2 + src/daemon/relay-gateway.e2e.test.ts | 1 + src/daemon/relay-promises.timing.test.ts | 1 + src/daemon/server.test.ts | 5 ++- src/daemon/server.ts | 7 ++++ src/daemon/stream-gateway.e2e.test.ts | 2 + src/daemon/test-relay-support.ts | 1 + src/daemon/worker-capabilities.e2e.test.ts | 1 + src/gateway/dispatcher.test.ts | 1 + src/gateway/fleet-coordinator.test.ts | 28 +++++++++++-- src/gateway/service.test.ts | 2 +- src/http/app.test.ts | 1 + src/http/app.ts | 4 ++ src/http/core-routes.test.ts | 1 + src/http/dispatcher-session.ts | 10 +++++ src/modules/types.ts | 2 + src/simlock-client/client.ts | 2 +- 37 files changed, 219 insertions(+), 29 deletions(-) create mode 100644 src/cli/commands/whoami.ts diff --git a/docs/CLI.md b/docs/CLI.md index f60ce2cbe..fb473d3d3 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1374,6 +1374,22 @@ under the pre-0.3.0 hand-written schemas (`leaseId`, `deviceId`, `allowDownload`, `requesterId`, ...); those did not change shape, only their schema's source of truth. +## `simlock whoami [--json]` + +Prints who Simlock thinks you are, for this CLI's own session: the principal, +the name to show, the role and how you signed in. Like every command it +starts the daemon when none runs. + +``` +$ simlock whoami +Principal: claude-1 +Name: claude-1 +Role: admin +Via: socket +``` + +`--json` prints `{"principal","name","role","via"}` as one object. + ## `simlock status` In `status --json`, an enrolled physical device's entry carries `driverDeviceId`, diff --git a/docs/CLIENT.md b/docs/CLIENT.md index ec2adc1d9..925281021 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -337,6 +337,14 @@ Three limits worth knowing: Paths in `args` resolve on the daemon's filesystem, not yours. Getting an `.app` or an `.apk` there is out of scope for now. +## Who you are: `identity()` + +`client.identity()` asks the daemon who it thinks this connection is and +resolves to `{ principal, name, role, via }`. `name` is the principal when +nothing else was declared, `role` is `"admin"` or `"agent"`, and `via` is +`"socket"` for a socket connection. Both `connectSimlock` and +`connectSimlockAdmin` clients have it. + ## Picking a device: `getCatalog` `getCatalog({ platform? })` returns what can be leased, per platform: diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 622fad3f2..147217358 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -140,6 +140,17 @@ ignores every one of them keeps working against a gateway unchanged. Unauthenticated liveness for tunnels/load balancers. → `200 {"ok":true}`. +### `GET /v1/identity` + +Role: `agent`. Who Simlock thinks the caller is: `principal` (the token's id), +`name` (the token's label, or its id when it has none), `role` (`admin` for an +operator token, `agent` for an agent token) and `via` (`token`). A `worker` +token is refused with `403`, as on every route. + +```json +{"principal":"tok_9f2c","name":"ci-runner","role":"agent","via":"token"} +``` + ### `GET /v1/status` Role: `agent`. The same view `simlock status --json` reads: a `daemon` block, diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 2b05bfc45..0d6fcc897 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -44,12 +44,18 @@ const scope = { clientId: "client-1", leaseProvider: "proxy", runId: "run-1" } a const adminSession = { manageEventSubscription: () => undefined, + via: "socket", principal: "admin", role: "admin", } as const; function sessionFor(principal: string) { - return { manageEventSubscription: () => undefined, principal, role: "agent" } as const; + return { + manageEventSubscription: () => undefined, + via: "socket", + principal, + role: "agent", + } as const; } interface Envelope { diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index e6f13d2b0..d606d6250 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -57,12 +57,18 @@ const endedMessage = "lease ended by simlock; run disconnect, then open"; const adminSession = { manageEventSubscription: () => undefined, + via: "socket", principal: "admin", role: "admin", } as const; function sessionFor(principal: string) { - return { manageEventSubscription: () => undefined, principal, role: "agent" } as const; + return { + manageEventSubscription: () => undefined, + via: "socket", + principal, + role: "agent", + } as const; } interface Envelope { diff --git a/src/cli/commands/whoami.ts b/src/cli/commands/whoami.ts new file mode 100644 index 000000000..3a1b3eeec --- /dev/null +++ b/src/cli/commands/whoami.ts @@ -0,0 +1,32 @@ +import { connectDaemonClient } from "../connect.js"; +import { commandArgs, writeResult } from "../args.js"; +import type { CommandContext } from "../tree.js"; + +async function run( + argv: readonly string[], + { environment, token }: CommandContext, +): Promise { + const values = commandArgs(argv, { + help: { type: "boolean", short: "h" }, + json: { type: "boolean" }, + }); + if (values.help) { + environment.stdout.write("Usage: simlock whoami [--json]\n"); + return 0; + } + const client = await connectDaemonClient(environment, token); + try { + const identity = await client.identity(); + if (values.json) writeResult((value) => environment.stdout.write(value), identity); + else { + environment.stdout.write( + `Principal: ${identity.principal}\nName: ${identity.name}\nRole: ${identity.role}\nVia: ${identity.via}\n`, + ); + } + return 0; + } finally { + await client.close(); + } +} + +export { run }; diff --git a/src/cli/tree.ts b/src/cli/tree.ts index 9db21d6e0..b9839227a 100644 --- a/src/cli/tree.ts +++ b/src/cli/tree.ts @@ -82,6 +82,7 @@ export const COMMANDS: readonly CommandNode[] = [ { name: "set", load: configModule }, ], }, + { name: "whoami", load: () => import("./commands/whoami.js") }, { name: "token", load: tokenModule, diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 734eccdc3..abb62b82d 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -55,7 +55,7 @@ Three identities: ## Protocol version -- Now `{ min: 46, max: 46 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. +- Now `{ min: 47, max: 47 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. - Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless a compatibility path stays side by side. - `hello` picks the highest overlap. None → `PROTOCOL_VERSION_UNSUPPORTED` with both ranges. diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 9ef84996c..90ff239af 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -1037,7 +1037,7 @@ export const identityGet = defineOperation({ principal: z.string(), name: z.string(), role: z.enum(["admin", "agent"]), - via: z.enum(["socket", "uplink"]), + via: z.enum(["token", "proxy", "socket", "uplink"]), signOutUrl: z.string().optional(), }), }); diff --git a/src/contract/protocol.test.ts b/src/contract/protocol.test.ts index e31628f65..2e7e89dc8 100644 --- a/src/contract/protocol.test.ts +++ b/src/contract/protocol.test.ts @@ -47,7 +47,7 @@ describe("helloRequestSchema", () => { }); describe("PROTOCOL_VERSION_RANGE", () => { - it("is 46, for usage.get and its ledger", () => { - expect(PROTOCOL_VERSION_RANGE).toEqual({ max: 46, min: 46 }); + it("is one above the base branch's, for identity.get", () => { + expect(PROTOCOL_VERSION_RANGE).toEqual({ max: 47, min: 47 }); }); }); diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index ab63485e2..aa56c4145 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 46, max: 46 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 47, max: 47 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; @@ -85,6 +85,7 @@ export const CORE_ROUTE_SEGMENTS: readonly string[] = [ "devices", "events", "healthz", + "identity", "lease-requests", "leases", "stats", diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 2060158ef..f81e2991b 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(46); + expect(DAEMON_PROTOCOL_VERSION).toBe(47); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 0cce45a08..f86f7c0cb 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -51,7 +51,7 @@ An HTTP bind failure after a good start stops the daemon (`http-start-failed`). Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid. Both are fixed for the connection's life. 3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE` - is `{ min: 46, max: 46 }` (`src/contract/protocol.ts`). No overlap → the + is `{ min: 47, max: 47 }` (`src/contract/protocol.ts`). No overlap → the connection stays open, and every request but `daemon.stop` gets `PROTOCOL_VERSION_UNSUPPORTED`. 4. **Request** — one frame → one `dispatch()` call. While stopping: `DAEMON_STOPPING`. diff --git a/src/daemon/dispatch.test.ts b/src/daemon/dispatch.test.ts index fc721c4eb..d03be1f99 100644 --- a/src/daemon/dispatch.test.ts +++ b/src/daemon/dispatch.test.ts @@ -27,6 +27,7 @@ function harness(handlers: DispatchPipeline["handlers"], level: LogLevel = "debu function session(overrides: Partial = {}): DispatchSession { return { manageEventSubscription: () => undefined, + via: "socket", principal: "agent-7", role: "agent", ...overrides, diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts index 06828a3df..92ffd1895 100644 --- a/src/daemon/dispatch.ts +++ b/src/daemon/dispatch.ts @@ -61,7 +61,7 @@ export interface DispatchSession { */ readonly isGatewayUplink?: boolean; readonly name?: string; - readonly via?: "token" | "proxy" | "socket" | "uplink"; + readonly via: "token" | "proxy" | "socket" | "uplink"; readonly signOutUrl?: string; /** Called for each progress update while this specific `lease.request` call is in flight. * Ignored by every other operation. */ @@ -123,10 +123,6 @@ export interface DispatchSession { /** Thrown for a role/ownership rejection or a malformed request; `DaemonServer` maps this the * same way it already maps its own protocol errors (see `errorCode` in `server.ts`), and * `classifyError` trusts its `code` verbatim (see `error-code.ts`). */ -export function identityGet(_input: unknown, session: DispatchSession) { - return { principal: "", name: "", role: session.role, via: "socket" as const }; -} - export class DispatchError extends Error { constructor( readonly code: string, @@ -138,6 +134,17 @@ export class DispatchError extends Error { } } +// why: the one handler both dispatchers use; `name` absent means the principal. +export function identityGet(_input: unknown, session: DispatchSession) { + return { + principal: session.principal, + name: session.name ?? session.principal, + role: session.role, + via: session.via, + ...(session.signOutUrl === undefined ? {} : { signOutUrl: session.signOutUrl }), + }; +} + /** * What a transport needs from a dispatcher, and all it needs: one call that takes an operation * name, a raw input, and a session. `Dispatcher` (worker, `dispatcher.ts`) and diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 81ef7978b..8491b0790 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -397,6 +397,7 @@ async function buildDispatcher( function session(overrides: Partial = {}): DispatchSession { return { manageEventSubscription: () => undefined, + via: "socket", principal: "tok_agent", role: "agent", ...overrides, diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index 31120cb1c..1f0d3184b 100644 --- a/src/daemon/gateway-fleet.e2e.test.ts +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -70,12 +70,18 @@ const gatewayUrl = (): string => `ws://127.0.0.1:${gatewayPort}`; const restartGatewayUrl = (): string => `ws://127.0.0.1:${restartGatewayPort}`; function adminSession(): DispatchSession { - return { manageEventSubscription: () => undefined, principal: "test-operator", role: "admin" }; + return { + manageEventSubscription: () => undefined, + via: "socket", + principal: "test-operator", + role: "admin", + }; } function agentSession(overrides: Partial = {}): DispatchSession { return { manageEventSubscription: () => undefined, + via: "socket", principal: "fleet-agent-1", role: "agent", ...overrides, diff --git a/src/daemon/gateway-modules.test.ts b/src/daemon/gateway-modules.test.ts index 03894d588..cf4013049 100644 --- a/src/daemon/gateway-modules.test.ts +++ b/src/daemon/gateway-modules.test.ts @@ -15,6 +15,7 @@ import type { DaemonServer } from "./server.js"; const admin = { manageEventSubscription: () => undefined, + via: "socket", principal: "test-operator", role: "admin", } as const; diff --git a/src/daemon/lease-requires.e2e.test.ts b/src/daemon/lease-requires.e2e.test.ts index 56bec04f3..52589400f 100644 --- a/src/daemon/lease-requires.e2e.test.ts +++ b/src/daemon/lease-requires.e2e.test.ts @@ -23,12 +23,13 @@ async function freeLoopbackPort(): Promise { const admin: DispatchSession = { manageEventSubscription: () => undefined, + via: "socket", principal: "test-operator", role: "admin", }; function agent(principal: string): DispatchSession { - return { manageEventSubscription: () => undefined, principal, role: "agent" }; + return { manageEventSubscription: () => undefined, via: "socket", principal, role: "agent" }; } type CapabilityState = "available" | "off" | "unavailable"; diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index a6d697913..d678a4a46 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -209,7 +209,7 @@ async function agentStatus(daemon: DaemonServer) { return (await daemon.dispatch( "status.get", {}, - { manageEventSubscription: () => undefined, principal: "agent", role: "agent" }, + { manageEventSubscription: () => undefined, via: "socket", principal: "agent", role: "agent" }, )) as { readonly host: { readonly tools: readonly unknown[] } }; } @@ -266,6 +266,7 @@ describe("startDaemon", () => { }); const admin = { manageEventSubscription: () => undefined, + via: "socket", principal: "operator", role: "admin", } as const; @@ -300,7 +301,12 @@ describe("startDaemon", () => { const replayed = (await daemon.dispatch( "events.replay", {}, - { manageEventSubscription: () => undefined, principal: "operator", role: "admin" }, + { + manageEventSubscription: () => undefined, + via: "socket", + principal: "operator", + role: "admin", + }, )) as readonly { readonly event: string; readonly payload: unknown }[]; const started = replayed.find((envelope) => envelope.event === "daemon.started"); @@ -337,6 +343,7 @@ describe("startDaemon", () => { }); const admin = { manageEventSubscription: () => undefined, + via: "socket", principal: "operator", role: "admin", } as const; @@ -370,6 +377,7 @@ describe("startDaemon", () => { } as const; const session = { manageEventSubscription: () => undefined, + via: "socket", principal: "agent", role: "agent", } as const; @@ -475,7 +483,12 @@ describe("startDaemon", () => { osVersion: "26.5", platform: "ios", }, - { manageEventSubscription: () => undefined, principal: "agent", role: "agent" }, + { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent", + role: "agent", + }, ) .catch((error: unknown) => error); await expect.poll(() => events).toEqual(["install-started"]); @@ -555,7 +568,12 @@ describe("startDaemon", () => { const listed = await daemon.dispatch( "component.list", {}, - { manageEventSubscription: () => undefined, principal: "agent", role: "agent" }, + { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent", + role: "agent", + }, ); expect(listed).toEqual({ components: [] }); @@ -581,11 +599,13 @@ describe("startDaemon", () => { describe("startDaemon wires core and leasing together", () => { const agent = { manageEventSubscription: () => undefined, + via: "socket", principal: "agent", role: "agent", } as const; const admin = { manageEventSubscription: () => undefined, + via: "socket", principal: "operator", role: "admin", } as const; @@ -2501,7 +2521,12 @@ describe("startDaemon logger wiring", () => { daemon.dispatch( "worker.drain", { workerId: "wrk_ghost" }, - { manageEventSubscription: () => undefined, principal: "test-operator", role: "admin" }, + { + manageEventSubscription: () => undefined, + via: "socket", + principal: "test-operator", + role: "admin", + }, ), ).rejects.toMatchObject({ code: "UNKNOWN_WORKER" }); @@ -2541,6 +2566,7 @@ describe("startDaemon with the agent-device edge", () => { } as const; const agent = { manageEventSubscription: () => undefined, + via: "socket", principal: "agent", role: "agent", } as const; @@ -2799,6 +2825,7 @@ describe("startDaemon with the agent-device edge", () => { it('a worker with no capabilities["agent-device"] section, and one with enabled false, answer status.get with { name: agent-device, state: off }', async () => { const admin = { manageEventSubscription: () => undefined, + via: "socket", principal: "op", role: "admin", } as const; @@ -2846,6 +2873,7 @@ describe("startDaemon with the agent-device edge", () => { it('a worker whose config has only the old agentDevice key warns `Unknown config key: "agentDevice"` and reports agent-device off', async () => { const admin = { manageEventSubscription: () => undefined, + via: "socket", principal: "op", role: "admin", } as const; @@ -2902,6 +2930,7 @@ describe("startDaemon with the agent-device edge", () => { describe("doctor.run", () => { const operator = { manageEventSubscription: () => undefined, + via: "socket", principal: "operator", role: "admin", } as const; @@ -3068,7 +3097,12 @@ describe("startDaemon host load", () => { return (await daemon.dispatch( "status.get", {}, - { manageEventSubscription: () => undefined, principal: "agent", role: "agent" }, + { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent", + role: "agent", + }, )) as Record; } @@ -3278,6 +3312,7 @@ describe("startDaemon in gateway mode host load", () => { }; const operator = { manageEventSubscription: () => undefined, + via: "socket", principal: "test-operator", role: "admin", } as const; diff --git a/src/daemon/optional-modules.test.ts b/src/daemon/optional-modules.test.ts index 67a8e323e..1b21261f1 100644 --- a/src/daemon/optional-modules.test.ts +++ b/src/daemon/optional-modules.test.ts @@ -18,11 +18,13 @@ import { openRelay, openUplink, relayInput, settleWithin } from "./test-relay-su const admin = { manageEventSubscription: () => undefined, + via: "socket", principal: "test-operator", role: "admin", } as const; const agent = { manageEventSubscription: () => undefined, + via: "socket", principal: "agent-1", role: "agent", } as const; diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index 2b99d1762..e718ea6fd 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -167,6 +167,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const agent = (overrides: Partial = {}): DispatchSession => ({ manageEventSubscription: () => undefined, + via: "socket", principal: "fleet-agent-1", role: "agent", ...overrides, diff --git a/src/daemon/relay-promises.timing.test.ts b/src/daemon/relay-promises.timing.test.ts index 6e6d000ab..3f7b5a186 100644 --- a/src/daemon/relay-promises.timing.test.ts +++ b/src/daemon/relay-promises.timing.test.ts @@ -23,6 +23,7 @@ const WORKER_TENANT = "gw.g1.alice"; const agent: DispatchSession = { manageEventSubscription: () => undefined, + via: "socket", principal: "fleet-agent-1", role: "agent", }; diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index b2fc730e4..cc03fbb4e 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -216,8 +216,9 @@ describe("DaemonServer", () => { [36, "cannot read the module-unavailable finding in doctor.run"], [37, "cannot read config.get's capabilities"], [38, "cannot read agent-device's section under config.get's capabilities"], + [46, "cannot call identity.get"], ])( - "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 46, to a client on protocol %i, which %s", + "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 47, to a client on protocol %i, which %s", async (version) => { const harness = await createHarness(); const previous = await createClient(harness.socketPath); @@ -227,7 +228,7 @@ describe("DaemonServer", () => { ).resolves.toMatchObject({ error: { code: "PROTOCOL_VERSION_UNSUPPORTED", - details: { client: { min: version, max: version }, daemon: { min: 46, max: 46 } }, + details: { client: { min: version, max: version }, daemon: { min: 47, max: 47 } }, }, ok: false, }); diff --git a/src/daemon/server.ts b/src/daemon/server.ts index b92578e3c..f0d2e0e2b 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1123,6 +1123,12 @@ export class DaemonServer { frame.payload ?? {}, this.#session(connection), ); + case "identity.get": + return this.#dispatcher.dispatch( + "identity.get", + frame.payload ?? {}, + this.#session(connection), + ); case "token.create": return this.#dispatcher.dispatch("token.create", frame.payload, this.#session(connection)); case "token.list": @@ -1208,6 +1214,7 @@ export class DaemonServer { principal: connection.principal, relays: connection.relays, role: connection.role, + via: connection.isGatewayUplink === true ? "uplink" : "socket", }; } diff --git a/src/daemon/stream-gateway.e2e.test.ts b/src/daemon/stream-gateway.e2e.test.ts index 58fcd14f1..17f3814c5 100644 --- a/src/daemon/stream-gateway.e2e.test.ts +++ b/src/daemon/stream-gateway.e2e.test.ts @@ -24,12 +24,14 @@ async function freeLoopbackPort(): Promise { const admin: DispatchSession = { manageEventSubscription: () => undefined, + via: "socket", principal: "test-operator", role: "admin", }; const agent: DispatchSession = { manageEventSubscription: () => undefined, + via: "socket", principal: "agent-1", role: "agent", }; diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index 18070c1a7..61909d4b6 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -24,6 +24,7 @@ export const adminSession: DispatchSession = { manageEventSubscription: () => undefined, principal: "test-operator", role: "admin", + via: "socket", }; async function freeLoopbackPort(): Promise { diff --git a/src/daemon/worker-capabilities.e2e.test.ts b/src/daemon/worker-capabilities.e2e.test.ts index b4f5a350d..c15482c23 100644 --- a/src/daemon/worker-capabilities.e2e.test.ts +++ b/src/daemon/worker-capabilities.e2e.test.ts @@ -23,6 +23,7 @@ async function freeLoopbackPort(): Promise { const admin: DispatchSession = { manageEventSubscription: () => undefined, + via: "socket", principal: "test-operator", role: "admin", }; diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 0e8dafcd4..9c5e55375 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -241,6 +241,7 @@ function session(overrides: Partial = {}): DispatchSession { manageEventSubscription: () => "sub_1", principal: "operator-1", role: "admin", + via: "socket", ...overrides, }; } diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index e7e2689ea..28521a833 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -1071,7 +1071,12 @@ describe("FleetLeaseCoordinator dispatch", () => { await coordinator.exec( { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, - { manageEventSubscription: () => undefined, principal: "agent-1", role: "agent" }, + { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent-1", + role: "agent", + }, ); expect(client.calls).toContain(`device.exec:${GATEWAY_PREFIX}agent-1`); @@ -1096,6 +1101,7 @@ describe("FleetLeaseCoordinator dispatch", () => { { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, { manageEventSubscription: () => undefined, + via: "socket", onOutput: () => { order.push("output"); }, @@ -1139,6 +1145,7 @@ describe("FleetLeaseCoordinator dispatch", () => { { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, { manageEventSubscription: () => undefined, + via: "socket", onStarted: () => { started = true; }, @@ -1246,6 +1253,7 @@ describe("FleetLeaseCoordinator dispatch", () => { { args: ["install", "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/path/to.app"], leaseId: grant.lease.id, tool: "simctl" }, { manageEventSubscription: () => undefined, + via: "socket", onStarted: () => { started = true; }, @@ -1276,6 +1284,7 @@ describe("FleetLeaseCoordinator dispatch", () => { { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, { manageEventSubscription: () => undefined, + via: "socket", onStarted: () => { started = true; }, @@ -1314,7 +1323,12 @@ describe("FleetLeaseCoordinator dispatch", () => { const execution = coordinator.exec( { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, - { manageEventSubscription: () => undefined, principal: "agent-1", role: "agent" }, + { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent-1", + role: "agent", + }, ); const executionState = promiseState(execution); const rejection = execution.catch((error: unknown) => error); @@ -1351,6 +1365,7 @@ describe("FleetLeaseCoordinator dispatch", () => { { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, { manageEventSubscription: () => undefined, + via: "socket", onOutput: (stream, chunk) => { relayed.push({ chunk, stream }); }, @@ -1387,6 +1402,7 @@ describe("FleetLeaseCoordinator dispatch", () => { { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, { manageEventSubscription: () => undefined, + via: "socket", onStarted: () => { startedCount += 1; }, @@ -1423,6 +1439,7 @@ describe("FleetLeaseCoordinator dispatch", () => { { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, { manageEventSubscription: () => undefined, + via: "socket", onStarted: () => { startedCount += 1; }, @@ -1799,7 +1816,12 @@ describe("drain and unreachable lifecycle (ADR §9/§28/§29, #119)", () => { const rejection = await coordinator .exec( { args: ["devices"], leaseId: "wrk_a.lse_1", tool: "adb" }, - { manageEventSubscription: () => undefined, principal: "agent-1", role: "agent" }, + { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent-1", + role: "agent", + }, ) .catch((error: unknown) => error); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 7195d8cab..217a9f0e7 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -1265,7 +1265,7 @@ describe("GatewayService", () => { min: PROTOCOL_VERSION_RANGE.max - 1, max: PROTOCOL_VERSION_RANGE.max - 1, }; - expect(PROTOCOL_VERSION_RANGE.max).toBe(46); + expect(PROTOCOL_VERSION_RANGE.max).toBe(47); expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, previous)).toBeUndefined(); const harness = fleet(); await harness.service.start(); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index dbc771bd0..8aea902b8 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1089,6 +1089,7 @@ describe("lease-request ownership", () => { { model: "iPhone 17 Pro", platform: "ios", requesterId: "tok_agent" }, { manageEventSubscription: () => undefined, + via: "socket", onRequestAdmitted: (admitted) => (id = admitted), principal: "tok_other", role: "agent", diff --git a/src/http/app.ts b/src/http/app.ts index 6578e5f43..2fdef76b3 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -629,6 +629,10 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa c.json(await deps.dispatch("token.list", {}, buildHttpSession(c.get("identity")))), ); + app.get("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/v1/identity", agentAuth, async (c) => + c.json(await deps.dispatch("identity.get", {}, buildHttpSession(c.get("identity")))), + ); + app.get("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/v1/devices", agentAuth, async (c) => { const devices = await deps.dispatch( "list.get", diff --git a/src/http/core-routes.test.ts b/src/http/core-routes.test.ts index b00c9c678..4d967fb98 100644 --- a/src/http/core-routes.test.ts +++ b/src/http/core-routes.test.ts @@ -44,6 +44,7 @@ describe("the routes createHttpApp registers", () => { "devices", "events", "healthz", + "identity", "lease-requests", "leases", "stats", diff --git a/src/http/dispatcher-session.ts b/src/http/dispatcher-session.ts index 7063bd1b1..355211c5f 100644 --- a/src/http/dispatcher-session.ts +++ b/src/http/dispatcher-session.ts @@ -25,6 +25,14 @@ function toRole(identityRole: Identity["role"]): Role { return identityRole === "operator" ? "admin" : "agent"; } +const VIA_VALUES = ["token", "proxy", "socket", "uplink"] as const; + +function toVia(via: string): DispatchSession["via"] { + const known = VIA_VALUES.find((value) => value === via); + if (known === undefined) throw new Error(`Unknown identity via: ${via}`); + return known; +} + // why: `onProgress` and the like are per-call, not part of the identity, so the routes that need one pass an override in `extra`; every other route gets inert defaults that no operation it dispatches ever calls. export function buildHttpSession( @@ -61,7 +69,9 @@ export function buildHttpSession( return { manageEventSubscription: extra?.manageEventSubscription ?? (() => undefined), principal: identity.principal, + name: identity.name, role: toRole(identity.role), + via: toVia(identity.via), ...(extra?.onProgress === undefined ? {} : { onProgress: extra.onProgress }), ...(extra?.onRequestAdmitted === undefined ? {} diff --git a/src/modules/types.ts b/src/modules/types.ts index 69979dda7..13be758c8 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -66,6 +66,8 @@ export type ModuleRelayTarget = ( export interface ModuleDispatchSession { readonly principal: string; readonly role: Role; + readonly name?: string; + readonly via: "token" | "proxy" | "socket" | "uplink"; readonly manageEventSubscription: (subscribe: boolean) => string | undefined; } diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index a2502d780..2f350251f 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -521,7 +521,7 @@ class SimlockClientImpl { } identity(): Promise { - return Promise.reject(new Error("not implemented")); + return this.#call("identity.get", {}); } listComponents(input: ComponentListInput = {}): Promise { From c4ef238392da6e6b5b4654827d5ba8e9ad3041cd Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 16:48:46 +0200 Subject: [PATCH 3/5] chore: keep fallow quiet about identity.get's operation and the MCP fake (#713) --- src/contract/operations.ts | 2 +- src/mcp/test-support.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 90ff239af..8011ec40b 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -1028,7 +1028,7 @@ export const relayCancel = defineOperation({ output: z.object({}), }); -export const identityGet = defineOperation({ +const identityGet = defineOperation({ name: "identity.get", role: "agent", effect: "read", diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 5c2fbe57b..41a266642 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -94,6 +94,7 @@ export class FakeSimlockClient implements SimlockClient { return this.#dead ? this.#deadConnection() : this.getCatalogImpl(input); } + // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP exposes no identity tool of its own. identity(): Promise { this.calls.push({ input: undefined, method: "identity" }); return this.#dead ? this.#deadConnection() : Promise.reject(new Error("not implemented")); From 2c397d5b09a1d796b56f8c5d4647558697541ee5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 17:02:18 +0200 Subject: [PATCH 4/5] fix: derive via from the contract and list whoami and identity.get in the help and docs (#713) --- docs/CLI.md | 2 +- src/cli/index.ts | 2 +- src/contract/AGENTS.md | 2 +- src/http/dispatcher-session.ts | 5 +++-- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index fb473d3d3..231220d6c 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -3,7 +3,7 @@ Part of the user manual: every command the simlock CLI is expected to implement. Results are JSON on **stdout**; progress/diagnostics are JSON lines on **stderr** — this is the default output, not an opt-in, because -agents are the primary audience. `status`, `catalog`, `stats` and +agents are the primary audience. `status`, `catalog`, `stats`, `whoami`, and `daemon ` are the exception: they default to a human-oriented view for interactive/operator use and accept `--json` to switch to the structured form. Every other command's output is already diff --git a/src/cli/index.ts b/src/cli/index.ts index 71fb8c2b7..7728dcc92 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -15,7 +15,7 @@ const USAGE = `Usage: simlock [options] Commands: lease, release, status, list, catalog, cleanup, doctor, nuke, events, stats, - daemon, config, token + daemon, config, token, whoami worker Inspect and manage the workers of a gateway; on a single host, list shows the host itself diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index abb62b82d..b538e9c27 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -30,7 +30,7 @@ park on readiness (all but `status.get`) → handler → parse output. `src/daemon/dispatcher.ts` and `src/gateway/dispatcher.ts` each hold a handler for every operation but `daemon.stop`, which `DaemonServer` answers. -- `agent`: `catalog.get`, `status.get`, `component.list`, `lease.request`, `lease.cancel`, +- `agent`: `identity.get`, `catalog.get`, `status.get`, `component.list`, `lease.request`, `lease.cancel`, `lease.renew`, `lease.release`, `lease.list`, `driver.passthrough`, `device.exec`, `doctor.run` without `fix` or `purgeOrphans`. - `admin`: every other operation (`list.get`, `config.get`, `daemon.stop`, `events.*`, diff --git a/src/http/dispatcher-session.ts b/src/http/dispatcher-session.ts index 355211c5f..b56f761cd 100644 --- a/src/http/dispatcher-session.ts +++ b/src/http/dispatcher-session.ts @@ -2,7 +2,8 @@ import type { z } from "zod"; import type { DispatchSession } from "../daemon/dispatcher.js"; import type { LeaseProgress } from "../core/index.js"; -import type { ComponentProgress, OPERATIONS, OperationName, Role } from "../contract/index.js"; +import { OPERATIONS } from "../contract/index.js"; +import type { ComponentProgress, OperationName, Role } from "../contract/index.js"; import type { Identity } from "../auth/index.js"; /** @@ -25,7 +26,7 @@ function toRole(identityRole: Identity["role"]): Role { return identityRole === "operator" ? "admin" : "agent"; } -const VIA_VALUES = ["token", "proxy", "socket", "uplink"] as const; +const VIA_VALUES = OPERATIONS["identity.get"].output.shape.via.options; function toVia(via: string): DispatchSession["via"] { const known = VIA_VALUES.find((value) => value === via); From fde8ac984c459cf9255bebf420bb78dab4b652c4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 20:02:06 +0200 Subject: [PATCH 5/5] test: Give the sessions main.test.ts builds a via (#713) --- src/daemon/main.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index d678a4a46..4e49ba559 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -1593,6 +1593,7 @@ describe("startDaemon HTTP status for a quarantined device", () => { manageEventSubscription: () => undefined, principal: "agent-1", role: "agent", + via: "socket", } as const; const grant = (await daemon.dispatch( "lease.request", @@ -2142,7 +2143,12 @@ describe("startDaemon event history", () => { const status = (await daemon.dispatch( "status.get", {}, - { manageEventSubscription: () => undefined, principal: "operator", role: "admin" }, + { + manageEventSubscription: () => undefined, + principal: "operator", + role: "admin", + via: "socket", + }, )) as { readonly history?: unknown }; expect(daemon.health).toBe("running"); expect(names).toContain("history.db.damaged-1000");