Cross-service Contracts and API Surface Boundaries

Overview

This section maps the boundaries where requests leave the frontend and enter either the backend service, the US API service, or the US data gateway. The code in this slice of the repository is mostly about contract translation: Next.js route handlers normalize incoming requests, forward auth when present, retry candidate backend URLs, and preserve legacy /api/v1/... compatibility surfaces.

The important distinction in this repository is not just the URL path, but where the request terminates. Some routes end inside the Next.js App Router and respond directly from local state or proxy logic. Others terminate in the US API service, where internal analytics routes are guarded by requireInternalAuth and write directly to the shared pool. The US data gateway is a separate HTTP service with its own Bearer-token contract and JSON error envelope.

Architecture Overview

flowchart TD
    Client[Client or partner service] --> NextRoutes[Next js App Router routes]

    subgraph FrontendBoundary[Frontend boundary]
        ApplicationsRoute[applications route handlers]
        ReadModelRoute[applications read model route]
        CreditScoreRoute[credit score proxy]
        PaymentsRoute[payments history proxy]
        AuthTokenRoute[auth token proxy]
        OcrRoute[residence permit ocr proxy]
    end

    subgraph USApiBoundary[US API service]
        InternalAnalytics[internal analytics routes]
        ScoringService[credit scoring service]
        InternalAuth[internal auth middleware]
    end

    subgraph USGatewayBoundary[US data gateway]
        GatewayHandlers[HTTP handlers]
    end

    subgraph LocalState[Local fallback state]
        ApplicationsJson[data applications json]
    end

    subgraph ExternalSystems[External systems]
        BackendApi[backend API]
        ProviderApi[provider callback]
        DatabasePool[shared pool]
        AuthProvider[auth verifier]
    end

    NextRoutes --> ApplicationsRoute
    NextRoutes --> ReadModelRoute
    NextRoutes --> CreditScoreRoute
    NextRoutes --> PaymentsRoute
    NextRoutes --> AuthTokenRoute
    NextRoutes --> OcrRoute

    ApplicationsRoute --> BackendApi
    ApplicationsRoute --> ApplicationsJson
    ReadModelRoute --> BackendApi
    CreditScoreRoute --> BackendApi
    PaymentsRoute --> BackendApi
    AuthTokenRoute --> BackendApi
    OcrRoute --> BackendApi

    InternalAnalytics --> InternalAuth
    InternalAnalytics --> DatabasePool

    ScoringService --> ProviderApi

    GatewayHandlers --> AuthProvider

Cross-Service Boundary Map

Surface Terminates In Auth Contract Data Contract Boundary Behavior
services/us-api/src/routes/internalAnalytics.ts US API service requireInternalAuth accepts x-internal-token or Bearer Authorization and compares against config.internalApiToken Zod-validated JSON body or query string Writes analytics events and returns aggregated PSU consent metrics from pool
frontend/app/api/applications/route.ts Next.js App Router No inbound auth requirement; forwards Bearer token to backend if present JSON application payload or HTML/JSON read surface Acts as a dual-mode edge surface and local fallback writer
frontend/app/api/applications/read-model/route.ts Next.js App Router None on inbound request JSON read-model rows Fetches from backend /api/v1/applications?format=json and reshapes rows for dashboard use
frontend/app/api/applications/[id]/credit-score/route.ts Next.js App Router No inbound auth requirement; forwards Bearer token if present Path parameter id Proxies to backend /api/v1/applications/{id}/credit-score across candidate base URLs
frontend/app/api/payments/history/route.ts Next.js App Router Forwards Bearer token if present JSON request body with token lists and optional dates Proxies to backend payments history endpoint and normalizes 204 to an empty response
frontend/app/api/v1/application/residence-permit/ocr/route.ts Next.js App Router None Multipart form data with file or file_url Forwards OCR work to backend /api/v1/application/residence-permit/ocr
services/us-data-gateway/internal/handlers/handlers.go US data gateway Bearer Authorization header required for authorize Provider-specific claims and request context Returns JSON responses and JSON error envelopes from an auth-gated HTTP handler

Frontend App Router Surfaces

[!IMPORTANT] The /api/v1/... files in frontend/app/api/v1/... are compatibility wrappers. They re-export the handlers from the non-versioned frontend/app/api/... routes and do not change the request contract.

