diff --git a/docs/guides/agent-service-runtime.md b/docs/guides/agent-service-runtime.md index 4aa1a88c78..7c17db58c7 100644 --- a/docs/guides/agent-service-runtime.md +++ b/docs/guides/agent-service-runtime.md @@ -67,6 +67,9 @@ HTTP 200 SSE responses. Error responses omit it. `VERYFRONT_PROJECT_ID` or `VERYFRONT_PROJECT_SLUG`, and a publicly reachable `VERYFRONT_AGENT_SERVICE_URL`. See [Configuration](./configuration.md) for the full list. +- For an installation whose API gives the service its own login: set + `VERYFRONT_AGENT_SERVICE_CLIENT_ID` and + `VERYFRONT_AGENT_SERVICE_CLIENT_SECRET` instead of a key or token. - Immutable deployment metadata for `runtimeSource` when the control plane invokes the service. - An immutable deployment artifact tag when release qualification needs the @@ -147,7 +150,12 @@ For non-standard project layouts, configure discovery paths in Control-plane registration is convention-first. In `auto` mode, the service registers only when `VERYFRONT_API_KEY` and -`VERYFRONT_AGENT_SERVICE_URL` are present. Leave `VERYFRONT_API_TOKEN_FILE` +`VERYFRONT_AGENT_SERVICE_URL` are present, or when `VERYFRONT_AGENT_SERVICE_URL` +and both `VERYFRONT_AGENT_SERVICE_CLIENT_ID` and +`VERYFRONT_AGENT_SERVICE_CLIENT_SECRET` are present. With the client ID and +secret, the service gets its own token from `/auth/token`, renews it before it +expires, and ignores `VERYFRONT_API_KEY`. Setting only one of the two is a +startup error. Leave `VERYFRONT_API_TOKEN_FILE` unset: when it is set, even to an empty value, the service does not read `VERYFRONT_API_KEY`, so `auto` mode skips registration and `enabled` mode fails at startup. Registration also requires the immutable `runtimeSource` binding @@ -161,6 +169,16 @@ VERYFRONT_AGENT_SERVICE_URL=https://agent.example.com VERYFRONT_AGENT_SERVICE_REGISTRATION=auto ``` +With the service's own login instead of a key: + +```bash +VERYFRONT_API_URL=https://api.example.com +VERYFRONT_AGENT_SERVICE_CLIENT_ID= +VERYFRONT_AGENT_SERVICE_CLIENT_SECRET= +VERYFRONT_AGENT_SERVICE_URL=https://agent.example.com +VERYFRONT_AGENT_SERVICE_REGISTRATION=auto +``` + When an agent service keeps control-plane traffic on an internal HTTP service URL, set `VERYFRONT_PUBLIC_API_BASE_URL` to the environment's HTTPS API origin. Run-scoped inference credentials use that public origin for provider gateway diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index ed7ecd8498..d1ec25043f 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -276,7 +276,9 @@ Common groups: - **Agent services**: `VERYFRONT_AGENT_SERVICE_NAME`, `VERYFRONT_AGENT_SERVICE_URL`, `VERYFRONT_AGENT_SERVICE_KEY`, `VERYFRONT_AGENT_SERVICE_REGISTRATION`, and - `VERYFRONT_AGENT_SERVICE_REGION`. + `VERYFRONT_AGENT_SERVICE_REGION`. Set `VERYFRONT_AGENT_SERVICE_CLIENT_ID` and + `VERYFRONT_AGENT_SERVICE_CLIENT_SECRET` together to let the service obtain and + renew its own registration token. - **Provider keys**: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY`, and provider-specific base URLs. - **Runtime**: `PORT`, `NODE_ENV`, `REDIS_URL` (backs the SSR transform cache, diff --git a/src/agent/service/config.test.ts b/src/agent/service/config.test.ts index 0109c99857..da61ed50e3 100644 --- a/src/agent/service/config.test.ts +++ b/src/agent/service/config.test.ts @@ -68,6 +68,17 @@ describe("agent/agent-service-config", () => { assertEquals(config.VERYFRONT_MCP_URL, "https://api.example.com/mcp"); }); + it("reads the registration client credentials, blank as unset", () => { + const set = parseHostedAgentServiceConfig({ + VERYFRONT_AGENT_SERVICE_CLIENT_ID: "agent", + VERYFRONT_AGENT_SERVICE_CLIENT_SECRET: "secret", + }); + assertEquals(set.VERYFRONT_AGENT_SERVICE_CLIENT_ID, "agent"); + assertEquals(set.VERYFRONT_AGENT_SERVICE_CLIENT_SECRET, "secret"); + const blank = parseHostedAgentServiceConfig({ VERYFRONT_AGENT_SERVICE_CLIENT_ID: " " }); + assertEquals(blank.VERYFRONT_AGENT_SERVICE_CLIENT_ID, undefined); + }); + it("builds agent service config defaults", () => { const config = parseHostedAgentServiceConfig({}); diff --git a/src/agent/service/config.ts b/src/agent/service/config.ts index 1f58ffb2c2..3081af83ba 100644 --- a/src/agent/service/config.ts +++ b/src/agent/service/config.ts @@ -30,6 +30,8 @@ export type AgentServiceConfig = { VERYFRONT_PROJECT_ID?: string; VERYFRONT_AGENT_SERVICE_URL?: string; VERYFRONT_AGENT_SERVICE_KEY?: string; + VERYFRONT_AGENT_SERVICE_CLIENT_ID?: string; + VERYFRONT_AGENT_SERVICE_CLIENT_SECRET?: string; VERYFRONT_AGENT_SERVICE_REGISTRATION: AgentServiceRegistrationMode; VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS: number; VERYFRONT_AGENT_SERVICE_REGION?: string; @@ -95,6 +97,8 @@ const getAgentServiceConfigSchema = defineSchema((v) => { VERYFRONT_PROJECT_ID: v.string().min(1).optional(), VERYFRONT_AGENT_SERVICE_URL: v.string().url().optional(), VERYFRONT_AGENT_SERVICE_KEY: v.string().min(1).max(128).optional(), + VERYFRONT_AGENT_SERVICE_CLIENT_ID: v.string().optional(), + VERYFRONT_AGENT_SERVICE_CLIENT_SECRET: v.string().optional(), VERYFRONT_AGENT_SERVICE_REGISTRATION: agentServiceRegistrationModeInputSchema, VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS: v.coerce.number().positive().default(30_000), VERYFRONT_AGENT_SERVICE_REGION: v.string().min(1).max(128).optional(), @@ -148,6 +152,8 @@ const getAgentServiceConfigSchema = defineSchema((v) => { VERYFRONT_PROJECT_ID: env.VERYFRONT_PROJECT_ID, VERYFRONT_AGENT_SERVICE_URL: env.VERYFRONT_AGENT_SERVICE_URL, VERYFRONT_AGENT_SERVICE_KEY: env.VERYFRONT_AGENT_SERVICE_KEY, + VERYFRONT_AGENT_SERVICE_CLIENT_ID: present(env.VERYFRONT_AGENT_SERVICE_CLIENT_ID), + VERYFRONT_AGENT_SERVICE_CLIENT_SECRET: present(env.VERYFRONT_AGENT_SERVICE_CLIENT_SECRET), VERYFRONT_AGENT_SERVICE_REGISTRATION: env.VERYFRONT_AGENT_SERVICE_REGISTRATION, VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS: env.VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS, diff --git a/src/agent/service/registration-credentials.test.ts b/src/agent/service/registration-credentials.test.ts new file mode 100644 index 0000000000..d3f28931c9 --- /dev/null +++ b/src/agent/service/registration-credentials.test.ts @@ -0,0 +1,263 @@ +import "#veryfront/schemas/_test-setup.ts"; +import { assert, assertEquals, assertRejects } from "#veryfront/testing/assert.ts"; +import { describe, it } from "#veryfront/testing/bdd.ts"; +import { FakeTime } from "#std/testing/time"; +import { createClientCredentialsFetch } from "./registration-credentials.ts"; +import { + createAgentServiceRegistrationLifecycle, + resolveAgentServiceRegistrationInput, +} from "./registration.ts"; + +const credentials = { clientId: "agent", clientSecret: "secret-value" }; +const API = "https://api.example.com"; + +function jwtExpiringIn(seconds: number, id: string): string { + const claims = btoa(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + seconds, jti: id })); + return `h.${claims.replace(/=+$/, "")}.s`; +} + +function fakeApi(options: { refuse?: (token: string) => boolean; tokenStatus?: number } = {}) { + const state = { issued: [] as string[], used: [] as string[], tokenInits: [] as RequestInit[] }; + const fetch: typeof globalThis.fetch = (input, init) => { + if (input.toString().endsWith("/auth/token")) { + state.tokenInits.push(init as RequestInit); + if (options.tokenStatus) { + return Promise.resolve(new Response("no", { status: options.tokenStatus })); + } + const token = jwtExpiringIn(900, String(state.issued.length)); + state.issued.push(token); + return Promise.resolve(Response.json({ access_token: token })); + } + const token = new Headers((init as RequestInit).headers).get("Authorization")!.slice(7); + state.used.push(token); + return Promise.resolve( + new Response("{}", { status: options.refuse?.(token) ? 401 : 200 }), + ); + }; + return { + state, + fetch, + client: createClientCredentialsFetch({ apiUrl: API, credentials, fetch }), + }; +} + +describe("agent/service/registration-credentials", () => { + it("reuses one token, and sends the secret only to the token endpoint", async () => { + const { state, client } = fakeApi(); + await client(`${API}/a`, { method: "POST" }); + await client(`${API}/b`, { method: "POST" }); + assertEquals(state.issued.length, 1); + assertEquals(state.used, [state.issued[0], state.issued[0]]); + assertEquals(state.tokenInits[0]?.redirect, "error"); + assertEquals(JSON.parse(String(state.tokenInits[0]?.body)), { + grant_type: "client_credentials", + client_id: "agent", + client_secret: "secret-value", + }); + }); + + it("renews before the token expires", async () => { + using time = new FakeTime(); + const { state, client } = fakeApi(); + await client(`${API}/a`); + await time.tickAsync(839_000); + await client(`${API}/a`); + assertEquals(state.issued.length, 1); + await time.tickAsync(2_000); + await client(`${API}/a`); + assertEquals(state.issued.length, 2); + }); + + it("renews an opaque token before the lifetime the API states", async () => { + using time = new FakeTime(); + let issued = 0; + const client = createClientCredentialsFetch({ + apiUrl: API, + credentials, + fetch: (input) => + Promise.resolve( + input.toString().endsWith("/auth/token") + ? Response.json({ access_token: `opaque-${++issued}`, expires_in: 120 }) + : new Response("{}"), + ), + }); + await client(`${API}/a`); + await time.tickAsync(59_000); + await client(`${API}/a`); + assertEquals(issued, 1); + await time.tickAsync(2_000); + await client(`${API}/a`); + assertEquals(issued, 2); + }); + + it("stops waiting for a token when the caller aborts", async () => { + let answer: ((response: Response) => void) | undefined; + const client = createClientCredentialsFetch({ + apiUrl: API, + credentials, + fetch: (input) => + input.toString().endsWith("/auth/token") + ? new Promise((resolve) => (answer = resolve)) + : Promise.resolve(new Response("{}")), + }); + const controller = new AbortController(); + const waiting = client(`${API}/a`, { signal: controller.signal }); + controller.abort(new Error("stopped")); + const error = await assertRejects(() => waiting); + assertEquals((error as Error).message, "stopped"); + // The shared request still completes and serves the next caller. + answer!(Response.json({ access_token: "late" })); + assertEquals((await client(`${API}/b`)).status, 200); + }); + + it("refuses an oversized token response or token", async () => { + for ( + const body of [ + JSON.stringify({ access_token: "a", pad: "x".repeat(200 * 1024) }), + JSON.stringify({ access_token: "a".repeat(70 * 1024) }), + ] + ) { + const client = createClientCredentialsFetch({ + apiUrl: API, + credentials, + fetch: (input) => + Promise.resolve( + input.toString().endsWith("/auth/token") + ? new Response(body, { headers: { "content-type": "application/json" } }) + : new Response("{}"), + ), + }); + await assertRejects(() => client(`${API}/a`)); + } + }); + + it("renews once when the API refuses the token", async () => { + let first: string | undefined; + const { state, client } = fakeApi({ refuse: (token) => token === (first ??= token) }); + assertEquals((await client(`${API}/a`)).status, 200); + assertEquals(state.issued.length, 2); + }); + + it("stops after one renewal when the API keeps refusing", async () => { + const { state, client } = fakeApi({ refuse: () => true }); + assertEquals((await client(`${API}/a`)).status, 401); + assertEquals(state.used.length, 2); + }); + + it("asks once for concurrent requests", async () => { + const { state, client } = fakeApi(); + await Promise.all([client(`${API}/a`), client(`${API}/b`), client(`${API}/c`)]); + assertEquals(state.issued.length, 1); + }); + + it("reports a refused login without the secret", async () => { + const { state, client } = fakeApi({ tokenStatus: 400 }); + const error = await assertRejects(() => client(`${API}/a`)); + assert(error instanceof Error); + assert(error.message.includes("HTTP 400")); + assert(!error.message.includes("secret-value")); + assertEquals(state.used.length, 0); + }); + + it("asks again after a failed token request", async () => { + let down = true; + const { fetch } = fakeApi(); + const client = createClientCredentialsFetch({ + apiUrl: API, + credentials, + fetch: (input, init) => down ? Promise.reject(new TypeError("down")) : fetch(input, init), + }); + await assertRejects(() => client(`${API}/a`)); + down = false; + assertEquals((await client(`${API}/a`)).status, 200); + }); + + it("refuses a token response without a usable token", async () => { + const client = createClientCredentialsFetch({ + apiUrl: API, + credentials, + fetch: () => Promise.resolve(Response.json({ access_token: "a\r\nb" })), + }); + await assertRejects(() => client(`${API}/a`)); + }); + + const config = { + VERYFRONT_API_URL: API, + VERYFRONT_AGENT_SERVICE_URL: "https://agent.example.com", + VERYFRONT_AGENT_SERVICE_REGISTRATION: "enabled" as const, + VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS: 30_000, + }; + + it("resolves client credentials without a fixed token, and prefers them", async () => { + const input = await resolveAgentServiceRegistrationInput({ + config: { + ...config, + VERYFRONT_API_TOKEN: "fixed", + VERYFRONT_AGENT_SERVICE_CLIENT_ID: "agent", + VERYFRONT_AGENT_SERVICE_CLIENT_SECRET: "secret-value", + }, + serviceName: "docs-agent", + }); + assertEquals(input?.clientCredentials, credentials); + assertEquals(input?.authToken, undefined); + }); + + it("refuses half of the client credentials", async () => { + for (const half of ["ID", "SECRET"]) { + await assertRejects(() => + resolveAgentServiceRegistrationInput({ + config: { ...config, [`VERYFRONT_AGENT_SERVICE_CLIENT_${half}`]: "x" }, + serviceName: "docs-agent", + }) + ); + } + }); + + it("registers and heartbeats with renewed tokens", async () => { + const used: (string | null)[] = []; + let issued = 0; + const service = { + id: "22222222-2222-4222-8222-222222222222", + service_name: "docs-agent", + service_key: "k", + scope_kind: "global", + scope_key: "global", + project_id: null, + agent_id: null, + base_url: "https://agent.example.com", + invoke_url: "https://agent.example.com/api/runs", + status: "active", + version: null, + runtime: null, + region: null, + capabilities: null, + metadata: null, + last_heartbeat_at: null, + created_at: "2026-05-13T00:00:00.000Z", + updated_at: "2026-05-13T00:00:00.000Z", + }; + const lifecycle = await createAgentServiceRegistrationLifecycle({ + apiUrl: API, + clientCredentials: credentials, + serviceName: "docs-agent", + serviceKey: "k", + scopeKind: "global", + baseUrl: "https://agent.example.com", + invokeUrl: "https://agent.example.com/api/runs", + heartbeatIntervalMs: 60_000, + fetch: (input, init) => { + if (input.toString().endsWith("/auth/token")) { + return Promise.resolve(Response.json({ access_token: `token-${++issued}` })); + } + const header = new Headers((init as RequestInit).headers).get("Authorization"); + used.push(header); + // The first token is refused at the heartbeat, as after a revocation. + const refused = input.toString().endsWith("/heartbeat") && header === "Bearer token-1"; + return Promise.resolve(Response.json({ service }, { status: refused ? 401 : 200 })); + }, + }); + await lifecycle.heartbeat(); + lifecycle.stop(); + assertEquals(used, ["Bearer token-1", "Bearer token-1", "Bearer token-2"]); + }); +}); diff --git a/src/agent/service/registration-credentials.ts b/src/agent/service/registration-credentials.ts new file mode 100644 index 0000000000..80b3959331 --- /dev/null +++ b/src/agent/service/registration-credentials.ts @@ -0,0 +1,131 @@ +import { CONFIG_INVALID, isVeryfrontError, NETWORK_ERROR } from "#veryfront/errors"; +import { awaitAbortable } from "#veryfront/utils/abort.ts"; +import { readProxyResponseJson, settleProxyResponseBody } from "#veryfront/proxy/response-body.ts"; + +/** Client credentials with which a service obtains its own registration token. */ +export type AgentServiceClientCredentials = { clientId: string; clientSecret: string }; + +/** Renew before the API refuses the token, so a heartbeat does not start with a refusal. */ +const RENEWAL_MARGIN_MS = 60_000; +/** Reuse period for a token that does not state when it expires. */ +const DEFAULT_LIFETIME_MS = 5 * 60_000; +const MAX_LIFETIME_MS = 60 * 60_000; +const TOKEN_REQUEST_TIMEOUT_MS = 5_000; +/** Same limits as the OAuth client: a broken API cannot make the service buffer without bound. */ +const MAX_TOKEN_RESPONSE_BYTES = 128 * 1024; +const MAX_ACCESS_TOKEN_LENGTH = 64 * 1024; + +function readExpiryMs(token: string): number | undefined { + try { + const part = token.split(".")[1]; + if (!part) return undefined; + const claims: unknown = JSON.parse(atob(part.replaceAll("-", "+").replaceAll("_", "/"))); + const exp = typeof claims === "object" && claims !== null + ? (claims as { exp?: unknown }).exp + : undefined; + return typeof exp === "number" && Number.isFinite(exp) ? exp * 1000 : undefined; + } catch { + // The token is opaque to this client: it is only read to decide when to renew. + return undefined; + } +} + +/** When to renew a token received now. `expiresIn` is the response's `expires_in`, in seconds. */ +function renewAtMs(token: string, expiresIn: unknown, nowMs: number): number { + const stated = typeof expiresIn === "number" && Number.isFinite(expiresIn) && expiresIn > 0 + ? nowMs + expiresIn * 1000 + : undefined; + const claimed = readExpiryMs(token); + const expiresAt = stated !== undefined && claimed !== undefined + ? Math.min(stated, claimed) + : stated ?? claimed ?? nowMs + DEFAULT_LIFETIME_MS + RENEWAL_MARGIN_MS; + // A short-lived token is still reused for half of its life. + const margin = Math.min(RENEWAL_MARGIN_MS, (expiresAt - nowMs) / 2); + return Math.min(expiresAt - margin, nowMs + MAX_LIFETIME_MS); +} + +/** + * A fetch that authenticates with client credentials. It reuses one token until + * shortly before it expires, and renews it once when the API answers 401. + */ +export function createClientCredentialsFetch(input: { + apiUrl: string; + credentials: AgentServiceClientCredentials; + fetch: typeof globalThis.fetch; +}): typeof globalThis.fetch { + const endpoint = new URL("/auth/token", input.apiUrl).toString(); + let current: { token: string; renewAtMs: number } | undefined; + let pending: Promise | undefined; + + async function requestToken(): Promise { + let response: Response; + let payload: unknown; + // Shared by every waiting request, so no single caller's signal may cancel it. + const signal = AbortSignal.timeout(TOKEN_REQUEST_TIMEOUT_MS); + try { + response = await input.fetch(endpoint, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + grant_type: "client_credentials", + client_id: input.credentials.clientId, + client_secret: input.credentials.clientSecret, + }), + // The secret goes to the configured API only. + redirect: "error", + signal, + }); + if (response.ok) { + payload = await readProxyResponseJson(response, MAX_TOKEN_RESPONSE_BYTES, signal); + } else { + await settleProxyResponseBody(response); + } + } catch (cause) { + if (cause instanceof SyntaxError || isVeryfrontError(cause)) throw cause; + throw NETWORK_ERROR.create({ detail: "Agent service token request failed", cause }); + } + if (!response.ok) { + throw NETWORK_ERROR.create({ + detail: `Agent service token request failed with HTTP ${response.status}`, + context: { httpStatus: response.status }, + }); + } + const body = typeof payload === "object" && payload !== null + ? payload as { access_token?: unknown; expires_in?: unknown } + : {}; + const token = body.access_token; + if ( + typeof token !== "string" || token.length > MAX_ACCESS_TOKEN_LENGTH || + !/^[\x21-\x7e]+$/.test(token) + ) { + throw CONFIG_INVALID.create({ detail: "Agent service token response has no usable token" }); + } + current = { token, renewAtMs: renewAtMs(token, body.expires_in, Date.now()) }; + return token; + } + + function getToken(refused?: string): Promise { + if (current && current.token !== refused && Date.now() < current.renewAtMs) { + return Promise.resolve(current.token); + } + pending ??= requestToken().finally(() => { + pending = undefined; + }); + return pending; + } + + return async (request, init) => { + const send = (token: string) => { + const headers = new Headers(init && "headers" in init ? init.headers : undefined); + headers.set("Authorization", `Bearer ${token}`); + return input.fetch(request, { ...init, headers }); + }; + // The token request is shared, so a caller that gives up stops waiting without cancelling it. + const signal = init?.signal ?? (request instanceof Request ? request.signal : undefined); + const token = await awaitAbortable(getToken(), signal ?? undefined); + const response = await send(token); + if (response.status !== 401) return response; + await response.body?.cancel(); + return await send(await awaitAbortable(getToken(token), signal ?? undefined)); + }; +} diff --git a/src/agent/service/registration.ts b/src/agent/service/registration.ts index 6f07fb7cdf..c4a6154763 100644 --- a/src/agent/service/registration.ts +++ b/src/agent/service/registration.ts @@ -8,6 +8,10 @@ import { retryWithBackoff, } from "#veryfront/errors"; import { computeHash } from "#veryfront/utils"; +import { + type AgentServiceClientCredentials, + createClientCredentialsFetch, +} from "./registration-credentials.ts"; /** Public API contract for agent service registration mode. */ export type AgentServiceRegistrationMode = "auto" | "enabled" | "disabled"; @@ -20,6 +24,9 @@ export type AgentServiceRegistrationConfig = { VERYFRONT_PROJECT_ID?: string; VERYFRONT_AGENT_SERVICE_URL?: string; VERYFRONT_AGENT_SERVICE_KEY?: string; + /** With the secret: the service obtains and renews its own registration token. */ + VERYFRONT_AGENT_SERVICE_CLIENT_ID?: string; + VERYFRONT_AGENT_SERVICE_CLIENT_SECRET?: string; VERYFRONT_AGENT_SERVICE_REGISTRATION: AgentServiceRegistrationMode; VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS: number; VERYFRONT_AGENT_SERVICE_REGION?: string; @@ -30,7 +37,10 @@ export type AgentServiceRegistrationConfig = { /** Input payload for resolved agent service registration. */ export type ResolvedAgentServiceRegistrationInput = { apiUrl: string; - authToken: string; + /** Fixed bearer token. Set unless `clientCredentials` is. */ + authToken?: string; + /** Credentials for a token the service renews itself. They win over `authToken`. */ + clientCredentials?: AgentServiceClientCredentials; serviceName: string; serviceKey: string; scopeKind: "global" | "project"; @@ -119,6 +129,8 @@ export const agentServiceRegistrationConfigSchema = lazySchema( VERYFRONT_PROJECT_ID: v.string().min(1).optional(), VERYFRONT_AGENT_SERVICE_URL: v.string().url().optional(), VERYFRONT_AGENT_SERVICE_KEY: v.string().min(1).max(128).optional(), + VERYFRONT_AGENT_SERVICE_CLIENT_ID: v.string().min(1).optional(), + VERYFRONT_AGENT_SERVICE_CLIENT_SECRET: v.string().min(1).optional(), VERYFRONT_AGENT_SERVICE_REGISTRATION: agentServiceRegistrationMode(v), VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS: v.number().positive(), VERYFRONT_AGENT_SERVICE_REGION: v.string().min(1).max(128).optional(), @@ -134,7 +146,11 @@ export const resolvedAgentServiceRegistrationInputSchema = lazySchema( defineSchema((v) => v.object({ apiUrl: v.string().url(), - authToken: v.string().min(1), + authToken: v.string().min(1).optional(), + clientCredentials: v.object({ + clientId: v.string().min(1), + clientSecret: v.string().min(1), + }).optional(), serviceName: v.string().min(1).max(128), serviceKey: v.string().min(1).max(128), scopeKind: v.enum(["global", "project"] as const), @@ -344,13 +360,31 @@ function missingRegistrationCredential(config: AgentServiceRegistrationConfig): : `${lead}VERYFRONT_API_TOKEN_FILE is set, so VERYFRONT_API_KEY is not read. Unset VERYFRONT_API_TOKEN_FILE and set VERYFRONT_API_KEY to an API key.`; } +function resolveClientCredentials( + config: AgentServiceRegistrationConfig, +): AgentServiceClientCredentials | undefined { + const clientId = config.VERYFRONT_AGENT_SERVICE_CLIENT_ID; + const clientSecret = config.VERYFRONT_AGENT_SERVICE_CLIENT_SECRET; + if (!clientId && !clientSecret) return undefined; + if (!clientId || !clientSecret) { + throw CONFIG_INVALID.create({ + detail: + "VERYFRONT_AGENT_SERVICE_CLIENT_ID and VERYFRONT_AGENT_SERVICE_CLIENT_SECRET must be set together", + }); + } + return { clientId, clientSecret }; +} + /** Input payload for resolve agent service registration. */ export async function resolveAgentServiceRegistrationInput( options: ResolveAgentServiceRegistrationInputOptions, ): Promise { const config = agentServiceRegistrationConfigSchema.parse(options.config); const enabled = config.VERYFRONT_AGENT_SERVICE_REGISTRATION === "enabled"; - const token = enabled + const clientCredentials = config.VERYFRONT_AGENT_SERVICE_REGISTRATION === "disabled" + ? undefined + : resolveClientCredentials(config); + const token = enabled && !clientCredentials ? requireExplicitRegistrationValue( config.VERYFRONT_API_TOKEN, missingRegistrationCredential(config), @@ -366,7 +400,7 @@ export async function resolveAgentServiceRegistrationInput( if (config.VERYFRONT_AGENT_SERVICE_REGISTRATION === "disabled") { return null; } - if (!token || !serviceUrl) { + if ((!token && !clientCredentials) || !serviceUrl) { return null; } @@ -384,7 +418,7 @@ export async function resolveAgentServiceRegistrationInput( return resolvedAgentServiceRegistrationInputSchema.parse({ apiUrl: config.VERYFRONT_API_URL, - authToken: token, + ...(clientCredentials ? { clientCredentials } : { authToken: token }), serviceName: options.serviceName, serviceKey, scopeKind, @@ -428,10 +462,11 @@ async function readAgentPushRuntimeServiceResponse( return parsed.service; } -function createHeaders(authToken: string): Headers { +function createHeaders(authToken: string | undefined): Headers { const headers = new Headers(); try { - headers.set("Authorization", `Bearer ${authToken}`); + // Absent with client credentials: their fetch sets the header. + if (authToken !== undefined) headers.set("Authorization", `Bearer ${authToken}`); } catch { // Header implementations may include the rejected credential in their error. throw CONFIG_INVALID.create({ @@ -485,7 +520,7 @@ async function registerAgentPushRuntimeService( type HeartbeatRequest = { apiUrl: string; - authToken: string; + authToken?: string; serviceId: string; heartbeatIntervalMs: number; }; @@ -597,8 +632,18 @@ async function heartbeatAgentPushRuntimeService( export async function createAgentServiceRegistrationLifecycle( options: CreateAgentServiceRegistrationLifecycleOptions, ): Promise { - const fetchImpl = options.fetch ?? globalThis.fetch; const input = resolvedAgentServiceRegistrationInputSchema.parse(options); + const baseFetch = options.fetch ?? globalThis.fetch; + if (!input.authToken && !input.clientCredentials) { + throw CONFIG_INVALID.create({ detail: "Agent service registration needs a credential" }); + } + const fetchImpl = input.clientCredentials + ? createClientCredentialsFetch({ + apiUrl: input.apiUrl, + credentials: input.clientCredentials, + fetch: baseFetch, + }) + : baseFetch; // Registration upserts the same scoped service key and immutable source binding. let service = await retryWithBackoff( (signal) => registerAgentPushRuntimeService(input, fetchImpl, signal),