Skip to content

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

TypeScript

fix(external-rest-api): distinguish reset outcomes from outages

Josuéc672d37204e1
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index fce3f950d..3904948b4 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.105",
+ "version": "0.1.106",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.105",
+ "version": "0.1.106",
"dependencies": {
"@clerum/jwt-key-policy": "file:../packages/jwt-key-policy",
"cors": "^2.8.5",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 9333effc9..93c1d6f2c 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.105",
+ "version": "0.1.106",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/http/passwordAdmissionError.ts b/external-rest-api/src/http/passwordAdmissionError.ts
index ee04946e3..0edc1e37b 100644
--- a/external-rest-api/src/http/passwordAdmissionError.ts
+++ b/external-rest-api/src/http/passwordAdmissionError.ts
@@ -4,6 +4,12 @@ import { ControlApiError } from '../controlApiClient.js'
/** Only the bounded public authority contract crosses this credential seam. */
export function sendPasswordAuthorityError(error: unknown, res: Response): boolean {
if (!(error instanceof ControlApiError) || ![429, 503].includes(error.status)) return false
+ const recoveryOutcomeUnknown =
+ error.status === 503 &&
+ error.body !== null &&
+ typeof error.body === 'object' &&
+ 'error' in error.body &&
+ error.body.error === 'recovery_outcome_unknown'
const retry = Number(error.headers['retry-after'])
const retryAfterSeconds =
Number.isFinite(retry) && retry > 0 ? Math.min(900, Math.max(1, Math.ceil(retry))) : 2
@@ -21,7 +27,12 @@ export function sendPasswordAuthorityError(error: unknown, res: Response): boole
res.setHeader('Retry-After', String(retryAfterSeconds))
res.setHeader('Cache-Control', 'no-store')
res.status(error.status).json({
- error: error.status === 429 ? 'rate_limited' : 'authority_unavailable',
+ error:
+ error.status === 429
+ ? 'rate_limited'
+ : recoveryOutcomeUnknown
+ ? 'recovery_outcome_unknown'
+ : 'authority_unavailable',
retryAfterSeconds,
})
return true
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index cdafea33e..237b037c2 100644
--- a/external-rest-api/src/releaseManifest.ts
+++ b/external-rest-api/src/releaseManifest.ts
@@ -8,7 +8,7 @@ export type ReleaseManifest = {
export const releaseManifest: ReleaseManifest = {
releaseId: 'v0.10.0',
- externalRestApiVersion: '0.1.105',
+ externalRestApiVersion: '0.1.106',
rpcProxyVersion: '0.1.126',
desktopVersion: '0.10.0',
minimumDesktopVersion: '0.1.252',
diff --git a/external-rest-api/src/services/invitationsService.ts b/external-rest-api/src/services/invitationsService.ts
index 6f8d51393..dca50f485 100644
--- a/external-rest-api/src/services/invitationsService.ts
+++ b/external-rest-api/src/services/invitationsService.ts
@@ -6,6 +6,51 @@ type AuthContext = {
sessionToken: string
}
+type ResetPasswordDomainError =
+ | 'not_found'
+ | 'forbidden'
+ | 'not_pending'
+ | 'expired'
+ | 'invalid_invitation'
+ | 'invalid_password'
+
+function controlApiErrorCode(error: ControlApiError): string | null {
+ if (
+ error.body !== null &&
+ typeof error.body === 'object' &&
+ 'error' in error.body &&
+ typeof error.body.error === 'string'
+ ) {
+ return error.body.error
+ }
+ return null
+}
+
+function resetPasswordDomainError(error: ControlApiError): ResetPasswordDomainError | null {
+ const code = controlApiErrorCode(error)
+ if (error.status === 400 && code === 'invalid_password') return 'invalid_password'
+ if (error.status === 400 && code === 'invalid_invitation') return 'invalid_invitation'
+ if (error.status === 403 && code === 'forbidden') return 'forbidden'
+ if (error.status === 404 && code === 'not_found') return 'not_found'
+ if (
+ error.status === 409 &&
+ (code === 'invitation_not_pending' || code === 'invitation_not_ready')
+ ) {
+ return 'not_pending'
+ }
+ if (error.status === 410 && code === 'expired') return 'expired'
+ return null
+}
+
+function unknownRecoveryOutcome(): ControlApiError {
+ return new ControlApiError(
+ 'Password recovery outcome is unknown',
+ 503,
+ { error: 'recovery_outcome_unknown' },
+ { 'retry-after': '2' }
+ )
+}
+
export type InvitationPreview = {
id: string
teamId: string | null
@@ -185,21 +230,11 @@ export async function setupInvitationPasswordWithToken(
return { data }
} catch (error) {
if (error instanceof ControlApiError && [429, 503].includes(error.status)) throw error
- if (
- error instanceof ControlApiError &&
- error.status === 400 &&
- error.body &&
- typeof error.body === 'object' &&
- 'error' in error.body &&
- error.body.error === 'invalid_invitation'
- ) {
- return { error: 'invalid_invitation' }
+ if (error instanceof ControlApiError) {
+ const domainError = resetPasswordDomainError(error)
+ if (domainError) return { error: domainError }
+ if (error.status < 500) return { error: 'invalid_invitation' }
}
- const message = error instanceof Error ? error.message : ''
- if (message.includes('(404)')) return { error: 'not_found' }
- if (message.includes('(403)')) return { error: 'forbidden' }
- if (message.includes('(409)')) return { error: 'not_pending' }
- if (message.includes('(410)')) return { error: 'expired' }
- return { error: 'invalid_password' }
+ throw unknownRecoveryOutcome()
}
}
diff --git a/external-rest-api/test/r2m3.resetTransport.public.test.ts b/external-rest-api/test/r2m3.resetTransport.public.test.ts
new file mode 100644
index 000000000..09241f14d
--- /dev/null
+++ b/external-rest-api/test/r2m3.resetTransport.public.test.ts
@@ -0,0 +1,174 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { config } from '../src/config.js'
+import { createInvitationsRouter } from '../src/routes/invitations.js'
+
+const fetchMock = vi.fn<typeof fetch>()
+
+const preview = {
+ id: 'synthetic-reset-row',
+ email: '[email protected]',
+ purpose: 'password_reset' as const,
+ status: 'pending',
+ expiresAt: '2030-01-01T00:00:00.000Z',
+ acceptedAt: null,
+ userId: 'synthetic-member-id',
+ passwordPending: true,
+ teamId: null,
+ teamName: null,
+ role: 'member',
+}
+
+function jsonResponse(status: number, body: unknown, headers: Record<string, string> = {}) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json', ...headers },
+ })
+}
+
+function makeApp() {
+ const app = express()
+ app.use(express.json())
+ app.use(createInvitationsRouter())
+ return app
+}
+
+describe('password reset transport outcomes', () => {
+ let previousControlApiBaseUrl: string
+ let previousControlApiServiceToken: string
+
+ beforeEach(() => {
+ previousControlApiBaseUrl = config.controlApiBaseUrl
+ previousControlApiServiceToken = config.controlApiServiceToken
+ config.controlApiBaseUrl = 'http://control-api.synthetic.test/api/v1'
+ config.controlApiServiceToken = 'synthetic-internal-service-token'
+ fetchMock.mockReset()
+ vi.stubGlobal('fetch', fetchMock)
+ })
+
+ afterEach(() => {
+ config.controlApiBaseUrl = previousControlApiBaseUrl
+ config.controlApiServiceToken = previousControlApiServiceToken
+ vi.unstubAllGlobals()
+ })
+
+ function previewRequest() {
+ return jsonResponse(200, preview)
+ }
+
+ async function submitReset() {
+ return request(makeApp()).post('/invitations/password').send({
+ token: 'synthetic-one-use-recovery-proof',
+ email: preview.email,
+ invitationId: preview.id,
+ password: 'Synthetic-Replacement-Password-123',
+ })
+ }
+
+ it('reports an unknown outcome after a potentially committed reset without replaying the proof', async () => {
+ let passwordChanged = false
+ let resetProofConsumed = false
+ fetchMock.mockImplementation(async (input, init) => {
+ const url = String(input)
+ if (init?.method === 'GET') return previewRequest()
+ if (url.endsWith('/external/invitations/password-token')) {
+ passwordChanged = true
+ resetProofConsumed = true
+ return new Response('<html>upstream gateway failure</html>', {
+ status: 502,
+ headers: { 'content-type': 'text/html' },
+ })
+ }
+ throw new Error('Unexpected Control API request')
+ })
+
+ const response = await submitReset()
+
+ expect(response.status).toBe(503)
+ expect(response.body).toEqual({ error: 'recovery_outcome_unknown', retryAfterSeconds: 2 })
+ expect(response.headers['retry-after']).toBe('2')
+ expect(response.headers['set-cookie']).toBeUndefined()
+ expect(JSON.stringify(response.body)).not.toContain('synthetic-one-use-recovery-proof')
+ expect(passwordChanged).toBe(true)
+ expect(resetProofConsumed).toBe(true)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('sanitizes a rejected reset transport as an unknown outcome and never retries', async () => {
+ fetchMock.mockImplementation(async (_input, init) => {
+ if (init?.method === 'GET') return previewRequest()
+ throw new TypeError('connection reset after request dispatch')
+ })
+
+ const response = await submitReset()
+
+ expect(response.status).toBe(503)
+ expect(response.body).toEqual({ error: 'recovery_outcome_unknown', retryAfterSeconds: 2 })
+ expect(response.headers['retry-after']).toBe('2')
+ expect(JSON.stringify(response.body)).not.toContain('connection reset')
+ expect(response.headers['set-cookie']).toBeUndefined()
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it.each([
+ {
+ status: 429,
+ upstreamError: 'verification_busy',
+ retryAfter: '9',
+ publicError: 'rate_limited',
+ retryAfterSeconds: 9,
+ },
+ {
+ status: 503,
+ upstreamError: 'authority_failure',
+ retryAfter: '1200',
+ publicError: 'authority_unavailable',
+ retryAfterSeconds: 900,
+ },
+ ])('preserves typed $status admission outcomes with bounded public retry guidance', async row => {
+ fetchMock
+ .mockResolvedValueOnce(previewRequest())
+ .mockResolvedValueOnce(
+ jsonResponse(
+ row.status,
+ { error: row.upstreamError, diagnostic: 'private Control API detail' },
+ { 'retry-after': row.retryAfter }
+ )
+ )
+
+ const response = await submitReset()
+
+ expect(response.status).toBe(row.status)
+ expect(response.body).toEqual({
+ error: row.publicError,
+ retryAfterSeconds: row.retryAfterSeconds,
+ })
+ expect(response.headers['retry-after']).toBe(String(row.retryAfterSeconds))
+ expect(response.headers['set-cookie']).toBeUndefined()
+ expect(JSON.stringify(response.body)).not.toContain('diagnostic')
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('reports only explicit password and recovery domain rejections', async () => {
+ fetchMock
+ .mockResolvedValueOnce(previewRequest())
+ .mockResolvedValueOnce(jsonResponse(400, { error: 'invalid_password' }))
+
+ const invalidPassword = await submitReset()
+ expect(invalidPassword.status).toBe(400)
+ expect(invalidPassword.body).toEqual({
+ error: 'Password must be between 8 and 256 characters',
+ })
+
+ fetchMock
+ .mockResolvedValueOnce(previewRequest())
+ .mockResolvedValueOnce(
+ jsonResponse(410, { error: 'expired', detail: 'private expired-link detail' })
+ )
+ const expiredProof = await submitReset()
+ expect(expiredProof.status).toBe(410)
+ expect(expiredProof.body).toEqual({ error: 'Invitation has expired' })
+ expect(JSON.stringify(expiredProof.body)).not.toContain('private')
+ })
+})