The frontend routes are not UI components; they are server-side contract adapters. They either proxy to the backend, enrich the backend response, or fall back to local JSON storage under data/applications.json when the backend cannot be reached.

Boundary Helpers

frontend/app/api/applications/common.ts

Method Description
resolveRequestOriginCandidate Derives the current request origin from Forwarded, x-forwarded-host, host, and proto headers so the frontend can avoid proxying to itself
resolveBackendApiUrlCandidates Builds the ordered list of backend base URL candidates from environment variables, localhost fallbacks, and the request origin
buildErrorResponse Produces the standard JSON error envelope { detail: message }
fetchApplicationsFromBackend Fetches application data from the backend and retries across candidate base URLs
fetchBackendApplicationById Resolves a single application by identifier from the backend
deleteApplicationsInBackend Deletes backend application records during the local delete flow
archiveApplicationInBackend Archives a backend application by identifier
updateApplicationReviewStatusInBackend Updates the review status for a backend application
readStoredApplications Reads locally stored application records from the resolved JSON file path
writeStoredApplications Persists locally stored application records
hydrateStoredApplications Normalizes stored records into backend-shaped application objects
extractAuthToken Pulls the Bearer token from the incoming request headers when present
hasDeletedAllMarker Reads the local marker used to suppress application listings after a bulk delete
writeDeletedAllMarker Writes the local bulk-delete marker
clearDeletedAllMarker Removes the local bulk-delete marker
resolveDataFilePath Resolves the filesystem path for the local application store using APPLICATIONS_DATA_FILE and fallback locations

Local Application Storage Contract

resolveDataFilePath resolves the storage file in this order:

  1. APPLICATIONS_DATA_FILE
  2. process.cwd()/data/applications.json
  3. process.cwd()/../data/applications.json

That file is the fallback write target when backend persistence is unavailable.

Application Payload

frontend/app/api/applications/route.ts

Property Type Description
id `number \ string`
email string Applicant email
phone string Applicant phone
country string Applicant country
employment_status string Employment state used by the backend contract
financing_consent string Consent value passed through to the backend
full_name string Applicant full name
date_of_birth string Optional date of birth
profession string Optional profession
current_employer string Optional employer name
job_title string Optional job title
industry string Optional industry
website string Optional website
linkedin string Optional LinkedIn URL
agree_policy boolean Policy acceptance flag
receive_updates boolean Marketing updates flag
skipped_connect_accounts boolean Optional local metadata flag used by the front end
connected_accounts Record<string, unknown[]> Optional connected account map
metadata Record<string, unknown> Optional free-form metadata forwarded to storage and backend
created_at string Optional creation timestamp used by the local fallback path

Application Read Model Row

frontend/app/api/applications/read-model/route.ts

Property Type Description
applicationId string Stable row identifier derived from id, identifier, or an index fallback
applicantName string Display name derived from full_name, email, or a fallback label
status string Normalized application status
reviewerName null Explicitly emitted as null in this route
riskScore `number \ null`
documentState null Explicitly emitted as null in this route
lastEventAt string Timestamp chosen from updated_at, created_at, or the current time

Applications List

Get Applications

frontend/app/api/applications/route.ts

{
    "title": "Get Applications",
    "description": "Returns applications as HTML when the request prefers text/html, or JSON when the request prefers application/json or format=json. Remote applications are fetched first when enabled, then stored applications are merged in.",
    "method": "GET",
    "baseUrl": "<NextJsAppUrl>",
    "endpoint": "/api/applications",
    "headers": [],
    "queryParams": [
        {
            "key": "format",
            "value": "html or json",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": 101,\n        \"email\": \"[email protected]\",\n        \"phone\": \"+1-555-0100\",\n        \"country\": \"US\",\n        \"employment_status\": \"employed\",\n        \"financing_consent\": \"granted\",\n        \"full_name\": \"Jane Doe\",\n        \"date_of_birth\": \"1990-05-14\",\n        \"profession\": \"Product Manager\",\n        \"current_employer\": \"Lita\",\n        \"job_title\": \"Senior Product Manager\",\n        \"industry\": \"Technology\",\n        \"website\": \"https://example.com\",\n        \"linkedin\": \"https://www.linkedin.com/in/janedoe\",\n        \"agree_policy\": true,\n        \"receive_updates\": false,\n        \"skipped_connect_accounts\": false,\n        \"connected_accounts\": [],\n        \"metadata\": [],\n        \"created_at\": \"2026-04-26T12:00:00.000Z\"\n    }\n]"
        }
    }
}

