Architecture and Runtime Foundations

Overview

The API process is bootstrapped from apps/api/src/index.ts, which loads buildServer() from apps/api/src/server.ts, binds the Fastify listener to 0.0.0.0:3000 by default, and starts the foreground HTTP server. That server is the main runtime surface for admin, consent, and regional data endpoints, with request authentication, tenant decoration, audit logging, and rate limiting applied before route handlers run.

A separate worker process in apps/worker/src/index.ts runs continuously in the background. Its responsibility is operational rather than request/response oriented: it polls pending webhook deliveries, processes due items in batches, and sleeps between iterations. Together, the two processes split synchronous API traffic from asynchronous delivery work, which keeps the API path focused on low-latency request handling and compliance-oriented auditing.

Architecture Overview

flowchart TB
    Client[API Clients and Partner Systems] --> ApiIndex[apps api src index ts]
    ApiIndex --> BuildServer[buildServer]
    BuildServer --> OTel[initOtel]
    BuildServer --> Logger[buildLogger]
    BuildServer --> Fastify[Fastify instance]

    Fastify --> Cors[CORS]
    Fastify --> Helmet[Helmet]
    Fastify --> RateLimit[Rate limit]
    RateLimit --> AuthPlugin[authPlugin]
    AuthPlugin --> TenantPlugin[tenantPlugin]
    TenantPlugin --> IdempotencyPlugin[idempotencyPlugin]
    IdempotencyPlugin --> AuditPlugin[auditPlugin]

    AuditPlugin --> Healthz[healthz readyz openapi endpoints]
    AuditPlugin --> AdminRoutes[v1 admin routes]
    AuditPlugin --> USRoutes[api v1 us routes]
    AuditPlugin --> JPRoutes[api v1 jp routes]

    subgraph WorkerProcess[Background Worker Process]
        WorkerIndex[apps worker src index ts] --> PollLoop[run loop]
        PollLoop --> PollDeliveries[pollDeliveries]
        PollDeliveries --> PrismaQuery[prisma delivery query]
        PollDeliveries --> ProcessDelivery[processDelivery]
    end

Runtime Entry Path

API Foreground Process

[!NOTE] GET /openapi.json returns a static document with paths: {} even though the server registers multiple route families under /v1, /api/v1/us, and /api/v1/jp. The endpoint exposes version metadata, but it is not emitting the live route surface.

apps/api/src/index.ts

The API entry file is intentionally small: it builds the server, resolves the listen target, and starts the process.

File Responsibility
apps/api/src/index.ts Loads buildServer(), reads PORT, binds to 0.0.0.0, and starts the HTTP listener.
apps/api/src/server.ts Creates Fastify, installs middleware, registers route families, and defines operational endpoints.

buildServer

apps/api/src/server.ts

Method Description
buildServer Initializes telemetry, constructs the Fastify app with logger and Zod type provider, installs middleware, registers plugins and route families, and exposes health, readiness, and OpenAPI endpoints.

Startup Sequence

  1. initOtel() is called before the Fastify instance is created.
  2. Fastify({ logger: buildLogger(), bodyLimit: 1_048_576 }) creates the HTTP server.
  3. withTypeProvider<ZodTypeProvider>() enables Zod-backed request and response schemas.
  4. Validator and serializer compilers are set from fastify-type-provider-zod.
  5. Security and rate controls are registered.
  6. Authentication, tenant decoration, idempotency, and audit plugins are installed.
  7. Admin and regional route modules are mounted.
  8. Health, readiness, and OpenAPI endpoints are attached.
  9. apps/api/src/index.ts calls listen({ port, host }) and logs startup.

apps/api/src/index.ts

Property / Value Type Description
port number Reads process.env.PORT or defaults to 3000.
host string Hard-coded to 0.0.0.0.

Foreground Server Runtime

apps/api/Dockerfile

The API container is built in two stages.

Stage Behavior
build Installs workspace dependencies with pnpm --frozen-lockfile, copies apps/api, and runs pnpm -C apps/api build.
runtime Copies only dist and package.json, sets NODE_ENV=production, exposes 3000, and starts node dist/index.js.

apps/api/tsconfig.json

Option Value Effect
extends ../../tsconfig.base.json Inherits the workspace TypeScript baseline.
rootDir src Compiles source from src.
outDir dist Emits built JavaScript to dist.
types ["node"] Uses Node.js ambient types.
include ["src"] Limits compilation to the source tree.

apps/api/package.json

Script Command Responsibility
dev node --watch --loader ts-node/esm/transpile-only src/index.ts Runs the API entry point in watch mode.
build tsc -p tsconfig.json Produces the production build.
lint eslint src --max-warnings=0 Lints the API source tree.
test vitest Runs the API test suite.

Middleware Stack and Request Lifecycle

Registration Order

buildServer() installs middleware and plugins in a fixed order. That order matters because later plugins and handlers inherit the decorations and request state produced earlier.

