From 7a3148643270ac016d4829acd2d738023287eb5c Mon Sep 17 00:00:00 2001 From: Shannon Sands Date: Tue, 2 Jun 2026 10:34:55 +1000 Subject: [PATCH] feat(hermes): use invoke JWT for inference Signed-off-by: Shannon Sands --- agents/hermes/host/tool-gateway-broker.ts | 100 ++++++++++++++++--- src/lib/hermes-provider-auth.test.ts | 111 +++++++++++++++++----- src/lib/hermes-provider-auth.ts | 34 +++++-- src/lib/oauth-device-code.test.ts | 45 +++++++++ src/lib/oauth-device-code.ts | 89 ++++++++++++++++- test/hermes-tool-gateway-broker.test.ts | 44 +++++---- 6 files changed, 361 insertions(+), 62 deletions(-) diff --git a/agents/hermes/host/tool-gateway-broker.ts b/agents/hermes/host/tool-gateway-broker.ts index 960ff9eecf7..40538e00fc6 100755 --- a/agents/hermes/host/tool-gateway-broker.ts +++ b/agents/hermes/host/tool-gateway-broker.ts @@ -64,6 +64,8 @@ const UPSTREAM_REQUEST_TIMEOUT_MS = readPositiveIntEnv( ); const DEFAULT_INFERENCE_BASE_URL = "https://inference-api.nousresearch.com/v1"; const TRUSTED_INFERENCE_BASE_URLS = new Set([DEFAULT_INFERENCE_BASE_URL]); +const NOUS_INFERENCE_INVOKE_SCOPE = "inference:invoke"; +const INFERENCE_CREDENTIAL_REFRESH_SKEW_MS = 120_000; if (!STATE_DIR) { console.error("HERMES_TOOL_GATEWAY_STATE_DIR required"); @@ -238,6 +240,68 @@ function timestampExpiresSoon(isoTimestamp, skewMs = 300_000) { return ms - Date.now() < skewMs; } +function decodeBase64UrlJson(value) { + try { + const base64 = String(value || "") + .replace(/-/g, "+") + .replace(/_/g, "/"); + const parsed = JSON.parse(Buffer.from(base64, "base64").toString("utf8")); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null; + } catch { + return null; + } +} + +function decodeJwtClaims(token) { + if (typeof token !== "string") return null; + const parts = token.split("."); + if (parts.length < 2) return null; + return decodeBase64UrlJson(parts[1]); +} + +function jwtScopes(claims) { + const scopes = new Set(); + const scope = claims?.scope; + if (typeof scope === "string") { + for (const value of scope.split(/\s+/)) { + if (value) scopes.add(value); + } + } + const scp = claims?.scp; + if (typeof scp === "string") { + for (const value of scp.split(/\s+/)) { + if (value) scopes.add(value); + } + } else if (Array.isArray(scp)) { + for (const value of scp) { + if (typeof value === "string" && value) scopes.add(value); + } + } + return scopes; +} + +function jwtExpiresAtIso(token) { + const exp = decodeJwtClaims(token)?.exp; + const seconds = + typeof exp === "number" ? exp : typeof exp === "string" && exp.trim() ? Number(exp) : NaN; + if (!Number.isFinite(seconds)) return null; + return new Date(seconds * 1000).toISOString(); +} + +function isUsableInvokeJwt(token) { + const claims = decodeJwtClaims(token); + if (!claims || !jwtScopes(claims).has(NOUS_INFERENCE_INVOKE_SCOPE)) return false; + const expiresAt = jwtExpiresAtIso(token); + return Boolean(expiresAt && !timestampExpiresSoon(expiresAt, INFERENCE_CREDENTIAL_REFRESH_SKEW_MS)); +} + +function inferenceCredentialExpiresSoon(state) { + return timestampExpiresSoon( + state?.inference_credential_expires_at || state?.inference_agent_key_expires_at, + INFERENCE_CREDENTIAL_REFRESH_SKEW_MS, + ); +} + function atomicWriteJson(file, value) { fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); const tmp = path.join( @@ -396,21 +460,35 @@ async function mintAgentKey(accessToken) { return payload; } -async function ensureInferenceAgentKey(loaded, refreshToken, options = {}) { - if (!options.force && !timestampExpiresSoon(loaded?.state?.inference_agent_key_expires_at)) { +async function ensureInferenceCredential(loaded, refreshToken, options = {}) { + if (!options.force && !inferenceCredentialExpiresSoon(loaded?.state)) { return false; } const accessToken = await refreshAccessToken(refreshToken, loaded); - const agentKey = await mintAgentKey(accessToken); - const inferenceBaseUrl = trustedInferenceBaseUrl(agentKey.inference_base_url); - updateOpenshellInferenceProvider(agentKey.api_key, inferenceBaseUrl); + let credential = accessToken; + let inferenceBaseUrl = DEFAULT_INFERENCE_BASE_URL; + let authPath = "invoke_jwt"; + let credentialExpiresAt = jwtExpiresAtIso(accessToken); + + if (!isUsableInvokeJwt(accessToken)) { + const agentKey = await mintAgentKey(accessToken); + credential = agentKey.api_key; + inferenceBaseUrl = trustedInferenceBaseUrl(agentKey.inference_base_url); + authPath = "legacy_agent_key"; + credentialExpiresAt = agentKeyExpiresAt(); + } + + updateOpenshellInferenceProvider(credential, inferenceBaseUrl); const nextState = { ...loaded.state, inference_provider_name: HERMES_INFERENCE_PROVIDER_NAME, inference_credential_env: HERMES_INFERENCE_CREDENTIAL_ENV, inference_base_url: inferenceBaseUrl, - inference_agent_key_expires_at: agentKeyExpiresAt(), - inference_agent_key_rotated_at: new Date().toISOString(), + inference_auth_path: authPath, + inference_credential_expires_at: credentialExpiresAt, + inference_agent_key_expires_at: + authPath === "legacy_agent_key" ? credentialExpiresAt : null, + inference_credential_rotated_at: new Date().toISOString(), updated_at: new Date().toISOString(), }; atomicWriteJson(loaded.file, nextState); @@ -425,9 +503,9 @@ async function refreshManagedInferenceForRuntimeCredentials(options = {}) { const refreshToken = resolveRuntimeRefreshToken(loaded); if (!refreshToken) continue; try { - await ensureInferenceAgentKey(loaded, refreshToken, options); + await ensureInferenceCredential(loaded, refreshToken, options); } catch (err) { - const code = errorCode(err) || "agent_key_refresh_failed"; + const code = errorCode(err) || "inference_credential_refresh_failed"; console.error(`Hermes inference provider refresh failed: ${code}`); } } @@ -538,8 +616,8 @@ async function handleProxy(req, res, route) { let accessToken; try { accessToken = await refreshAccessToken(refreshToken, loaded); - ensureInferenceAgentKey(loaded, refreshToken).catch((err) => { - const code = errorCode(err) || "agent_key_refresh_failed"; + ensureInferenceCredential(loaded, refreshToken).catch((err) => { + const code = errorCode(err) || "inference_credential_refresh_failed"; console.error(`Hermes inference provider refresh failed: ${code}`); }); } catch (err) { diff --git a/src/lib/hermes-provider-auth.test.ts b/src/lib/hermes-provider-auth.test.ts index 6882f1c176a..82f9c18753d 100644 --- a/src/lib/hermes-provider-auth.test.ts +++ b/src/lib/hermes-provider-auth.test.ts @@ -47,6 +47,19 @@ function loadAuthWithBrokerStub(brokerStub: Record): Record): string { + const encode = (value: Record) => + Buffer.from(JSON.stringify(value)).toString("base64url"); + return `${encode({ alg: "none", typ: "JWT" })}.${encode(claims)}.sig`; +} + +function invokeJwt(seconds = 3600): string { + return jwtWithClaims({ + exp: Math.floor(Date.now() / 1000) + seconds, + scope: "inference:invoke inference:mint_agent_key", + }); +} + afterEach(() => { clearDistModule(DIST_AUTH); clearDistModule(DIST_BROKER); @@ -84,12 +97,13 @@ describe("Hermes provider OpenShell credential handoff", () => { } }); - it("uses OAuth only as an in-memory minting step before OpenShell registration", async () => { + it("uses OAuth invoke JWTs directly for OpenShell registration", async () => { const originalHome = process.env.HOME; const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-oauth-")); try { process.env.HOME = tmp; const auth = loadAuth(); + const token = invokeJwt(); const fetchCalls: Array<{ url: string; auth: string | null; body: string }> = []; const providerCalls: Array<{ args: string[]; env?: Record }> = []; const state = await auth.ensureHermesProviderOAuthCredentials("my-assistant", { @@ -116,23 +130,16 @@ describe("Hermes provider OpenShell credential handoff", () => { if (String(url).endsWith("/api/oauth/token")) { return new Response( JSON.stringify({ - access_token: "access-2", + access_token: token, refresh_token: "refresh-2", expires_in: 900, + inference_base_url: "https://staging.nous.example/v1", token_type: "Bearer", }), { status: 200, headers: { "Content-Type": "application/json" } }, ); } - return new Response( - JSON.stringify({ - api_key: "agent-key-1", - key_id: "agent-key-id", - expires_in: 1800, - inference_base_url: "https://staging.nous.example/v1", - }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ); + throw new Error(`unexpected fetch ${url}`); }) as typeof fetch, log: () => {}, noBrowser: true, @@ -148,9 +155,12 @@ describe("Hermes provider OpenShell credential handoff", () => { expect(state.auth_method).toBe("oauth"); expect(state.credential_env).toBe("OPENAI_API_KEY"); expect(state.inference_base_url).toBe("https://staging.nous.example/v1"); - expect(fetchCalls.some((call) => call.auth === "Bearer access-2")).toBe(true); + expect(state.auth_path).toBe("invoke_jwt"); + expect(new URLSearchParams(fetchCalls[0]?.body).get("scope")).toBe( + "inference:invoke inference:mint_agent_key", + ); expect( - providerCalls.some((call) => call.env?.OPENAI_API_KEY === "agent-key-1"), + providerCalls.some((call) => call.env?.OPENAI_API_KEY === token), ).toBe(true); expect( providerCalls.some((call) => @@ -165,6 +175,64 @@ describe("Hermes provider OpenShell credential handoff", () => { } }); + it("falls back to legacy agent-key minting when OAuth returns a non-invoke token", async () => { + const auth = loadAuth(); + const fetchCalls: Array<{ url: string; auth: string | null }> = []; + const providerCalls: Array<{ args: string[]; env?: Record }> = []; + const state = await auth.ensureHermesProviderOAuthCredentials("my-assistant", { + allowInteractiveLogin: true, + fetch: (async (url, init) => { + const headers = new Headers(init?.headers); + fetchCalls.push({ url: String(url), auth: headers.get("authorization") }); + if (String(url).endsWith("/api/oauth/device/code")) { + return new Response( + JSON.stringify({ + device_code: "device-1", + user_code: "USER-1", + verification_uri: "https://portal.example/verify", + expires_in: 900, + interval: 1, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + } + if (String(url).endsWith("/api/oauth/token")) { + return new Response( + JSON.stringify({ + access_token: "opaque-access", + refresh_token: "refresh-2", + expires_in: 900, + token_type: "Bearer", + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + } + return new Response( + JSON.stringify({ + api_key: "agent-key-1", + key_id: "agent-key-id", + expires_in: 1800, + inference_base_url: "https://staging.nous.example/v1", + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + }) as typeof fetch, + log: () => {}, + noBrowser: true, + runOpenshell: (args: string[], opts: { env?: Record } = {}) => { + providerCalls.push({ args, env: opts.env }); + if (args[0] === "provider" && args[1] === "get") { + return { status: 1, stdout: "", stderr: "" }; + } + return { status: 0, stdout: "", stderr: "" }; + }, + }); + + expect(state.auth_path).toBe("legacy_agent_key"); + expect(fetchCalls.some((call) => call.auth === "Bearer opaque-access")).toBe(true); + expect(providerCalls.some((call) => call.env?.OPENAI_API_KEY === "agent-key-1")).toBe(true); + }); + it("registers a separate managed-tool refresh provider without writing raw OAuth state", async () => { const originalHome = process.env.HOME; const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-tool-oauth-")); @@ -185,6 +253,7 @@ describe("Hermes provider OpenShell credential handoff", () => { }, }); const providerCalls: Array<{ args: string[]; env?: Record }> = []; + const token = invokeJwt(); const state = await auth.ensureHermesProviderOAuthCredentials("my-assistant", { allowInteractiveLogin: true, fetch: (async (url, init) => { @@ -203,7 +272,7 @@ describe("Hermes provider OpenShell credential handoff", () => { if (String(url).endsWith("/api/oauth/token")) { return new Response( JSON.stringify({ - access_token: "access-3", + access_token: token, refresh_token: "refresh-3", expires_in: 900, token_type: "Bearer", @@ -211,16 +280,7 @@ describe("Hermes provider OpenShell credential handoff", () => { { status: 200, headers: { "Content-Type": "application/json" } }, ); } - const headers = new Headers(init?.headers); - expect(headers.get("authorization")).toBe("Bearer access-3"); - return new Response( - JSON.stringify({ - api_key: "agent-key-3", - key_id: "agent-key-id", - expires_in: 1800, - }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ); + throw new Error(`unexpected fetch ${url}`); }) as typeof fetch, log: () => {}, noBrowser: true, @@ -235,7 +295,8 @@ describe("Hermes provider OpenShell credential handoff", () => { }); expect(state.auth_method).toBe("oauth"); - expect(providerCalls.some((call) => call.env?.OPENAI_API_KEY === "agent-key-3")).toBe(true); + expect(state.auth_path).toBe("invoke_jwt"); + expect(providerCalls.some((call) => call.env?.OPENAI_API_KEY === token)).toBe(true); expect(brokerCalls).toEqual([{ sandboxName: "my-assistant", refreshToken: "refresh-3" }]); expect(fs.existsSync(path.join(tmp, ".nemoclaw", "hermes-oauth"))).toBe(false); } finally { diff --git a/src/lib/hermes-provider-auth.ts b/src/lib/hermes-provider-auth.ts index 172ce6a2fb2..f3c5b71f677 100644 --- a/src/lib/hermes-provider-auth.ts +++ b/src/lib/hermes-provider-auth.ts @@ -66,6 +66,8 @@ export type HermesProviderCredentialState = { provider: typeof HERMES_PROVIDER_NAME; credential_env: string; inference_base_url: string; + auth_path?: "invoke_jwt" | "legacy_agent_key"; + credential_expires_at?: string | null; agent_key_expires_at?: string | null; }; @@ -137,16 +139,28 @@ export async function ensureHermesProviderOAuthCredentials( } const tokens = await oauth.runDeviceCodeFlow({ fetch, log, noBrowser }); - const minted = await oauth.mintAgentKeyWithAccessToken(tokens.access_token, { - fetch, - minTtlSeconds: AGENT_KEY_MIN_TTL_SECONDS, - }); - const inferenceBaseUrl = minted.inference_base_url || baseUrl; + const inferenceBaseUrl = tokens.inference_base_url || baseUrl; + const useInvokeJwt = oauth.isNousInvokeAccessToken(tokens.access_token); + const minted = useInvokeJwt + ? null + : await oauth.mintAgentKeyWithAccessToken(tokens.access_token, { + fetch, + minTtlSeconds: AGENT_KEY_MIN_TTL_SECONDS, + }); + const credential = useInvokeJwt ? tokens.access_token : minted?.api_key; + if (!credential) { + throw new Error("Hermes Provider credential is empty"); + } + const credentialExpiresAt = useInvokeJwt + ? oauth.jwtExpiresAt(tokens.access_token) + : minted + ? agentKeyExpiresAt(minted) + : null; registerHermesInferenceProvider( - minted.api_key, + credential, runOpenshell, HERMES_INFERENCE_CREDENTIAL_ENV, - inferenceBaseUrl, + minted?.inference_base_url || inferenceBaseUrl, ); if (Array.isArray(toolGatewayPresets) && toolGatewayPresets.length > 0) { const hermesToolGateway = getHermesToolGatewayBroker(); @@ -163,8 +177,10 @@ export async function ensureHermesProviderOAuthCredentials( auth_method: "oauth", provider: HERMES_PROVIDER_NAME, credential_env: HERMES_INFERENCE_CREDENTIAL_ENV, - inference_base_url: inferenceBaseUrl, - agent_key_expires_at: agentKeyExpiresAt(minted), + inference_base_url: minted?.inference_base_url || inferenceBaseUrl, + auth_path: useInvokeJwt ? "invoke_jwt" : "legacy_agent_key", + credential_expires_at: credentialExpiresAt, + agent_key_expires_at: useInvokeJwt ? null : credentialExpiresAt, }; } diff --git a/src/lib/oauth-device-code.test.ts b/src/lib/oauth-device-code.test.ts index b2a982ba968..5ccd5b72eb0 100644 --- a/src/lib/oauth-device-code.test.ts +++ b/src/lib/oauth-device-code.test.ts @@ -4,11 +4,44 @@ import { describe, expect, it } from "vitest"; import { + DEFAULT_SCOPE, + isNousInvokeAccessToken, mintAgentKeyWithAccessToken, pollForToken, + requestDeviceCode, refreshAccessTokenWithRefreshToken, } from "../../dist/lib/oauth-device-code"; +function jwtWithClaims(claims: Record): string { + const encode = (value: Record) => + Buffer.from(JSON.stringify(value)).toString("base64url"); + return `${encode({ alg: "none", typ: "JWT" })}.${encode(claims)}.sig`; +} + +describe("requestDeviceCode", () => { + it("requests both invoke JWT and legacy agent-key scopes by default", async () => { + const calls: Array<{ body: string }> = []; + await requestDeviceCode({ + fetch: (async (_url, init) => { + calls.push({ body: String(init?.body ?? "") }); + return new Response( + JSON.stringify({ + device_code: "device-1", + user_code: "USER-1", + verification_uri: "https://portal.example/verify", + expires_in: 900, + interval: 1, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + }) as typeof fetch, + }); + + expect(DEFAULT_SCOPE).toBe("inference:invoke inference:mint_agent_key"); + expect(new URLSearchParams(calls[0]?.body).get("scope")).toBe(DEFAULT_SCOPE); + }); +}); + describe("pollForToken", () => { it("rejects successful token responses missing an access token", async () => { await expect( @@ -41,6 +74,18 @@ describe("pollForToken", () => { }); }); +describe("isNousInvokeAccessToken", () => { + it("accepts unexpired JWTs with inference invoke scope", () => { + const token = jwtWithClaims({ + exp: Math.floor(Date.now() / 1000) + 3600, + scope: "inference:invoke inference:mint_agent_key", + }); + + expect(isNousInvokeAccessToken(token)).toBe(true); + expect(isNousInvokeAccessToken("opaque-access-token")).toBe(false); + }); +}); + describe("refreshAccessTokenWithRefreshToken", () => { it("sends the refresh token in x-nous-refresh-token instead of the form body", async () => { const calls: Array<{ diff --git a/src/lib/oauth-device-code.ts b/src/lib/oauth-device-code.ts index 2c8168cf420..d914491ed75 100644 --- a/src/lib/oauth-device-code.ts +++ b/src/lib/oauth-device-code.ts @@ -12,12 +12,15 @@ */ import { spawn } from "node:child_process"; +import { Buffer } from "node:buffer"; export const DEFAULT_PORTAL_BASE_URL = "https://portal.nousresearch.com"; export const DEFAULT_INFERENCE_BASE_URL = "https://inference-api.nousresearch.com/v1"; export const DEFAULT_CLIENT_ID = "hermes-cli"; -export const DEFAULT_SCOPE = "inference:mint_agent_key"; +export const NOUS_LEGACY_AGENT_KEY_SCOPE = "inference:mint_agent_key"; +export const NOUS_INFERENCE_INVOKE_SCOPE = "inference:invoke"; +export const DEFAULT_SCOPE = `${NOUS_INFERENCE_INVOKE_SCOPE} ${NOUS_LEGACY_AGENT_KEY_SCOPE}`; const POLL_INTERVAL_MIN_SECONDS = 1; const POLL_INTERVAL_MAX_SECONDS = 30; @@ -39,6 +42,7 @@ export interface TokenResponse { expires_in: number; token_type: string; scope?: string; + inference_base_url?: string; iat?: number; exp?: number; } @@ -138,6 +142,83 @@ function createRequestTimeout(timeoutMs: number | undefined): { }; } +function decodeBase64UrlJson(value: string): Record | null { + try { + const padded = value.replace(/-/g, "+").replace(/_/g, "/"); + const json = Buffer.from(padded, "base64").toString("utf8"); + const parsed = JSON.parse(json) as unknown; + return parsed && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Record) + : null; + } catch { + return null; + } +} + +export function decodeJwtClaims(token: unknown): Record | null { + if (typeof token !== "string") return null; + const parts = token.split("."); + if (parts.length < 2) return null; + return decodeBase64UrlJson(parts[1] || ""); +} + +function jwtScopeSet(claims: Record): Set { + const scopes = new Set(); + const scope = claims.scope; + if (typeof scope === "string") { + for (const value of scope.split(/\s+/)) { + if (value) scopes.add(value); + } + } + const scp = claims.scp; + if (typeof scp === "string") { + for (const value of scp.split(/\s+/)) { + if (value) scopes.add(value); + } + } else if (Array.isArray(scp)) { + for (const value of scp) { + if (typeof value === "string" && value) scopes.add(value); + } + } + return scopes; +} + +export function accessTokenHasScope(token: unknown, scope: string): boolean { + const claims = decodeJwtClaims(token); + return Boolean(claims && jwtScopeSet(claims).has(scope)); +} + +export function jwtExpiresAt(token: unknown): string | null { + const claims = decodeJwtClaims(token); + const exp = claims?.exp; + const seconds = + typeof exp === "number" + ? exp + : typeof exp === "string" && exp.trim() + ? Number(exp) + : NaN; + if (!Number.isFinite(seconds)) return null; + return new Date(seconds * 1000).toISOString(); +} + +export function isNousInvokeAccessToken( + token: unknown, + minTtlSeconds = 120, +): boolean { + const claims = decodeJwtClaims(token); + if (!claims || !jwtScopeSet(claims).has(NOUS_INFERENCE_INVOKE_SCOPE)) { + return false; + } + const exp = claims.exp; + const seconds = + typeof exp === "number" + ? exp + : typeof exp === "string" && exp.trim() + ? Number(exp) + : NaN; + return Number.isFinite(seconds) && seconds * 1000 - Date.now() > minTtlSeconds * 1000; +} + async function postForm( url: string, body: Record, @@ -403,9 +484,15 @@ module.exports = { DEFAULT_PORTAL_BASE_URL, DEFAULT_INFERENCE_BASE_URL, DEFAULT_CLIENT_ID, + NOUS_LEGACY_AGENT_KEY_SCOPE, + NOUS_INFERENCE_INVOKE_SCOPE, DEFAULT_SCOPE, OAuthError, OAuthTimeoutError, + decodeJwtClaims, + accessTokenHasScope, + jwtExpiresAt, + isNousInvokeAccessToken, requestDeviceCode, pollForToken, refreshAccessTokenWithRefreshToken, diff --git a/test/hermes-tool-gateway-broker.test.ts b/test/hermes-tool-gateway-broker.test.ts index e992524a979..94eac5914ce 100644 --- a/test/hermes-tool-gateway-broker.test.ts +++ b/test/hermes-tool-gateway-broker.test.ts @@ -37,6 +37,19 @@ function sha256(value: string): string { return crypto.createHash("sha256").update(value).digest("hex"); } +function jwtWithClaims(claims: Record): string { + const encode = (value: Record) => + Buffer.from(JSON.stringify(value)).toString("base64url"); + return `${encode({ alg: "none", typ: "JWT" })}.${encode(claims)}.sig`; +} + +function invokeJwt(seconds = 3600): string { + return jwtWithClaims({ + exp: Math.floor(Date.now() / 1000) + seconds, + scope: "inference:invoke inference:mint_agent_key", + }); +} + function freePort(): Promise { return new Promise((resolve, reject) => { const server = net.createServer(); @@ -123,7 +136,7 @@ describe("Hermes managed-tool gateway broker", () => { ).toBe(true); }); - it("refreshes via header, replaces upstream auth, normalizes responses, and rotates OpenShell storage", async () => { + it("refreshes via header, registers invoke JWTs, normalizes responses, and rotates OpenShell storage", async () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-tool-broker-")); const stateDir = path.join(tmp, "state"); const binDir = path.join(tmp, "bin"); @@ -163,6 +176,7 @@ describe("Hermes managed-tool gateway broker", () => { { mode: 0o600 }, ); + const accessToken = invokeJwt(); const tokenRequests: Array<{ body: string; refreshHeader?: string }> = []; const agentKeyRequests: Array<{ body: string; authorization?: string }> = []; const portal = http.createServer((req, res) => { @@ -191,7 +205,7 @@ describe("Hermes managed-tool gateway broker", () => { }); res.end( JSON.stringify({ - access_token: "access-2", + access_token: accessToken, refresh_token: "refresh-2", expires_in: 900, token_type: "Bearer", @@ -303,14 +317,10 @@ describe("Hermes managed-tool gateway broker", () => { expect(tokenRequests[0]?.refreshHeader).toBe("refresh-1"); expect(new URLSearchParams(tokenRequests[0]?.body).get("refresh_token")).toBeNull(); expect(new URLSearchParams(tokenRequests[0]?.body).get("grant_type")).toBe("refresh_token"); - expect(agentKeyRequests).toHaveLength(1); - expect(agentKeyRequests[0]?.authorization).toBe("Bearer access-2"); - expect(JSON.parse(agentKeyRequests[0]?.body || "{}")).toEqual({ - min_ttl_seconds: 1800, - }); + expect(agentKeyRequests).toHaveLength(0); expect(upstreamRequests[0]).toMatchObject({ url: "/v1/scrape?debug=1", - authorization: "Bearer access-2", + authorization: `Bearer ${accessToken}`, acceptEncoding: "identity", }); expect(upstreamRequests[0]?.apiKey).toBeUndefined(); @@ -325,10 +335,12 @@ describe("Hermes managed-tool gateway broker", () => { expect(openshellOutput).toContain( "provider update hermes-provider --credential OPENAI_API_KEY --config OPENAI_BASE_URL=https://inference-api.nousresearch.com/v1", ); - expect(openshellOutput).toContain("openai=agent-key-2"); + expect(openshellOutput).toContain(`openai=${accessToken}`); expect(rotatedState.inference_provider_name).toBe("hermes-provider"); expect(rotatedState.inference_credential_env).toBe("OPENAI_API_KEY"); - expect(rotatedState.inference_agent_key_expires_at).toBeTruthy(); + expect(rotatedState.inference_auth_path).toBe("invoke_jwt"); + expect(rotatedState.inference_credential_expires_at).toBeTruthy(); + expect(rotatedState.inference_agent_key_expires_at).toBeNull(); const checks = [ ["/browser-use/browsers", { "X-Browser-Use-API-Key": "broker-1" }, "browser"], @@ -346,26 +358,26 @@ describe("Hermes managed-tool gateway broker", () => { } expect(upstreamRequests[1]).toMatchObject({ url: "/browsers", - browserUseApiKey: "access-2", + browserUseApiKey: accessToken, }); expect(upstreamRequests[1]?.authorization).toBeUndefined(); expect(upstreamRequests[2]).toMatchObject({ url: "/fal-ai/test", - authorization: "Key access-2", + authorization: `Key ${accessToken}`, }); expect(upstreamRequests[3]).toMatchObject({ url: "/v1/audio/speech", - authorization: "Bearer access-2", + authorization: `Bearer ${accessToken}`, }); expect(upstreamRequests[4]).toMatchObject({ url: "/sandboxes", - authorization: "Bearer access-2", + authorization: `Bearer ${accessToken}`, }); expect(tokenRequests).toHaveLength(1); - expect(agentKeyRequests).toHaveLength(1); + expect(agentKeyRequests).toHaveLength(0); expect(output).not.toContain("refresh-1"); expect(output).not.toContain("refresh-2"); - expect(output).not.toContain("access-2"); + expect(output).not.toContain(accessToken); expect(output).not.toContain("sandbox-secret"); expect(output).not.toContain("agent-key-2"); } finally {