Create Application

frontend/app/api/applications/route.ts

{
    "title": "Create Application",
    "description": "Validates the incoming payload, forwards it to the backend when possible, and falls back to local persistence when the backend is unavailable.",
    "method": "POST",
    "baseUrl": "<NextJsAppUrl>",
    "endpoint": "/api/applications",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"phone\": \"+1-555-0100\",\n    \"country\": \"US\",\n    \"employment_status\": \"employed\",\n    \"financing_consent\": \"granted\",\n    \"full_name\": \"Jane Doe\",\n    \"date_of_birth\": \"1990-05-14\",\n    \"profession\": \"Product Manager\",\n    \"current_employer\": \"Lita\",\n    \"job_title\": \"Senior Product Manager\",\n    \"industry\": \"Technology\",\n    \"website\": \"https://example.com\",\n    \"linkedin\": \"https://www.linkedin.com/in/janedoe\",\n    \"agree_policy\": true,\n    \"receive_updates\": false,\n    \"skipped_connect_accounts\": false,\n    \"connected_accounts\": [],\n    \"metadata\": [],\n    \"created_at\": \"2026-04-26T12:00:00.000Z\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Local fallback success",
            "body": "{\n    \"id\": 102,\n    \"created_at\": \"2026-04-26T12:00:00.000Z\",\n    \"persisted\": \"local_fallback\",\n    \"detail\": \"Backend persistence is currently unavailable. Saved locally so submission can continue.\"\n}"
        }
    }
}

Delete Applications

frontend/app/api/applications/route.ts

{
    "title": "Delete Applications",
    "description": "Deletes backend applications when an auth token is present, then clears the local stored application list and delete marker.",
    "method": "DELETE",
    "baseUrl": "<NextJsAppUrl>",
    "endpoint": "/api/applications",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"deleted\": 3\n}"
        }
    }
}

Read Model Surface

Get Application Read Model

frontend/app/api/applications/read-model/route.ts

{
    "title": "Get Application Read Model",
    "description": "Fetches backend applications and reshapes them into dashboard-ready rows.",
    "method": "GET",
    "baseUrl": "<NextJsAppUrl>",
    "endpoint": "/api/applications/read-model",
    "headers": [
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"applicationId\": \"101\",\n        \"applicantName\": \"Jane Doe\",\n        \"status\": \"approved\",\n        \"reviewerName\": null,\n        \"riskScore\": 712,\n        \"documentState\": null,\n        \"lastEventAt\": \"2026-04-26T12:00:00.000Z\"\n    }\n]"
        }
    }
}

Credit Score Proxy Surface

Get Application Credit Score

frontend/app/api/applications/[id]/credit-score/route.ts

{
    "title": "Get Application Credit Score",
    "description": "Proxies a credit score lookup to the backend credit-score endpoint across resolved backend base URLs.",
    "method": "GET",
    "baseUrl": "<NextJsAppUrl>",
    "endpoint": "/api/applications/{id}/credit-score",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "101",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"decision_id\": \"decision_101\",\n    \"payload\": [],\n    \"audit\": {\n        \"evidence_ref\": \"evidence_101\",\n        \"feature_set\": \"credit-feature-set\",\n        \"schema_version\": \"1\",\n        \"features\": [],\n        \"model_artifact\": {\n            \"id\": \"artifact_101\",\n            \"name\": \"credit-model\",\n            \"version\": \"2026.04.01\",\n            \"schema_version\": \"1\",\n            \"training_snapshot_ref\": \"snapshot_101\",\n            \"hyperparameters\": [],\n            \"metrics\": []\n        }\n    }\n}"
        }
    }
}

Payments History Proxy Surface

Post Payments History

frontend/app/api/payments/history/route.ts