Order Registration Runtime Effect
1 cors Enables cross-origin responses with origin: true.
2 helmet Adds security headers.
3 rateLimit Caps requests at max: 300 per timeWindow: "1 minute".
4 authPlugin Enforces Authorization and X-Request-Id on non-public routes.
5 tenantPlugin Copies authenticated tenant information to request.tenantId.
6 idempotencyPlugin Registered before route handlers and audit logging.
7 auditPlugin Adds request.logAuditEvent.
8 registerV1Routes(app) Mounts /v1 admin route families.
9 app.register(usRoutes, { prefix: "/api/v1/us" }) Mounts the US regional surface.
10 app.register(jpRoutes, { prefix: "/api/v1/jp" }) Mounts the JP regional surface.
11 app.get("/healthz") Public liveness check.
12 app.get("/readyz") Public readiness check.
13 app.get("/openapi.json") Public OpenAPI document.

Request Decorations

Decoration Type Set By Purpose
request.auth AuthContext authPlugin Holds authenticated tenant and actor context.
request.usAccess UsAccessContext authPlugin Stores US access-token context when the bearer token is a US consent token.
request.jpAccess JpAccessContext authPlugin Stores JP access-token context when the bearer token is a JP consent token.
request.tenantId string tenantPlugin Carries the tenant ID into route handlers and audit logging.
request.logAuditEvent function auditPlugin Writes structured audit records through recordAuditEvent.

Authentication Gate

apps/api/src/plugins/auth.ts is the first gate for all non-public routes.

Export Type Description
authPlugin FastifyPluginAsync Validates request identity and populates auth context.

Auth Resolution Order

  1. resolveApiKey(token)
  2. verifyJwt(token)
  3. verifyUsAccessToken(token)
  4. verifyJpAccessToken(token)

If US or JP token verification succeeds, the plugin synthesizes an AuthContext with:

Field Value Source
tenantId usAccess.tenantId or jpAccess.tenantId
actorType "client"
actorId consentId from the access token
scopes dataCategories from the access token

Required Headers

Header Requirement Runtime Check
X-Request-Id Required on non-public routes Rejected with 400 invalid_request if absent or blank.
Authorization Required on non-public routes Must begin with Bearer .
Authorization: Bearer ... Required value form Parsed as API key, JWT, US access token, or JP access token.

Public Path Allowlist

[!NOTE] The unauthorized response message says Authorization: Bearer <PARTNER_API_KEY> is required, but the plugin actually accepts API keys, JWTs, US access tokens, and JP access tokens in that bearer slot.

The auth plugin bypasses itself for:

  • /healthz
  • /readyz
  • /openapi.json

It also skips any route whose URL starts with /docs.

Tenant Decoration

apps/api/src/plugins/tenant.ts maps authenticated tenant information into a request-level convenience field.

Export Type Description
tenantPlugin FastifyPluginAsync Adds request.tenantId when authentication has already populated request.auth.

Behavior

  • If request.auth is absent, the hook returns without touching the request.
  • If request.auth.tenantId exists, it is copied to request.tenantId.
  • If request.auth exists but no tenant ID can be resolved, the hook sends 400 with { "error": "missing tenant" }.

Audit Decoration

[!NOTE] tenantPlugin returns a raw { "error": "missing tenant" } payload instead of the structured error envelope used by authPlugin and many route handlers.

apps/api/src/plugins/audit.ts adds a request-scoped audit writer.

Export Type Description
auditPlugin FastifyPluginAsync Adds request.logAuditEvent and forwards structured audit records to recordAuditEvent.

Audit Payload Fields

Field Source
tenantId request.tenantId
actorType request.auth.actorType
actorId request.auth.actorId
action input.action
targetType input.targetType
targetId input.targetId
ip request.ip
userAgent request.headers["user-agent"] ?? "unknown"
metadata input.metadata ?? {}

request.logAuditEvent is a no-op when either tenantId or auth is missing.

Authorization Helper

apps/api/src/services/authz.ts provides scope checking.

Export Type Description
requireScope function Throws a 403 error when the current request does not contain the required scope.

Method

Method Description
requireScope Reads request.auth.scopes, checks for a required scope, and throws Error("forbidden") with statusCode = 403 when missing.

Observability and Logging

Bootstrap Behavior

buildServer() calls initOtel() before Fastify is instantiated. That means instrumentation is initialized before request handling and plugin registration begins. The server logger comes from buildLogger() and is passed directly into Fastify construction.

Service Usage
initOtel Initializes OpenTelemetry before the app starts listening.
buildLogger Supplies the Fastify logger instance.
server.log.info({ port }, "api listening") Writes the startup event after bind completes.

Logging and Telemetry Flow

sequenceDiagram
    participant Boot as API Bootstrap
    participant OTel as initOtel
    participant Log as buildLogger
    participant Fastify as Fastify
    participant Listener as Server Listen

    Boot->>OTel: initialize tracing
    Boot->>Log: create logger
    Boot->>Fastify: build app with logger and Zod provider
    Fastify->>Fastify: register plugins and routes
    Boot->>Listener: listen on port and host
    Listener-->>Boot: startup complete
    Boot->>Log: info api listening

Public and Operational Endpoints

Health Check

apps/api/src/server.ts

GET /healthz

