US API Service Internals and Data Gateway Boundary

apps/api/src/services/us-api.ts, apps/api/src/routes/us/index.ts, services/us-data-gateway/Dockerfile, services/us-api/.env.example, documents/us-api.md, documents/us-api-openapi.yaml

Overview

The US regional surface implements the consent-led data path for Lita’s US API: partner-authenticated consent creation and revocation, token exchange and introspection, access-token-gated account and transaction retrieval, cashflow feature computation, immutable evidence snapshots, KYC output, and scoring replay. The service is built around tenant-scoped consent records and evidence rows stored through Prisma, with JWT signing and verification controlling access-token lifecycle.

The boundary is split across two deployable units. The main Fastify + TypeScript US API owns the public contract and the consent/token/evidence state machine, while us-data-gateway is packaged as a separate Go container and deployed beside it as a private regional companion service on port 8084.

Architecture Overview

flowchart TD
    subgraph PublicEdge[Public API Edge]
        Kong[Kong gateway]
    end

    subgraph USBoundary[US Regional Boundary]
        USRoutes[US API routes]
        USService[us api service]
        USGateway[us data gateway]
        JobStore[In memory job store]
        Accounts[In memory account bundle cache]
    end

    Prisma[Prisma and PostgreSQL]
    JWTKeys[JWT key material]
    Scoring[Partner scoring callback]
    Webhooks[Webhook delivery]

    Kong --> USRoutes
    USRoutes --> USService
    USService --> Prisma
    USService --> JWTKeys
    USService --> Scoring
    USService --> Webhooks
    USService --> JobStore
    USService --> Accounts

Contract Vocabulary and Authentication

documents/us-api.md, documents/us-api-openapi.yaml, apps/api/src/routes/us/index.ts

Regional contract summary

Item Value
Base URL https://api.joinlita.com/api/v1/us
Region US
Versioning Version is embedded in the URL
Ownership Tobias Andersen, CTO
Retained artifacts Consent records, access logs, evidence snapshots
Data posture Consent-based access with partner-controlled decisions

Authentication matrix

Endpoint family Guard chain Token type
Consent creation, receipt, revocation, token exchange, introspection, consent status, evidence, KYC, score, replay, job status requirePartnerAuth Partner bearer JWT
Account, balance, transaction, income, and consent-scoped data endpoints requireAccessToken, ensurePurpose, ensureCategory, ensureConnection Access bearer JWT
POST /features/compute Dual path: requirePartnerAuth when consent_id is present, otherwise requireAccessToken Partner or access bearer JWT
GET /consents/:consentId/authorize No auth guard None

Request vocabulary

Term Meaning
consent_id Consent record identifier
applicant_id Partner-stable end-user identifier
connection_id Financial institution session bound to a consent
evidence_ref Immutable feature snapshot identifier
request_id Request tracing identifier threaded into error responses

JWT and Token Handling

Note: documents/us-api-openapi.yaml models consent creation response data under auth.link_url and auth.link_token, but the runtime handler returns authorization_url, redirect_url, status, and expires_at. Note: services/us-api/.env.example names JWT keys as JWT_PRIVATE_KEY and JWT_PUBLIC_KEY, while apps/api/src/services/us-api.ts reads US_JWT_PRIVATE_KEY and US_JWT_PUBLIC_KEY. Note: The visible route code builds authorization and reauthorization URLs from API_PUBLIC_BASE_URL, not LINK_BASE_URL. Note: ConsentPurpose in apps/api/src/services/us-api.ts does not include GENERAL_PERSONAL_FINANCE, but the create-consent route schema and OpenAPI contract accept it.

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

The service signs and verifies access tokens with RS256. It first tries to load PEM keys from the environment, and if those are absent it generates a process-local RSA key pair in memory.

Constant Value Role
TOKEN_ISSUER lita-us-api JWT issuer claim
TOKEN_AUDIENCE lita-us-clients JWT audience claim
ACCESS_TOKEN_TTL_MS 15 * 60 * 1000 Access token lifetime
CONSENT_TTL_MS 90 * 24 * 60 * 60 * 1000 Consent lifetime constant
PRIVATE_KEY_PEM process.env.US_JWT_PRIVATE_KEY Private key source
PUBLIC_KEY_PEM process.env.US_JWT_PUBLIC_KEY Public key source

JWT claim set

Claim or field Source
alg RS256
typ JWT
iss TOKEN_ISSUER
aud TOKEN_AUDIENCE
exp ACCESS_TOKEN_TTL_MS
jti randomUUID()
tenantId Consent tenant
consentId Consent ID
purpose Consent purpose
dataCategories Consent data categories
scope Space-delimited access scope

JWT key handling flow

sequenceDiagram
    participant Partner
    participant USAPI as US API
    participant Keys as JWT keys
    participant Prisma

    Partner->>USAPI: POST /consents/:consentId/token
    USAPI->>Prisma: Load consent and set status ACTIVE
    USAPI->>Keys: Import or generate private key
    USAPI->>Keys: SignJWT RS256
    USAPI-->>Partner: access_token and refresh_token

    Partner->>USAPI: Send access token to data endpoint
    USAPI->>Keys: jwtVerify with public key
    USAPI->>Prisma: Load consent and tenant scoped state
    USAPI-->>Partner: Authorized response

