Skip to content

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

TypeScript

feat(control-api): hub self-enrollment service with host guard, negative cache, boot hook

Jose Ramirez2f742431accf
diff --git a/control-api/src/services/memberRegistrationEnrollment.ts b/control-api/src/services/memberRegistrationEnrollment.ts
new file mode 100644
index 000000000..909a9dec9
--- /dev/null
+++ b/control-api/src/services/memberRegistrationEnrollment.ts
@@ -0,0 +1,189 @@
+import { config } from '../config.js'
+import { rootLogger } from '../observability/logger.js'
+import {
+ MemberRegistrationMisconfiguredError,
+ MemberRegistrationUnavailableError,
+} from './memberRegistrationErrors.js'
+import {
+ getActiveMemberRegistrationCredential,
+ insertMemberRegistrationCredential,
+ type MemberRegistrationCredential,
+} from './memberRegistrationCredentialsDb.js'
+
+// Hosted-mode self-enrollment against the shared hub (spec §8.3/§8.4).
+// Lock-free: in-flight promise map (per-replica) + the partial unique index
+// with adopt-winner (cross-replica). NO transaction or advisory lock may span
+// the mint fetch. Log hygiene: never log the secret or a raw mint body.
+const MINT_TIMEOUT_MS = 10_000
+const HUB_REJECTION_TTL_MS = 10 * 60 * 1000
+const BACKOFF_BASE_MS = 5_000
+const BACKOFF_CAP_MS = 5 * 60 * 1000
+
+const inFlight = new Map<string, Promise<MemberRegistrationCredential>>()
+const negativeCache = new Map<string, { until: number; message: string }>()
+const consecutiveTransientFailures = new Map<string, number>()
+
+export function __resetMemberRegistrationEnrollmentForTests(): void {
+ inFlight.clear()
+ negativeCache.clear()
+ consecutiveTransientFailures.clear()
+}
+
+export function normalizeEnrollmentHost(baseUrl: string): string {
+ try {
+ return new URL(baseUrl).hostname.toLowerCase()
+ } catch {
+ throw new MemberRegistrationMisconfiguredError(
+ `member-registration destination is not a valid URL: ${baseUrl}`
+ )
+ }
+}
+
+const IPV4_RE = /^\d{1,3}(\.\d{1,3}){3}$/
+
+function assertEnrollableHost(host: string): void {
+ const reason =
+ host === 'localhost' || host.endsWith('.localhost')
+ ? 'localhost'
+ : IPV4_RE.test(host)
+ ? 'an IPv4 literal'
+ : host.startsWith('[') || host.includes(':')
+ ? 'an IPv6 literal'
+ : !host.includes('.')
+ ? 'a dotless hostname'
+ : null
+ if (reason) {
+ throw new MemberRegistrationMisconfiguredError(
+ `hosted member-registration requires a real, publicly resolvable domain — '${host}' is ${reason}. Set CONTROL_API_DESKTOP_PROFILE_UI_BASE_URL / CONTROL_API_CONTROL_UI_BASE_URL to real domains.`
+ )
+ }
+}
+
+function hubOrigin(): string {
+ return new URL(config.memberRegistrationExternalHubBaseUrl).origin
+}
+
+export async function ensureEnrollment(domain: string): Promise<MemberRegistrationCredential> {
+ assertEnrollableHost(domain)
+ const cached = negativeCache.get(domain)
+ if (cached) {
+ if (cached.until > Date.now()) throw new MemberRegistrationUnavailableError(cached.message)
+ negativeCache.delete(domain)
+ }
+ const pending = inFlight.get(domain)
+ if (pending) return pending
+ const attempt = enroll(domain).finally(() => inFlight.delete(domain))
+ inFlight.set(domain, attempt)
+ return attempt
+}
+
+async function enroll(domain: string): Promise<MemberRegistrationCredential> {
+ const existing = await getActiveMemberRegistrationCredential(domain)
+ if (existing) return existing
+
+ let response: Response
+ try {
+ response = await fetch(`${hubOrigin()}/public/tenants`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ domain }),
+ signal: AbortSignal.timeout(MINT_TIMEOUT_MS),
+ })
+ } catch (error) {
+ throw transientFailure(
+ domain,
+ `member-registration hub unreachable: ${error instanceof Error ? error.message : String(error)}`
+ )
+ }
+
+ if (!response.ok) {
+ // Log hygiene: status only — never stringify the response body.
+ if (response.status >= 400 && response.status < 500) {
+ const message = `member-registration hub rejected enrollment for '${domain}' (${response.status})`
+ negativeCache.set(domain, { until: Date.now() + HUB_REJECTION_TTL_MS, message })
+ rootLogger.error(
+ { event: 'member_registration_enrollment_rejected', domain, status: response.status },
+ message
+ )
+ throw new MemberRegistrationUnavailableError(message)
+ }
+ throw transientFailure(domain, `member-registration hub error (${response.status})`)
+ }
+
+ consecutiveTransientFailures.delete(domain)
+ const minted = (await response.json()) as { tenantId?: unknown; kid?: unknown; secret?: unknown }
+ if (
+ typeof minted.tenantId !== 'string' ||
+ typeof minted.kid !== 'string' ||
+ typeof minted.secret !== 'string'
+ ) {
+ throw transientFailure(domain, 'member-registration hub returned a malformed mint response')
+ }
+
+ const { inserted } = await insertMemberRegistrationCredential({
+ boundDomain: domain,
+ tenantId: minted.tenantId,
+ kid: minted.kid,
+ secret: minted.secret,
+ })
+ const winner = await getActiveMemberRegistrationCredential(domain)
+ if (!winner) {
+ throw transientFailure(domain, 'credential row missing after insert')
+ }
+ if (!inserted) {
+ rootLogger.warn(
+ {
+ event: 'member_registration_enrollment_orphan',
+ domain,
+ kid: winner.kid,
+ tenantId: winner.tenantId,
+ },
+ 'lost the cross-replica mint race; adopting the winning credential (orphan minted hub-side)'
+ )
+ } else {
+ rootLogger.info(
+ { event: 'member_registration_enrolled', domain, kid: winner.kid, tenantId: winner.tenantId },
+ 'enrolled with the member-registration hub'
+ )
+ }
+ return winner
+}
+
+function transientFailure(domain: string, message: string): MemberRegistrationUnavailableError {
+ const failures = (consecutiveTransientFailures.get(domain) ?? 0) + 1
+ consecutiveTransientFailures.set(domain, failures)
+ const backoffMs = Math.min(BACKOFF_BASE_MS * 2 ** (failures - 1), BACKOFF_CAP_MS)
+ negativeCache.set(domain, { until: Date.now() + backoffMs, message })
+ rootLogger.error(
+ { event: 'member_registration_enrollment_failed', domain, failures, backoffMs },
+ message
+ )
+ return new MemberRegistrationUnavailableError(message)
+}
+
+// Boot hook (spec §8.4): exported and unit-testable; contract = never rejects.
+// main.ts only calls this — do NOT inline a try/catch there.
+export async function runBootEnrollment(): Promise<void> {
+ if (config.memberRegistrationMode !== 'hosted') return
+ const hosts = new Set<string>()
+ for (const base of [config.desktopProfileUiBaseUrl, config.controlUiBaseUrl]) {
+ try {
+ hosts.add(normalizeEnrollmentHost(base))
+ } catch (error) {
+ rootLogger.error(
+ { event: 'member_registration_boot_enrollment_failed', base },
+ error instanceof Error ? error.message : String(error)
+ )
+ }
+ }
+ for (const host of hosts) {
+ try {
+ await ensureEnrollment(host)
+ } catch (error) {
+ rootLogger.error(
+ { event: 'member_registration_boot_enrollment_failed', domain: host },
+ error instanceof Error ? error.message : String(error)
+ )
+ }
+ }
+}
diff --git a/control-api/src/services/memberRegistrationErrors.ts b/control-api/src/services/memberRegistrationErrors.ts
new file mode 100644
index 000000000..71899f9a8
--- /dev/null
+++ b/control-api/src/services/memberRegistrationErrors.ts
@@ -0,0 +1,29 @@
+// Typed member-registration failures (spec §8.6). Routes rethrow these ahead of
+// their bare 400 catch-alls; the app.ts error middleware maps them to 503.
+export class MemberRegistrationUnavailableError extends Error {
+ readonly code = 'member_registration_unavailable' as const
+ constructor(message = 'member registration is temporarily unavailable') {
+ super(message)
+ this.name = 'MemberRegistrationUnavailableError'
+ }
+}
+
+export class MemberRegistrationMisconfiguredError extends Error {
+ readonly code = 'member_registration_misconfigured' as const
+ constructor(message: string) {
+ super(message)
+ this.name = 'MemberRegistrationMisconfiguredError'
+ }
+}
+
+export function memberRegistrationErrorResponse(
+ err: unknown
+): { status: 503; error: 'member_registration_unavailable' | 'member_registration_misconfigured' } | null {
+ if (
+ err instanceof MemberRegistrationUnavailableError ||
+ err instanceof MemberRegistrationMisconfiguredError
+ ) {
+ return { status: 503, error: err.code }
+ }
+ return null
+}
diff --git a/control-api/test/services.memberRegistrationEnrollment.test.ts b/control-api/test/services.memberRegistrationEnrollment.test.ts
new file mode 100644
index 000000000..0784cd6ed
--- /dev/null
+++ b/control-api/test/services.memberRegistrationEnrollment.test.ts
@@ -0,0 +1,258 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { cfg } = vi.hoisted(() => ({
+ cfg: {
+ memberRegistrationMode: 'hosted',
+ memberRegistrationExternalHubBaseUrl: 'https://registration.evenfire.ai/api/v1',
+ desktopProfileUiBaseUrl: 'https://profile.acme.com',
+ controlUiBaseUrl: 'https://control.acme.com',
+ } as Record<string, unknown>,
+}))
+vi.mock('../src/config.js', () => ({ config: cfg }))
+
+const store = vi.hoisted(() => ({
+ getActiveMemberRegistrationCredential: vi.fn(),
+ insertMemberRegistrationCredential: vi.fn(),
+}))
+vi.mock('../src/services/memberRegistrationCredentialsDb.js', () => store)
+
+const logSink = vi.hoisted(() => ({ lines: [] as string[] }))
+vi.mock('../src/observability/logger.js', () => ({
+ rootLogger: {
+ info: (...args: unknown[]) => logSink.lines.push(JSON.stringify(args)),
+ warn: (...args: unknown[]) => logSink.lines.push(JSON.stringify(args)),
+ error: (...args: unknown[]) => logSink.lines.push(JSON.stringify(args)),
+ },
+}))
+
+import {
+ MemberRegistrationMisconfiguredError,
+ MemberRegistrationUnavailableError,
+} from '../src/services/memberRegistrationErrors.js'
+import {
+ __resetMemberRegistrationEnrollmentForTests,
+ ensureEnrollment,
+ normalizeEnrollmentHost,
+ runBootEnrollment,
+} from '../src/services/memberRegistrationEnrollment.js'
+
+const CRED = {
+ boundDomain: 'profile.acme.com',
+ tenantId: 'ext-abc123',
+ kid: 'ext-abc123-deadbeef',
+ secret: 'hub-secret',
+}
+
+function mintResponse(): Response {
+ return new Response(
+ JSON.stringify({ tenantId: CRED.tenantId, kid: CRED.kid, secret: CRED.secret }),
+ { status: 201, headers: { 'content-type': 'application/json' } }
+ )
+}
+
+describe('memberRegistrationEnrollment', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.useFakeTimers()
+ logSink.lines.length = 0
+ __resetMemberRegistrationEnrollmentForTests()
+ cfg.memberRegistrationMode = 'hosted'
+ cfg.desktopProfileUiBaseUrl = 'https://profile.acme.com'
+ cfg.controlUiBaseUrl = 'https://control.acme.com'
+ store.getActiveMemberRegistrationCredential.mockResolvedValue(null)
+ store.insertMemberRegistrationCredential.mockResolvedValue({ inserted: true })
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ it('normalizeEnrollmentHost lowercases and strips port/scheme/path', () => {
+ expect(normalizeEnrollmentHost('https://Profile.ACME.com:8443/x/y')).toBe('profile.acme.com')
+ })
+
+ it('mints against the hub ORIGIN (not /api/v1) with a 10s bounded timeout, persists, returns', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(mintResponse())
+ vi.stubGlobal('fetch', fetchMock)
+ // Observe the BOUND, not merely "some signal": toBeInstanceOf(AbortSignal)
+ // is satisfied by a never-firing controller signal or a 999s timeout.
+ const timeoutSpy = vi.spyOn(AbortSignal, 'timeout')
+ store.getActiveMemberRegistrationCredential
+ .mockResolvedValueOnce(null) // pre-mint check
+ .mockResolvedValueOnce(CRED) // adopt-winner re-select
+ const cred = await ensureEnrollment('profile.acme.com')
+ expect(cred).toEqual(CRED)
+ const [url, init] = fetchMock.mock.calls[0]
+ expect(url).toBe('https://registration.evenfire.ai/public/tenants')
+ expect(timeoutSpy).toHaveBeenCalledWith(10_000)
+ expect(init.signal).toBe(timeoutSpy.mock.results[0].value)
+ expect(JSON.parse(init.body)).toEqual({ domain: 'profile.acme.com' })
+ expect(store.insertMemberRegistrationCredential).toHaveBeenCalledWith({
+ boundDomain: 'profile.acme.com',
+ tenantId: CRED.tenantId,
+ kid: CRED.kid,
+ secret: CRED.secret,
+ })
+ })
+
+ it('reuses a stored credential without minting', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ store.getActiveMemberRegistrationCredential.mockResolvedValue(CRED)
+ expect(await ensureEnrollment('profile.acme.com')).toEqual(CRED)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('collapses concurrent calls into one mint (in-flight map)', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(mintResponse())
+ vi.stubGlobal('fetch', fetchMock)
+ // STATEFUL store: a `mockResolvedValueOnce(null).mockResolvedValue(CRED)`
+ // sequence would let caller 2's PRE-MINT select consume the persisted CRED
+ // and skip minting, so the test would pass with the in-flight map deleted.
+ // Here both callers see null until an insert happens — only the map can
+ // hold fetch at 1.
+ let stored: typeof CRED | null = null
+ store.getActiveMemberRegistrationCredential.mockImplementation(async () => stored)
+ store.insertMemberRegistrationCredential.mockImplementation(async () => {
+ stored = CRED
+ return { inserted: true }
+ })
+ const [a, b] = await Promise.all([
+ ensureEnrollment('profile.acme.com'),
+ ensureEnrollment('profile.acme.com'),
+ ])
+ expect(a).toEqual(CRED)
+ expect(b).toEqual(CRED)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('adopts the winner on a lost insert race and logs the orphan WITHOUT the secret', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(mintResponse())
+ vi.stubGlobal('fetch', fetchMock)
+ store.insertMemberRegistrationCredential.mockResolvedValue({ inserted: false })
+ store.getActiveMemberRegistrationCredential
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({ ...CRED, kid: 'ext-winner-kid', secret: 'winner-secret' })
+ const cred = await ensureEnrollment('profile.acme.com')
+ expect(cred.kid).toBe('ext-winner-kid')
+ expect(logSink.lines.join('\n')).toContain('orphan')
+ expect(logSink.lines.join('\n')).not.toContain('hub-secret')
+ expect(logSink.lines.join('\n')).not.toContain('winner-secret')
+ })
+
+ it('negative-caches a hub 4xx for the FULL 10min TTL, not the transient backoff window', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(new Response(JSON.stringify({ error: 'domain_blocked' }), { status: 403 }))
+ vi.stubGlobal('fetch', fetchMock)
+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(
+ MemberRegistrationUnavailableError
+ )
+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(
+ MemberRegistrationUnavailableError
+ )
+ expect(fetchMock).toHaveBeenCalledTimes(1) // second call served from the negative cache
+
+ // Intermediate sample PAST the transient backoff cap (5min) but INSIDE the
+ // 4xx TTL (10min): pins TTL(4xx) > backoff-cap, so routing 4xx through the
+ // transient path (an easy collapse — both write negativeCache) fails here.
+ vi.advanceTimersByTime(5 * 60 * 1000)
+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(
+ MemberRegistrationUnavailableError
+ )
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+
+ vi.advanceTimersByTime(5 * 60 * 1000 + 1) // now past the 10min TTL
+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(
+ MemberRegistrationUnavailableError
+ )
+ expect(fetchMock).toHaveBeenCalledTimes(2) // TTL expired → one fresh attempt
+ })
+
+ it('backs off exponentially on network errors and recovers after the window', async () => {
+ const fetchMock = vi.fn().mockRejectedValue(new TypeError('fetch failed'))
+ vi.stubGlobal('fetch', fetchMock)
+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(
+ MemberRegistrationUnavailableError
+ )
+ // within the 5s backoff window: cached, no new fetch
+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(
+ MemberRegistrationUnavailableError
+ )
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ vi.advanceTimersByTime(5_000 + 1)
+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(
+ MemberRegistrationUnavailableError
+ )
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('treats a hub 5xx as transient (5s backoff), NOT as a terminal 4xx rejection', async () => {
+ // Without this, the 5xx branch is dead code: an implementation that treats
+ // every !response.ok as terminal blanks invitations for 10min on a hub 502.
+ const fetchMock = vi.fn().mockResolvedValue(new Response('', { status: 502 }))
+ vi.stubGlobal('fetch', fetchMock)
+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(
+ MemberRegistrationUnavailableError
+ )
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ vi.advanceTimersByTime(5_000 + 1) // transient window, well inside the 4xx TTL
+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(
+ MemberRegistrationUnavailableError
+ )
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('rejects localhost / IP-literal / dotless hosts with the misconfiguration error, never fetching', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ for (const host of ['localhost', '127.0.0.1', '[::1]', 'minikube']) {
+ await expect(ensureEnrollment(host)).rejects.toBeInstanceOf(
+ MemberRegistrationMisconfiguredError
+ )
+ }
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('runBootEnrollment enrolls each unique host and NEVER rejects on failure', async () => {
+ const fetchMock = vi.fn().mockRejectedValue(new TypeError('fetch failed'))
+ vi.stubGlobal('fetch', fetchMock)
+ await expect(runBootEnrollment()).resolves.toBeUndefined()
+ expect(fetchMock).toHaveBeenCalledTimes(2) // profile.acme.com + control.acme.com
+ expect(logSink.lines.join('\n')).toContain('member_registration_boot_enrollment_failed')
+ })
+
+ it('runBootEnrollment swallows UNTYPED failures too (the catch is unconditional)', async () => {
+ // The fetch-rejection case above only proves typed errors are caught —
+ // enroll() wraps them. A hook whose catch is narrowed to the typed error
+ // ("rethrow unexpected errors for visibility") would still pass that one,
+ // then crash-loop boot when Postgres is briefly unreachable at startup.
+ vi.stubGlobal('fetch', vi.fn())
+ store.getActiveMemberRegistrationCredential.mockRejectedValue(new Error('db down'))
+ await expect(runBootEnrollment()).resolves.toBeUndefined()
+ expect(logSink.lines.join('\n')).toContain('member_registration_boot_enrollment_failed')
+ })
+
+ it('runBootEnrollment dedupes hosts sharing a hostname and no-ops in remote mode', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(mintResponse())
+ vi.stubGlobal('fetch', fetchMock)
+ store.getActiveMemberRegistrationCredential
+ .mockResolvedValueOnce(null)
+ .mockResolvedValue(CRED)
+ cfg.desktopProfileUiBaseUrl = 'https://apps.acme.com:3001'
+ cfg.controlUiBaseUrl = 'https://apps.acme.com:3000'
+ await runBootEnrollment()
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+
+ fetchMock.mockClear()
+ // Assert at the STORE boundary: with a stored credential lingering from the
+ // hosted half, a dropped mode gate would still show fetch=0 while running
+ // enrollment DB reads on every remote (incl. managed/MCC) boot.
+ store.getActiveMemberRegistrationCredential.mockClear()
+ cfg.memberRegistrationMode = 'remote'
+ await runBootEnrollment()
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(store.getActiveMemberRegistrationCredential).not.toHaveBeenCalled()
+ })
+})