{
    "title": "Health Check",
    "description": "Returns the process liveness status",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/healthz",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"status\": \"ok\"\n}"
        }
    }
}

Readiness Check

apps/api/src/server.ts

GET /readyz

{
    "title": "Readiness Check",
    "description": "Returns the process readiness status",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/readyz",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"status\": \"ready\"\n}"
        }
    }
}

OpenAPI Document

apps/api/src/server.ts

GET /openapi.json

{
    "title": "OpenAPI Document",
    "description": "Returns the static OpenAPI document emitted by the API bootstrap",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/openapi.json",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"openapi\": \"3.0.3\",\n    \"info\": {\n        \"title\": \"Lita Platform API\",\n        \"version\": \"1.2.0\"\n    },\n    \"paths\": []\n}"
        }
    }
}

Admin Route Registration

Mounted Route Families

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

registerV1Routes() mounts the admin route families in this order:

  1. authRoutes at /v1/auth
  2. tenantsRoutes at /v1/tenants
  3. creditProfilesRoutes at /v1/credit-profiles
  4. decisionsRoutes at /v1/decisions
  5. webhooksRoutes at /v1/webhooks
  6. eventsRoutes at /v1/events

registerV1Routes

Method Description
registerV1Routes Registers the /v1 admin route modules on the Fastify instance.

Token Introspection

apps/api/src/routes/v1/auth.ts

POST /v1/auth/token/introspect

{
    "title": "Token Introspection",
    "description": "Checks whether a token string is present and echoes the current request auth context",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/auth/token/introspect",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"token\": \"partner-token-123\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"active\": true,\n    \"tenantId\": \"tenant_123\",\n    \"scopes\": [\n        \"admin:tenants\",\n        \"internal:events\"\n    ]\n}"
        }
    }
}

Tenant Administration

[!NOTE] The handler does not actually validate the posted token value. It sets active from Boolean(body.token) and returns the current request auth context from the middleware chain.

apps/api/src/routes/v1/tenants.ts

POST /v1/tenants

{
    "title": "Create Tenant",
    "description": "Creates a tenant record and writes an audit event",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/tenants",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"name\": \"Northwind Lending LLC\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"id\": \"tenant_01HXYZ9ABCD123456789\",\n    \"name\": \"Northwind Lending LLC\",\n    \"status\": \"ACTIVE\"\n}"
        }
    }
}

GET /v1/tenants/:id

{
    "title": "Get Tenant",
    "description": "Fetches a tenant by UUID",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/tenants/:id",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "id",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"1f2b3c4d-5e6f-7081-92a3-b4c5d6e7f809\",\n    \"name\": \"Northwind Lending LLC\",\n    \"status\": \"ACTIVE\"\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": \"not_found\"\n}"
        }
    }
}

Credit Profile Administration

[!NOTE] The handler returns a 404 payload shaped as { "error": "not_found" }, but the route schema only declares a 200 response.

apps/api/src/routes/v1/credit-profiles.ts

POST /v1/credit-profiles

{
    "title": "Upsert Credit Profile",
    "description": "Creates or updates a credit profile for a tenant and emits an audit event",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/credit-profiles",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"externalUserId\": \"user_12345\",\n    \"data\": {\n        \"score\": 712,\n        \"tier\": \"prime\",\n        \"lastUpdatedAt\": \"2025-03-01T12:30:00.000Z\"\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"cp_01HXYZ9ABCD123456789\",\n    \"externalUserId\": \"user_12345\",\n    \"dataJson\": {\n        \"score\": 712,\n        \"tier\": \"prime\",\n        \"lastUpdatedAt\": \"2025-03-01T12:30:00.000Z\"\n    }\n}"
        }
    }
}

GET /v1/credit-profiles/:id

{
    "title": "Get Credit Profile",
    "description": "Fetches a tenant-scoped credit profile by UUID",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/credit-profiles/:id",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "id",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": \"cp_01HXYZ9ABCD123456789\",\n    \"externalUserId\": \"user_12345\",\n    \"dataJson\": {\n        \"score\": 712,\n        \"tier\": \"prime\",\n        \"lastUpdatedAt\": \"2025-03-01T12:30:00.000Z\"\n    }\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": \"not_found\"\n}"
        }
    }
}

Webhook Administration

[!NOTE] The handler returns a 404 payload shaped as { "error": "not_found" }, but the route schema only declares a 200 response.

apps/api/src/routes/v1/webhooks.ts

POST /v1/webhooks/endpoints

{
    "title": "Create Webhook Endpoint",
    "description": "Creates a webhook endpoint for the current tenant and records an audit event",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/webhooks/endpoints",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"url\": \"https://hooks.example.com/lita\",\n    \"events\": [\n        \"consent.activated\",\n        \"score.completed\"\n    ]\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"id\": \"we_01HXYZ9ABCD123456789\",\n    \"url\": \"https://hooks.example.com/lita\",\n    \"events\": [\n        \"consent.activated\",\n        \"score.completed\"\n    ]\n}"
        }
    }
}

GET /v1/webhooks/endpoints