Service Types and Internal Data Shapes

Note: When the PEM environment variables are missing, the key pair is generated inside the process. That key material is not shared across separate processes.

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

ConsentPurpose

RENTAL_SCREENING, LENDING_UNDERWRITING, EMPLOYMENT_SCREENING, ACCOUNT_OPENING, INCOME_VERIFICATION, FRAUD_PREVENTION, PERSONAL_FINANCE

DataCategory

identity_basic, accounts, balances, transactions, income, employment, cashflow_features, device_risk, watchlist_screening

ConnectionStatus

Note: The route layer accepts uppercase aliases and additional request categories such as PAYMENT_BEHAVIOR and OBLIGATIONS; the service type keeps the canonical lowercase set.

ACTIVE, REAUTH_REQUIRED, DEGRADED, DISCONNECTED

ConsentStatus

PENDING_USER_ACTION, ACTIVE, REVOKED

RefreshPermissions

Property Type Description
enabled boolean Enables refresh behavior for a consent
max_refresh_per_day number Daily refresh ceiling

RefreshTokenRecord

Property Type Description
token string Stored refresh token
consentId string Consent bound to the refresh token
tenantId string Tenant scope
expiresAt Date Token expiry timestamp

EvidenceSnapshot

Property Type Description
evidenceRef string Snapshot identifier
consentId string Bound consent
computedAt Date Snapshot creation time
featureSet "US_CASHFLOW_V1" Supported feature-set label
features Record<string, number> Numeric feature map

UsAccessContext

Property Type Description
consentId string Bound consent
tenantId string Partner tenant
purpose ConsentPurpose Authorized purpose
dataCategories DataCategory[] Authorized categories

AccountData

Property Type Description
accounts Array<{ account_id: string; name: string; type: string; mask: string; institution: string; }> Account list returned by getAccounts
balances Array<{ account_id: string; available: number; current: number; currency: string; }> Balance list
transactions Array<{ transaction_id: string; account_id: string; posted_at: string; amount: number; currency: string; description: string; category: string; }> Transaction list
income `{ method: "PROVIDER_REPORTED" \ "INFERRED"; gross_monthly: number; net_monthly: number; currency: string; }`

UsJobRecord

