diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index 953bef0f..f9587994 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -51,6 +51,22 @@ Gateway and runs Agents. The daemon exits with the app. ComputerDaemon, Status, PowerGuard, WindowManager, Tray, DesktopIpc). `status.ts`, `tray-menu.ts` and `tray-icon.ts` hold the pure status summary, tray menu and tray icons, drawn from the logo PNGs in `resources/tray/` with a status badge. +- `src/main/enrollment.ts`: Enrollment. Every enrollment names this + machine's Daemon ID, read from the public key in + `/computer/state/daemon-identity.json`, which outlives + unenrolling, when the server's `/v0/me` lists the + `local_computer_enrollment_daemon_id` server capability; a TeamHub older + than the desktop omits it and gets the request without `daemon_id`, which + it would reject. TeamHub then renews the signed-in owner's Computer that holds + that Daemon Identity, with its Agents, instead of pairing a new one, and + removes the Computer the request named if it never connected and has no + Agents (the orphan an earlier Set Up Again left). Another account's + Computer holding it refuses with `DAEMON_IDENTITY_IN_USE`, shown as "This + computer is connected to another Linger account". The config keeps the + Daemon ID the enrollment named; at start an enrollment that named none or + another one is renewed once the server lists the capability, which heals a + computer stuck behind its own Daemon Identity. The Runner Gateway closes a Computer whose Daemon Identity + another Computer holds with 1008 `daemon_identity_in_use:`. - `src/main/local-server.ts`: LocalServer, the setup page's Quick Install path. It fetches the pinned Node runtime and unpacks the linger source package into the install location (the default home, or a folder picked under @@ -190,7 +206,8 @@ Gateway and runs Agents. The daemon exits with the app. finishes it, reusing a finished job only while its origin answers (a stopped server gets a new job, which starts the services again). The start failure page's Set Up Again forgets the record, unenrolls the computer, clears the - server address and shows setup; the instance and its data stay. Before installing or resuming it moves the + server address and shows setup; the instance and its data stay, and the + next enrollment gets the same Computer back (see `src/main/enrollment.ts`). Before installing or resuming it moves the `COMPOSIO_API_KEY`, `SONIOX_API_KEY`, `XAI_API_KEY` and `TZ` of an unpacked source package's `.env` into `/instances/desktop/user.env` once and deletes that `.env` (never a `LINGER_CHECKOUT`'s), logging only the names diff --git a/apps/desktop/src/main/config.ts b/apps/desktop/src/main/config.ts index c1084f37..afbe998c 100644 --- a/apps/desktop/src/main/config.ts +++ b/apps/desktop/src/main/config.ts @@ -24,6 +24,9 @@ const desktopConfig = z.object({ computerId: z.string().optional(), tenantId: z.string().optional(), ownerActorId: z.string().optional(), + // The Daemon ID this computer's enrollment named; an enrollment that named + // none or another one is renewed at start. + daemonId: z.string().optional(), workspaceGrants: z.array(workspaceGrant).default([]), // Always-on mode: keep the system awake even when idle. preventSleep: z.boolean().default(false), diff --git a/apps/desktop/src/main/enrollment.test.ts b/apps/desktop/src/main/enrollment.test.ts index 2c022635..7af4b914 100644 --- a/apps/desktop/src/main/enrollment.test.ts +++ b/apps/desktop/src/main/enrollment.test.ts @@ -1,8 +1,18 @@ import { createHash } from "node:crypto"; +import { writeFileSync } from "node:fs"; +import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; -import { EnrollmentError, enrollComputer } from "./enrollment.js"; +import { CredentialStore } from "./computer-credential.js"; +import type { DesktopConfig } from "./config.js"; +import { + EnrollmentError, + EnrollmentModule, + enrollComputer, + readDaemonId, +} from "./enrollment.js"; +import { stubModule, tempDirectory, testHost } from "./test-support.js"; const claims = (value: object): string => Buffer.from(JSON.stringify(value)).toString("base64url"); @@ -19,7 +29,13 @@ interface Call { } const fakeServer = ( - overrides: { exchangeStatus?: number; bundle?: Record } = {}, + overrides: { + capabilities?: readonly string[]; + createStatus?: number; + createError?: string; + exchangeStatus?: number; + bundle?: Record; + } = {}, ): { fetch: typeof fetch; calls: Call[] } => { const calls: Call[] = []; let challenge = ""; @@ -37,8 +53,24 @@ const fakeServer = ( const json = (value: unknown, status = 200): Response => new Response(JSON.stringify(value), { status }); if (input.pathname === "/v0/me") - return json({ actors: [{ kind: "human", tenant_id: "tenant_acme" }] }); + return json({ + actors: [{ kind: "human", tenant_id: "tenant_acme" }], + ...(overrides.capabilities + ? { server_capabilities: overrides.capabilities } + : {}), + }); if (input.pathname.endsWith("/local-computer-enrollments")) { + if (overrides.createStatus) + return json( + { + error: { + code: overrides.createError ?? "INTERNAL_ERROR", + message: "Refused", + request_id: "request_1", + }, + }, + overrides.createStatus, + ); challenge = String(body?.code_challenge); return json({ enrollment_id: "enr_1", @@ -134,6 +166,44 @@ describe("enrollComputer", () => { ).rejects.toMatchObject({ code: "INVALID_RESPONSE" }); }); + it("names the machine's Daemon so TeamHub can renew the Computer it holds", async () => { + const server = fakeServer({ capabilities: DAEMON_CAPABLE }); + const enrolled = await enrollComputer({ + ...input, + daemonId: DAEMON_ID, + fetch: server.fetch, + }); + expect(server.calls[1]?.body).toMatchObject({ daemon_id: DAEMON_ID }); + expect(enrolled.daemonId).toBe(DAEMON_ID); + }); + + it("enrolls without the Daemon on a server that does not accept it", async () => { + // A team server older than the desktop rejects fields it does not know. + const server = fakeServer({ capabilities: [] }); + const enrolled = await enrollComputer({ + ...input, + daemonId: DAEMON_ID, + fetch: server.fetch, + }); + expect(server.calls[1]?.body).not.toHaveProperty("daemon_id"); + expect(enrolled).toMatchObject({ computerId: "computer_1" }); + expect(enrolled.daemonId).toBeUndefined(); + }); + + it("reports a Daemon another account's Computer holds", async () => { + const failure = await enrollComputer({ + ...input, + daemonId: DAEMON_ID, + fetch: fakeServer({ + capabilities: DAEMON_CAPABLE, + createStatus: 409, + createError: "DAEMON_IDENTITY_IN_USE", + }).fetch, + }).catch((error: unknown) => error); + expect(failure).toBeInstanceOf(EnrollmentError); + expect(failure).toMatchObject({ code: "DAEMON_IDENTITY_IN_USE" }); + }); + it("reports a removed enrollment", async () => { const failure = await enrollComputer({ ...input, @@ -158,3 +228,151 @@ describe("enrollComputer", () => { ).rejects.toMatchObject({ code: "INVALID_RESPONSE" }); }); }); + +// The daemon keeps its identity key (public and private) here; the Daemon ID +// is the SHA-256 of the raw public key, as the daemon derives it. +const PUBLIC_KEY = Buffer.alloc(32, 7); +const DAEMON_CAPABLE = ["local_computer_enrollment_daemon_id"]; +const DAEMON_ID = createHash("sha256").update(PUBLIC_KEY).digest("base64url"); + +const daemonIdentityFile = (): string => { + const file = path.join(tempDirectory(), "daemon-identity.json"); + writeFileSync( + file, + JSON.stringify({ + public_key: PUBLIC_KEY.toString("base64").replace(/=+$/, ""), + private_key: Buffer.alloc(64, 9).toString("base64").replace(/=+$/, ""), + }), + ); + return file; +}; + +const startEnrollment = async ( + config: Partial, + options: { + credentialFor?: string; + capabilities?: readonly string[]; + } = {}, +) => { + const server = fakeServer({ + capabilities: options.capabilities ?? DAEMON_CAPABLE, + }); + const credentials = new CredentialStore( + path.join(tempDirectory(), "credential.json"), + ); + if (options.credentialFor) + credentials.write({ + computerId: options.credentialFor, + gatewayUrl: "wss://linger.example.com/v1/runner", + token: TOKEN, + }); + const module = new EnrollmentModule({ + sessionCookie: async () => "teamhub_session=abc", + defaultDisplayName: "Laptop", + credentials, + daemonIdentityFile: daemonIdentityFile(), + fetch: server.fetch, + }); + const host = testHost([stubModule("Config"), module], { + serverUrl: "https://linger.example.com", + ...config, + }); + await host.start(); + return { host, module, server }; +}; + +describe("readDaemonId", () => { + it("derives the Daemon ID from the stored public key", () => { + expect(readDaemonId(daemonIdentityFile())).toBe(DAEMON_ID); + }); + + it("has none before the daemon first ran", () => { + expect( + readDaemonId(path.join(tempDirectory(), "daemon-identity.json")), + ).toBeUndefined(); + }); +}); + +describe("EnrollmentModule", () => { + it("pairs the Computer the daemon holds after Set Up Again forgot it", async () => { + const { host, module, server } = await startEnrollment({}); + await module.enroll(); + const create = server.calls.find((call) => + call.url.endsWith("/local-computer-enrollments"), + ); + expect(create?.body).toMatchObject({ daemon_id: DAEMON_ID }); + expect(create?.body).not.toHaveProperty("computer_id"); + expect(host.ctx.config.get()).toMatchObject({ + computerId: "computer_1", + daemonId: DAEMON_ID, + }); + }); + + it("renews once an enrollment made without the daemon's identity", async () => { + // Set Up Again in an earlier release paired the orphan computer_9 while + // the daemon's identity stayed with computer_1. + const { host, server } = await startEnrollment( + { + computerId: "computer_9", + tenantId: "tenant_acme", + ownerActorId: "actor_ann", + }, + { credentialFor: "computer_9" }, + ); + await vi.waitFor(() => + expect(host.ctx.config.get().computerId).toBe("computer_1"), + ); + expect( + server.calls.find((call) => + call.url.endsWith("/local-computer-enrollments"), + )?.body, + ).toMatchObject({ computer_id: "computer_9", daemon_id: DAEMON_ID }); + expect(host.ctx.config.get().daemonId).toBe(DAEMON_ID); + }); + + it("enrolls without the daemon's identity on a server that does not accept it", async () => { + const { host, module, server } = await startEnrollment( + {}, + { capabilities: [] }, + ); + await module.enroll(); + expect( + server.calls.find((call) => + call.url.endsWith("/local-computer-enrollments"), + )?.body, + ).not.toHaveProperty("daemon_id"); + expect(host.ctx.config.get()).toMatchObject({ computerId: "computer_1" }); + expect(host.ctx.config.get().daemonId).toBeUndefined(); + }); + + it("does not renew at start only to name the daemon to a server that cannot take it", async () => { + const { host, server } = await startEnrollment( + { + computerId: "computer_9", + tenantId: "tenant_acme", + ownerActorId: "actor_ann", + }, + { credentialFor: "computer_9", capabilities: [] }, + ); + await vi.waitFor(() => + expect(server.calls.map((call) => call.url)).toEqual(["/v0/me"]), + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(server.calls.map((call) => call.url)).toEqual(["/v0/me"]); + expect(host.ctx.config.get().computerId).toBe("computer_9"); + }); + + it("does not renew an enrollment made with the daemon's identity", async () => { + const { server } = await startEnrollment( + { + computerId: "computer_1", + tenantId: "tenant_acme", + ownerActorId: "actor_ann", + daemonId: DAEMON_ID, + }, + { credentialFor: "computer_1" }, + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(server.calls).toEqual([]); + }); +}); diff --git a/apps/desktop/src/main/enrollment.ts b/apps/desktop/src/main/enrollment.ts index b8e5dbaa..e754ae49 100644 --- a/apps/desktop/src/main/enrollment.ts +++ b/apps/desktop/src/main/enrollment.ts @@ -1,4 +1,5 @@ import { createHash, randomBytes } from "node:crypto"; +import { readFileSync } from "node:fs"; import type { components } from "@linger/wire-contracts/teamhub-public/types"; @@ -10,6 +11,11 @@ type CreateRequest = Schemas["LocalComputerEnrollmentCreateRequest"]; type Authorization = Schemas["LocalComputerEnrollmentAuthorization"]; type ExchangeRequest = Schemas["LocalComputerEnrollmentExchangeRequest"]; type CredentialBundle = Schemas["LocalComputerCredentialBundle"]; +type ServerCapability = NonNullable< + Schemas["CurrentIdentity"]["server_capabilities"] +>[number]; +const DAEMON_ID_CAPABILITY: ServerCapability = + "local_computer_enrollment_daemon_id"; // The main process both creates and exchanges the enrollment, so nothing is // ever redirected here. TeamHub still requires a loopback redirect URI. @@ -23,6 +29,7 @@ export class EnrollmentError extends Error { | "NO_TENANT" | "REJECTED" | "ENROLLMENT_REMOVED" + | "DAEMON_IDENTITY_IN_USE" | "INVALID_RESPONSE", message: string, ) { @@ -38,6 +45,10 @@ export interface EnrollInput { readonly displayName: string; // Keeps the same Computer identity when enrolling again. readonly computerId?: string; + // This machine's Daemon ID. TeamHub renews the owner's Computer that holds + // it instead of computerId or a new Computer. Sent only to a server that + // lists the capability, since an older one rejects the field. + readonly daemonId?: string; readonly fetch?: typeof fetch; } @@ -49,6 +60,8 @@ export interface Enrolled { // The Runner Gateway the daemon connects to (ws or wss). readonly gatewayUrl: string; readonly credential: string; + // The Daemon ID the enrollment named, when the server accepted one. + readonly daemonId?: string; } // PKCE enrollment for this computer with the current web session: @@ -77,9 +90,12 @@ export const enrollComputer = async (input: EnrollInput): Promise => { if (me.status === 401) throw new EnrollmentError("NOT_SIGNED_IN", "Sign in before enrolling"); if (!me.ok) throw rejected("Reading the signed-in account", me.status); - const tenantId = humanTenant(await me.json()); + const identity: unknown = await me.json(); + const tenantId = humanTenant(identity); if (!tenantId) throw new EnrollmentError("NO_TENANT", "The account has no workspace"); + const daemonId = + input.daemonId && acceptsDaemonId(identity) ? input.daemonId : undefined; const verifier = randomBytes(32).toString("base64url"); const createBody: CreateRequest = { @@ -87,6 +103,7 @@ export const enrollComputer = async (input: EnrollInput): Promise => { redirect_uri: REDIRECT_URI, code_challenge: createHash("sha256").update(verifier).digest("base64url"), ...(input.computerId ? { computer_id: input.computerId } : {}), + ...(daemonId ? { daemon_id: daemonId } : {}), }; const created = await call( `/v0/tenants/${encodeURIComponent(tenantId)}/local-computer-enrollments`, @@ -94,6 +111,14 @@ export const enrollComputer = async (input: EnrollInput): Promise => { ); if (created.status === 401) throw new EnrollmentError("NOT_SIGNED_IN", "Sign in before enrolling"); + if ( + created.status === 409 && + (await errorCode(created)) === "DAEMON_IDENTITY_IN_USE" + ) + throw new EnrollmentError( + "DAEMON_IDENTITY_IN_USE", + "This computer is connected to another Linger account. Remove it from that account's Computers, then connect it again.", + ); if (!created.ok) throw rejected("Creating the enrollment", created.status); const authorization = (await created.json()) as Authorization; if (!authorization.enrollment_id || !authorization.authorization_code) @@ -137,9 +162,20 @@ export const enrollComputer = async (input: EnrollInput): Promise => { ownerActorId, gatewayUrl: bundle.gateway_url, credential: bundle.gateway_token, + ...(daemonId ? { daemonId } : {}), }; }; +// Whether the server's /v0/me lists that its enrollment accepts daemon_id. +// A TeamHub older than the desktop omits the list and rejects the field. +export const acceptsDaemonId = (identity: unknown): boolean => { + const capabilities = (identity as { server_capabilities?: unknown }) + ?.server_capabilities; + return ( + Array.isArray(capabilities) && capabilities.includes(DAEMON_ID_CAPABILITY) + ); +}; + const isGatewayUrl = (value: unknown): value is string => { if (typeof value !== "string") return false; try { @@ -190,6 +226,33 @@ export const humanTenant = (value: unknown): string | undefined => { return human?.tenant_id; }; +const errorCode = async (response: Response): Promise => { + try { + const body = (await response.json()) as { error?: { code?: unknown } }; + return body.error?.code; + } catch { + return undefined; + } +}; + +// The Daemon ID of the daemon's identity file, derived as the daemon derives +// it: the SHA-256 of the raw public key. Only the public key is read. None +// before the daemon first ran, or when the file is unreadable. +export const readDaemonId = (file: string): string | undefined => { + try { + const identity = JSON.parse(readFileSync(file, "utf8")) as { + public_key?: unknown; + }; + if (typeof identity.public_key !== "string") return undefined; + const publicKey = Buffer.from(identity.public_key, "base64"); + return publicKey.length === 32 + ? createHash("sha256").update(publicKey).digest("base64url") + : undefined; + } catch { + return undefined; + } +}; + const rejected = (step: string, status: number): EnrollmentError => new EnrollmentError("REJECTED", `${step} failed (${String(status)})`); const invalid = (): EnrollmentError => @@ -204,6 +267,9 @@ export interface EnrollmentOptions { readonly defaultDisplayName: string; // Where the Gateway credential is kept for the daemon. readonly credentials: CredentialStore; + // The daemon's identity file, which keeps the machine's Daemon Identity + // across enrollments. + readonly daemonIdentityFile: string; readonly fetch?: typeof fetch; } @@ -233,15 +299,23 @@ export class EnrollmentModule implements Module { // Enrollments made before the owner was kept, or whose credential did // not carry over from the bridge, are renewed for the same Computer. const config = ctx.config.get(); + if (!config.computerId) return; + const renewFailed = (error: unknown): void => + ctx.log.warn("enrollment.renew_failed", { error: String(error) }); if ( - config.computerId && - (!config.ownerActorId || - this.#options.credentials.read()?.computerId !== config.computerId) + !config.ownerActorId || + this.#options.credentials.read()?.computerId !== config.computerId ) { - void this.enroll().catch((error: unknown) => - ctx.log.warn("enrollment.renew_failed", { error: String(error) }), - ); + void this.enroll().catch(renewFailed); + return; } + // So are enrollments that did not name the daemon's identity, once the + // server accepts it: Set Up Again in an earlier release paired a new + // Computer whose daemon identity another Computer holds, and TeamHub + // renews the holder instead. + const daemonId = readDaemonId(this.#options.daemonIdentityFile); + if (daemonId !== undefined && config.daemonId !== daemonId) + void this.#nameDaemon().catch(renewFailed); } async stop(): Promise { @@ -250,10 +324,16 @@ export class EnrollmentModule implements Module { // Whether the window holds a valid session for the configured server. async signedIn(): Promise { + return (await this.#identity()) !== undefined; + } + + // The signed-in identity (/v0/me) on the configured server, or undefined + // when signed out or unreachable. + async #identity(): Promise { const serverUrl = this.#ctx!.config.get().serverUrl; - if (!serverUrl) return false; + if (!serverUrl) return undefined; const cookie = await this.#options.sessionCookie(serverUrl); - if (!cookie) return false; + if (!cookie) return undefined; try { const response = await (this.#options.fetch ?? fetch)( new URL("/v0/me", serverUrl), @@ -263,12 +343,18 @@ export class EnrollmentModule implements Module { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }, ); - return response.ok; + return response.ok ? ((await response.json()) as unknown) : undefined; } catch { - return false; + return undefined; } } + // Renews the enrollment so it names the daemon's identity, only on a + // server that accepts it; on an older one nothing changes until it does. + async #nameDaemon(): Promise { + if (acceptsDaemonId(await this.#identity())) await this.enroll(); + } + enroll(): Promise<{ computerId: string }> { // Concurrent clicks share one enrollment instead of creating two. this.#pending ??= this.#enroll().finally(() => { @@ -284,6 +370,7 @@ export class EnrollmentModule implements Module { computerId: undefined, tenantId: undefined, ownerActorId: undefined, + daemonId: undefined, }); ctx.bus.emit("computer.changed", undefined); ctx.log.info("enrollment.cleared"); @@ -296,11 +383,13 @@ export class EnrollmentModule implements Module { const cookie = await this.#options.sessionCookie(config.serverUrl); if (!cookie) throw new EnrollmentError("NOT_SIGNED_IN", "Sign in before enrolling"); + const daemonId = readDaemonId(this.#options.daemonIdentityFile); const enrolled = await enrollComputer({ serverUrl: config.serverUrl, cookie, displayName: config.displayName ?? this.#options.defaultDisplayName, ...(config.computerId ? { computerId: config.computerId } : {}), + ...(daemonId ? { daemonId } : {}), ...(this.#options.fetch ? { fetch: this.#options.fetch } : {}), }); this.#options.credentials.write({ @@ -312,6 +401,7 @@ export class EnrollmentModule implements Module { computerId: enrolled.computerId, tenantId: enrolled.tenantId, ownerActorId: enrolled.ownerActorId, + daemonId: enrolled.daemonId, }); ctx.bus.emit("computer.changed", enrolled.computerId); ctx.log.info("enrollment.completed", { computer_id: enrolled.computerId }); diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 2c822a8f..837acaf8 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -268,6 +268,11 @@ async function main(): Promise { new EnrollmentModule({ defaultDisplayName, credentials, + daemonIdentityFile: path.join( + daemonDirectory, + "state", + "daemon-identity.json", + ), sessionCookie: webSessionCookie, }), new WorkspaceGrantsModule({ diff --git a/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts b/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts index c67f3b00..82aa0f37 100644 --- a/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts +++ b/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts @@ -15,6 +15,7 @@ import { type RuntimeStateSchemas, type TeamHubRuntimeStateClient, } from "../executor/teamhub-runtime-state-client.js"; +import { RunnerDaemonIdentityInUseError } from "./runner-operation.js"; export interface LocalComputerOwner { readonly ownerActorId: string; @@ -117,26 +118,38 @@ export const createTeamHubLocalComputerRegistry = ( status, recommendedVersion, }) { - const result = await client.connectLocalComputer({ - computer_id: computerId, - owner: { tenant_id: owner.tenantId, owner_actor_id: owner.ownerActorId }, - credential_generation: String(credentialGeneration), - daemon_id: hello.daemon_identity.daemon_id, - daemon_public_key: hello.daemon_identity.public_key, - identity_version: String(hello.daemon_identity.identity_version), - status, - seen_at: new Date().toISOString(), - display_name: hello.display_name ?? computerId, - platform: hello.platform, - ...(hello.capacity === undefined ? {} : { capacity: hello.capacity }), - runtimes: [...hello.runtimes], - runtime_diagnostics: jsonObjects(hello.runtime_diagnostics), - workspace_grants: jsonObjects(hello.workspace_grants), - daemon_version: hello.daemon_version, - ...(recommendedVersion === undefined - ? {} - : { recommended_version: recommendedVersion }), - }); + const result = await client + .connectLocalComputer({ + computer_id: computerId, + owner: { + tenant_id: owner.tenantId, + owner_actor_id: owner.ownerActorId, + }, + credential_generation: String(credentialGeneration), + daemon_id: hello.daemon_identity.daemon_id, + daemon_public_key: hello.daemon_identity.public_key, + identity_version: String(hello.daemon_identity.identity_version), + status, + seen_at: new Date().toISOString(), + display_name: hello.display_name ?? computerId, + platform: hello.platform, + ...(hello.capacity === undefined ? {} : { capacity: hello.capacity }), + runtimes: [...hello.runtimes], + runtime_diagnostics: jsonObjects(hello.runtime_diagnostics), + workspace_grants: jsonObjects(hello.workspace_grants), + daemon_version: hello.daemon_version, + ...(recommendedVersion === undefined + ? {} + : { recommended_version: recommendedVersion }), + }) + .catch((error: unknown) => { + if ( + error instanceof TeamHubRuntimeStateError && + error.code === "DAEMON_IDENTITY_IN_USE" + ) + throw new RunnerDaemonIdentityInUseError(); + throw error; + }); return result.placements.map((placement) => ({ agentId: placement.agent_id, tenantId: placement.tenant_id, diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts index 156c42df..cc1cfe5e 100644 --- a/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts +++ b/apps/node-services/src/agent/runner-gateway/runner-gateway-websocket.ts @@ -25,6 +25,7 @@ import { import type { OperationEnvelope } from "./runner-operation.js"; import { RunnerGatewayProtocolError, + RunnerDaemonIdentityInUseError, RunnerUpgradeRequiredError, type InvalidOperationFrame, type RunnerGateway, @@ -68,6 +69,11 @@ const MAX_QUEUED_BYTES = 16 * 1024 * 1024; const MAX_TIMER_DELAY_MS = 2_147_000_000; export const RUNNER_UPGRADE_REQUIRED_CLOSE_REASON = "upgrade_required: rerun the Linger Computer installer"; +// 1008 without upgrade_required keeps the Daemon redialing on backoff and +// counts no fault against its release; the Computer's app renews the +// Computer that holds the identity. +export const RUNNER_DAEMON_IDENTITY_IN_USE_CLOSE_REASON = + "daemon_identity_in_use: another Computer holds this daemon identity"; // Every Computer release that can update itself declares this in its hello. const SELF_UPDATE_CAPABILITY = "self_update_v2"; @@ -653,6 +659,13 @@ export class RunnerSocketSession { this.#closeProtocol(1008, RUNNER_UPGRADE_REQUIRED_CLOSE_REASON); return; } + if (error instanceof RunnerDaemonIdentityInUseError) { + logAgentEvent("warn", "runner.hello.daemon_identity_in_use", { + computerId: this.#credential.runnerId, + }); + this.#closeProtocol(1008, RUNNER_DAEMON_IDENTITY_IN_USE_CLOSE_REASON); + return; + } this.#closeProtocol( error instanceof RunnerCredentialScopeError ? 1008 diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts index d50771cf..f6d4bcae 100644 --- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts +++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts @@ -114,6 +114,7 @@ export type { RunnerModelInvokeRequest, } from "./runner-model-invocation.js"; export { + RunnerDaemonIdentityInUseError, RunnerGatewayError, RunnerGatewayProtocolError, RunnerOperationError, diff --git a/apps/node-services/src/agent/runner-gateway/runner-operation.ts b/apps/node-services/src/agent/runner-gateway/runner-operation.ts index 26bf91d5..6e8c75f4 100644 --- a/apps/node-services/src/agent/runner-gateway/runner-operation.ts +++ b/apps/node-services/src/agent/runner-gateway/runner-operation.ts @@ -181,6 +181,22 @@ export class RunnerUpgradeRequiredError extends RunnerGatewayError { } } +/** + * Another Computer holds the Daemon Identity this Computer connected with: + * the machine was paired again as a new Computer while the one its Daemon + * belongs to was kept. The Computer's app renews the holder to recover. + */ +export class RunnerDaemonIdentityInUseError extends RunnerGatewayError { + readonly code = "daemon_identity_in_use"; + + constructor( + message = "Another Local Computer holds this Computer's Daemon Identity", + ) { + super(message); + this.name = "RunnerDaemonIdentityInUseError"; + } +} + export class RunnerOperationError extends RunnerGatewayError { constructor( readonly code: string, diff --git a/apps/node-services/tests/agent/runner-gateway/local-computer-registry.test.ts b/apps/node-services/tests/agent/runner-gateway/local-computer-registry.test.ts new file mode 100644 index 00000000..45fd19de --- /dev/null +++ b/apps/node-services/tests/agent/runner-gateway/local-computer-registry.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from "vitest"; + +import { TeamHubRuntimeStateError } from "../../../src/agent/executor/teamhub-runtime-state-client.js"; +import { createTeamHubLocalComputerRegistry } from "../../../src/agent/runner-gateway/local-computer-registry.js"; +import { RunnerDaemonIdentityInUseError } from "../../../src/agent/runner-gateway/runner-gateway.js"; +import { MINIMUM_CURRENT_COMPUTER_VERSION } from "../../../src/agent/runner-gateway/local-computer-management.js"; +import { + CURRENT_RUNNER_CAPABILITIES, + currentRunnerIdentity, +} from "../test-support/runner-capabilities.js"; +import { runtimeDiagnostics } from "./runtime-diagnostics-fixture.js"; + +const unused = (): never => { + throw new Error("not called"); +}; + +describe("TeamHub Local Computer registry", () => { + it("reports a Daemon Identity another Computer holds as its own error", async () => { + const registry = createTeamHubLocalComputerRegistry({ + getLocalComputer: unused, + touchLocalComputer: unused, + removeLocalComputer: unused, + recordLocalModels: unused, + connectLocalComputer: () => + Promise.reject( + new TeamHubRuntimeStateError( + 409, + "Another Local Computer holds this Daemon Identity", + "DAEMON_IDENTITY_IN_USE", + ), + ), + }); + await expect( + registry.connect({ + computerId: "runner-local", + owner: { tenantId: "tenant-acme", ownerActorId: "actor-alice" }, + credentialGeneration: 0, + hello: { + type: "runner.hello", + platform: "darwin", + daemon_version: MINIMUM_CURRENT_COMPUTER_VERSION, + protocol_version: "2", + ...currentRunnerIdentity(), + capabilities: [...CURRENT_RUNNER_CAPABILITIES], + runner_id: "runner-local", + connection_nonce: "nonce-1", + sent_at: "2026-07-29T00:00:00.000Z", + runtimes: ["codex"], + runtime_diagnostics: runtimeDiagnostics(), + workspace_grants: [], + agent_runners: [], + active_operations: [], + }, + status: "offline", + }), + ).rejects.toBeInstanceOf(RunnerDaemonIdentityInUseError); + }); +}); diff --git a/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts index d0b124b6..a8d9c2bb 100644 --- a/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts +++ b/apps/node-services/tests/agent/runner-gateway/runner-gateway-websocket.test.ts @@ -40,10 +40,12 @@ import type { import { type RunnerCredentialAuthenticator } from "../../../src/agent/runner-gateway/runner-credential-authority.js"; import { attachRunnerGatewayWebSocket, + RUNNER_DAEMON_IDENTITY_IN_USE_CLOSE_REASON, RUNNER_UPGRADE_REQUIRED_CLOSE_REASON, type AttachRunnerGatewayWebSocketOptions, } from "../../../src/agent/runner-gateway/runner-gateway-websocket.js"; import { + RunnerDaemonIdentityInUseError, RunnerGatewayProtocolError, RunnerUpgradeRequiredError, type RunnerOperation, @@ -1168,6 +1170,26 @@ describe("Runner Gateway WebSocket", () => { } }); + it("turns away a Computer whose Daemon Identity another Computer holds with its own close reason", async () => { + const fixture = await startFixture(); + vi.spyOn(fixture.computerRegistry, "connect").mockRejectedValue( + new RunnerDaemonIdentityInUseError(), + ); + const socket = new WebSocket(fixture.url, { + headers: { Authorization: "Bearer runner-secret" }, + }); + await opened(socket); + const closed = onceClosed(socket); + socket.send(JSON.stringify(hello())); + // 1008 keeps the daemon redialing on backoff without counting a fault + // against its release. + expect(await closed).toEqual({ + code: 1008, + reason: RUNNER_DAEMON_IDENTITY_IN_USE_CLOSE_REASON, + }); + socket.terminate(); + }); + it("requires a reinstall from a protocol 2 build older than the first protocol 2 release", async () => { const fixture = await startFixture(); const socket = new WebSocket(fixture.url, { diff --git a/apps/teamhub/internal/agentruntimestate/runner.go b/apps/teamhub/internal/agentruntimestate/runner.go index c15aa190..974232e4 100644 --- a/apps/teamhub/internal/agentruntimestate/runner.go +++ b/apps/teamhub/internal/agentruntimestate/runner.go @@ -262,58 +262,129 @@ func (s *Service) RemoveLocalComputer(ctx context.Context, input LocalComputerCr }) } -func (s *Service) CreateLocalComputerEnrollment(ctx context.Context, input CreateLocalComputerEnrollmentInput) error { +// CreateLocalComputerEnrollment authorizes one enrollment and returns the +// Computer it pairs. A machine keeps its Daemon Identity when its app forgets +// the Computer (Set Up Again), so when one of the owner's Computers holds the +// Daemon ID the enrollment names, the enrollment renews that Computer, with +// its Agents, instead of the requested or a new one; see +// renewComputerHoldingDaemon. Another owner's Computer is never renewed. +func (s *Service) CreateLocalComputerEnrollment(ctx context.Context, input CreateLocalComputerEnrollmentInput) (string, error) { if !validText(input.EnrollmentID, 8, 128) || !validComputerID(input.ComputerID) || !validDisplayName(input.DisplayName) || !validOwner(input.Owner) || !validText(input.RedirectURI, 1, 2000) || - !validText(input.CodeChallenge, 43, 128) || len(input.AuthorizationCodeHash) != sha256.Size || input.ExpiresAt.IsZero() { - return ErrInvalid + !validText(input.CodeChallenge, 43, 128) || len(input.AuthorizationCodeHash) != sha256.Size || input.ExpiresAt.IsZero() || + (input.DaemonID != "" && !daemonIDPattern.MatchString(input.DaemonID)) { + return "", ErrInvalid } - _, err := executeLocalComputerTx(ctx, s, func(ctx context.Context, _ pgx.Tx, queries *store.Queries) (bool, *LocalComputerOwner, error) { + return executeLocalComputerTx(ctx, s, func(ctx context.Context, _ pgx.Tx, queries *store.Queries) (string, *LocalComputerOwner, error) { now, err := queries.AgentRuntimeDatabaseNow(ctx) if err != nil { - return false, nil, err + return "", nil, err } if !now.Valid || !input.ExpiresAt.After(now.Time) { - return false, nil, ErrInvalid + return "", nil, ErrInvalid } if err := requireOwnerActor(ctx, queries, input.Owner); err != nil { - return false, nil, err + return "", nil, err + } + var changed *LocalComputerOwner + if input.DaemonID != "" { + removedOrphan, err := renewComputerHoldingDaemon(ctx, queries, &input) + if err != nil { + return "", nil, err + } + if removedOrphan { + changed = &input.Owner + } } computer, lockComputerErr := queries.LockAgentRuntimeLocalComputer(ctx, input.ComputerID) if input.RenewsExistingComputer { if isNoRows(lockComputerErr) { - return false, nil, ErrNotFound + return "", nil, ErrNotFound } if lockComputerErr != nil { - return false, nil, lockComputerErr + return "", nil, lockComputerErr } if computer.OwnerTenantID != input.Owner.TenantID || computer.OwnerActorID != input.Owner.OwnerActorID { - return false, nil, ErrNotFound + return "", nil, ErrNotFound } if computer.Status == "removed" { - return false, nil, ErrRemoved + return "", nil, ErrRemoved } } else if lockComputerErr == nil || !isNoRows(lockComputerErr) { if lockComputerErr != nil { - return false, nil, lockComputerErr + return "", nil, lockComputerErr } - return false, nil, ErrConflict + return "", nil, ErrConflict } if err := queries.DeletePendingAgentRuntimeLocalComputerEnrollments(ctx, store.DeletePendingAgentRuntimeLocalComputerEnrollmentsParams{ TenantID: input.Owner.TenantID, OwnerActorID: input.Owner.OwnerActorID, }); err != nil { - return false, nil, err + return "", nil, err } - _, err = queries.InsertAgentRuntimeLocalComputerEnrollment(ctx, store.InsertAgentRuntimeLocalComputerEnrollmentParams{ + if _, err := queries.InsertAgentRuntimeLocalComputerEnrollment(ctx, store.InsertAgentRuntimeLocalComputerEnrollmentParams{ EnrollmentID: input.EnrollmentID, TenantID: input.Owner.TenantID, OwnerActorID: input.Owner.OwnerActorID, ComputerID: input.ComputerID, RenewsExistingComputer: input.RenewsExistingComputer, DisplayName: strings.TrimSpace(input.DisplayName), RedirectUri: input.RedirectURI, CodeChallenge: input.CodeChallenge, AuthorizationCodeHash: append([]byte(nil), input.AuthorizationCodeHash...), ExpiresAt: timestamptz(input.ExpiresAt), - }) - return true, nil, err + }); err != nil { + return "", nil, err + } + return input.ComputerID, changed, nil }) - return err +} + +// renewComputerHoldingDaemon points the enrollment at the owner's Computer +// that holds its Daemon ID, if there is one. The Computer the enrollment +// named instead is the orphan an earlier Set Up Again paired: it never +// connected, because the Daemon Identity it would bind was taken, so it is +// removed unless an Agent was placed on it. It reports that removal. +func renewComputerHoldingDaemon(ctx context.Context, queries *store.Queries, input *CreateLocalComputerEnrollmentInput) (bool, error) { + holder, err := queries.LockAgentRuntimeLocalComputerByDaemonID(ctx, input.DaemonID) + if isNoRows(err) { + return false, nil + } + if err != nil { + return false, err + } + if holder.OwnerTenantID != input.Owner.TenantID || holder.OwnerActorID != input.Owner.OwnerActorID { + return false, ErrDaemonIdentityInUse + } + if holder.ComputerID == input.ComputerID { + return false, nil + } + requested, renewsRequested := input.ComputerID, input.RenewsExistingComputer + input.ComputerID, input.RenewsExistingComputer = holder.ComputerID, true + if !renewsRequested { + return false, nil + } + orphan, err := queries.LockAgentRuntimeLocalComputer(ctx, requested) + if isNoRows(err) { + return false, nil + } + if err != nil { + return false, err + } + if orphan.Status == "removed" || orphan.DaemonID.Valid || + orphan.OwnerTenantID != input.Owner.TenantID || orphan.OwnerActorID != input.Owner.OwnerActorID { + return false, nil + } + placedAgents, err := queries.CountLocalAgentRegistrationsByComputer(ctx, store.CountLocalAgentRegistrationsByComputerParams{ + TenantID: input.Owner.TenantID, ComputerID: requested, + }) + if err != nil || placedAgents > 0 { + return false, err + } + if err := queries.PurgeAgentRuntimeLocalComputerEnrollmentsByComputer(ctx, requested); err != nil { + return false, err + } + if err := queries.DeleteLocalComputerModelSnapshot(ctx, requested); err != nil { + return false, err + } + if _, err := queries.RemoveAgentRuntimeLocalComputer(ctx, requested); err != nil { + return false, err + } + return true, nil } func (s *Service) ConsumeLocalComputerEnrollment(ctx context.Context, input ConsumeLocalComputerEnrollmentInput) (ConsumeLocalComputerEnrollmentResult, error) { diff --git a/apps/teamhub/internal/agentruntimestate/runner_types.go b/apps/teamhub/internal/agentruntimestate/runner_types.go index 92c91b8f..67410ca5 100644 --- a/apps/teamhub/internal/agentruntimestate/runner_types.go +++ b/apps/teamhub/internal/agentruntimestate/runner_types.go @@ -99,6 +99,9 @@ type CreateLocalComputerEnrollmentInput struct { AuthorizationCodeHash []byte `json:"authorization_code_hash"` ExpiresAt time.Time `json:"expires_at"` RenewsExistingComputer bool `json:"renews_existing_computer"` + // DaemonID names the Daemon Identity of the machine that enrolls, when it + // has one already. + DaemonID string `json:"daemon_id,omitempty"` } type ConsumeLocalComputerEnrollmentInput struct { diff --git a/apps/teamhub/internal/app/contract_server_agent_runtime_error_test.go b/apps/teamhub/internal/app/contract_server_agent_runtime_error_test.go index bf9846e9..71a214f6 100644 --- a/apps/teamhub/internal/app/contract_server_agent_runtime_error_test.go +++ b/apps/teamhub/internal/app/contract_server_agent_runtime_error_test.go @@ -28,6 +28,7 @@ func TestAgentRuntimeInboxAuthorizationDoesNotFenceContext(t *testing.T) { {"Context lease or identity", agentruntimestate.ErrFenced, 409, "CONTEXT_FENCED"}, {"real fence wins", errors.Join(agentruntimestate.ErrInboxNotAuthorized, agentruntimestate.ErrFenced), 409, "CONTEXT_FENCED"}, {"selection race", agentruntimestate.ErrConflict, 409, "AGENT_RUNTIME_CONFLICT"}, + {"Daemon Identity held by another Computer", agentruntimestate.ErrDaemonIdentityInUse, 409, "DAEMON_IDENTITY_IN_USE"}, } { t.Run(tc.name, func(t *testing.T) { response := httptest.NewRecorder() diff --git a/apps/teamhub/internal/app/contract_server_agent_runtime_state.go b/apps/teamhub/internal/app/contract_server_agent_runtime_state.go index edcb5837..8cea26d1 100644 --- a/apps/teamhub/internal/app/contract_server_agent_runtime_state.go +++ b/apps/teamhub/internal/app/contract_server_agent_runtime_state.go @@ -583,6 +583,8 @@ func (a *App) writeAgentRuntimeStateError(c *gin.Context, operation string, err status, code, message = http.StatusConflict, "CONTEXT_FENCED", "Agent Runtime Context identity or Agent Service epoch is no longer authoritative" case errors.Is(err, agentruntimestate.ErrInboxNotAuthorized): status, code, message = http.StatusForbidden, "INBOX_NOT_AUTHORIZED", "Agent Runtime Context cannot receive this Inbox" + case errors.Is(err, agentruntimestate.ErrDaemonIdentityInUse): + status, code, message = http.StatusConflict, "DAEMON_IDENTITY_IN_USE", "Another Local Computer holds this Daemon Identity" case errors.Is(err, agentruntimestate.ErrConflict): status, code, message = http.StatusConflict, "AGENT_RUNTIME_CONFLICT", "Agent Runtime State conflicts with the request" case errors.Is(err, agentruntimestate.ErrDependency): diff --git a/apps/teamhub/internal/app/handlers_local_computer_enrollment.go b/apps/teamhub/internal/app/handlers_local_computer_enrollment.go index 05220de7..61787354 100644 --- a/apps/teamhub/internal/app/handlers_local_computer_enrollment.go +++ b/apps/teamhub/internal/app/handlers_local_computer_enrollment.go @@ -23,6 +23,7 @@ import ( var ( localComputerIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`) localComputerPKCEPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) + localComputerDaemonPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) localComputerSecretPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43,128}$`) ) @@ -49,14 +50,18 @@ func (a *App) createLocalComputerEnrollment(c *gin.Context) { enrollmentID, authorizationCode := ids.New("enrollment"), newLocalComputerAuthorizationCode() codeHash := sha256.Sum256([]byte(authorizationCode)) expiresAt := time.Now().UTC().Add(localComputerEnrollmentLifetime) - err := a.agentRuntimeState.CreateLocalComputerEnrollment(c.Request.Context(), agentruntimestate.CreateLocalComputerEnrollmentInput{ + computerID, err := a.agentRuntimeState.CreateLocalComputerEnrollment(c.Request.Context(), agentruntimestate.CreateLocalComputerEnrollmentInput{ EnrollmentID: enrollmentID, ComputerID: computerID, DisplayName: request.DisplayName, Owner: agentruntimestate.LocalComputerOwner{TenantID: tenantID, OwnerActorID: ownerID}, RedirectURI: request.RedirectUri, CodeChallenge: request.CodeChallenge, AuthorizationCodeHash: codeHash[:], ExpiresAt: expiresAt, RenewsExistingComputer: renews, + DaemonID: optionalStringValue(request.DaemonId), }) switch { case err == nil: + case errors.Is(err, agentruntimestate.ErrDaemonIdentityInUse): + a.writeError(c, http.StatusConflict, "DAEMON_IDENTITY_IN_USE", "This computer is paired with another account's Local Computer") + return case errors.Is(err, agentruntimestate.ErrRemoved): a.writeError(c, http.StatusGone, "LOCAL_COMPUTER_REMOVED", "Local Computer was removed") return @@ -175,6 +180,7 @@ func (a *App) exchangeLocalComputerEnrollment(c *gin.Context) { func validLocalComputerEnrollmentCreate(request httpapi.LocalComputerEnrollmentCreateRequest) bool { return strings.TrimSpace(request.DisplayName) != "" && len(request.DisplayName) <= 120 && (request.ComputerId == nil || localComputerIDPattern.MatchString(*request.ComputerId)) && + (request.DaemonId == nil || localComputerDaemonPattern.MatchString(*request.DaemonId)) && localComputerPKCEPattern.MatchString(request.CodeChallenge) && validLocalComputerRedirect(request.RedirectUri) } diff --git a/apps/teamhub/internal/app/models.go b/apps/teamhub/internal/app/models.go index 68154f53..6df8b664 100644 --- a/apps/teamhub/internal/app/models.go +++ b/apps/teamhub/internal/app/models.go @@ -33,11 +33,19 @@ func (a *App) identity(ctx context.Context, session store.GetActiveSessionRow) ( models = append(models, collaboration.ActorModel(actor)) } return httpapi.CurrentIdentity{ - Account: accountModel(session.AccountID, session.Email, session.AccountCreatedAt), - Actors: models, + Account: accountModel(session.AccountID, session.Email, session.AccountCreatedAt), + Actors: models, + ServerCapabilities: &serverCapabilities, }, nil } +// serverCapabilities lists the request fields this TeamHub accepts that an +// earlier release rejected, so a client newer than its server sends one only +// when it is listed here. +var serverCapabilities = []httpapi.CurrentIdentityServerCapabilities{ + httpapi.LocalComputerEnrollmentDaemonId, +} + func (a *App) sessionModel(ctx context.Context, session store.GetActiveSessionRow) (httpapi.Session, error) { identity, err := a.identity(ctx, session) if err != nil { diff --git a/apps/teamhub/internal/store/agent_runtime_state.sql.go b/apps/teamhub/internal/store/agent_runtime_state.sql.go index d34935d7..81f0ae81 100644 --- a/apps/teamhub/internal/store/agent_runtime_state.sql.go +++ b/apps/teamhub/internal/store/agent_runtime_state.sql.go @@ -3289,6 +3289,44 @@ func (q *Queries) LockAgentRuntimeLocalComputer(ctx context.Context, computerID return i, err } +const lockAgentRuntimeLocalComputerByDaemonID = `-- name: LockAgentRuntimeLocalComputerByDaemonID :one +SELECT computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id +FROM local_computers +WHERE daemon_id=$1::text +FOR UPDATE +` + +// Removing a Computer frees its Daemon Identity, so only a Computer that was +// not removed holds one. +func (q *Queries) LockAgentRuntimeLocalComputerByDaemonID(ctx context.Context, daemonID string) (LocalComputer, error) { + row := q.db.QueryRow(ctx, lockAgentRuntimeLocalComputerByDaemonID, daemonID) + var i LocalComputer + err := row.Scan( + &i.ComputerID, + &i.DisplayName, + &i.Status, + &i.CredentialGeneration, + &i.Capacity, + &i.ActiveOperations, + &i.RuntimeInventory, + &i.WorkspaceGrants, + &i.RuntimeDiagnostics, + &i.LastSeenAt, + &i.RemovedAt, + &i.CreatedAt, + &i.UpdatedAt, + &i.DaemonID, + &i.DaemonPublicKey, + &i.DaemonIdentityVersion, + &i.Platform, + &i.DaemonVersion, + &i.RecommendedVersion, + &i.OwnerTenantID, + &i.OwnerActorID, + ) + return i, err +} + const lockAgentRuntimeLocalComputerEnrollment = `-- name: LockAgentRuntimeLocalComputerEnrollment :one SELECT enrollment_id, tenant_id, owner_actor_id, requested_computer_id, renews_existing_computer, display_name, redirect_uri, code_challenge, authorization_code_hash, expires_at, exchanged_at, exchanged_generation, created_at FROM local_computer_enrollments diff --git a/apps/teamhub/internal/store/queries/agent_runtime_state.sql b/apps/teamhub/internal/store/queries/agent_runtime_state.sql index 773127b6..6ccaabf3 100644 --- a/apps/teamhub/internal/store/queries/agent_runtime_state.sql +++ b/apps/teamhub/internal/store/queries/agent_runtime_state.sql @@ -947,6 +947,14 @@ FROM local_computers WHERE computer_id=sqlc.arg(computer_id)::text FOR UPDATE; +-- name: LockAgentRuntimeLocalComputerByDaemonID :one +-- Removing a Computer frees its Daemon Identity, so only a Computer that was +-- not removed holds one. +SELECT * +FROM local_computers +WHERE daemon_id=sqlc.arg(daemon_id)::text +FOR UPDATE; + -- name: InsertAgentRuntimeLocalComputer :one INSERT INTO local_computers( computer_id,display_name,status,capacity,owner_tenant_id,owner_actor_id diff --git a/apps/teamhub/tests/integration/agent_runtime_runner_state_test.go b/apps/teamhub/tests/integration/agent_runtime_runner_state_test.go index d3b76fe9..3485f2ab 100644 --- a/apps/teamhub/tests/integration/agent_runtime_runner_state_test.go +++ b/apps/teamhub/tests/integration/agent_runtime_runner_state_test.go @@ -27,7 +27,7 @@ func TestAgentRuntimeLocalComputerEnrollmentExchangeIsReplaySafe(t *testing.T) { DisplayName: "Runtime enrollment", Owner: owner, RedirectURI: "http://127.0.0.1:53100/callback", CodeChallenge: strings.Repeat("a", 43), AuthorizationCodeHash: firstHash[:], ExpiresAt: expiresAt, } - if err := env.service.CreateLocalComputerEnrollment(t.Context(), first); err != nil { + if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), first); err != nil { t.Fatalf("create Local Computer enrollment: %v", err) } consumeFirst := agentruntimestate.ConsumeLocalComputerEnrollmentInput{ @@ -46,7 +46,7 @@ func TestAgentRuntimeLocalComputerEnrollmentExchangeIsReplaySafe(t *testing.T) { CodeChallenge: strings.Repeat("b", 43), AuthorizationCodeHash: secondHash[:], ExpiresAt: expiresAt, RenewsExistingComputer: true, } - if err := env.service.CreateLocalComputerEnrollment(t.Context(), renewal); err != nil { + if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), renewal); err != nil { t.Fatalf("create Local Computer renewal: %v", err) } consumeRenewal := agentruntimestate.ConsumeLocalComputerEnrollmentInput{ @@ -77,7 +77,7 @@ func TestAgentRuntimeLocalComputerEnrollmentExchangeIsReplaySafe(t *testing.T) { pending := first pending.EnrollmentID = "enrollment_rejected_" + rejection pending.ComputerID = "computer_rejected_" + rejection - if err := env.service.CreateLocalComputerEnrollment(t.Context(), pending); err != nil { + if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), pending); err != nil { t.Fatal(err) } exchange := consumeFirst @@ -191,6 +191,137 @@ func TestAgentRuntimeLocalComputerRepairsWithSameDaemonAfterRemoval(t *testing.T } } +// Set Up Again forgets the Computer on the desktop but the machine keeps its +// Daemon Identity, so the next enrollment names it and renews the Computer +// that Daemon holds, with its Agents, instead of pairing a new one. +func TestAgentRuntimeLocalComputerEnrollmentRenewsTheComputerItsDaemonHolds(t *testing.T) { + allowParallelIntegrationTest(t) + env := newRuntimeStateTestEnv(t) + enrollRuntimeComputer(t, env, "computer_runtime_held") + held := runtimeConnectInput("computer_runtime_held", 0, time.Now()) + if _, err := env.service.ConnectLocalComputer(t.Context(), held); err != nil { + t.Fatalf("connect held Computer: %v", err) + } + setRuntimeAgentPlacementFields(t, env, "computer_runtime_held", "codex") + + again := runtimeEnrollmentInput("computer_runtime_set_up_again", runtimeComputerOwner()) + again.DaemonID = held.DaemonID + computerID, err := env.service.CreateLocalComputerEnrollment(t.Context(), again) + if err != nil || computerID != "computer_runtime_held" { + t.Fatalf("enroll a Daemon that holds a Computer: computer=%q err=%v, want computer_runtime_held", computerID, err) + } + consumed, err := env.service.ConsumeLocalComputerEnrollment(t.Context(), runtimeEnrollmentExchange(again)) + assertConsumedEnrollment(t, consumed, err, "computer_runtime_held", 1) + assertNoLocalComputer(t, env, "computer_runtime_set_up_again") + + connected, err := env.service.ConnectLocalComputer(t.Context(), runtimeConnectInput("computer_runtime_held", 1, time.Now())) + if err != nil || len(connected.Placements) != 1 || connected.Placements[0].AgentID != testRuntimeAgentID { + t.Fatalf("reconnect the renewed Computer: %+v err=%v, want its Agent", connected.Placements, err) + } +} + +// A desktop that Set Up Again paired as a new Computer before this fix keeps +// that Computer, whose Daemon Identity another Computer holds. Renewing it +// with the Daemon ID renews the holder and removes the orphan. +func TestAgentRuntimeLocalComputerRenewalHealsAComputerStuckBehindItsDaemonIdentity(t *testing.T) { + allowParallelIntegrationTest(t) + env := newRuntimeStateTestEnv(t) + owner := runtimeComputerOwner() + enrollRuntimeComputer(t, env, "computer_runtime_held") + held := runtimeConnectInput("computer_runtime_held", 0, time.Now()) + if _, err := env.service.ConnectLocalComputer(t.Context(), held); err != nil { + t.Fatalf("connect held Computer: %v", err) + } + enrollRuntimeComputer(t, env, "computer_runtime_orphan") + orphan := runtimeConnectInput("computer_runtime_orphan", 0, time.Now()) + orphan.DaemonID, orphan.DaemonPublicKey = held.DaemonID, held.DaemonPublicKey + if _, err := env.service.ConnectLocalComputer(t.Context(), orphan); !errors.Is(err, agentruntimestate.ErrDaemonIdentityInUse) { + t.Fatalf("connect the orphan: err=%v, want Daemon Identity in use", err) + } + + renewal := runtimeEnrollmentInput("computer_runtime_orphan", owner) + renewal.EnrollmentID, renewal.RenewsExistingComputer, renewal.DaemonID = "enrollment-runtime-heal", true, held.DaemonID + computerID, err := env.service.CreateLocalComputerEnrollment(t.Context(), renewal) + if err != nil || computerID != "computer_runtime_held" { + t.Fatalf("renew the orphan with its Daemon ID: computer=%q err=%v, want computer_runtime_held", computerID, err) + } + if _, err := env.service.GetLocalComputer(t.Context(), "computer_runtime_orphan"); !errors.Is(err, agentruntimestate.ErrNotFound) { + t.Fatalf("read the orphan after healing: err=%v, want removed", err) + } + consumed, err := env.service.ConsumeLocalComputerEnrollment(t.Context(), runtimeEnrollmentExchange(renewal)) + assertConsumedEnrollment(t, consumed, err, "computer_runtime_held", 1) + if _, err := env.service.ConnectLocalComputer(t.Context(), runtimeConnectInput("computer_runtime_held", 1, time.Now())); err != nil { + t.Fatalf("reconnect the healed Computer: %v", err) + } +} + +// A Computer that already connected with its own Daemon, or that has Agents, +// is not an orphan, so naming it next to another Computer's Daemon ID keeps +// it; and a Daemon ID never renews another owner's Computer. +func TestAgentRuntimeLocalComputerEnrollmentByDaemonIDKeepsOwnersApart(t *testing.T) { + allowParallelIntegrationTest(t) + env := newRuntimeStateTestEnv(t) + owner := runtimeComputerOwner() + enrollRuntimeComputer(t, env, "computer_runtime_held") + held := runtimeConnectInput("computer_runtime_held", 0, time.Now()) + if _, err := env.service.ConnectLocalComputer(t.Context(), held); err != nil { + t.Fatalf("connect held Computer: %v", err) + } + enrollRuntimeComputer(t, env, "computer_runtime_paired") + if _, err := env.service.ConnectLocalComputer(t.Context(), runtimeConnectInput("computer_runtime_paired", 0, time.Now())); err != nil { + t.Fatalf("connect paired Computer: %v", err) + } + enrollRuntimeComputer(t, env, "computer_runtime_placed") + setRuntimeAgentPlacementFields(t, env, "computer_runtime_placed", "codex") + for _, kept := range []string{"computer_runtime_paired", "computer_runtime_placed"} { + renewal := runtimeEnrollmentInput(kept, owner) + renewal.EnrollmentID, renewal.RenewsExistingComputer, renewal.DaemonID = "enrollment-keep-"+kept, true, held.DaemonID + if computerID, err := env.service.CreateLocalComputerEnrollment(t.Context(), renewal); err != nil || computerID != "computer_runtime_held" { + t.Fatalf("renew %s with the held Daemon ID: computer=%q err=%v", kept, computerID, err) + } + if _, err := env.service.GetLocalComputer(t.Context(), kept); err != nil { + t.Fatalf("read %s: %v, want kept", kept, err) + } + } + + seedPeerHumanActor(t, env.pool) + other := agentruntimestate.LocalComputerOwner{TenantID: "tenant_acme", OwnerActorID: "actor_acme_bob"} + foreign := runtimeEnrollmentInput("computer_runtime_foreign", other) + foreign.DaemonID = held.DaemonID + if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), foreign); !errors.Is(err, agentruntimestate.ErrDaemonIdentityInUse) { + t.Fatalf("enroll another owner with a held Daemon ID: err=%v, want Daemon Identity in use", err) + } + assertNoLocalComputer(t, env, "computer_runtime_foreign") + computer, err := env.service.GetLocalComputer(t.Context(), "computer_runtime_held") + if err != nil || computer.Owner != owner { + t.Fatalf("held Computer after another owner's enrollment: %+v err=%v", computer, err) + } +} + +func runtimeEnrollmentInput(computerID string, owner agentruntimestate.LocalComputerOwner) agentruntimestate.CreateLocalComputerEnrollmentInput { + codeHash := sha256.Sum256([]byte("authorization-code-" + computerID)) + return agentruntimestate.CreateLocalComputerEnrollmentInput{ + EnrollmentID: "enrollment-" + computerID, ComputerID: computerID, DisplayName: computerID, + Owner: owner, RedirectURI: "http://127.0.0.1:53100/callback", CodeChallenge: strings.Repeat("a", 43), + AuthorizationCodeHash: codeHash[:], ExpiresAt: time.Now().UTC().Truncate(time.Microsecond).Add(time.Hour), + } +} + +func runtimeEnrollmentExchange(input agentruntimestate.CreateLocalComputerEnrollmentInput) agentruntimestate.ConsumeLocalComputerEnrollmentInput { + return agentruntimestate.ConsumeLocalComputerEnrollmentInput{ + EnrollmentID: input.EnrollmentID, RedirectURI: input.RedirectURI, + CodeChallenge: input.CodeChallenge, AuthorizationCodeHash: input.AuthorizationCodeHash, + } +} + +func assertNoLocalComputer(t *testing.T, env runtimeStateTestEnv, computerID string) { + t.Helper() + var exists bool + if err := env.pool.QueryRow(t.Context(), `SELECT EXISTS(SELECT 1 FROM local_computers WHERE computer_id=$1)`, computerID).Scan(&exists); err != nil || exists { + t.Fatalf("Local Computer %q exists=%v err=%v, want none", computerID, exists, err) + } +} + // A move only changes the registration row. The Computer the Agent left no // longer lists it when it connects, so its Runner there is removed and its // late results have no placement; the new Computer lists it at the next @@ -411,19 +542,11 @@ func enrollRuntimeComputer(t *testing.T, env runtimeStateTestEnv, computerID str // exchange, the only path that creates Local Computers. func enrollRuntimeComputerFor(t *testing.T, env runtimeStateTestEnv, computerID string, owner agentruntimestate.LocalComputerOwner) error { t.Helper() - codeHash := sha256.Sum256([]byte("authorization-code-" + computerID)) - enrollment := agentruntimestate.CreateLocalComputerEnrollmentInput{ - EnrollmentID: "enrollment-" + computerID, ComputerID: computerID, DisplayName: computerID, - Owner: owner, RedirectURI: "http://127.0.0.1:53100/callback", CodeChallenge: strings.Repeat("a", 43), - AuthorizationCodeHash: codeHash[:], ExpiresAt: time.Now().UTC().Truncate(time.Microsecond).Add(time.Hour), - } - if err := env.service.CreateLocalComputerEnrollment(t.Context(), enrollment); err != nil { + enrollment := runtimeEnrollmentInput(computerID, owner) + if _, err := env.service.CreateLocalComputerEnrollment(t.Context(), enrollment); err != nil { return err } - result, err := env.service.ConsumeLocalComputerEnrollment(t.Context(), agentruntimestate.ConsumeLocalComputerEnrollmentInput{ - EnrollmentID: enrollment.EnrollmentID, RedirectURI: enrollment.RedirectURI, - CodeChallenge: enrollment.CodeChallenge, AuthorizationCodeHash: enrollment.AuthorizationCodeHash, - }) + result, err := env.service.ConsumeLocalComputerEnrollment(t.Context(), runtimeEnrollmentExchange(enrollment)) if err == nil && !result.Available { return errors.New("Local Computer enrollment was unavailable") } diff --git a/apps/teamhub/tests/integration/local_computer_test.go b/apps/teamhub/tests/integration/local_computer_test.go index 3c32deff..b7dda8e4 100644 --- a/apps/teamhub/tests/integration/local_computer_test.go +++ b/apps/teamhub/tests/integration/local_computer_test.go @@ -290,6 +290,61 @@ WHERE computer_id=$1`, computerID, acmeTenant); err != nil { } } +// The desktop names its Daemon ID when it enrolls: its owner gets back the +// Computer that Daemon holds, and another account gets a distinct refusal. +func TestLocalComputerEnrollmentByDaemonIDOverHTTP(t *testing.T) { + allowParallelIntegrationTest(t) + artifactRoot := integrationArtifactRoot(t) + databaseURL := newIntegrationDatabase(t) + pool, err := pgxpool.New(context.Background(), databaseURL) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + application, err := newIntegrationApp(context.Background(), localComputerEnrollmentConfig(config.ForTest(func(c *config.Config) { + c.ArtifactStorageRoot = artifactRoot + c.DatabaseURL = databaseURL + c.SessionTTL = time.Hour + c.CookieName = "teamhub_session" + })), withLocalComputers(&recordingLocalComputers{})) + if err != nil { + t.Fatal(err) + } + t.Cleanup(application.Close) + server := httptest.NewServer(application.Handler()) + registerIntegrationServerCleanup(t, server) + env := &testEnv{t: t, databaseURL: databaseURL, pool: pool, server: server} + alice, bob := env.login("alice", alicePassword), seedPeerHuman(t, env) + + // A desktop newer than its server names the Daemon only when /v0/me + // lists the capability; an older TeamHub rejects the unknown field. + if status, _, body := env.request(alice, http.MethodGet, "/v0/me", nil, ""); status != http.StatusOK || + !strings.Contains(string(body), `"server_capabilities":["local_computer_enrollment_daemon_id"]`) { + t.Fatalf("read the enrollment capability: status=%d body=%s", status, body) + } + computerID := enrollLocalComputerOverHTTP(t, env, alice, "Alice's Mac", "") + publicKey := sha256.Sum256([]byte("daemon-public-key")) + daemonHash := sha256.Sum256(publicKey[:]) + daemonID := base64.RawURLEncoding.EncodeToString(daemonHash[:]) + if _, err := pool.Exec(t.Context(), `UPDATE local_computers SET daemon_id=$1,daemon_public_key=$2 WHERE computer_id=$3`, + daemonID, publicKey[:], computerID); err != nil { + t.Fatal(err) + } + request := func(client *http.Client) (int, []byte) { + status, _, body := env.request(client, http.MethodPost, "/v0/tenants/"+acmeTenant+"/local-computer-enrollments", map[string]any{ + "display_name": "Mac", "redirect_uri": "http://127.0.0.1:45123/callback", + "code_challenge": strings.Repeat("a", 43), "daemon_id": daemonID, + }, "") + return status, body + } + if status, body := request(alice); status != http.StatusCreated || !containsJSONText(body, computerID) { + t.Fatalf("owner enrolls the Daemon again: status=%d body=%s, want %s", status, body, computerID) + } + if status, body := request(bob); status != http.StatusConflict || !containsJSONText(body, "DAEMON_IDENTITY_IN_USE") { + t.Fatalf("another account enrolls the Daemon: status=%d body=%s", status, body) + } +} + // enrollLocalComputerOverHTTP pairs a Computer as the CLI does: the owner // authorizes a PKCE enrollment and the CLI exchanges it, twice, as a retry // of an uncertain exchange would. renew names an enrolled Computer. diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.go index 9433ed27..a84de448 100644 --- a/contracts/generated/go/teamhubpublic/openapi.gen.go +++ b/contracts/generated/go/teamhubpublic/openapi.gen.go @@ -818,6 +818,21 @@ func (e CreatableAgentType) Valid() bool { } } +// Defines values for CurrentIdentityServerCapabilities. +const ( + LocalComputerEnrollmentDaemonId CurrentIdentityServerCapabilities = "local_computer_enrollment_daemon_id" +) + +// Valid indicates whether the value is a known member of the CurrentIdentityServerCapabilities enum. +func (e CurrentIdentityServerCapabilities) Valid() bool { + switch e { + case LocalComputerEnrollmentDaemonId: + return true + default: + return false + } +} + // Defines values for DecisionAnswerDecision. const ( DecisionAnswerApprove DecisionAnswerDecision = "approve" @@ -4837,8 +4852,14 @@ type CurrentIdentity struct { // Actors Active Human Actor identities available to this Account, one per Tenant in V0. Actors []Actor `json:"actors"` + + // ServerCapabilities Request fields this TeamHub accepts that earlier releases rejected, so a client newer than its server sends one only when the server lists it. A TeamHub that predates this list omits it. local_computer_enrollment_daemon_id: Local Computer enrollment accepts daemon_id. + ServerCapabilities *[]CurrentIdentityServerCapabilities `json:"server_capabilities,omitempty"` } +// CurrentIdentityServerCapabilities defines model for CurrentIdentity.ServerCapabilities. +type CurrentIdentityServerCapabilities string + // Cursor Opaque pagination cursor. Clients must not parse or modify it. type Cursor = string @@ -6194,9 +6215,12 @@ type LocalComputerEnrollmentCreateRequest struct { CodeChallenge string `json:"code_challenge"` // ComputerId Opaque, case-sensitive identifier. Clients must not infer type or time from it. - ComputerId *Id `json:"computer_id,omitempty"` - DisplayName string `json:"display_name"` - RedirectUri string `json:"redirect_uri"` + ComputerId *Id `json:"computer_id,omitempty"` + + // DaemonId Daemon Identity of the enrolling machine, when it has one. When one of the caller's Computers holds it, the enrollment renews that Computer instead of computer_id or a new one, and removes the requested Computer if it never connected and has no Agents. Another account's Computer holding it refuses the enrollment with 409 DAEMON_IDENTITY_IN_USE. + DaemonId *string `json:"daemon_id,omitempty"` + DisplayName string `json:"display_name"` + RedirectUri string `json:"redirect_uri"` } // LocalComputerEnrollmentExchangeRequest defines model for LocalComputerEnrollmentExchangeRequest. diff --git a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts b/contracts/generated/typescript/src/generated/teamhub-internal/types.ts index 4d147fc9..843b9af9 100644 --- a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts +++ b/contracts/generated/typescript/src/generated/teamhub-internal/types.ts @@ -681,7 +681,7 @@ export interface paths { put?: never; /** * Record a Computer's hello and read the Agent Runners it should hold. - * @description Checks the Runner credential generation and owner, binds the Computer Daemon Identity on first use, records the observation, and returns every active Agent placed on this Computer. The Agent Service computes the Computer's Agent Runners from these placements; a Runner the Computer reports for an Agent not listed here is removed. + * @description Checks the Runner credential generation and owner, binds the Computer Daemon Identity on first use, records the observation, and returns every active Agent placed on this Computer. The Agent Service computes the Computer's Agent Runners from these placements; a Runner the Computer reports for an Agent not listed here is removed. A Daemon Identity that another Computer holds is rejected with 409 DAEMON_IDENTITY_IN_USE. */ post: operations["connectAgentRuntimeLocalComputer"]; delete?: never; diff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.ts index 4ca8e5d4..4a8cf4a7 100644 --- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts +++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts @@ -4114,6 +4114,8 @@ export interface components { account: components["schemas"]["Account"]; /** @description Active Human Actor identities available to this Account, one per Tenant in V0. */ actors: components["schemas"]["Actor"][]; + /** @description Request fields this TeamHub accepts that earlier releases rejected, so a client newer than its server sends one only when the server lists it. A TeamHub that predates this list omits it. local_computer_enrollment_daemon_id: Local Computer enrollment accepts daemon_id. */ + server_capabilities?: "local_computer_enrollment_daemon_id"[]; }; Session: { id: components["schemas"]["Id"]; @@ -4827,6 +4829,8 @@ export interface components { }; LocalComputerEnrollmentCreateRequest: { computer_id?: components["schemas"]["Id"]; + /** @description Daemon Identity of the enrolling machine, when it has one. When one of the caller's Computers holds it, the enrollment renews that Computer instead of computer_id or a new one, and removes the requested Computer if it never connected and has no Agents. Another account's Computer holding it refuses the enrollment with 409 DAEMON_IDENTITY_IN_USE. */ + daemon_id?: string; display_name: string; /** Format: uri */ redirect_uri: string; @@ -9039,6 +9043,7 @@ export interface operations { 400: components["responses"]["BadRequest"]; 401: components["responses"]["Unauthenticated"]; 404: components["responses"]["NotFound"]; + 409: components["responses"]["Conflict"]; 410: components["responses"]["Gone"]; 503: components["responses"]["ServiceUnavailable"]; }; diff --git a/contracts/openapi/components/domain.yaml b/contracts/openapi/components/domain.yaml index caec2fdd..9e3c0fbd 100644 --- a/contracts/openapi/components/domain.yaml +++ b/contracts/openapi/components/domain.yaml @@ -334,6 +334,16 @@ components: properties: computer_id: $ref: "./common.yaml#/components/schemas/Id" + daemon_id: + type: string + pattern: "^[A-Za-z0-9_-]{43}$" + description: >- + Daemon Identity of the enrolling machine, when it has one. When one + of the caller's Computers holds it, the enrollment renews that + Computer instead of computer_id or a new one, and removes the + requested Computer if it never connected and has no Agents. Another + account's Computer holding it refuses the enrollment with 409 + DAEMON_IDENTITY_IN_USE. display_name: type: string minLength: 1 @@ -669,6 +679,16 @@ components: description: Active Human Actor identities available to this Account, one per Tenant in V0. items: $ref: "#/components/schemas/Actor" + server_capabilities: + type: array + description: >- + Request fields this TeamHub accepts that earlier releases rejected, so a client + newer than its server sends one only when the server lists it. A TeamHub that + predates this list omits it. local_computer_enrollment_daemon_id: Local Computer + enrollment accepts daemon_id. + items: + type: string + enum: [local_computer_enrollment_daemon_id] Session: type: object additionalProperties: false diff --git a/contracts/openapi/paths/teamhub-agent-runtime-state.yaml b/contracts/openapi/paths/teamhub-agent-runtime-state.yaml index ccba27a9..2c783b15 100644 --- a/contracts/openapi/paths/teamhub-agent-runtime-state.yaml +++ b/contracts/openapi/paths/teamhub-agent-runtime-state.yaml @@ -789,7 +789,8 @@ connectLocalComputer: Daemon Identity on first use, records the observation, and returns every active Agent placed on this Computer. The Agent Service computes the Computer's Agent Runners from these placements; a Runner the Computer - reports for an Agent not listed here is removed. + reports for an Agent not listed here is removed. A Daemon Identity that + another Computer holds is rejected with 409 DAEMON_IDENTITY_IN_USE. requestBody: required: true content: diff --git a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml index 26252f77..a675ba8a 100644 --- a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml +++ b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml @@ -897,6 +897,8 @@ paths: $ref: '../components/common.yaml#/components/responses/Unauthenticated' '404': $ref: '../components/common.yaml#/components/responses/NotFound' + '409': + $ref: '../components/common.yaml#/components/responses/Conflict' '410': $ref: '../components/common.yaml#/components/responses/Gone' '503':