{
    "title": "List Webhook Endpoints",
    "description": "Lists webhook endpoints for the current tenant",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/webhooks/endpoints",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": \"we_01HXYZ9ABCD123456789\",\n        \"url\": \"https://hooks.example.com/lita\",\n        \"events\": [\n            \"consent.activated\",\n            \"score.completed\"\n        ]\n    }\n]"
        }
    }
}

POST /v1/webhooks/test

{
    "title": "Test Webhook Delivery",
    "description": "Queues a test delivery for each registered webhook endpoint for the current tenant",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/webhooks/test",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"eventType\": \"score.completed\",\n    \"payload\": {\n        \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n        \"evidence_ref\": \"ev_01HXYZ9ABCD123456789\"\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"queued\": 2\n}"
        }
    }
}

Internal Event Ingestion

apps/api/src/routes/v1/events.ts

The route module is registered at /v1/events, and its handler writes an audit event with action: "event.ingest". The body schema is named eventSchema, but its explicit fields are not shown in the provided file context.

POST /v1/events

Regional API Surfaces

US Regional Surface

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

The US route module is mounted under /api/v1/us. It uses the same middleware stack as the admin routes, but many handlers add access-token validation, consent checks, purpose checks, category checks, connection-state checks, and webhook side effects before returning data.

POST /api/v1/us/consents

{
    "title": "Create US Consent",
    "description": "Creates a consent and returns the authorization URL for the US regional surface",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/consents",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"applicant_id\": \"applicant_12345\",\n    \"purpose\": \"LENDING_UNDERWRITING\",\n    \"data_categories\": [\n        \"ACCOUNTS\",\n        \"BALANCES\",\n        \"TRANSACTIONS\"\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": "Created",
            "body": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"authorization_url\": \"https://api.joinlita.com/api/v1/us/consents/consent_01HXYZ9ABCD123456789/authorize\",\n    \"redirect_url\": \"https://api.joinlita.com/api/v1/us/consents/consent_01HXYZ9ABCD123456789/authorize\",\n    \"status\": \"PENDING\",\n    \"expires_at\": \"2025-04-01T12:30:00.000Z\"\n}"
        },
        "401": {
            "description": "Unauthorized",
            "body": "{\n    \"error\": {\n        \"code\": \"unauthorized\",\n        \"message\": \"Authorization: Bearer <PARTNER_API_KEY> is required\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

GET /api/v1/us/consents/:consentId

{
    "title": "Get US Consent",
    "description": "Returns the consent state, connection list, and activation status for the given consent",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/:consentId",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "consentId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"status\": \"ACTIVE\",\n    \"applicant_id\": \"applicant_12345\",\n    \"purpose\": \"LENDING_UNDERWRITING\",\n    \"activated_at\": \"2025-03-01T12:30:00.000Z\",\n    \"expires_at\": \"2025-04-01T12:30:00.000Z\",\n    \"connections\": [\n        {\n            \"connection_id\": \"conn_01HXYZ9ABCD123456789\",\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        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

POST /api/v1/us/consents/:consentId/revoke

{
    "title": "Revoke US Consent",
    "description": "Revokes a consent and emits a consent.revoked webhook when the tenant is known",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/:consentId/revoke",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "consentId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"status\": \"REVOKED\"\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"not_found\",\n        \"message\": \"Consent not found\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

POST /api/v1/us/consents/:consentId/token

{
    "title": "Exchange US Consent Token",
    "description": "Exchanges an authorization code for access and refresh tokens",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/:consentId/token",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "consentId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"authorization_code\": \"auth_code_123456\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"access_token\": \"access_01HXYZ9ABCD123456789\",\n    \"refresh_token\": \"refresh_01HXYZ9ABCD123456789\",\n    \"expires_in\": 3600,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions\"\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"CONSENT_NOT_FOUND\",\n        \"message\": \"Consent not found\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

POST /api/v1/us/tokens/refresh

{
    "title": "Refresh US Access Token",
    "description": "Refreshes an access token and emits reauthentication webhooks when the refresh limit is exceeded",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/tokens/refresh",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"refresh_token\": \"refresh_01HXYZ9ABCD123456789\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"access_token\": \"access_01HXYZ9ABCD123456789\",\n    \"refresh_token\": \"refresh_01HXYZ9ABCD123456789\",\n    \"expires_in\": 3600,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions\"\n}"
        },
        "400": {
            "description": "Refresh not allowed",
            "body": "{\n    \"error\": {\n        \"code\": \"PROVIDER_UNAVAILABLE\",\n        \"message\": \"Refresh not allowed\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        },
        "401": {
            "description": "Consent revoked",
            "body": "{\n    \"error\": {\n        \"code\": \"CONSENT_REVOKED\",\n        \"message\": \"Refresh not allowed\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

POST /api/v1/us/tokens/introspect

{
    "title": "Introspect US Access Token",
    "description": "Introspects a US access token through the US service helper",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/tokens/introspect",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"token\": \"access_01HXYZ9ABCD123456789\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"active\": true,\n    \"expires_at\": \"2025-03-01T13:30:00.000Z\",\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"purpose\": \"LENDING_UNDERWRITING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\"\n    ]\n}"
        }
    }
}

GET /api/v1/us/data/accounts

{
    "title": "Get US Accounts",
    "description": "Returns account data for the access token consent and refreshes the connection when possible",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/data/accounts",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"accounts\": [\n        {\n            \"account_id\": \"acc_01HXYZ9ABCD123456789\",\n            \"name\": \"Operating Checking\",\n            \"type\": \"checking\",\n            \"mask\": \"1234\",\n            \"institution\": \"Fin Bank\"\n        }\n    ]\n}"
        }
    }
}

GET /api/v1/us/data/balances

{
    "title": "Get US Balances",
    "description": "Returns account balances for the access token consent",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/data/balances",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"balances\": [\n        {\n            \"account_id\": \"acc_01HXYZ9ABCD123456789\",\n            \"available\": 1520.55,\n            \"current\": 1625.55,\n            \"currency\": \"USD\"\n        }\n    ]\n}"
        }
    }
}