{
    "title": "Post Payments History",
    "description": "Validates the payment history request, forwards it to the backend, and normalizes a 204 backend response into an empty transaction payload.",
    "method": "POST",
    "baseUrl": "<NextJsAppUrl>",
    "endpoint": "/api/payments/history",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"plaid_access_tokens\": [\n        \"access-token-1\"\n    ],\n    \"saltedge_accounts\": [],\n    \"start_date\": \"2026-04-01\",\n    \"end_date\": \"2026-04-30\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Normalized empty-history response after backend 204",
            "body": "{\n    \"transactions\": [],\n    \"start_date\": \"2026-04-01\",\n    \"end_date\": \"2026-04-30\"\n}"
        }
    }
}

Residence Permit OCR Proxy Surface

Post Residence Permit OCR

frontend/app/api/v1/application/residence-permit/ocr/route.ts

{
    "title": "Post Residence Permit OCR",
    "description": "Accepts multipart form data containing either a file upload or a file_url, then forwards the request to the backend OCR endpoint.",
    "method": "POST",
    "baseUrl": "<NextJsAppUrl>",
    "endpoint": "/api/v1/application/residence-permit/ocr",
    "headers": [
        {
            "key": "Content-Type",
            "value": "multipart/form-data",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "form-data",
    "requestBody": "",
    "formData": [
        {
            "key": "file",
            "value": "<binary file>",
            "required": false
        },
        {
            "key": "file_url",
            "value": "https://example.com/document.jpg",
            "required": false
        }
    ],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"detail\": \"OCR completed\"\n}"
        }
    }
}

Health Surfaces

Get Frontend Health

frontend/app/api/health/route.ts

{
    "title": "Get Frontend Health",
    "description": "Checks the backend health endpoint and returns the backend payload or a normalized error body.",
    "method": "GET",
    "baseUrl": "<NextJsAppUrl>",
    "endpoint": "/api/health",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"ok\": true\n}"
        }
    }
}

Get Frontend Ready

frontend/app/api/ready/route.ts

{
    "title": "Get Frontend Ready",
    "description": "Returns a readiness JSON payload for the frontend route layer.",
    "method": "GET",
    "baseUrl": "<NextJsAppUrl>",
    "endpoint": "/api/ready",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"ok\": true\n}"
        }
    }
}

Backend US API Surfaces

The US API service is where authenticated internal analytics are written and where the scoring service consolidates provider callbacks, stored decisions, and model metadata. The visible routes use Fastify and Zod, and their contracts are explicit at the route boundary.

Internal Auth Middleware

services/us-api/src/middleware/internalAuth.ts

Method Description
requireInternalAuth Validates the internal API token from x-internal-token or Bearer Authorization and throws ApiError(403, 'FORBIDDEN', 'Internal API token required.') when the token does not match config.internalApiToken

Internal Auth Contract

requireInternalAuth accepts either of these inputs:

  • x-internal-token: <token>
  • Authorization: Bearer <token>

The route proceeds only when the extracted token exactly matches config.internalApiToken.

Internal Analytics Routes

services/us-api/src/routes/internalAnalytics.ts

Method Description
registerInternalAnalyticsRoutes Registers the internal analytics event ingestion and PSU consent metrics endpoints on the provided Fastify instance

Event Schema

services/us-api/src/routes/internalAnalytics.ts

Property Type Description
psu_id string PSU identifier
consent_session_id string Consent session identifier
product string Product identifier
country string Country code
provider string Provider identifier
institution_id `string \ null \
timestamp string Datetime string validated by z.string().datetime()
failure_reason `string \ null \
event_name ConsentEventNames Enum value from ConsentEventNames

services/us-api/src/routes/internalAnalytics.ts

Property Type Description
start_date string Required YYYY-MM-DD date string
end_date string Required YYYY-MM-DD date string
product `string \ undefined`
country `string \ undefined`
provider `string \ undefined`
institution_id `string \ undefined`

Post Internal Analytics Event

services/us-api/src/routes/internalAnalytics.ts

