Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): type member-registration transport failures as 503
Jose Ramirezea1fdd84eee6
diff --git a/control-api/src/memberRegistrationServiceClient.ts b/control-api/src/memberRegistrationServiceClient.tsindex bb018ed6b..fc2795096 100644--- a/control-api/src/memberRegistrationServiceClient.ts+++ b/control-api/src/memberRegistrationServiceClient.ts@@ -1,8 +1,10 @@import { config } from './config.js'+import { rootLogger } from './observability/logger.js'import {ensureEnrollment,normalizeEnrollmentHost,} from './services/memberRegistrationEnrollment.js'+import { MemberRegistrationUnavailableError } from './services/memberRegistrationErrors.js'import {type MemberRegistrationSigningCredential,signMemberRegistrationJwt,@@ -10,6 +12,8 @@ import {type RequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'+const SEND_TIMEOUT_MS = 10_000+function buildUrl(baseUrl: string, path: string): string {const base = baseUrl.replace(/\/+$/, '')const normalizedPath = path.startsWith('/') ? path : `/${path}`@@ -46,6 +50,24 @@ async function resolveTarget(destinationBaseUrl: string): Promise<{}}+// Log hygiene (mirrors memberRegistrationEnrollment.ts:100): status only —+// never stringify the upstream response body into the log or the error.+function unavailable(+ context: { baseUrl: string; method: string; path: string; upstreamStatus?: number },+ message: string,+ cause?: unknown+): MemberRegistrationUnavailableError {+ rootLogger.error(+ {+ event: 'member_registration_request_failed',+ ...context,+ cause: cause instanceof Error ? cause.message : undefined,+ },+ message+ )+ return new MemberRegistrationUnavailableError(message)+}+export async function memberRegistrationServiceRequest<T>(method: RequestMethod,path: string,@@ -55,17 +77,51 @@ export async function memberRegistrationServiceRequest<T>(}): Promise<T> {const { baseUrl, credential } = await resolveTarget(options.destinationBaseUrl)- const response = await fetch(buildUrl(baseUrl, path), {- method,- headers: {- 'content-type': 'application/json',- authorization: `Bearer ${signMemberRegistrationJwt(credential)}`,- },- body: options.body !== undefined ? JSON.stringify(options.body) : undefined,- })+ const context = { baseUrl, method, path }++ let response: Response+ try {+ response = await fetch(buildUrl(baseUrl, path), {+ method,+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${signMemberRegistrationJwt(credential)}`,+ },+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),+ })+ } catch (cause) {+ throw unavailable(context, 'member-registration service is unreachable', cause)+ }++ // Upstream 5xx is an availability problem: typed, so the app.ts middleware+ // returns 503. 4xx is a domain answer from the hub and keeps the legacy+ // message verbatim — `Member registration service` and `(status)` are matched+ // by routes/external/invitations.ts:212, routes/admin/teams.ts:42 and+ // routes/external/teams.ts:36 (spec §4.1).+ if (response.status >= 500) {+ throw unavailable(+ { ...context, upstreamStatus: response.status },+ `member-registration service ${method} ${path} failed (${response.status})`+ )+ }const raw = await response.text()- const parsed = raw ? (JSON.parse(raw) as unknown) : null+ let parsed: unknown = null+ if (raw) {+ try {+ parsed = JSON.parse(raw) as unknown+ } catch (cause) {+ if (response.ok) {+ throw unavailable(+ { ...context, upstreamStatus: response.status },+ 'member-registration service returned a non-JSON response',+ cause+ )+ }+ parsed = null+ }+ }if (!response.ok) {let errorMessage =diff --git a/control-api/test/memberRegistrationClient.errors.test.ts b/control-api/test/memberRegistrationClient.errors.test.tsnew file mode 100644index 000000000..4512667f2--- /dev/null+++ b/control-api/test/memberRegistrationClient.errors.test.ts@@ -0,0 +1,115 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { registerAndSendInvitation } from '../src/services/invitationFlowRegistrationService.js'+import { MemberRegistrationUnavailableError } from '../src/services/memberRegistrationErrors.js'++const { cfg } = vi.hoisted(() => ({+ cfg: {+ memberRegistrationMode: 'remote',+ memberRegistrationExternalHubBaseUrl: 'https://registration.evenfire.ai/api/v1',+ memberRegistrationServiceBaseUrl: 'http://member-registration-service.local:8092/api/v1',+ memberRegistrationServiceHmacSecret: 'env-secret',+ memberRegistrationServiceHmacKid: 'env-kid',+ memberRegistrationTenantId: 'clerum-dev',+ desktopProfileUiBaseUrl: 'https://profile.acme.com',+ controlUiBaseUrl: 'https://control.acme.com',+ desktopExternalRestApiBaseUrl: 'http://127.0.0.1:8091',+ desktopRpcProxyBaseUrl: 'http://127.0.0.1:8094',+ desktopAppName: 'Evenfire',+ controlUiAppName: 'Evenfire',+ } as Record<string, unknown>,+}))+vi.mock('../src/config.js', () => ({ config: cfg }))++const enrollment = vi.hoisted(() => ({+ ensureEnrollment: vi.fn(),+ normalizeEnrollmentHost: (baseUrl: string) => new URL(baseUrl).hostname.toLowerCase(),+}))+vi.mock('../src/services/memberRegistrationEnrollment.js', () => enrollment)++function send(): Promise<void> {+ return registerAndSendInvitation('[email protected]', 'uuid-1', 'team', '2026-01-01', '2026-02-01')+}++async function caught(): Promise<Error> {+ return send().then(+ () => {+ throw new Error('expected send() to reject')+ },+ (error: unknown) => error as Error+ )+}++describe('member-registration client failure classification', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.unstubAllGlobals()+ cfg.memberRegistrationMode = 'remote'+ })++ it('fetch rejecting (minikube: no registration namespace) becomes Unavailable, not a raw TypeError', async () => {+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('fetch failed')))+ await expect(send()).rejects.toBeInstanceOf(MemberRegistrationUnavailableError)+ })++ it('a timeout/abort becomes Unavailable', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockRejectedValue(new DOMException('aborted due to timeout', 'TimeoutError'))+ )+ await expect(send()).rejects.toBeInstanceOf(MemberRegistrationUnavailableError)+ })++ it('passes an AbortSignal so a stalled hub cannot hang the request forever', async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response('{"sent":true}', { status: 200 }))+ vi.stubGlobal('fetch', fetchMock)+ await send()+ const [, init] = fetchMock.mock.calls[0]+ expect(init.signal).toBeInstanceOf(AbortSignal)+ })++ it('a non-JSON 2xx body becomes Unavailable, not a raw SyntaxError', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(+ new Response('<html>gateway</html>', {+ status: 200,+ headers: { 'content-type': 'text/html' },+ })+ )+ )+ await expect(send()).rejects.toBeInstanceOf(MemberRegistrationUnavailableError)+ })++ it('an upstream 5xx becomes Unavailable and never leaks the response body', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(new Response('{"error":"SECRET_BODY"}', { status: 500 }))+ )+ const error = await caught()+ expect(error).toBeInstanceOf(MemberRegistrationUnavailableError)+ expect(error.message).not.toContain('SECRET_BODY')+ expect(error.message).toContain('500')+ })++ it('REGRESSION: an upstream 404 keeps the legacy plain Error and message so routes still match (spec §4.1)', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(new Response('{"error":"nope"}', { status: 404 }))+ )+ const error = await caught()+ expect(error).not.toBeInstanceOf(MemberRegistrationUnavailableError)+ expect(error.message).toContain('Member registration service')+ expect(error.message).toContain('(404)')+ })++ it('REGRESSION: an upstream 403 keeps the legacy plain Error (teams routes sniff this message)', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(new Response('{"error":"forbidden"}', { status: 403 }))+ )+ const error = await caught()+ expect(error).not.toBeInstanceOf(MemberRegistrationUnavailableError)+ expect(error.message).toContain('Member registration service')+ expect(error.message).toContain('(403)')+ })+})