Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(control-api,rpc-proxy,external-rest-api): share one dev JWT key identity

Alfredo Lopezae3f4e25988c
diff --git a/control-api/README.md b/control-api/README.md
index 875559430..75ce1e680 100644
--- a/control-api/README.md
+++ b/control-api/README.md
@@ -172,10 +172,17 @@ Auth settings:
Local development: run with `CLERUM_DEV_MODE=true` and no signing-key env vars.
Control API generates one RSA-2048 key per slot under the gitignored
-`control-api/.dev-keys/` directory (`0700` directory, `0600` files) on first
-use and reuses it across restarts. Outside dev mode the three env vars above
-are always required, and keys whose public halves were ever committed to this
-repository are rejected in every slot, including the RPC verifier public key.
+`control-api/.dev-keys/` directory (`0700` directory, `0600` signing files,
+`0644` derived public files) on first use, reuses it across restarts, and
+publishes each derived public half as `<slot>.public.pem`. When
+`rpc-proxy` and `external-rest-api` also run with `CLERUM_DEV_MODE=true`, they
+load `rpc.public.pem` and `session.public.pem` from that store, so a monorepo
+dev boot keeps one shared key identity. Set `EVENFIRE_DEV_KEY_STORE` to
+relocate the store, or set the explicit `RPC_PROXY_JWT_PUBLIC_KEY` /
+`EXTERNAL_REST_API_JWT_PUBLIC_KEY` env vars to override it. Outside dev mode
+the three env vars above are always required, and keys whose public halves
+were ever committed to this repository are rejected in every slot, including
+the RPC verifier public key.
- `CONTROL_API_RPC_JWT_PRIVATE_KEY`: RSA private key used to sign RPC access JWTs for `rpc-proxy` (RS256).
- `CONTROL_API_JWT_ISSUER`: expected `iss` for session token signing and verification.
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 681d569f4..3a52cd988 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.682",
+ "version": "0.1.683",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.682",
+ "version": "0.1.683",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index e82aab44f..a552b0270 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.682",
+ "version": "0.1.683",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/devSigningKeys.ts b/control-api/src/devSigningKeys.ts
index 3b8d75924..90e6ae896 100644
--- a/control-api/src/devSigningKeys.ts
+++ b/control-api/src/devSigningKeys.ts
@@ -1,4 +1,4 @@
-import { createPrivateKey, generateKeyPairSync, randomBytes } from 'node:crypto'
+import { createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes } from 'node:crypto'
import {
type Stats,
linkSync,
@@ -22,7 +22,7 @@ export type DevJwtSlot = 'rpc' | 'session' | 'admin'
* falls back to the service working directory used by every test/npm script.
*/
const SERVICE_ROOT = typeof __dirname === 'string' && __dirname ? dirname(__dirname) : process.cwd()
-const DEFAULT_STORE_DIR = join(SERVICE_ROOT, '.dev-keys')
+const DEFAULT_STORE_DIR = process.env.EVENFIRE_DEV_KEY_STORE ?? join(SERVICE_ROOT, '.dev-keys')
export function defaultDevSigningKeyStoreDir(): string {
return DEFAULT_STORE_DIR
@@ -107,6 +107,53 @@ function readPersistedKey(filePath: string, slot: DevJwtSlot): string | undefine
let warnedOnce = false
+function readStoredDerivedPublic(publicPath: string): string | undefined {
+ const stats = lstatSync(publicPath, { throwIfNoEntry: false })
+ if (!stats) return undefined
+ if (stats.isSymbolicLink() || !stats.isFile()) {
+ throw new Error(`Dev JWT key store public path is not a regular file: ${publicPath}`)
+ }
+ return readFileSync(publicPath, 'utf8').trim()
+}
+
+/**
+ * Publish the verifying half derived from the signing material as
+ * `<slot>.public.pem` (0644 inside the 0700 store). Sibling dev verifiers read
+ * this file so the monorepo dev boot shares one key identity; it is never
+ * written independently, and an existing copy that disagrees with the signing
+ * material is a hard error.
+ */
+function ensureDerivedPublicKey(slot: DevJwtSlot, storeDir: string, signingPem: string): void {
+ const publicPath = join(storeDir, `${slot}.public.pem`)
+ const derived = createPublicKey(signingPem)
+ .export({ type: 'spki', format: 'pem' })
+ .toString()
+ .trim()
+ const existing = readStoredDerivedPublic(publicPath)
+ if (existing !== undefined) {
+ if (existing !== derived) {
+ throw new Error(
+ `Dev JWT key store public file does not match its signing material: ${publicPath}. ` +
+ 'Delete the store only if you accept losing local dev tokens.'
+ )
+ }
+ return
+ }
+ const tempPath = `${publicPath}.tmp-${process.pid.toString(36)}-${randomBytes(6).toString('hex')}`
+ try {
+ writeFileSync(tempPath, derived, { mode: 0o644 })
+ linkSync(tempPath, publicPath)
+ unlinkSync(tempPath)
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'EEXIST') {
+ removeIfPresent(tempPath)
+ // Another process published first; its content is validated on the next read.
+ return
+ }
+ throw err
+ }
+}
+
/**
* Returns the dev private key for a slot, generating and persisting it with
* exclusive creation on first use. Concurrent first starts converge on one
@@ -123,6 +170,8 @@ export function loadOrGenerateDevJwtPrivateKey(
ensureStoreDir(storeDir)
const existing = readPersistedKey(filePath, slot)
if (existing) {
+ warnOnce()
+ ensureDerivedPublicKey(slot, storeDir, existing)
warnOnce()
return existing
}
@@ -147,6 +196,8 @@ export function loadOrGenerateDevJwtPrivateKey(
// Another local process published a complete key first; adopt it.
const winner = readPersistedKey(filePath, slot)
if (winner) {
+ warnOnce()
+ ensureDerivedPublicKey(slot, storeDir, winner)
warnOnce()
return winner
}
@@ -154,8 +205,11 @@ export function loadOrGenerateDevJwtPrivateKey(
throw err
}
assertOwnedRegularFile(filePath)
+ assertOwnedRegularFile(filePath)
+ ensureDerivedPublicKey(slot, storeDir, privateKey)
warnOnce()
return privateKey.trim()
+ return privateKey.trim()
}
function warnOnce(): void {
diff --git a/control-api/test/devSigningKeys.test.ts b/control-api/test/devSigningKeys.test.ts
index 005ede69b..c6d30aaf7 100644
--- a/control-api/test/devSigningKeys.test.ts
+++ b/control-api/test/devSigningKeys.test.ts
@@ -1,5 +1,6 @@
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
import { spawn, spawnSync } from 'node:child_process'
+import { createPublicKey } from 'node:crypto'
import {
chmodSync,
mkdirSync,
@@ -199,4 +200,42 @@ describe('devSigningKeys persistence contract', () => {
/Dev JWT key store path is not a directory/
)
})
+
+ it('publishes the derived verifying half next to the signing material', () => {
+ const store = tempStore()
+ const signing = loadOrGenerateDevJwtPrivateKey('rpc', store)
+ const publicPath = join(store, 'rpc.public.pem')
+ const published = readFileSync(publicPath, 'utf8').trim()
+ expect(published).toBe(
+ createPublicKey(signing).export({ type: 'spki', format: 'pem' }).toString().trim()
+ )
+ expect(statSync(publicPath).mode & 0o777).toBe(0o644)
+ loadOrGenerateDevJwtPrivateKey('rpc', store)
+ expect(readFileSync(publicPath, 'utf8').trim()).toBe(published)
+ })
+
+ it('backfills a missing verifying half on reuse', () => {
+ const store = tempStore()
+ const signing = loadOrGenerateDevJwtPrivateKey('session', store)
+ rmSync(join(store, 'session.public.pem'))
+ loadOrGenerateDevJwtPrivateKey('session', store)
+ expect(readFileSync(join(store, 'session.public.pem'), 'utf8').trim()).toBe(
+ createPublicKey(signing).export({ type: 'spki', format: 'pem' }).toString().trim()
+ )
+ })
+
+ it('rejects a published verifying half that disagrees with the signing material', () => {
+ const store = tempStore()
+ loadOrGenerateDevJwtPrivateKey('admin', store)
+ const other = loadOrGenerateDevJwtPrivateKey('rpc', store)
+ rmSync(join(store, 'admin.public.pem'))
+ writeFileSync(
+ join(store, 'admin.public.pem'),
+ createPublicKey(other).export({ type: 'spki', format: 'pem' }).toString(),
+ { mode: 0o644 }
+ )
+ expect(() => loadOrGenerateDevJwtPrivateKey('admin', store)).toThrow(
+ /public file does not match its signing material/
+ )
+ })
})
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index 81c281065..c47638178 100644
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.85",
+ "version": "0.1.86",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.85",
+ "version": "0.1.86",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index ce716823a..01619c163 100644
--- a/external-rest-api/package.json
+++ b/external-rest-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.85",
+ "version": "0.1.86",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/config.ts b/external-rest-api/src/config.ts
index 4c24d431e..8da3d6f0e 100644
--- a/external-rest-api/src/config.ts
+++ b/external-rest-api/src/config.ts
@@ -1,3 +1,6 @@
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+
type Config = {
port: number
jsonBodyLimit: string
@@ -138,6 +141,38 @@ function parseExternalGfsEdgeRateLimits() {
const externalGfsEdgeRateLimits = parseExternalGfsEdgeRateLimits()
+function serviceRoot(): string {
+ // Works in every supported runtime: CommonJS (dist and ts-node) resolves
+ // __dirname to <service>/dist or <service>/src; Vitest's ESM transform falls
+ // back to the service working directory used by every test/npm script.
+ return typeof __dirname === 'string' && __dirname ? dirname(__dirname) : process.cwd()
+}
+
+/**
+ * In explicit dev mode, verify with the public half control-api publishes next
+ * to its generated session signing key, so a monorepo dev boot keeps one
+ * shared key identity across the signer and this verifier.
+ * EVENFIRE_DEV_KEY_STORE can relocate the store; EXTERNAL_REST_API_JWT_PUBLIC_KEY
+ * always takes precedence.
+ */
+function resolveSessionJwtPublicKey(): string {
+ const fromEnv = process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
+ if (fromEnv) return fromEnv
+ if (process.env.CLERUM_DEV_MODE === 'true') {
+ const storeDir =
+ process.env.EVENFIRE_DEV_KEY_STORE ?? join(serviceRoot(), '..', 'control-api', '.dev-keys')
+ const publicPath = join(storeDir, 'session.public.pem')
+ try {
+ return readFileSync(publicPath, 'utf8')
+ } catch {
+ throw new Error(
+ `CLERUM_DEV_MODE=true requires the control-api dev key store at ${storeDir}. ` +
+ 'Start control-api once with CLERUM_DEV_MODE=true, or set EXTERNAL_REST_API_JWT_PUBLIC_KEY.'
+ )
+ }
+ }
+ return DEV_SESSION_JWT_PUBLIC_KEY
+}
export const config: Config = {
port: Number(process.env.EXTERNAL_REST_API_PORT || 8091),
jsonBodyLimit: process.env.EXTERNAL_REST_API_JSON_BODY_LIMIT || '150mb',
@@ -162,9 +197,7 @@ export const config: Config = {
})(),
controlApiServiceName:
process.env.EXTERNAL_REST_API_CONTROL_API_SERVICE_NAME || 'external-rest-api',
- jwtPublicKey: normalizePem(
- requiredOrDevDefault('EXTERNAL_REST_API_JWT_PUBLIC_KEY', DEV_SESSION_JWT_PUBLIC_KEY)
- ),
+ jwtPublicKey: normalizePem(resolveSessionJwtPublicKey()),
jwtIssuer: requiredOrDevDefault('EXTERNAL_REST_API_JWT_ISSUER', 'control-api'),
jwtAudience: requiredOrDevDefault('EXTERNAL_REST_API_JWT_AUDIENCE', 'profile-ui'),
profileSessionCookieTtlSeconds: positiveIntegerFromEnv(
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index f159b47b7..f1c578244 100644
--- a/external-rest-api/src/releaseManifest.ts
+++ b/external-rest-api/src/releaseManifest.ts
@@ -8,8 +8,8 @@ export type ReleaseManifest = {
export const releaseManifest: ReleaseManifest = {
releaseId: 'v0.10.0',
- externalRestApiVersion: '0.1.85',
- rpcProxyVersion: '0.1.111',
+ externalRestApiVersion: '0.1.86',
+ rpcProxyVersion: '0.1.112',
desktopVersion: '0.10.0',
minimumDesktopVersion: '0.1.252',
}
diff --git a/external-rest-api/test/config.devKeyStore.test.ts b/external-rest-api/test/config.devKeyStore.test.ts
new file mode 100644
index 000000000..370c905d0
--- /dev/null
+++ b/external-rest-api/test/config.devKeyStore.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { generateKeyPairSync } from 'node:crypto'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+const ORIGINAL_ENV = { ...process.env }
+let store: string
+
+function seedSharedSessionVerifyingHalf(): string {
+ const verifying = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ }).publicKey
+ writeFileSync(join(store, 'session.public.pem'), verifying, { mode: 0o644 })
+ return verifying
+}
+
+beforeEach(() => {
+ vi.resetModules()
+ process.env = { ...ORIGINAL_ENV }
+ delete process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
+ process.env.CLERUM_DEV_MODE = 'true'
+ store = mkdtempSync(join(tmpdir(), 'evenfire-ext-dev-keys-'))
+ process.env.EVENFIRE_DEV_KEY_STORE = store
+})
+
+afterEach(() => {
+ process.env = ORIGINAL_ENV
+ rmSync(store, { recursive: true, force: true })
+ vi.resetModules()
+})
+
+describe('external-rest-api shared dev key identity', () => {
+ it('loads exactly the verifying half published by control-api', async () => {
+ const published = seedSharedSessionVerifyingHalf()
+ const { config } = await import('../src/config.js')
+ expect(config.jwtPublicKey).toBe(published.trim())
+ })
+
+ it('fails loud when the shared store has not been created', async () => {
+ await expect(() => import('../src/config.js')).rejects.toThrow(
+ /requires the control-api dev key store/
+ )
+ })
+
+ it('prefers an explicit verifier env var over the shared store', async () => {
+ seedSharedSessionVerifyingHalf()
+ const explicit = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ }).publicKey
+ process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY = explicit
+ const { config } = await import('../src/config.js')
+ expect(config.jwtPublicKey).toBe(explicit.trim())
+ })
+})
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index 5bb586f38..6e2967f85 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.111",
+ "version": "0.1.112",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.111",
+ "version": "0.1.112",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index 7544d37ea..ed2a02696 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.111",
+ "version": "0.1.112",
"description": "External-facing RPC proxy for tenant-scoped MCP access",
"main": "dist/main.js",
"engines": {
diff --git a/rpc-proxy/src/__tests__/config.devKeyStore.test.ts b/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
new file mode 100644
index 000000000..c15d4d262
--- /dev/null
+++ b/rpc-proxy/src/__tests__/config.devKeyStore.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { generateKeyPairSync } from 'node:crypto'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+const ORIGINAL_ENV = { ...process.env }
+let store: string
+
+function seedSharedRpcVerifyingHalf(): string {
+ const verifying = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ }).publicKey
+ writeFileSync(join(store, 'rpc.public.pem'), verifying, { mode: 0o644 })
+ return verifying
+}
+
+beforeEach(() => {
+ vi.resetModules()
+ process.env = { ...ORIGINAL_ENV }
+ delete process.env.RPC_PROXY_JWT_PUBLIC_KEY
+ process.env.CLERUM_DEV_MODE = 'true'
+ store = mkdtempSync(join(tmpdir(), 'evenfire-rpc-dev-keys-'))
+ process.env.EVENFIRE_DEV_KEY_STORE = store
+})
+
+afterEach(() => {
+ process.env = ORIGINAL_ENV
+ rmSync(store, { recursive: true, force: true })
+ vi.resetModules()
+})
+
+describe('rpc-proxy shared dev key identity', () => {
+ it('loads exactly the verifying half published by control-api', async () => {
+ const published = seedSharedRpcVerifyingHalf()
+ const { config } = await import('../config.js')
+ expect(config.jwtPublicKey).toBe(published.trim())
+ })
+
+ it('fails loud when the shared store has not been created', async () => {
+ await expect(() => import('../config.js')).rejects.toThrow(
+ /requires the control-api dev key store/
+ )
+ })
+
+ it('prefers an explicit verifier env var over the shared store', async () => {
+ seedSharedRpcVerifyingHalf()
+ const explicit = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ }).publicKey
+ process.env.RPC_PROXY_JWT_PUBLIC_KEY = explicit
+ const { config } = await import('../config.js')
+ expect(config.jwtPublicKey).toBe(explicit.trim())
+ })
+})
diff --git a/rpc-proxy/src/config.ts b/rpc-proxy/src/config.ts
index 1a2bc84fe..7931162ca 100644
--- a/rpc-proxy/src/config.ts
+++ b/rpc-proxy/src/config.ts
@@ -1,3 +1,6 @@
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+
type Config = {
port: number
corsOrigin: string[] | '*'
@@ -184,14 +187,43 @@ RRu+QZm3Lo+5AiCaHkijDCglHsXLhqsYi2AdRiavD1Gk9LKP/ztKw7q/D6fYFzmO
QwIDAQAB
-----END PUBLIC KEY-----`)
+function serviceRoot(): string {
+ // Works in every supported runtime: CommonJS (dist and ts-node) resolves
+ // __dirname to <service>/dist or <service>/src; Vitest's ESM transform falls
+ // back to the service working directory used by every test/npm script.
+ return typeof __dirname === 'string' && __dirname ? dirname(__dirname) : process.cwd()
+}
+
+/**
+ * In explicit dev mode, verify with the public half control-api publishes next
+ * to its generated RPC signing key, so a monorepo dev boot keeps one shared
+ * key identity across the signer and this verifier. EVENFIRE_DEV_KEY_STORE can
+ * relocate the store; RPC_PROXY_JWT_PUBLIC_KEY always takes precedence.
+ */
+function resolveRpcJwtPublicKey(): string {
+ const fromEnv = process.env.RPC_PROXY_JWT_PUBLIC_KEY
+ if (fromEnv) return fromEnv
+ if (process.env.CLERUM_DEV_MODE === 'true') {
+ const storeDir =
+ process.env.EVENFIRE_DEV_KEY_STORE ?? join(serviceRoot(), '..', 'control-api', '.dev-keys')
+ const publicPath = join(storeDir, 'rpc.public.pem')
+ try {
+ return readFileSync(publicPath, 'utf8')
+ } catch {
+ throw new Error(
+ `CLERUM_DEV_MODE=true requires the control-api dev key store at ${storeDir}. ` +
+ 'Start control-api once with CLERUM_DEV_MODE=true, or set RPC_PROXY_JWT_PUBLIC_KEY.'
+ )
+ }
+ }
+ return DEV_RPC_JWT_PUBLIC_KEY
+}
export const config: Config = {
port: Number(process.env.RPC_PROXY_PORT || 8094),
corsOrigin: parseCorsOrigin(
requiredOrDevDefault('RPC_PROXY_CORS_ORIGIN', 'http://localhost:3000')
),
- jwtPublicKey: normalizePem(
- requiredOrDevDefault('RPC_PROXY_JWT_PUBLIC_KEY', DEV_RPC_JWT_PUBLIC_KEY)
- ),
+ jwtPublicKey: normalizePem(resolveRpcJwtPublicKey()),
jwtIssuer: requiredOrDevDefault('RPC_PROXY_JWT_ISSUER', 'control-api'),
jwtAudience: requiredOrDevDefault('RPC_PROXY_JWT_AUDIENCE', 'rpc-proxy'),
upstreamTimeoutMs: parsePositiveIntMs(