GET /api/v1/us/data/transactions

{
    "title": "Get US Transactions",
    "description": "Returns transaction rows for the access token consent after purpose and category checks",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/data/transactions",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "name": "start_date",
            "type": "string",
            "required": false
        },
        {
            "name": "end_date",
            "type": "string",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"transactions\": [\n        {\n            \"transaction_id\": \"txn_01HXYZ9ABCD123456789\",\n            \"account_id\": \"acc_01HXYZ9ABCD123456789\",\n            \"posted_at\": \"2025-03-01T12:00:00.000Z\",\n            \"amount\": -84.12,\n            \"currency\": \"USD\",\n            \"description\": \"Coffee Roasters\",\n            \"category\": \"Food and Drink\"\n        }\n    ]\n}"
        }
    }
}

GET /api/v1/us/data/income

{
    "title": "Get US Income",
    "description": "Returns income aggregates for the access token consent",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/data/income",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"method\": \"income\",\n    \"gross_monthly\": 7200,\n    \"net_monthly\": 5600,\n    \"currency\": \"USD\"\n}"
        }
    }
}

POST /api/v1/us/features/compute

{
    "title": "Compute US Features",
    "description": "Computes cashflow features. When consent_id is included the handler uses partner-auth mode and returns a queued job response; without consent_id it follows access-token mode and can return an evidence snapshot directly.",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/features/compute",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"feature_set\": \"US_CASHFLOW_V1\",\n    \"as_of\": \"2025-03-01T12:30:00.000Z\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "202": {
            "description": "Queued job",
            "body": "{\n    \"job_id\": \"job_7c1f3d4a9b2e\",\n    \"status\": \"PROCESSING\",\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"estimated_completion_ms\": 0\n}"
        },
        "200": {
            "description": "Computed snapshot",
            "body": "{\n    \"evidence_ref\": \"ev_01HXYZ9ABCD123456789\",\n    \"features\": {\n        \"monthly_income\": 5600,\n        \"avg_balance\": 1625.55,\n        \"overdraft_count\": 0,\n        \"cashflow_surplus\": 1180.44,\n        \"cashflow_inflow\": 8420.44,\n        \"cashflow_outflow\": 7240,\n        \"cashflow_net\": 1180.44\n    }\n}"
        }
    }
}

GET /api/v1/us/consents/:consentId/authorize

{
    "title": "Authorize US Consent",
    "description": "Completes authorization for a consent that is still valid and returns an authorization code for token exchange",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/:consentId/authorize",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "consentId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"purpose\": \"LENDING_UNDERWRITING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\"\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}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"consent_not_found\",\n        \"message\": \"Consent not found\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        },
        "409": {
            "description": "Expired or revoked",
            "body": "{\n    \"error\": {\n        \"code\": \"consent_revoked\",\n        \"message\": \"Consent has expired\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

GET /api/v1/us/consents/:consentId/receipt

{
    "title": "US Consent Receipt",
    "description": "Returns the immutable receipt view for a consent",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/:consentId/receipt",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "consentId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"purpose\": \"LENDING_UNDERWRITING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\"\n    ],\n    \"disclosure_version\": \"2025-03\",\n    \"status\": \"ACTIVE\",\n    \"created_at\": \"2025-03-01T12:00:00.000Z\",\n    \"revoked_at\": null\n}"
        }
    }
}

GET /api/v1/us/status/:jobId

