import { systemClock } from "../platform/system-clock.ts"; import { getApiOperation } from "../../contracts/api-operations.ts"; import { createFailure as failure, kindForStatus as statusKind, safeValidationIssues, } from "../../contracts/errors.ts"; import { mapOperationPayload } from "./resource-mapper.ts"; import { retryDelay, shouldRetry } from "./retry-policy.ts"; import { parseRetryAfterDelay } from "../platform/retry-after.ts"; import { validateEnvelope, validateOperationPayload, validateOperationRequest, } from "./schema-registry.ts"; import { buildRequestTarget } from "./request-builder.ts"; import { attemptBucket, durationBucket, statusGroup, } from "../../contracts/diagnostics.ts"; import type { AuthSessionPort, CredentialOperationContext, } from "../../application/ports/auth-session-port.ts"; import { isValidIdempotencyKey } from "../../contracts/mutation-intent.ts"; /** Sentinel for a credential wait ended by the attempt lifetime. */ const ATTEMPT_ABORTED = Symbol("ATTEMPT_ABORTED"); /** * LEG-02. The pre-V2 operations have no installed auth profile, so this is the * legacy allowance the shared validator applies to them. It requires nothing, * which preserves their existing behaviour exactly. */ const LEGACY_ALLOWED_CREDENTIAL_HEADERS = Object.freeze([ "authorization", "x-csrf-token", ] as const); import type { ClockPort } from "../../application/ports/clock-port.ts"; import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts"; import type { TelemetryPort } from "../../application/ports/telemetry-port.ts"; import type { ApiOperation } from "../../contracts/api-operations.ts"; import type { ApiFailure, FailureKind } from "../../contracts/errors.ts"; import type { OperationRequestInput } from "./request-builder.ts"; import { readBoundedJson } from "./bounded-json.ts"; import { admitCredentialHeaders } from "./http-contract-bridge.ts"; import type { MappingResult } from "../../contracts/boundary-mapper.ts"; import { createRestProviderProfile, resolveRestSecurityProfiles, INSTALLED_REST_AUTH_PROFILES, REST_CSRF_PROFILES, type RestAuthProfile, type RestCsrfProfile, type RestProviderProfile, } from "../../contracts/rest-profiles.ts"; type HttpAuthSession = Pick< AuthSessionPort, "getState" | "credentialPatch" | "recover" | "onUnauthenticated" >; const noAuthSession: HttpAuthSession = Object.freeze({ getState: () => "integration-failed", credentialPatch: async () => { throw new TypeError("Auth session is not installed"); }, recover: async () => "no-session", onUnauthenticated: () => {}, } satisfies HttpAuthSession); export type HttpFailure = ApiFailure; export type Scheduler = Readonly<{ setTimeout(callback: () => void, milliseconds: number): unknown; clearTimeout(handle: unknown): void; }>; export type HttpResult = | Readonly<{ ok: true; value: unknown; meta: Readonly>; }> | Readonly<{ ok: false; error: HttpFailure }>; type SchemaValidator = ( schemaId: string, value: unknown, ) => | Readonly<{ success: true; data: unknown }> | Readonly<{ success: false }>; export type HttpClientDependencies = Readonly<{ baseUrl: string; fetcher?: typeof fetch; authSession?: AuthSessionPort; clock?: ClockPort; random?: () => number; validatePayload?: SchemaValidator; validateRequest?: SchemaValidator; validatePath?: SchemaValidator; mapPayload?: ( operationId: string, payload: unknown, ) => MappingResult; idempotencyKeyFactory?: () => string; /** * Default total deadline for an operation without its own `timeoutMs`. Not a * ceiling: an operation may set a longer one. V3 treats `REQUEST_TIMEOUT_MS` * as a ceiling instead (03-06). */ timeoutMs?: number; maxRetryAttempts?: number; scheduler?: Scheduler; getOperation?: typeof getApiOperation; diagnostics?: DiagnosticsPort; telemetry?: TelemetryPort; correlationIdFactory?: () => string; providerProfile?: RestProviderProfile; authProfiles?: Readonly>; csrfProfiles?: Readonly>; maxCumulativeSleepMs?: number; }>; export type LegacyHttpInput = Readonly<{ body?: unknown; routeId?: string; pathParams?: Readonly>; searchParams?: unknown; signal?: AbortSignal; idempotencyKey?: string; correlationId?: string; }>; export type HttpClient = Readonly<{ execute( request: string | OperationRequestInput, legacyInput?: LegacyHttpInput, ): Promise; }>; export function createHttpClient( dependencies: HttpClientDependencies, ): HttpClient { const fetcher = dependencies.fetcher ?? fetch; const authSession = dependencies.authSession ?? noAuthSession; const clock = dependencies.clock ?? systemClock; const random = dependencies.random ?? Math.random; const validatePayload = dependencies.validatePayload ?? validateOperationPayload; const validateRequest = dependencies.validateRequest ?? validateOperationRequest; const validatePath = dependencies.validatePath ?? validateRequest; const mapPayload = dependencies.mapPayload ?? mapOperationPayload; const idempotencyKeyFactory = dependencies.idempotencyKeyFactory ?? (() => crypto.randomUUID()); const defaultTimeoutMs = dependencies.timeoutMs ?? 10_000; const maxRetryAttempts = dependencies.maxRetryAttempts ?? 2; const maxCumulativeSleepMs = dependencies.maxCumulativeSleepMs ?? defaultTimeoutMs; const selectOperation = dependencies.getOperation ?? getApiOperation; const diagnostics = dependencies.diagnostics; const telemetry = dependencies.telemetry; const correlationIdFactory = dependencies.correlationIdFactory ?? (() => `request-${Math.floor(random() * 1_000_000).toString(36)}`); const scheduler = dependencies.scheduler ?? ({ setTimeout: (callback, milliseconds) => globalThis.setTimeout(callback, milliseconds), clearTimeout: (handle) => globalThis.clearTimeout( handle as ReturnType, ), } satisfies Scheduler); async function execute( request: string | OperationRequestInput, legacyInput: LegacyHttpInput = {}, ): Promise { const input = typeof request === "string" ? { operationId: request, routeId: legacyInput.routeId ?? "UNSPECIFIED_ROUTE", pathParams: legacyInput.pathParams, searchParams: legacyInput.searchParams, body: legacyInput.body, signal: legacyInput.signal, idempotencyKey: legacyInput.idempotencyKey, correlationId: legacyInput.correlationId, } : request; const startedAt = clock.now(); let correlationId: string; try { correlationId = correlationIdValue( input.correlationId ?? correlationIdFactory(), ); } catch { correlationId = "client-generated"; } let operation: ApiOperation; try { operation = selectOperation(input.operationId); } catch { return { ok: false, error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, 0, { code: "OPERATION_NOT_REGISTERED", }), }; } const totalDeadlineMs = operation.timeoutMs ?? defaultTimeoutMs; const deadlineAt = startedAt + totalDeadlineMs; let physicalAttemptCount = 0; function finalize( outcome: HttpResult, outcomeKind: "success" | "recovered" | "failed" | "aborted", ): HttpResult { const error = outcome.ok ? undefined : outcome.error; const context = { route_id: input.routeId, operation_id: input.operationId, correlation_id: correlationId, outcome: outcomeKind, error_kind: error?.kind ?? "NONE", http_status_group: statusGroup( error?.httpStatus ?? (outcome.ok ? Number(outcome.meta.httpStatus) : undefined), ), attempt_count_bucket: attemptBucket( error?.attemptCount ?? Math.max(1, physicalAttemptCount), ), duration_bucket: durationBucket(clock.now() - startedAt), }; try { diagnostics?.record({ level: error ? "warn" : "info", eventId: "http.request.completed", context, }); } catch { // Diagnostics cannot change the HTTP result. } if (error && outcomeKind !== "aborted") { try { telemetry?.emit("api.request.failed", { error_kind: context.error_kind, http_status_group: context.http_status_group, attempt_count_bucket: context.attempt_count_bucket, route_id: context.route_id, operation_id: context.operation_id, duration_bucket: context.duration_bucket, }); } catch { // Telemetry cannot change the HTTP result. } } return outcome; } // N-06. A caller-supplied key is validated before credentials, timers or // fetch. An invalid value is rejected outright rather than trimmed or // replaced, so a keyed command can never replay with no key at all. let logicalIdempotencyKey: string | undefined; if (operation.idempotency === "keyed") { if (input.idempotencyKey !== undefined) { if (!isValidIdempotencyKey(input.idempotencyKey)) { return finalize( { ok: false, error: failure("VALIDATION_REJECTED", input.operationId, 0, { code: "IDEMPOTENCY_KEY_INVALID", }), }, "failed", ); } logicalIdempotencyKey = input.idempotencyKey; } else { let generated: string; try { generated = idempotencyKeyFactory(); } catch { return finalize( { ok: false, error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, 0, { code: "IDEMPOTENCY_KEY_CREATION_FAILED", }), }, "failed", ); } if (!isValidIdempotencyKey(generated)) { return finalize( { ok: false, error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, 0, { code: "IDEMPOTENCY_KEY_CREATION_FAILED", }), }, "failed", ); } logicalIdempotencyKey = generated; } } let retryCount = 0; let recoveryUsed = false; let cumulativeSleepMs = 0; while (true) { const attempt = physicalAttemptCount; physicalAttemptCount += 1; let outcome: HttpResult; try { outcome = await performAttempt({ operation, input, attempt, idempotencyKey: logicalIdempotencyKey, deadlineAt, correlationId, }); } catch { outcome = { ok: false, error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, attempt, { code: "HTTP_EXECUTION_CONTRACT_VIOLATION", }), }; } if (outcome.ok) { return finalize( outcome, retryCount > 0 || recoveryUsed ? "recovered" : "success", ); } // Q-6.3-11. Recovery is its own single replay, bounded by // `recoveryUsed` and the deadline, not by the retry budget: a disabled // or spent budget must not turn a recoverable 401 into a logout. if (outcome.error.httpStatus === 401 && !recoveryUsed) { recoveryUsed = true; let recovered: SessionRecoveryOutcome; // LEG-01. The recovery collaborator receives the request lifetime, and // the transport races the same signal so a non-cooperative owner cannot // hold the request open. const recoveryLifetime = new AbortController(); try { recovered = await withinLogicalDeadline( recoverSession( authSession, operation, outcome.error, Object.freeze({ signal: recoveryLifetime.signal, deadlineAtMonotonicMs: deadlineAt, }), ), deadlineAt, input.signal, ); } catch (error) { // The request is over. Whatever the recovery answers next is observed // by its own owner, never adopted here. recoveryLifetime.abort(); return finalize( { ok: false, error: failure( error instanceof LogicalDeadlineError ? "REQUEST_TIMEOUT" : "REQUEST_ABORTED", operation.operationId, attempt, { code: error instanceof LogicalDeadlineError ? "OPERATION_DEADLINE_EXCEEDED" : "REQUEST_ABORTED", }, ), }, error instanceof LogicalDeadlineError ? "failed" : "aborted", ); } if (!recovered.ok) { // The result is adopted here, so the notification happens here. if (recovered.notifyUnauthenticated) authSession.onUnauthenticated(); return finalize( { ok: false, error: recovered.error }, "failed", ); } if (operation.idempotency === "none") { return finalize( { ok: false, error: { ...outcome.error, retryable: false, action: "retry", }, }, "failed", ); } continue; } if (outcome.error.httpStatus === 401 && recoveryUsed) { authSession.onUnauthenticated(); return finalize(outcome, "failed"); } if ( !shouldRetry( operation, outcome.error, retryCount, maxRetryAttempts, ) ) { return finalize( outcome, outcome.error.kind === "REQUEST_ABORTED" ? "aborted" : "failed", ); } const delay = retryDelay(outcome.error, retryCount, random, clock.now()); retryCount += 1; cumulativeSleepMs += delay; if ( clock.now() + delay >= deadlineAt || cumulativeSleepMs > maxCumulativeSleepMs ) { return finalize( { ok: false, error: failure("REQUEST_TIMEOUT", input.operationId, attempt, { code: "OPERATION_DEADLINE_EXCEEDED", }), }, "failed", ); } try { await clock.sleep(delay, input.signal); } catch { return finalize( { ok: false, error: failure("REQUEST_ABORTED", input.operationId, retryCount, { code: "REQUEST_ABORTED", }), }, "aborted", ); } } } async function performAttempt( context: Readonly<{ operation: ApiOperation; input: OperationRequestInput; attempt: number; idempotencyKey?: string; deadlineAt: number; correlationId: string; }>, ): Promise { const { operation, input, attempt, idempotencyKey, deadlineAt, correlationId, } = context; if (clock.now() >= deadlineAt) { return { ok: false, error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, { code: "OPERATION_DEADLINE_EXCEEDED", }), }; } let parsedSearch: unknown = {}; let parsedBody: unknown; let parsedPath: Readonly> = input.pathParams ?? {}; if (operation.pathSchema) { const pathValidation = validatePath( operation.pathSchema, input.pathParams ?? {}, ); if ( !pathValidation.success || !isPathParameterRecord(pathValidation.data) ) { return { ok: false, error: failure( "VALIDATION_REJECTED", operation.operationId, attempt, { code: "PATH_SCHEMA_INVALID" }, ), }; } parsedPath = pathValidation.data; } const requestValue = operation.requestSource === "search" ? input.searchParams ?? {} : operation.requestSource === "body" ? input.body : {}; if (operation.requestSource !== "none") { const requestValidation = validateRequest( operation.requestSchema, requestValue, ); if (!requestValidation.success) { return { ok: false, error: failure("VALIDATION_REJECTED", operation.operationId, attempt, { code: "REQUEST_SCHEMA_INVALID", }), }; } if (operation.requestSource === "search") { parsedSearch = requestValidation.data; } else { parsedBody = requestValidation.data; } } let target: ReturnType; let provider: RestProviderProfile | null = null; let security: | ReturnType | undefined; try { provider = dependencies.providerProfile ?? createRestProviderProfile( operation.providerId ?? "LEGACY_API", dependencies.baseUrl, ["omit", "same-origin"], ); if ( operation.contractVersion === 2 && operation.providerId !== provider.providerId ) { throw new TypeError("REST provider binding mismatch."); } if (operation.contractVersion === 2) { security = resolveRestSecurityProfiles( operation, provider, dependencies.authProfiles ?? INSTALLED_REST_AUTH_PROFILES, dependencies.csrfProfiles ?? REST_CSRF_PROFILES, ); } target = buildRequestTarget( provider.baseUrl, operation, parsedPath, parsedSearch, ); } catch { target = { success: false, code: "BASE_URL_INVALID" }; } if (!target.success || !provider) { return { ok: false, error: failure("VALIDATION_REJECTED", operation.operationId, attempt, { code: target.success ? "BASE_URL_INVALID" : target.code, }), }; } const controller = new AbortController(); let timedOut = false; const remainingMs = Math.max(1, deadlineAt - clock.now()); const timeout = scheduler.setTimeout(() => { timedOut = true; controller.abort("timeout"); }, remainingMs); const onExternalAbort = () => controller.abort(input.signal?.reason); input.signal?.addEventListener("abort", onExternalAbort, { once: true }); if (input.signal?.aborted) onExternalAbort(); try { const headers = new Headers({ Accept: operation.responseMediaTypes?.join(", ") ?? "application/json", "X-Correlation-ID": correlationIdValue(correlationId), }); if (parsedBody !== undefined) headers.set("Content-Type", "application/json"); if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey); if (operation.auth === "external-session") { let sessionState: ReturnType; try { sessionState = authSession.getState(); } catch { return { ok: false, error: failure( "AUTH_INTEGRATION_FAILURE", operation.operationId, attempt, { code: "AUTH_STATE_FAILED" }, ), }; } if (sessionState === "unauthenticated") { return { ok: false, error: failure("AUTH_REQUIRED", operation.operationId, attempt, { code: "AUTH_REQUIRED", }), }; } if (sessionState !== "authenticated") { return { ok: false, error: failure( "AUTH_INTEGRATION_FAILURE", operation.operationId, attempt, { code: "AUTH_SESSION_UNAVAILABLE" }, ), }; } try { // N-07. The credential owner is bounded by the attempt lifetime that // already carries the total deadline and the caller signal, so a // non-cooperative owner cannot hold the request open and no extra // timer is introduced. A late completion is observed and discarded. const raced = await raceAttemptSignal( Promise.resolve( authSession.credentialPatch( { origin: target.url.origin, method: operation.method, operationId: operation.operationId, }, Object.freeze({ signal: controller.signal, deadlineAtMonotonicMs: deadlineAt, }), ), ), controller.signal, ); if (raced === ATTEMPT_ABORTED) { return { ok: false, error: timedOut ? failure( "REQUEST_TIMEOUT", operation.operationId, attempt, { code: "OPERATION_DEADLINE_EXCEEDED" }, ) : failure( "REQUEST_ABORTED", operation.operationId, attempt, { code: "REQUEST_ABORTED" }, ), }; } const patch = raced; // LEG-02. The same admission validator V3 uses. Checking only the // allowed set let a bearer profile dispatch with no Authorization at // all, which is precisely the anonymous downgrade the required set // exists to prevent. const admission = admitCredentialHeaders(patch.headers, { allowedCredentialHeaders: security?.auth.allowedCredentialHeaders ?? LEGACY_ALLOWED_CREDENTIAL_HEADERS, requiredCredentialHeaders: security?.auth.requiredCredentialHeaders ?? [], }); if (!admission.ok) { return { ok: false, error: failure( "AUTH_INTEGRATION_FAILURE", operation.operationId, attempt, { code: "AUTH_ATTACH_FAILED" }, ), }; } for (const [name, value] of Object.entries(admission.headers)) { headers.set(name, value); } } catch { // An ordinary owner rejection stays an integration failure. return { ok: false, error: failure("AUTH_INTEGRATION_FAILURE", operation.operationId, attempt, { code: "AUTH_ATTACH_FAILED", }), }; } } const request = new Request(target.url, { method: operation.method, headers, body: parsedBody === undefined ? undefined : JSON.stringify(parsedBody), signal: controller.signal, credentials: security?.auth.credentials ?? "same-origin", cache: "no-store", redirect: provider.redirect, referrerPolicy: provider.referrerPolicy, }); const response = await fetcher(request); return await parseResponse( response, operation, attempt, validatePayload, mapPayload, clock.now(), ); } catch { if (timedOut) { return { ok: false, error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, { code: "REQUEST_TIMEOUT", }), }; } if (controller.signal.aborted || input.signal?.aborted) { const externalReason = input.signal?.reason; if (externalReason === "timeout") { return { ok: false, error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, { code: "REQUEST_TIMEOUT", }), }; } if ( externalReason !== undefined && !["navigation", "user", "superseded"].includes(String(externalReason)) ) { return { ok: false, error: failure("UNKNOWN_FAILURE", operation.operationId, attempt, { code: "EXTERNAL_ABORT_UNRESOLVED", }), }; } return { ok: false, error: failure("REQUEST_ABORTED", operation.operationId, attempt, { code: "REQUEST_ABORTED", }), }; } return { ok: false, error: failure("NETWORK_UNREACHABLE", operation.operationId, attempt, { code: "NETWORK_UNREACHABLE", }), }; } finally { scheduler.clearTimeout(timeout); input.signal?.removeEventListener("abort", onExternalAbort); } } return Object.freeze({ execute }); function raceAttemptSignal( operation: Promise, signal: AbortSignal, ): Promise { operation.catch(() => {}); if (signal.aborted) return Promise.resolve(ATTEMPT_ABORTED); return new Promise((resolve, reject) => { const onAbort = () => resolve(ATTEMPT_ABORTED); signal.addEventListener("abort", onAbort, { once: true }); operation.then( (value) => { signal.removeEventListener("abort", onAbort); resolve(value); }, (error: unknown) => { signal.removeEventListener("abort", onAbort); reject(error instanceof Error ? error : new Error("rejected")); }, ); }); } function withinLogicalDeadline( promise: Promise, deadlineAt: number, externalSignal: AbortSignal | undefined, ): Promise { const remaining = deadlineAt - clock.now(); if (remaining <= 0) return Promise.reject(new LogicalDeadlineError()); return new Promise((resolve, reject) => { let settled = false; const timeout = scheduler.setTimeout( () => settle(() => reject(new LogicalDeadlineError())), remaining, ); const onAbort = () => settle(() => reject(new DOMException("Aborted", "AbortError"))); externalSignal?.addEventListener("abort", onAbort, { once: true }); const settle = (complete: () => void) => { if (settled) return; settled = true; scheduler.clearTimeout(timeout); externalSignal?.removeEventListener("abort", onAbort); complete(); }; if (externalSignal?.aborted) { onAbort(); return; } promise.then( (value) => settle(() => resolve(value)), (error: unknown) => settle(() => reject(error)), ); }); } } class LogicalDeadlineError extends Error {} /** * Q-6.3-3b. A gateway 5xx/408/425 with an HTML, empty or broken body is a * server outage, not a contract breach: it keeps its status and the normal * SERVER_FAILURE retry rule instead of a non-retryable body error. */ function gatewayFailureOr(status: number, kind: FailureKind): FailureKind { return status >= 500 || status === 408 || status === 425 ? "SERVER_FAILURE" : kind; } async function parseResponse( response: Response, operation: ApiOperation, attempt: number, validatePayload: SchemaValidator, mapPayload: ( operationId: string, payload: unknown, ) => MappingResult, now: number, ): Promise { // R3-1. Retry-After is read only where the retry policy honors it; 502/504 // keep the local backoff. const retryAfterMs = [408, 425, 429, 503].includes(response.status) ? (parseRetryAfterDelay(response.headers.get("retry-after"), now) ?? undefined) : undefined; const contentType = mediaType(response.headers.get("content-type")); const acceptedMedia = operation.responseMediaTypes ?? ["application/json"]; if (!contentType || !acceptedMedia.includes(contentType)) { // N-08. A rejected response still owns an open body stream. Cancellation is // best-effort cleanup, so it is started but not awaited: the closed result // must not depend on stream teardown settling. void response.body?.cancel().catch(() => {}); return { ok: false, error: failure( gatewayFailureOr(response.status, "CONTENT_TYPE_MISMATCH"), operation.operationId, attempt, { code: "CONTENT_TYPE_MISMATCH", httpStatus: response.status, retryAfterMs, }, ), }; } const decoded = await readBoundedJson( response, operation.maxResponseBytes ?? 1_048_576, ); if (!decoded.ok) { return { ok: false, error: failure( gatewayFailureOr(response.status, decoded.code), operation.operationId, attempt, { code: decoded.code, httpStatus: response.status, retryAfterMs }, ), }; } const envelope = decoded.value; const envelopeValidation = validateEnvelope(envelope); if (!envelopeValidation.success) { return { ok: false, error: failure( response.ok ? "ENVELOPE_MISMATCH" : gatewayFailureOr(response.status, statusKind(response.status)), operation.operationId, attempt, { code: response.ok ? "ENVELOPE_MISMATCH" : "HTTP_FAILURE", httpStatus: response.status, retryAfterMs, }, ), }; } const envelopeRecord = envelopeValidation.data as Record; const successStatus = operation.successStatuses ? operation.successStatuses.includes(response.status) : response.ok; if (successStatus && envelopeRecord.success === true && "data" in envelopeRecord) { const payload = validatePayload(operation.responseSchema, envelopeRecord.data); if (!payload.success) { return { ok: false, error: failure("SCHEMA_MISMATCH", operation.operationId, attempt, { code: "SCHEMA_MISMATCH", httpStatus: response.status, }), }; } try { const mapped = mapPayload(operation.operationId, payload.data); if (!mapped.ok) { return { ok: false, error: failure( "MAPPING_CONTRACT_VIOLATION", operation.operationId, attempt, { code: mapped.code, httpStatus: response.status, }, ), }; } return { ok: true, value: mapped.value, meta: { ...safeMeta(envelopeRecord.meta), httpStatus: String(response.status), }, }; } catch { return { ok: false, error: failure( "MAPPING_CONTRACT_VIOLATION", operation.operationId, attempt, { code: "MAPPING_CONTRACT_VIOLATION", httpStatus: response.status, }, ), }; } } if (successStatus !== response.ok || (successStatus && envelopeRecord.success !== true)) { return { ok: false, error: failure("ENVELOPE_MISMATCH", operation.operationId, attempt, { code: "STATUS_ENVELOPE_MISMATCH", httpStatus: response.status, }), }; } // R3-1. V2 treats a 408/425 error envelope as the same server failure as a // gateway body; the shared status map in contracts is not changed. const kind = gatewayFailureOr(response.status, statusKind(response.status)); const backendError = envelopeRecord.error && typeof envelopeRecord.error === "object" ? (envelopeRecord.error as Record) : {}; return { ok: false, error: failure(kind, operation.operationId, attempt, { code: safeBackendCode(envelope), httpStatus: response.status, requestId: safeMeta(envelopeRecord.meta).requestId, traceId: safeMeta(envelopeRecord.meta).traceId, retryAfterMs, validationIssues: response.status === 422 ? safeValidationIssues(backendError.details) : undefined, }), }; } /** * LEG-01. Recovery returns data only. * * The sign-out notification is a user-visible side effect, so it belongs to * whoever adopts this result — not to the raw recovery call. A recovery that * loses the race against the deadline or a caller abort still settles, and * signing the user out then would attribute a request nobody is waiting on to * an expired session. */ type SessionRecoveryOutcome = | Readonly<{ ok: true }> | Readonly<{ ok: false; error: HttpFailure; notifyUnauthenticated: boolean; }>; async function recoverSession( authSession: HttpAuthSession, operation: ApiOperation, originalFailure: HttpFailure, context: CredentialOperationContext, ): Promise { try { const result = await authSession.recover(context); if (result === "restored") return { ok: true }; if (result === "no-session") { return { ok: false, notifyUnauthenticated: true, error: failure("AUTH_REQUIRED", operation.operationId, originalFailure.attemptCount - 1, { code: "AUTH_REQUIRED", httpStatus: 401, }), }; } } catch { // Normalized below. } return { ok: false, notifyUnauthenticated: false, error: failure( "AUTH_INTEGRATION_FAILURE", operation.operationId, originalFailure.attemptCount - 1, { code: "AUTH_RECOVERY_FAILED" }, ), }; } function safeBackendCode(envelope: unknown): string { if (!envelope || typeof envelope !== "object") return "HTTP_FAILURE"; const error = (envelope as Record).error; if (!error || typeof error !== "object") return "HTTP_FAILURE"; const code = (error as Record).code; return typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code) ? code : "HTTP_FAILURE"; } function safeMeta(meta: unknown): Record { if (!meta || typeof meta !== "object") return {}; const metaRecord = meta as Record; return { ...(typeof metaRecord.requestId === "string" ? safeIdentifier(metaRecord.requestId, "requestId") : {}), ...(typeof metaRecord.traceId === "string" ? safeIdentifier(metaRecord.traceId, "traceId") : {}), }; } function safeIdentifier( value: string, property: "requestId" | "traceId", ): Record { return /^[A-Za-z0-9._:-]{1,128}$/.test(value) ? { [property]: value } : {}; } function mediaType(value: string | null): string | null { if (!value) return null; const selected = value.split(";", 1)[0]?.trim().toLowerCase(); return selected && /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(selected) ? selected : null; } function correlationIdValue(value: string | undefined): string { return value && /^[A-Za-z0-9._:-]{1,128}$/.test(value) ? value : "client-generated"; } function isPathParameterRecord( value: unknown, ): value is Readonly> { return ( value !== null && typeof value === "object" && !Array.isArray(value) && Object.values(value).every( (item) => typeof item === "string" || typeof item === "number", ) ); }