{
    "title": "Post Internal Analytics Event",
    "description": "Validates the event payload, applies the consent event against the shared pool, and returns the resulting status. Auth is enforced by requireInternalAuth before the handler runs.",
    "method": "POST",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/internal/analytics/events",
    "headers": [
        {
            "key": "x-internal-token",
            "value": "<token>",
            "required": true
        },
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": false
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"psu_id\": \"psu_123\",\n    \"consent_session_id\": \"consent_session_456\",\n    \"product\": \"psu-consent\",\n    \"country\": \"US\",\n    \"provider\": \"bank-provider\",\n    \"institution_id\": \"inst_789\",\n    \"timestamp\": \"2026-04-26T12:00:00.000Z\",\n    \"failure_reason\": null,\n    \"event_name\": \"consent_granted\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"status\": \"ok\"\n}"
        },
        "409": {
            "description": "Dimension mismatch",
            "body": "{\n    \"status\": \"dimension_mismatch\"\n}"
        }
    }
}

services/us-api/src/routes/internalAnalytics.ts

{
    "title": "Get PSU Consent Metrics",
    "description": "Validates the date range, normalizes filters, and resolves daily, funnel, failure, and latency metrics in parallel.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/internal/analytics/psu-consent/metrics",
    "headers": [
        {
            "key": "x-internal-token",
            "value": "<token>",
            "required": true
        },
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": false
        }
    ],
    "queryParams": [
        {
            "key": "start_date",
            "value": "2026-04-01",
            "required": true
        },
        {
            "key": "end_date",
            "value": "2026-04-30",
            "required": true
        },
        {
            "key": "product",
            "value": "psu-consent",
            "required": false
        },
        {
            "key": "country",
            "value": "US",
            "required": false
        },
        {
            "key": "provider",
            "value": "bank-provider",
            "required": false
        },
        {
            "key": "institution_id",
            "value": "inst_789",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"daily\": [],\n    \"funnel\": [],\n    \"failures\": [],\n    \"latency\": []\n}"
        }
    }
}

Internal Analytics Execution Flow

registerInternalAnalyticsRoutes follows a strict runtime path:

  1. requireInternalAuth runs first.
  2. The event route validates the JSON body with eventSchema.
  3. The metrics route validates the query with metricsQuerySchema.
  4. The metrics route rejects invalid dates and any start_date later than end_date.
  5. Both handlers use the shared pool and the imported metric functions.

Credit Scoring Orchestration

services/us-api/src/services/scoringService.ts

This service is the contract boundary behind credit scoring. The visible flow shows three outcomes:

  • a provider callback returns a fresh decision payload
  • an existing stored decision is returned with audit metadata
  • a missing decision yields ApiError(404, 'NOT_FOUND')

The service also records model lineage through recordModelLineage, reads model artifacts with prisma.modelArtifact.findUnique, and stamps audit data with GLOBAL_CREDIT_FEATURE_SCHEMA_VERSION.

Scoring Service Dependency Surface

Dependency Description
crypto Generates hash or token material used by the scoring flow
prisma Reads stored model artifact data
config Supplies runtime configuration for the scoring flow
fetchEvidence Retrieves evidence used to build the scoring snapshot
ApiError Represents provider failures and not-found conditions
recordModelLineage Persists lineage for the scoring result
GLOBAL_CREDIT_FEATURE_SCHEMA_VERSION Provides the feature schema version included in snapshots

Credit Scoring Sequence

sequenceDiagram
    participant Caller as Caller
    participant Service as Scoring service
    participant Provider as Provider callback
    participant Prisma as Prisma
    participant Audit as Model lineage

    Caller->>Service: request scoring result
    Service->>Service: fetch evidence and build snapshot
    Service->>Provider: send feature set and snapshot
    Provider-->>Service: decision payload or error
    alt callback succeeds
        Service->>Service: validate decision
        Service->>Audit: record model lineage
        Service-->>Caller: decision_id and payload
    else callback fails
        Service-->>Caller: ApiError 502 PROVIDER_UNAVAILABLE
    end
    alt existing stored decision
        Service->>Prisma: find model artifact
        Prisma-->>Service: model artifact or null
        Service-->>Caller: decision_id, payload, audit
    end

US Data Gateway Surface

The US data gateway uses a simpler HTTP contract than the US API service. It requires Bearer token authorization, returns JSON responses, and turns internal errors into a stable error envelope.

Handler Helpers

services/us-data-gateway/internal/handlers/handlers.go