Property Type Description
jobId string Job identifier
status `"PROCESSING" \ "COMPLETE" \
consentId string Consent tied to the job
completedAt string Completion timestamp
error string Error message when present

Internal helper behavior

Method Description
ensureGeneratedKeys Lazily creates an RSA key pair when PEM keys are absent
getGeneratedPublicKeyPem Ensures fallback key material exists and returns the generated public key
buildSampleAccountData Synthesizes one checking account, one balance row, two transactions, and inferred income for a consent
getAccounts Returns a stored account bundle from accountsByConsent or falls back to buildSampleAccountData

Service Methods

Note: GET /consents/:consentId can derive EXPIRED from the stored expiration timestamp even though ConsentStatus does not include that value.

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

Exported service functions

Method Description
createConsent Creates a consent row and authorization data for a tenant-scoped partner request
getConsent Loads a consent by ID with optional tenant filtering
revokeConsent Marks a consent revoked, disconnects linked connections, and deletes refresh tokens
exchangeConsentToken Activates a consent and returns a signed access token plus refresh token
refreshAccessToken Validates refresh state, increments the refresh counter, and returns a new access token
introspectToken Verifies a token and returns active state plus consent metadata
verifyUsAccessToken Verifies an access token and returns the access context used by route guards
getConsentConnectionStatus Reads the first connection row for a consent and optional tenant
updateConnectionStatus Persists a connection status transition and optional reauth URL
touchConnection Updates lastRefreshedAt and promotes DEGRADED connections back to ACTIVE
createEvidenceSnapshot Persists feature values as an immutable evidence snapshot with US_CASHFLOW_V1
getEvidenceSnapshot Loads an evidence snapshot by evidenceRef with optional tenant filtering
getLatestEvidenceSnapshotByConsent Loads the newest evidence snapshot for a consent
getAccounts Returns stored or synthetic account data for a consent

Token lifecycle notes

  • exchangeConsentToken signs a new access token with tenantId, consentId, purpose, dataCategories, and scope.
  • refreshAccessToken keeps a per-consent, per-day counter and sets linked connections to REAUTH_REQUIRED when the daily limit is exceeded.
  • introspectToken returns active: false when the key material is unavailable or the token fails validation.
  • verifyUsAccessToken rejects tokens that do not carry consentId, tenantId, and purpose.
  • revokeConsent updates the consent to REVOKED, marks linked connections DISCONNECTED, and clears refresh tokens.
  • createEvidenceSnapshot persists tenantId from the consent when available and falls back to "unknown" when it is not.
  • getLatestEvidenceSnapshotByConsent orders snapshots by createdAt descending.

State Management

apps/api/src/services/us-api.ts, apps/api/src/routes/us/index.ts

stateDiagram-v2
    [*] --> PENDING_USER_ACTION
    PENDING_USER_ACTION --> ACTIVE: exchangeConsentToken
    ACTIVE --> REVOKED: revokeConsent

The persisted consent state is normalized through exchangeConsentToken and revokeConsent. The read handler derives EXPIRED from the stored expiration timestamp while keeping the database enum unchanged.

Connection state

stateDiagram-v2
    ACTIVE --> DEGRADED: ensureConnection path
    DEGRADED --> ACTIVE: touchConnection
    ACTIVE --> REAUTH_REQUIRED: refresh limit reached
    ACTIVE --> DISCONNECTED: revokeConsent
    DEGRADED --> DISCONNECTED: revokeConsent
    REAUTH_REQUIRED --> DISCONNECTED: revokeConsent

touchConnection is the only visible helper that promotes a degraded connection back to active. refreshAccessToken transitions a consent’s connections to REAUTH_REQUIRED when the daily refresh ceiling is reached.

Job state

usJobStore tracks feature-compute jobs in memory under jobId.

Stored status Meaning
PROCESSING Client-facing in-flight state
COMPLETE Stored terminal state after the partner-auth branch finishes
FAILED Stored terminal failure state

Error Handling

Note: In the partner-auth branch of POST /features/compute, the job is stored as COMPLETE in usJobStore while the HTTP response returns PROCESSING.

apps/api/src/routes/us/index.ts

The route layer uses sendError to normalize failures into code, message, and request ID payloads. Auth checks, consent ownership checks, purpose checks, category checks, connection checks, and scoring callback failures all short-circuit before the business payload is returned.

if (params.consentId !== request.usAccess!.consentId) {
  return sendError(reply, "CONSENT_MISMATCH", "Consent ID does not match token", 403, request.id);
}

Notable runtime errors

Code Trigger
CONSENT_NOT_FOUND Missing consent lookup
CONSENT_MISMATCH Consent ID in the path does not match the access token
consent_not_active Consent exists but is not active
score_not_ready Evidence snapshot is missing
LEGAL_RESTRICTION Scoring returned DENY without reason codes
PROVIDER_UNAVAILABLE Scoring callback failure or unavailable provider
REFRESH_LIMIT_EXCEEDED Refresh counter exceeded the configured daily limit

Scoring callback failure path

try {
  const scoringData = await fetchScoringDecision(...);
} catch (error) {
  reply.log.error({ err: error }, "scoring callback failed");
  return sendError(reply, "PROVIDER_UNAVAILABLE", "Scoring provider error", 502, request.id, true);
}

Caching and Storage Strategy

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

Store Type Key
accountsByConsent In-memory Map consentId
usJobStore In-memory Map jobId
usConsent Prisma/PostgreSQL Consent ID, tenant ID, timestamps
usConnection Prisma/PostgreSQL Connection ID and consent ID
usRefreshToken Prisma/PostgreSQL Refresh token and consent ID
usRefreshCounter Prisma/PostgreSQL Consent ID and date bucket
usEvidenceSnapshot Prisma/PostgreSQL evidenceRef, consentId, tenant ID

getAccounts uses the in-memory consent map first and falls back to synthetic sample data when no stored bundle exists. revokeConsent clears refresh tokens and disconnects linked connections in the database.

US Data Gateway Boundary

services/us-data-gateway/Dockerfile, services/us-api/.env.example, documents/us-jp-api-vm-migration.md

us-data-gateway is packaged as a separate Go service and deployed beside the main US API service. The container is private, non-root, and listens on 8084, which keeps the gateway boundary distinct from the Fastify API that serves the public US contract.

Build or runtime detail Value
Build image golang:1.20-alpine
Runtime image alpine:3.19
Build output /bin/us-data-gateway
Entry point /bin/us-data-gateway
Exposed port 8084
Runtime user app
Module path built ./cmd/us-data-gateway

The VM migration guide places us-data-gateway in the same deployment set as the US API service, consent service, token service, and scoring orchestrator, with shared Postgres and Redis connectivity plus shared secrets.

API Contract and Runtime Endpoints

apps/api/src/routes/us/index.ts, documents/us-api-openapi.yaml

{
    "title": "Create Consent",
    "description": "Creates a consent and returns the user authorization URL.",
    "method": "POST",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"applicant_id\": \"app_12821\",\n    \"purpose\": \"RENTAL_SCREENING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"transactions\",\n        \"income\"\n    ],\n    \"expires_in_days\": 30,\n    \"refresh_permissions\": {\n        \"enabled\": true,\n        \"max_refresh_per_day\": 3\n    },\n    \"user\": {\n        \"country\": \"US\"\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Consent created",
            "body": "{\n    \"consent_id\": \"cons_34921\",\n    \"authorization_url\": \"https://api.joinlita.com/api/v1/us/consents/cons_34921/authorize\",\n    \"redirect_url\": \"https://api.joinlita.com/api/v1/us/consents/cons_34921/authorize\",\n    \"status\": \"PENDING\",\n    \"expires_at\": \"2026-04-30T12:00:00.000Z\"\n}"
        },
        "401": {
            "description": "Unauthorized",
            "body": "{\n    \"error\": {\n        \"code\": \"unauthorized\",\n        \"message\": \"Unauthorized\"\n    },\n    \"request_id\": \"req_01\"\n}"
        }
    }
}
{
    "title": "Get Consent",
    "description": "Returns consent status, activation time, expiration, and linked connections.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Consent details",
            "body": "{\n    \"consent_id\": \"cons_34921\",\n    \"status\": \"ACTIVE\",\n    \"applicant_id\": \"app_12821\",\n    \"purpose\": \"RENTAL_SCREENING\",\n    \"activated_at\": \"2026-04-01T10:15:00.000Z\",\n    \"expires_at\": \"2026-04-30T12:00:00.000Z\",\n    \"connections\": [\n        {\n            \"connection_id\": \"conn_8821\",\n            \"provider\": \"Financial Provider\",\n            \"status\": \"ACTIVE\"\n        }\n    ]\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"not_found\",\n        \"message\": \"Consent not found\"\n    },\n    \"request_id\": \"req_02\"\n}"
        }
    }
}
{
    "title": "Get Consent Authorization",
    "description": "Returns the authorization code after the user completes the authorization step.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/authorize",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Authorization complete",
            "body": "{\n    \"consent_id\": \"cons_34921\",\n    \"purpose\": \"RENTAL_SCREENING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"transactions\",\n        \"income\"\n    ],\n    \"status\": \"ACTIVE\",\n    \"authorization_code\": \"ok\",\n    \"message\": \"Authorization complete. Exchange this code for an access token via POST /consents/:consentId/token\"\n}"
        },
        "409": {
            "description": "Consent revoked or expired",
            "body": "{\n    \"error\": {\n        \"code\": \"consent_revoked\",\n        \"message\": \"Consent is no longer valid\"\n    },\n    \"request_id\": \"req_03\"\n}"
        }
    }
}
{
    "title": "Get Consent Receipt",
    "description": "Returns the persisted consent receipt for partner review and audit.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/receipt",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Consent receipt",
            "body": "{\n    \"consent_id\": \"cons_34921\",\n    \"purpose\": \"RENTAL_SCREENING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"transactions\",\n        \"income\"\n    ],\n    \"disclosure_version\": \"2026-01\",\n    \"status\": \"ACTIVE\",\n    \"created_at\": \"2026-04-01T10:00:00.000Z\",\n    \"revoked_at\": null\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"CONSENT_NOT_FOUND\",\n        \"message\": \"Consent not found\"\n    },\n    \"request_id\": \"req_04\"\n}"
        }
    }
}
{
    "title": "Revoke Consent",
    "description": "Revokes a consent, disconnects linked connections, and clears refresh tokens.",
    "method": "DELETE",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Consent revoked",
            "body": "{\n    \"consent_id\": \"cons_34921\",\n    \"status\": \"REVOKED\",\n    \"revoked_at\": \"2026-04-10T09:30:00.000Z\"\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"CONSENT_NOT_FOUND\",\n        \"message\": \"Consent not found\"\n    },\n    \"request_id\": \"req_05\"\n}"
        }
    }
}

Token APIs

{
    "title": "Exchange Consent for Tokens",
    "description": "Activates consent and exchanges the authorization code for access and refresh tokens.",
    "method": "POST",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/token",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"authorization_code\": \"ok\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Tokens issued",
            "body": "{\n    \"access_token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...\",\n    \"refresh_token\": \"rtk_67d5f02a9b4c4f0c8bcd\",\n    \"expires_in\": 900,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions income cashflow_features\"\n}"
        },
        "404": {
            "description": "Consent not found",
            "body": "{\n    \"error\": {\n        \"code\": \"CONSENT_NOT_FOUND\",\n        \"message\": \"Consent not found\"\n    },\n    \"request_id\": \"req_06\"\n}"
        }
    }
}

Refresh Access Token

{
    "title": "Refresh Access Token",
    "description": "Refreshes an access token using a refresh token and enforces the daily refresh ceiling.",
    "method": "POST",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/tokens/refresh",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"refresh_token\": \"rtk_67d5f02a9b4c4f0c8bcd\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Tokens refreshed",
            "body": "{\n    \"access_token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...\",\n    \"refresh_token\": \"rtk_68efb9bb1f3e4e3e88c1\",\n    \"expires_in\": 900,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions income cashflow_features\"\n}"
        },
        "400": {
            "description": "Refresh rejected",
            "body": "{\n    \"error\": {\n        \"code\": \"REFRESH_LIMIT_EXCEEDED\",\n        \"message\": \"Refresh not allowed\"\n    },\n    \"request_id\": \"req_07\"\n}"
        }
    }
}

Introspect Token

{
    "title": "Introspect Token",
    "description": "Checks whether a token is active and returns consent metadata when the token is valid.",
    "method": "POST",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/tokens/introspect",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Token status",
            "body": "{\n    \"active\": true,\n    \"expires_at\": \"2026-04-01T10:30:00.000Z\",\n    \"consent_id\": \"cons_34921\",\n    \"purpose\": \"RENTAL_SCREENING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"transactions\",\n        \"income\"\n    ]\n}"
        }
    }
}

Data APIs

List Accounts

{
    "title": "List Accounts",
    "description": "Returns account data for the consent scoped access token.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/data/accounts",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Account list",
            "body": "{\n    \"accounts\": [\n        {\n            \"account_id\": \"acct_cons_3492\",\n            \"name\": \"Everyday Checking\",\n            \"type\": \"checking\",\n            \"mask\": \"4321\",\n            \"institution\": \"Example Bank\"\n        }\n    ]\n}"
        },
        "403": {
            "description": "Consent mismatch or scope failure",
            "body": "{\n    \"error\": {\n        \"code\": \"CONSENT_MISMATCH\",\n        \"message\": \"Consent ID does not match token\"\n    },\n    \"request_id\": \"req_08\"\n}"
        }
    }
}

List Balances

{
    "title": "List Balances",
    "description": "Returns balances for the consent scoped access token.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/data/balances",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Balances list",
            "body": "{\n    \"balances\": [\n        {\n            \"account_id\": \"acct_cons_3492\",\n            \"available\": 2450.12,\n            \"current\": 2625.34,\n            \"currency\": \"USD\"\n        }\n    ]\n}"
        }
    }
}

List Transactions

{
    "title": "List Transactions",
    "description": "Returns a paginated transaction page using the runtime envelope returned by the handler.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/data/transactions",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "start_date",
            "required": false,
            "type": "string"
        },
        {
            "key": "end_date",
            "required": false,
            "type": "string"
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Transaction page",
            "body": "{\n    \"data\": [\n        {\n            \"transaction_id\": \"txn_cons_3492_1\",\n            \"date\": \"2026-04-01\",\n            \"amount\": -82.45,\n            \"currency\": \"USD\",\n            \"description\": \"Grocery Store\",\n            \"category\": \"GROCERIES\",\n            \"type\": \"DEBIT\"\n        }\n    ],\n    \"next_cursor\": \"cur_50\",\n    \"total_count\": 1\n}"
        }
    }
}

Sync Transactions

{
    "title": "Sync Transactions",
    "description": "Returns a sync payload with added, modified, and removed transactions.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/data/transactions/sync",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "cursor",
            "required": false,
            "type": "string"
        },
        {
            "key": "limit",
            "required": false,
            "type": "number"
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Transaction sync",
            "body": "{\n    \"cursor\": \"cursor_1743500000000\",\n    \"added\": [\n        {\n            \"transaction_id\": \"txn_cons_3492_1\",\n            \"account_id\": \"acct_cons_3492\",\n            \"posted_at\": \"2026-04-01T10:00:00.000Z\",\n            \"amount\": -82.45,\n            \"currency\": \"USD\",\n            \"description\": \"Grocery Store\",\n            \"category\": \"GROCERIES\"\n        }\n    ],\n    \"modified\": [\n        {\n            \"transaction_id\": \"txn_cons_3492_2\",\n            \"account_id\": \"acct_cons_3492\",\n            \"posted_at\": \"2026-03-31T10:00:00.000Z\",\n            \"amount\": 2500,\n            \"currency\": \"USD\",\n            \"description\": \"Payroll\",\n            \"category\": \"INCOME\"\n        }\n    ],\n    \"removed\": [\n        {\n            \"transaction_id\": \"txn_cons_3492_3\"\n        }\n    ]\n}"
        }
    }
}

Get Income Summary

{
    "title": "Get Income Summary",
    "description": "Returns the income summary for the consent scoped access token.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/data/income",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Income summary",
            "body": "{\n    \"method\": \"INFERRED\",\n    \"gross_monthly\": 5000,\n    \"net_monthly\": 4200,\n    \"currency\": \"USD\"\n}"
        }
    }
}
{
    "title": "Consent Scoped Accounts",
    "description": "Returns account data for a specific consent after access-token validation and consent matching.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/data/accounts",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Account list",
            "body": "{\n    \"accounts\": [\n        {\n            \"account_id\": \"acct_cons_3492\",\n            \"name\": \"Everyday Checking\",\n            \"type\": \"checking\",\n            \"mask\": \"4321\",\n            \"institution\": \"Example Bank\"\n        }\n    ]\n}"
        },
        "403": {
            "description": "Consent mismatch",
            "body": "{\n    \"error\": {\n        \"code\": \"CONSENT_MISMATCH\",\n        \"message\": \"Consent ID does not match token\"\n    },\n    \"request_id\": \"req_09\"\n}"
        }
    }
}
{
    "title": "Consent Scoped Balances",
    "description": "Returns balances for a specific consent after access-token validation and consent matching.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/data/balances",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Balances list",
            "body": "{\n    \"balances\": [\n        {\n            \"account_id\": \"acct_cons_3492\",\n            \"available\": 2450.12,\n            \"current\": 2625.34,\n            \"currency\": \"USD\"\n        }\n    ]\n}"
        }
    }
}
{
    "title": "Consent Scoped Transactions",
    "description": "Returns the transaction list for a specific consent after access-token validation and consent matching.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/data/transactions",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "start_date",
            "required": false,
            "type": "string"
        },
        {
            "key": "end_date",
            "required": false,
            "type": "string"
        },
        {
            "key": "from_date",
            "required": false,
            "type": "string"
        },
        {
            "key": "to_date",
            "required": false,
            "type": "string"
        },
        {
            "key": "limit",
            "required": false,
            "type": "number"
        },
        {
            "key": "cursor",
            "required": false,
            "type": "string"
        }
    ],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Transaction list",
            "body": "{\n    \"transactions\": [\n        {\n            \"transaction_id\": \"txn_cons_3492_1\",\n            \"account_id\": \"acct_cons_3492\",\n            \"posted_at\": \"2026-04-01T10:00:00.000Z\",\n            \"amount\": -82.45,\n            \"currency\": \"USD\",\n            \"description\": \"Grocery Store\",\n            \"category\": \"GROCERIES\"\n        }\n    ]\n}"
        }
    }
}
{
    "title": "Consent Scoped Transaction Sync",
    "description": "Returns a transaction sync payload scoped to a consent.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/data/transactions/sync",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "cursor",
            "required": false,
            "type": "string"
        },
        {
            "key": "limit",
            "required": false,
            "type": "number"
        }
    ],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Transaction sync",
            "body": "{\n    \"cursor\": \"cursor_1743500000000\",\n    \"added\": [\n        {\n            \"transaction_id\": \"txn_cons_3492_1\",\n            \"account_id\": \"acct_cons_3492\",\n            \"posted_at\": \"2026-04-01T10:00:00.000Z\",\n            \"amount\": -82.45,\n            \"currency\": \"USD\",\n            \"description\": \"Grocery Store\",\n            \"category\": \"GROCERIES\"\n        }\n    ],\n    \"modified\": [\n        {\n            \"transaction_id\": \"txn_cons_3492_2\",\n            \"account_id\": \"acct_cons_3492\",\n            \"posted_at\": \"2026-03-31T10:00:00.000Z\",\n            \"amount\": 2500,\n            \"currency\": \"USD\",\n            \"description\": \"Payroll\",\n            \"category\": \"INCOME\"\n        }\n    ],\n    \"removed\": [\n        {\n            \"transaction_id\": \"txn_cons_3492_3\"\n        }\n    ]\n}"
        }
    }
}
{
    "title": "Consent Scoped Income",
    "description": "Returns the income summary for a specific consent after access-token validation and consent matching.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/data/income",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Income summary",
            "body": "{\n    \"method\": \"INFERRED\",\n    \"gross_monthly\": 5000,\n    \"net_monthly\": 4200,\n    \"currency\": \"USD\"\n}"
        }
    }
}

Feature, Evidence, and Job APIs

Compute Cashflow Features

{
    "title": "Compute Cashflow Features",
    "description": "Computes cashflow features and either returns evidence immediately or creates a job depending on the auth mode.",
    "method": "POST",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/features/compute",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"consent_id\": \"cons_34921\",\n    \"feature_set\": \"US_CASHFLOW_V1\",\n    \"as_of\": \"2026-04-01\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Feature payload",
            "body": "{\n    \"evidence_ref\": \"ev_7bd8c31142\",\n    \"features\": {\n        \"monthly_income\": 4200,\n        \"avg_balance\": 2625.34,\n        \"overdraft_count\": 0,\n        \"cashflow_surplus\": 2417.55,\n        \"cashflow_inflow\": 2500,\n        \"cashflow_outflow\": 82.45,\n        \"cashflow_net\": 2417.55\n    }\n}"
        },
        "202": {
            "description": "Job accepted",
            "body": "{\n    \"job_id\": \"job_7a2d2b9b1c2e\",\n    \"status\": \"PROCESSING\",\n    \"consent_id\": \"cons_34921\",\n    \"estimated_completion_ms\": 0\n}"
        }
    }
}
{
    "title": "Consent Scoped Feature Compute",
    "description": "Computes cashflow features for a consent and returns an evidence snapshot.",
    "method": "POST",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/features/compute",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <access token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"feature_set\": \"US_CASHFLOW_V1\",\n    \"as_of\": \"2026-04-01\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Evidence snapshot summary",
            "body": "{\n    \"evidence_ref\": \"ev_7bd8c31142\",\n    \"features\": {\n        \"monthly_income\": 4200,\n        \"avg_balance\": 2625.34,\n        \"overdraft_count\": 0,\n        \"cashflow_surplus\": 2417.55,\n        \"cashflow_inflow\": 2500,\n        \"cashflow_outflow\": 82.45,\n        \"cashflow_net\": 2417.55\n    }\n}"
        }
    }
}

Get Evidence Snapshot

{
    "title": "Get Evidence Snapshot",
    "description": "Returns the immutable evidence snapshot used for score replay and audit.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/evidence/{evidenceRef}",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "evidenceRef",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Evidence snapshot",
            "body": "{\n    \"evidence_ref\": \"ev_7bd8c31142\",\n    \"consent_id\": \"cons_34921\",\n    \"applicant_id\": \"app_12821\",\n    \"snapshot_version\": \"1.2.0\",\n    \"created_at\": \"2026-04-01T10:20:00.000Z\",\n    \"score_inputs\": {\n        \"payment_behavior\": {\n            \"payments_observed\": 25,\n            \"avg_payment_delay_days\": 0,\n            \"late_payment_count_30d_plus\": 0\n        },\n        \"income\": {\n            \"monthly_net_income\": 4200,\n            \"income_stability_score\": 0.95\n        },\n        \"obligations\": {\n            \"total_monthly_obligations\": 1260,\n            \"obligation_to_income_ratio\": 0.3\n        }\n    },\n    \"kyc_result\": {\n        \"status\": \"PASSED\",\n        \"checks\": [\n            \"identity\",\n            \"sanctions\",\n            \"pep\"\n        ]\n    },\n    \"delinquency_bucket\": \"CURRENT\",\n    \"features\": {\n        \"monthly_income\": 4200,\n        \"avg_balance\": 2625.34,\n        \"overdraft_count\": 0,\n        \"cashflow_surplus\": 2417.55,\n        \"cashflow_inflow\": 2500,\n        \"cashflow_outflow\": 82.45,\n        \"cashflow_net\": 2417.55\n    }\n}"
        }
    }
}

Get Job Status

{
    "title": "Get Job Status",
    "description": "Returns the stored status for a feature-compute job.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/status/{jobId}",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "jobId",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Job status",
            "body": "{\n    \"job_id\": \"job_7a2d2b9b1c2e\",\n    \"status\": \"COMPLETE\",\n    \"consent_id\": \"cons_34921\",\n    \"completed_at\": \"2026-04-01T10:20:00.000Z\",\n    \"error\": null\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"not_found\",\n        \"message\": \"Job not found\"\n    },\n    \"request_id\": \"req_10\"\n}"
        }
    }
}
{
    "title": "Get Consent KYC",
    "description": "Returns the KYC and AML summary derived from the latest evidence snapshot.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/kyc",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "KYC result",
            "body": "{\n    \"consent_id\": \"cons_34921\",\n    \"status\": \"PASSED\",\n    \"checks\": {\n        \"identity\": {\n            \"status\": \"PASSED\",\n            \"method\": \"document_biometric\"\n        },\n        \"sanctions\": {\n            \"status\": \"PASSED\",\n            \"lists_screened\": [\n                \"OFAC\",\n                \"UN\",\n                \"EU\"\n            ]\n        },\n        \"pep\": {\n            \"status\": \"PASSED\"\n        },\n        \"aml\": {\n            \"status\": \"PASSED\",\n            \"risk_level\": \"LOW\"\n        }\n    },\n    \"completed_at\": \"2026-04-01T10:20:00.000Z\"\n}"
        },
        "422": {
            "description": "Consent not active",
            "body": "{\n    \"error\": {\n        \"code\": \"consent_not_active\",\n        \"message\": \"KYC checks are run during feature computation. Activate the consent first.\"\n    },\n    \"request_id\": \"req_11\"\n}"
        }
    }
}

Decision APIs

{
    "title": "Get Consent Score",
    "description": "Replays the partner scoring callback using the latest evidence snapshot.",
    "method": "GET",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/{consent_id}/score",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consent_id",
            "required": true,
            "type": "string"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Score result",
            "body": "{\n    \"consent_id\": \"cons_34921\",\n    \"applicant_id\": \"app_12821\",\n    \"score\": 712,\n    \"score_range\": {\n        \"min\": 300,\n        \"max\": 850\n    },\n    \"decision\": \"APPROVE\",\n    \"score_factors\": [\n        \"LOW_BALANCE_VOLATILITY\",\n        \"CONSISTENT_PAYMENT_HISTORY\"\n    ],\n    \"evidence_ref\": \"ev_7bd8c31142\",\n    \"scored_at\": \"2026-04-01T10:25:00.000Z\",\n    \"model_version\": \"1.2.0\"\n}"
        },
        "422": {
            "description": "Score not ready",
            "body": "{\n    \"error\": {\n        \"code\": \"score_not_ready\",\n        \"message\": \"Feature computation has not completed. Wait for score.completed webhook.\"\n    },\n    \"request_id\": \"req_12\"\n}"
        }
    }
}

Replay Decision

{
    "title": "Replay Decision",
    "description": "Replays a stored evidence snapshot through the partner scoring endpoint.",
    "method": "POST",
    "baseUrl": "<UsApiBaseUrl>",
    "endpoint": "/api/v1/us/decisions/replay",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"evidence_ref\": \"ev_7bd8c31142\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Decision replayed",
            "body": "{\n    \"evidence_ref\": \"ev_7bd8c31142\",\n    \"decision\": \"APPROVE\",\n    \"reason_codes\": [\n        \"LOW_BALANCE_VOLATILITY\",\n        \"CONSISTENT_PAYMENT_HISTORY\"\n    ]\n}"
        },
        "404": {
            "description": "Evidence not found",
            "body": "{\n    \"error\": {\n        \"code\": \"EVIDENCE_NOT_FOUND\",\n        \"message\": \"Evidence not found\"\n    },\n    \"request_id\": \"req_13\"\n}"
        }
    }
}

Feature and Data Flow

sequenceDiagram
    participant Partner
    participant User
    participant USAPI as US API
    participant Prisma
    participant Webhooks

    Partner->>USAPI: POST /consents
    USAPI->>Prisma: Create consent
    USAPI-->>Partner: consent_id and authorization_url

    User->>USAPI: GET /consents/:consentId/authorize
    Partner->>USAPI: POST /consents/:consentId/token
    USAPI->>Prisma: Set consent ACTIVE and store refresh token
    USAPI->>Webhooks: consent.activated
    USAPI->>Webhooks: connection.created
    USAPI-->>Partner: access_token and refresh_token

Feature computation and scoring replay

sequenceDiagram
    participant Partner
    participant USAPI as US API
    participant Prisma
    participant Scoring as Partner scoring
    participant Webhooks

    Partner->>USAPI: POST /features/compute or /consents/:consentId/features/compute
    USAPI->>Prisma: Load consent and connections
    USAPI->>Prisma: createEvidenceSnapshot
    USAPI->>Scoring: fetchScoringDecision
    USAPI->>Webhooks: features.computed or score.completed
    USAPI-->>Partner: Evidence or job response

    Partner->>USAPI: POST /decisions/replay
    USAPI->>Prisma: Load evidence snapshot and consent
    USAPI->>Scoring: fetchScoringDecision
    USAPI-->>Partner: decision and reason codes

Dependencies

Note: documents/us-api-openapi.yaml advertises POST /api/v1/us/consents/{consent_id}/revoke, but the runtime route is DELETE /consents/:consentId. Note: documents/us-api-openapi.yaml models POST /api/v1/us/features/compute as an access-token-only endpoint with FeatureComputeResponse, but the runtime handler also supports partner-auth mode when consent_id is supplied in the body and returns 202 job metadata. Note: documents/us-api-openapi.yaml models GET /api/v1/us/data/transactions as TransactionList, but the runtime handler returns { data, next_cursor, total_count }. Note: documents/us-api-openapi.yaml models Account.institution_name, but the runtime account payload uses institution.

apps/api/src/services/us-api.ts, services/us-data-gateway/Dockerfile, apps/api/src/routes/us/index.ts

Runtime and library dependencies

  • @lita/db Prisma client for usConsent, usConnection, usRefreshToken, usRefreshCounter, and usEvidenceSnapshot
  • jose for RS256 JWT import, signing, and verification
  • node:crypto for randomUUID and fallback RSA key generation
  • Fastify for request routing and response lifecycle
  • Zod for request and response schema definitions
  • Go 1.20 and Alpine runtime for us-data-gateway

Integration points

  • SCORING_CALLBACK_URL as the fallback scoring endpoint for partner-hosted scoring
  • Webhook delivery for consent.activated, consent.revoked, connection.created, connection.degraded, connection.refreshed, connection.reauth_required, features.computed, score.completed, and decision.completed
  • API_PUBLIC_BASE_URL for authorization and reauthorization URLs
  • PostgreSQL for consent, connection, token, counter, and evidence persistence

Testing Considerations

apps/api/src/routes/us/index.ts

  • Create consent with GENERAL_PERSONAL_FINANCE and verify the route accepts the value even though the internal ConsentPurpose type does not include it.
  • Exchange a consent for tokens and confirm consent.activated and connection.created webhook emissions.
  • Call access-token data endpoints with a mismatched consent ID and confirm CONSENT_MISMATCH.
  • Hit /tokens/refresh until the daily counter trips and confirm REAUTH_REQUIRED is written for the connection.
  • Verify that /features/compute returns 202 in partner-auth mode and stores a job record.
  • Confirm /consents/:consentId/score returns 422 until an evidence snapshot exists.
  • Confirm /evidence/:evidenceRef and /consents/:consentId/kyc both filter by tenant scope.
  • Confirm DELETE /consents/:consentId removes refresh tokens and disconnects connections.

Key Classes Reference

Class Responsibility
us-api.ts Consent, token, evidence, connection, and synthetic account state management
index.ts US route handlers, guard orchestration, and webhook-triggered request flow
Dockerfile Builds and packages the standalone us-data-gateway Go service
.env.example Regional runtime configuration and secret placeholders
us-api.md Human-readable US API contract, glossary, and policy summary
us-api-openapi.yaml Machine-readable US API contract, endpoints, and schemas