{
    "title": "US Feature Job Status",
    "description": "Returns the in-memory job status for a US feature-compute job",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/status/:jobId",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "jobId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"job_id\": \"job_7c1f3d4a9b2e\",\n    \"status\": \"COMPLETE\",\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"completed_at\": \"2025-03-01T12:30:00.000Z\",\n    \"error\": null\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"not_found\",\n        \"message\": \"Job not found\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

JP Regional Surface

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

The JP route module is mounted under /api/v1/jp. Its handlers mirror the US surface but call the JP-specific service helpers and emit JP-specific snapshots and token responses.

POST /api/v1/jp/consents

{
    "title": "Create JP Consent",
    "description": "Creates a consent and returns the authorization URL for the JP regional surface",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/consents",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"applicant_id\": \"applicant_12345\",\n    \"purpose\": \"ACCOUNT_OPENING\",\n    \"data_categories\": [\n        \"ACCOUNTS\",\n        \"BALANCES\",\n        \"TRANSACTIONS\"\n    ],\n    \"expires_in_days\": 30,\n    \"refresh_permissions\": {\n        \"enabled\": true,\n        \"max_refresh_per_day\": 3\n    },\n    \"user\": {\n        \"country\": \"JP\"\n    },\n    \"appi_provision\": {\n        \"purpose\": \"Open banking consent\",\n        \"consent_method\": \"web\"\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"authorization_url\": \"https://api.joinlita.com/api/v1/jp/consents/consent_01HXYZ9ABCD123456789/authorize\",\n    \"redirect_url\": \"https://api.joinlita.com/api/v1/jp/consents/consent_01HXYZ9ABCD123456789/authorize\",\n    \"status\": \"PENDING\",\n    \"expires_at\": \"2025-04-01T12:30:00.000Z\"\n}"
        },
        "401": {
            "description": "Unauthorized",
            "body": "{\n    \"error\": {\n        \"code\": \"unauthorized\",\n        \"message\": \"Authorization: Bearer <PARTNER_API_KEY> is required\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

GET /api/v1/jp/consents/:consentId

{
    "title": "Get JP Consent",
    "description": "Returns the consent state, connection list, and activation status for the given JP consent",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/consents/:consentId",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "consentId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"status\": \"ACTIVE\",\n    \"applicant_id\": \"applicant_12345\",\n    \"purpose\": \"ACCOUNT_OPENING\",\n    \"activated_at\": \"2025-03-01T12:30:00.000Z\",\n    \"expires_at\": \"2025-04-01T12:30:00.000Z\",\n    \"connections\": [\n        {\n            \"connection_id\": \"conn_01HXYZ9ABCD123456789\",\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        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

GET /api/v1/jp/consents/:consentId/authorize

{
    "title": "Authorize JP Consent",
    "description": "Completes authorization for a valid JP consent and returns an authorization code",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/consents/:consentId/authorize",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "consentId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"purpose\": \"ACCOUNT_OPENING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\"\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}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"consent_not_found\",\n        \"message\": \"Consent not found\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        },
        "409": {
            "description": "Expired or revoked",
            "body": "{\n    \"error\": {\n        \"code\": \"consent_revoked\",\n        \"message\": \"Consent has expired\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

GET /api/v1/jp/consents/:consentId/receipt

{
    "title": "JP Consent Receipt",
    "description": "Returns the immutable receipt view for a JP consent including APPI provision metadata",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/consents/:consentId/receipt",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "consentId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"purpose\": \"ACCOUNT_OPENING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\"\n    ],\n    \"disclosure_version\": \"2025-03\",\n    \"status\": \"ACTIVE\",\n    \"created_at\": \"2025-03-01T12:00:00.000Z\",\n    \"revoked_at\": null,\n    \"appi_provision\": {\n        \"purpose\": \"Open banking consent\",\n        \"consent_method\": \"web\"\n    }\n}"
        }
    }
}

POST /api/v1/jp/consents/:consentId/token

{
    "title": "Exchange JP Consent Token",
    "description": "Exchanges a JP authorization code for access and refresh tokens",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/consents/:consentId/token",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "name": "consentId",
            "type": "string",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"authorization_code\": \"auth_code_123456\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"access_token\": \"access_01HXYZ9ABCD123456789\",\n    \"refresh_token\": \"refresh_01HXYZ9ABCD123456789\",\n    \"expires_in\": 3600,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions\"\n}"
        },
        "404": {
            "description": "Not found",
            "body": "{\n    \"error\": {\n        \"code\": \"CONSENT_NOT_FOUND\",\n        \"message\": \"Consent not found\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

POST /api/v1/jp/tokens/refresh

{
    "title": "Refresh JP Access Token",
    "description": "Refreshes a JP access token and emits reauthentication webhooks when the refresh limit is exceeded",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/tokens/refresh",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"refresh_token\": \"refresh_01HXYZ9ABCD123456789\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"access_token\": \"access_01HXYZ9ABCD123456789\",\n    \"refresh_token\": \"refresh_01HXYZ9ABCD123456789\",\n    \"expires_in\": 3600,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions\"\n}"
        },
        "400": {
            "description": "Refresh not allowed",
            "body": "{\n    \"error\": {\n        \"code\": \"PROVIDER_UNAVAILABLE\",\n        \"message\": \"Refresh not allowed\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        },
        "401": {
            "description": "Consent revoked",
            "body": "{\n    \"error\": {\n        \"code\": \"CONSENT_REVOKED\",\n        \"message\": \"Refresh not allowed\",\n        \"request_id\": \"req_01HXYZ9ABCD123456789\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

POST /api/v1/jp/tokens/introspect

{
    "title": "Introspect JP Access Token",
    "description": "Introspects a JP access token through the JP service helper",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/tokens/introspect",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"token\": \"access_01HXYZ9ABCD123456789\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"active\": true,\n    \"expires_at\": \"2025-03-01T13:30:00.000Z\",\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"purpose\": \"ACCOUNT_OPENING\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\"\n    ]\n}"
        }
    }
}

GET /api/v1/jp/data/accounts

{
    "title": "Get JP Accounts",
    "description": "Returns account data for the JP access token consent and refreshes the connection when possible",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/data/accounts",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"accounts\": [\n        {\n            \"account_id\": \"acc_01HXYZ9ABCD123456789\",\n            \"name\": \"Operating Checking\",\n            \"type\": \"checking\",\n            \"mask\": \"1234\",\n            \"institution\": \"Fin Bank JP\"\n        }\n    ]\n}"
        }
    }
}

GET /api/v1/jp/data/balances

{
    "title": "Get JP Balances",
    "description": "Returns account balances for the JP access token consent",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/data/balances",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"balances\": [\n        {\n            \"account_id\": \"acc_01HXYZ9ABCD123456789\",\n            \"available\": 1520.55,\n            \"current\": 1625.55,\n            \"currency\": \"JPY\"\n        }\n    ]\n}"
        }
    }
}