Method Description
authorize Validates the Authorization header, requires a Bearer prefix, and verifies the token through h.Auth.Verify
writeError Normalizes errors into JSON error bodies with {"error": code}
writeJSON Writes JSON responses with the Content-Type: application/json header
contains Returns whether a slice contains a target string

Authorization Contract

authorize enforces the following request shape:

  • Authorization: Bearer <token>

If the prefix is missing, it returns apiError{Status: 403, Code: "TOKEN_REQUIRED"}. If token verification fails in h.Auth.Verify, that error is propagated to the handler.

Error Envelope Contract

writeError always emits JSON:

{
  "error": "ERROR_CODE"
}

Known codes visible in the handler flow:

  • TOKEN_REQUIRED
  • INTERNAL_ERROR

Income Handler Flow

The visible handler path in handlers.go does the following:

  1. Calls authorize(r).
  2. Uses the authenticated claims, including claims.ConsentID.
  3. Calls h.Provider.FetchIncome(ctx, claims.ConsentID, lookback).
  4. Returns JSON shaped as { "income": income }.

US Data Gateway Sequence

sequenceDiagram
    participant Client as Client
    participant Handler as Gateway handler
    participant Auth as Auth verifier
    participant Provider as Data provider

    Client->>Handler: HTTP request with Authorization Bearer token
    Handler->>Handler: authorize
    Handler->>Auth: Verify token
    Auth-->>Handler: claims or error
    Handler->>Provider: FetchIncome using ConsentID and lookback
    Provider-->>Handler: income value
    Handler-->>Client: JSON income response

Contract Normalization and Error Handling

The visible route layers normalize errors at the boundary instead of leaking backend implementation details.

  • frontend/app/api/applications/route.ts uses buildErrorResponse for invalid payloads and backend failure fallbacks.
  • frontend/app/api/payments/history/route.ts translates invalid JSON, schema errors, backend non-OK responses, and non-JSON backend responses into JSON error bodies.
  • services/us-api/src/routes/internalAnalytics.ts throws ApiError(400, 'INVALID_BODY', ...) or ApiError(400, 'INVALID_QUERY', ...) for validation failures, and ApiError(409, ...) for dimension mismatches.
  • services/us-data-gateway/internal/handlers/handlers.go converts all handler failures into JSON objects with an error key.

Integration Points

[!NOTE] The /api/applications surface is intentionally dual-format. The same handler can emit HTML for browser navigation or JSON for programmatic access, so the route is both a data API and a human-readable fallback page.

  • frontend/app/api/applications/read-model/route.ts feeds frontend/lib/server/applications.ts, which consumes the read model to compute dashboard KPIs and application summaries.
  • frontend/app/api/applications/route.ts is the main persistence boundary for application submission and deletion, with a local JSON fallback when backend writes fail.
  • frontend/app/api/applications/[id]/credit-score/route.ts is the client-facing entrypoint for scoring results and is the closest visible contract to the backend scoring service.
  • services/us-api/src/routes/internalAnalytics.ts is the internal analytics ingestion and metrics surface for consent events.
  • services/us-data-gateway/internal/handlers/handlers.go is the provider-facing data entrypoint for consent-scoped income retrieval.

Dependencies

Frontend Route Dependencies

  • next/headers
  • next/server
  • zod
  • filesystem access through node:fs/promises and node:path
  • backend URL resolution from environment variables and request-origin headers

US API Dependencies

  • fastify
  • zod
  • pool from ../db.js
  • ApiError
  • requireInternalAuth
  • metric helper functions from ../analytics/psuConsentMetrics.js

US Data Gateway Dependencies

  • net/http
  • strings
  • encoding/json
  • auth.Claims
  • a verifier exposed as h.Auth

Key Classes Reference

Class Responsibility
internalAnalytics.ts Registers internal analytics event ingestion and PSU consent metrics routes
internalAuth.ts Enforces the internal API token contract for privileged US API routes
scoringService.ts Orchestrates credit scoring callbacks, stored decision reads, and audit metadata assembly
common.ts Resolves backend URLs, local storage paths, and proxy/error helper behavior for frontend API routes
route.ts Implements the application collection, read model, credit score proxy, payments proxy, and readiness surfaces
handlers.go Authenticates gateway requests, writes JSON responses, and forwards consent-scoped provider calls