|
| 1 | +import { calculateJwkThumbprint, exportJWK, importPKCS8, type JWK, SignJWT } from "jose"; |
| 2 | + |
| 3 | +import { getCloudAwareEnv } from "../runtime/cloud-bindings"; |
| 4 | + |
| 5 | +export type AgentTokenMintResult = { |
| 6 | + token: string; |
| 7 | + expiresAt: string; |
| 8 | +}; |
| 9 | + |
| 10 | +const DEFAULT_TTL_SECONDS = 15 * 60; |
| 11 | +const MIN_TTL_SECONDS = 60; |
| 12 | +const MAX_TTL_SECONDS = 60 * 60; |
| 13 | +const ISSUER = "eliza-cloud"; |
| 14 | +const AUDIENCE = "steward"; |
| 15 | +const ALGORITHM = "RS256"; |
| 16 | + |
| 17 | +let cachedPrivateKey: CryptoKey | null = null; |
| 18 | +let cachedPrivateKeySource: string | null = null; |
| 19 | +let cachedPublicJwk: JWK | null = null; |
| 20 | +let cachedPublicJwkSource: string | null = null; |
| 21 | +let cachedKeyId: string | null = null; |
| 22 | +let cachedKeyIdSource: string | null = null; |
| 23 | + |
| 24 | +function envString(name: string): string | undefined { |
| 25 | + const value = getCloudAwareEnv()[name]; |
| 26 | + return typeof value === "string" && value.trim() ? value.trim() : undefined; |
| 27 | +} |
| 28 | + |
| 29 | +function normalizePem(value: string): string { |
| 30 | + const trimmed = value.trim().replace(/\\n/g, "\n"); |
| 31 | + if (trimmed.includes("-----BEGIN")) return trimmed; |
| 32 | + return `-----BEGIN PRIVATE KEY-----\n${trimmed}\n-----END PRIVATE KEY-----`; |
| 33 | +} |
| 34 | + |
| 35 | +function getPrivateKeyPem(): string | undefined { |
| 36 | + const raw = |
| 37 | + envString("AGENT_TOKEN_PRIVATE_KEY_PEM") ?? envString("ELIZA_AGENT_TOKEN_PRIVATE_KEY_PEM"); |
| 38 | + return raw ? normalizePem(raw) : undefined; |
| 39 | +} |
| 40 | + |
| 41 | +export function isAgentTokenSigningConfigured(): boolean { |
| 42 | + return Boolean(getPrivateKeyPem()); |
| 43 | +} |
| 44 | + |
| 45 | +export function normalizeAgentTokenTtl(ttl?: unknown): number { |
| 46 | + const requested = |
| 47 | + typeof ttl === "number" && Number.isFinite(ttl) ? Math.floor(ttl) : DEFAULT_TTL_SECONDS; |
| 48 | + return Math.min(Math.max(requested, MIN_TTL_SECONDS), MAX_TTL_SECONDS); |
| 49 | +} |
| 50 | + |
| 51 | +function normalizeAgentId(agentId: string): string { |
| 52 | + const normalized = agentId.trim(); |
| 53 | + if (!/^[a-zA-Z0-9_.:-]{1,128}$/.test(normalized)) { |
| 54 | + throw new Error("invalid agentId"); |
| 55 | + } |
| 56 | + return normalized; |
| 57 | +} |
| 58 | + |
| 59 | +async function getAgentTokenPrivateKey(): Promise<CryptoKey> { |
| 60 | + const pem = getPrivateKeyPem(); |
| 61 | + if (!pem) { |
| 62 | + throw new Error("AGENT_TOKEN_PRIVATE_KEY_PEM is not configured"); |
| 63 | + } |
| 64 | + if (cachedPrivateKey && cachedPrivateKeySource === pem) return cachedPrivateKey; |
| 65 | + cachedPrivateKey = await importPKCS8(pem, ALGORITHM, { extractable: true }); |
| 66 | + cachedPrivateKeySource = pem; |
| 67 | + cachedPublicJwk = null; |
| 68 | + cachedPublicJwkSource = null; |
| 69 | + cachedKeyId = null; |
| 70 | + cachedKeyIdSource = null; |
| 71 | + return cachedPrivateKey; |
| 72 | +} |
| 73 | + |
| 74 | +async function exportedPublicJwkForCurrentKey(): Promise<JWK> { |
| 75 | + const privateKey = await getAgentTokenPrivateKey(); |
| 76 | + const jwk = await exportJWK(privateKey); |
| 77 | + // Strip private RSA parameters before exposing the public JWK. |
| 78 | + delete jwk.d; |
| 79 | + delete jwk.p; |
| 80 | + delete jwk.q; |
| 81 | + delete jwk.dp; |
| 82 | + delete jwk.dq; |
| 83 | + delete jwk.qi; |
| 84 | + delete (jwk as Record<string, unknown>).oth; |
| 85 | + return jwk; |
| 86 | +} |
| 87 | + |
| 88 | +export async function getAgentTokenKeyId(): Promise<string> { |
| 89 | + const configured = envString("AGENT_TOKEN_KEY_ID") ?? envString("ELIZA_AGENT_TOKEN_KEY_ID"); |
| 90 | + if (configured) return configured; |
| 91 | + |
| 92 | + const pem = getPrivateKeyPem(); |
| 93 | + if (!pem) { |
| 94 | + throw new Error("AGENT_TOKEN_PRIVATE_KEY_PEM is not configured"); |
| 95 | + } |
| 96 | + if (cachedKeyId && cachedKeyIdSource === pem) return cachedKeyId; |
| 97 | + |
| 98 | + cachedKeyId = ( |
| 99 | + await calculateJwkThumbprint(await exportedPublicJwkForCurrentKey(), "sha256") |
| 100 | + ).slice(0, 16); |
| 101 | + cachedKeyIdSource = pem; |
| 102 | + return cachedKeyId; |
| 103 | +} |
| 104 | + |
| 105 | +export async function getAgentTokenPublicJwk(): Promise<JWK> { |
| 106 | + const pem = getPrivateKeyPem(); |
| 107 | + if (!pem) { |
| 108 | + throw new Error("AGENT_TOKEN_PRIVATE_KEY_PEM is not configured"); |
| 109 | + } |
| 110 | + if (cachedPublicJwk && cachedPublicJwkSource === pem) return cachedPublicJwk; |
| 111 | + |
| 112 | + const jwk = await exportedPublicJwkForCurrentKey(); |
| 113 | + jwk.kid = await getAgentTokenKeyId(); |
| 114 | + jwk.alg = ALGORITHM; |
| 115 | + jwk.use = "sig"; |
| 116 | + |
| 117 | + cachedPublicJwk = jwk; |
| 118 | + cachedPublicJwkSource = pem; |
| 119 | + return jwk; |
| 120 | +} |
| 121 | + |
| 122 | +export async function getAgentTokenJWKS(): Promise<{ keys: JWK[] }> { |
| 123 | + return { keys: [await getAgentTokenPublicJwk()] }; |
| 124 | +} |
| 125 | + |
| 126 | +export async function mintAgentToken( |
| 127 | + agentId: string, |
| 128 | + ttl?: unknown, |
| 129 | +): Promise<AgentTokenMintResult> { |
| 130 | + const normalizedAgentId = normalizeAgentId(agentId); |
| 131 | + const ttlSeconds = normalizeAgentTokenTtl(ttl); |
| 132 | + const issuedAt = Math.floor(Date.now() / 1000); |
| 133 | + const expiresAtSeconds = issuedAt + ttlSeconds; |
| 134 | + const privateKey = await getAgentTokenPrivateKey(); |
| 135 | + |
| 136 | + const token = await new SignJWT({ agent_id: normalizedAgentId }) |
| 137 | + .setProtectedHeader({ alg: ALGORITHM, typ: "JWT", kid: await getAgentTokenKeyId() }) |
| 138 | + .setSubject(`agent:${normalizedAgentId}`) |
| 139 | + .setIssuer(ISSUER) |
| 140 | + .setAudience(AUDIENCE) |
| 141 | + .setIssuedAt(issuedAt) |
| 142 | + .setNotBefore(issuedAt) |
| 143 | + .setExpirationTime(expiresAtSeconds) |
| 144 | + .sign(privateKey); |
| 145 | + |
| 146 | + return { token, expiresAt: new Date(expiresAtSeconds * 1000).toISOString() }; |
| 147 | +} |
0 commit comments