GET /api/v1/jp/data/transactions

{
    "title": "Get JP Transactions",
    "description": "Returns transaction rows for the JP access token consent after purpose and category checks",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/data/transactions",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "name": "start_date",
            "type": "string",
            "required": false
        },
        {
            "name": "end_date",
            "type": "string",
            "required": false
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"transactions\": [\n        {\n            \"transaction_id\": \"txn_01HXYZ9ABCD123456789\",\n            \"account_id\": \"acc_01HXYZ9ABCD123456789\",\n            \"posted_at\": \"2025-03-01T12:00:00.000Z\",\n            \"amount\": -8400,\n            \"currency\": \"JPY\",\n            \"description\": \"Coffee Roasters\",\n            \"category\": \"Food and Drink\"\n        }\n    ]\n}"
        }
    }
}

GET /api/v1/jp/data/income

{
    "title": "Get JP Income",
    "description": "Returns income aggregates for the JP access token consent",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/data/income",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"method\": \"income\",\n    \"gross_monthly\": 720000,\n    \"net_monthly\": 560000,\n    \"currency\": \"JPY\"\n}"
        }
    }
}

POST /api/v1/jp/features/compute

{
    "title": "Compute JP Features",
    "description": "Computes cashflow features. When consent_id is included the handler uses partner-auth mode and returns a queued job response; without consent_id it follows access-token mode and can return an evidence snapshot directly.",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/features/compute",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"feature_set\": \"JP_CASHFLOW_V1\",\n    \"as_of\": \"2025-03-01T12:30:00.000Z\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "202": {
            "description": "Queued job",
            "body": "{\n    \"job_id\": \"job_7c1f3d4a9b2e\",\n    \"status\": \"PROCESSING\",\n    \"consent_id\": \"consent_01HXYZ9ABCD123456789\",\n    \"estimated_completion_ms\": 0\n}"
        },
        "200": {
            "description": "Computed snapshot",
            "body": "{\n    \"evidence_ref\": \"ev_01HXYZ9ABCD123456789\",\n    \"features\": {\n        \"monthly_income\": 560000,\n        \"avg_balance\": 1625.55,\n        \"overdraft_count\": 0,\n        \"cashflow_surplus\": 118044,\n        \"cashflow_inflow\": 842044,\n        \"cashflow_outflow\": 724000,\n        \"cashflow_net\": 118044\n    }\n}"
        }
    }
}

Feature Flows

API Bootstrapping and Route Mounting

sequenceDiagram
    participant Entry as apps api src index ts
    participant Server as buildServer
    participant OTel as initOtel
    participant Fastify as Fastify
    participant Plugins as Middleware and plugins
    participant Routes as Route modules
    participant Listen as server listen

    Entry->>Server: buildServer
    Server->>OTel: initOtel
    Server->>Fastify: create app with logger and body limit
    Fastify->>Plugins: register cors helmet rateLimit auth tenant idempotency audit
    Fastify->>Routes: register v1 us jp routes
    Fastify->>Fastify: add healthz readyz openapi handlers
    Entry->>Listen: listen on port and host
    Listen-->>Entry: api listening

Authenticated Request Path

sequenceDiagram
    participant Client as API Client
    participant Auth as authPlugin
    participant Tenant as tenantPlugin
    participant Audit as auditPlugin
    participant Route as Route Handler
    participant Webhooks as webhook service

    Client->>Auth: request with Authorization and X Request Id
    Auth->>Auth: reject public path or validate header set
    Auth->>Auth: resolveApiKey verifyJwt verifyUsAccessToken verifyJpAccessToken
    Auth-->>Tenant: request.auth and optional regional access context
    Tenant->>Tenant: set request.tenantId from request.auth
    Tenant-->>Audit: decorated request object
    Audit-->>Route: request.logAuditEvent available
    Route->>Webhooks: optional enqueueWebhookDelivery
    Route-->>Client: response

Background Worker Delivery Loop

sequenceDiagram
    participant Worker as apps worker src index ts
    participant DB as prisma
    participant Delivery as processDelivery

    Worker->>Worker: run
    loop every poll interval
        Worker->>DB: find deliveries with pending or retrying status
        DB-->>Worker: due deliveries
        Worker->>Delivery: processDelivery delivery id
        Delivery-->>Worker: completion or error
    end

Background Worker

Background Process Responsibility

apps/worker/src/index.ts

The worker is a separate long-running process from the API. It does not listen on a port; instead it loops forever and processes due deliveries.

File Responsibility
apps/worker/src/index.ts Imports persistence and delivery helpers, polls for due deliveries, and runs the delivery loop.
apps/worker/Dockerfile Builds the worker bundle and starts node dist/index.js.
apps/worker/package.json Defines dev, build, lint, and test scripts for the worker process.
apps/worker/tsconfig.json Compiles src to dist using the workspace TypeScript baseline.

apps/worker/src/index.ts

Imported Symbol Source Role
prisma @lita/db Used to query due webhook deliveries.
signWebhook @lita/webhooks Imported as part of the delivery pipeline.
recordAuditEvent @lita/compliance Imported for compliance-oriented side effects.

Runtime Loop

Step Behavior
1 run() starts immediately at module load.
2 pollDeliveries() selects deliveries whose status is pending or retrying.
3 Deliveries are limited to take: 10 and must have nextRetryAt unset or due.
4 Each selected delivery is passed to processDelivery(delivery.id).
5 Errors are logged with console.error("worker poll failed", error).
6 The worker waits for POLL_INTERVAL_MS and then repeats.

apps/worker/package.json

Script Command Responsibility
dev node --watch --loader ts-node/esm/transpile-only src/index.ts Runs the worker entry point in watch mode.
build tsc -p tsconfig.json Produces the worker build.
lint eslint src --max-warnings=0 Lints worker source.
test vitest Runs worker tests.

apps/worker/Dockerfile

Stage Behavior
build Installs workspace dependencies and runs the worker TypeScript build.
runtime Copies only dist and package.json, sets NODE_ENV=production, and runs node dist/index.js.

apps/worker/tsconfig.json

Option Value Effect
extends ../../tsconfig.base.json Inherits workspace compiler rules.
rootDir src Builds from the worker source folder.
outDir dist Emits runtime JavaScript to dist.
types ["node"] Uses Node.js types.
include ["src"] Compiles the worker source tree.

Process Model

Foreground API Process

The API process is the synchronous surface for tenant administration, consent lifecycle management, regional data access, and audit emission. It is containerized to run as a single Node.js server process on port 3000, with OpenTelemetry and logging initialized before any route handlers can execute.

Background Worker Process

The worker process is the asynchronous complement to the API. It is optimized for polling and delivery processing rather than request latency. The absence of a listen step is intentional: all work happens in the polling loop.

Package and Container Boundaries

Artifact API Process Worker Process
Entry file apps/api/src/index.ts apps/worker/src/index.ts
Build output apps/api/dist apps/worker/dist
Container port 3000 none exposed
Runtime command node dist/index.js node dist/index.js
Build tool pnpm -C apps/api build pnpm -C apps/worker build

Dependencies

External Packages

Package Usage
fastify HTTP server and route registration.
@fastify/cors CORS middleware.
@fastify/helmet Security headers.
@fastify/rate-limit Request throttling.
fastify-type-provider-zod Zod-backed validation and serialization.
zod Request and response schemas.
pino Logging backend used through buildLogger.
@lita/observability OpenTelemetry bootstrap and logger factory.
@lita/auth API key, JWT, and access-token verification.
@lita/core Tenant and credit profile persistence used by admin routes.
@lita/webhooks Webhook endpoint and delivery helpers.
@lita/compliance Audit event recording.
@lita/db Persistence access used by the worker.
jose Declared API dependency for JWT-related work.

Internal Dependencies

Module Role
apps/api/src/plugins/auth.ts Authentication and request context setup.
apps/api/src/plugins/tenant.ts Tenant decoration.
apps/api/src/plugins/audit.ts Audit logging decoration.
apps/api/src/services/authz.ts Scope enforcement helper.
apps/api/src/routes/v1/index.ts Mounts admin route families.
apps/api/src/routes/us/index.ts US regional surface.
apps/api/src/routes/jp/index.ts JP regional surface.

Key Classes Reference

Class Responsibility
index.ts API process entry point and listener startup.
server.ts Fastify bootstrap, middleware ordering, and route registration.
auth.ts Request authentication and bearer-token resolution.
tenant.ts Tenant ID decoration from authenticated context.
audit.ts Audit-event decoration and compliance logging.
authz.ts Scope guard helper.
v1/index.ts Admin route registration.
v1/auth.ts Token introspection route.
v1/tenants.ts Tenant admin routes.
v1/credit-profiles.ts Credit profile admin routes.
v1/webhooks.ts Webhook endpoint administration.
v1/events.ts Internal event ingestion.
us/index.ts US consent and data access surface.
jp/index.ts JP consent and data access surface.
worker/src/index.ts Background delivery polling loop.
api/Dockerfile API container build and runtime image.
worker/Dockerfile Worker container build and runtime image.
api/tsconfig.json API TypeScript build settings.
worker/tsconfig.json Worker TypeScript build settings.