Authentication and Authorization Domain

Overview

This domain covers how Dwilar/lita-api authenticates requests, distinguishes partner tokens from regional access tokens, and enforces authorization at the route level. The Fastify request pipeline accepts a Bearer token, resolves it into request.auth, and then lets route handlers decide whether the caller is a partner, an end-user access token, or a scoped internal caller.

The domain also includes token lifecycle endpoints in the US and JP surfaces: authorization code issuance, token exchange, refresh, and introspection. Those flows are backed by consent state in PostgreSQL and JWT signing and verification in the API process, while services/token-service/Dockerfile defines a separate deployable runtime boundary for token-service.

Architecture Overview

flowchart TB
    Client[Bearer client]

    subgraph APIProcess [Fastify API process]
        AuthPlugin[authPlugin onRequest]
        V1Auth[authRoutes token introspect]
        V1Index[registerV1Routes]
        ScopeGuard[requireScope]
        TenantsRoutes[tenantsRoutes]
        EventsRoutes[eventsRoutes]
        USRoutes[US regional token routes]
        JPRoutes[JP regional token routes]
        PartnerGuard[requirePartnerAuth]
        AccessGuard[requireAccessToken]
    end

    subgraph DataLayer [Persistence and token crypto]
        PrismaDB[Prisma PostgreSQL]
        JoseJWT[jose sign and verify]
    end

    subgraph TokenBoundary [Token service deployment boundary]
        TokenImage[services token-service Dockerfile]
    end

    Client --> AuthPlugin
    AuthPlugin --> V1Index
    V1Index --> V1Auth
    V1Index --> TenantsRoutes
    V1Index --> EventsRoutes
    V1Index --> USRoutes
    V1Index --> JPRoutes

    TenantsRoutes --> ScopeGuard
    EventsRoutes --> ScopeGuard

    USRoutes --> PartnerGuard
    USRoutes --> AccessGuard
    JPRoutes --> PartnerGuard
    JPRoutes --> AccessGuard

    USRoutes --> JoseJWT
    JPRoutes --> JoseJWT
    USRoutes --> PrismaDB
    JPRoutes --> PrismaDB

Request Authentication Guard

apps/api/src/plugins/auth.ts

[!NOTE] The POST /api/v1/auth/token/introspect handler does not introspect the submitted token value. It returns active as Boolean(body.token) and echoes the current request.auth context. That means the endpoint is a request-context probe, not a validation of the body token itself.

This plugin runs on every non-public request before route handlers execute. It requires x-request-id, reads the Authorization header, and then resolves the Bearer token in a fixed order: API key, JWT, US access token, JP access token.

Module state

Property Type Description
publicPaths Set<string> Paths excluded from auth and request ID enforcement: /healthz, /readyz, /openapi.json, and any route starting with /docs.

Fastify request augmentation

Property Type Description
auth `AuthContext \ undefined`
usAccess `UsAccessContext \ undefined`
jpAccess `JpAccessContext \ undefined`

Authorization resolution order

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

What the guard enforces

  • Rejects requests without a non-empty x-request-id header with a 400 response.
  • Rejects requests without a valid Bearer token with a 401 response.
  • Treats US and JP access tokens as client tokens by setting:
    • request.auth.tenantId
    • request.auth.actorType = "client"
    • request.auth.actorId = consentId
    • request.auth.scopes = dataCategories
  • Leaves public health and docs endpoints unguarded.
sequenceDiagram
    participant Client
    participant Guard as authPlugin
    participant Resolver as token resolvers
    participant Route as route handler

    Client->>Guard: Bearer request with x-request-id
    Guard->>Guard: Check public path and request id
    Guard->>Resolver: resolveApiKey
    Resolver-->>Guard: api key context or null
    Guard->>Resolver: verifyJwt
    Resolver-->>Guard: jwt context or null
    Guard->>Resolver: verifyUsAccessToken
    Resolver-->>Guard: US access context or null
    Guard->>Resolver: verifyJpAccessToken
    Resolver-->>Guard: JP access context or null
    Guard-->>Route: request.auth plus optional access context

V1 Auth Token Introspection

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

authRoutes exposes a single introspection endpoint under the v1 auth namespace. It is mounted by registerV1Routes at /v1/auth, which places the full path at /api/v1/auth/token/introspect in the API surface used by the local smoke scripts.

Public methods

Method Description
authRoutes Registers the v1 auth token introspection endpoint.

Token introspection response model

Property Type Description
active boolean true when the submitted request body contains a non-empty token string.
tenantId `string \ undefined`
scopes string[] The scopes from the current authenticated request context, or an empty array.

Introspect Request Auth Context

{
    "title": "Introspect Request Auth Context",
    "description": "Returns the current request auth context together with a boolean derived from the submitted token string",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/auth/token/introspect",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "x-request-id",
            "value": "smoke-check",
            "required": true
        },
        {
            "key": "content-type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example\"\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}"
        }
    }
}

V1 Route Registration

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

[!WARNING] The handler does not verify the submitted token against any key, database record, or signature. It returns active solely from Boolean(body.token) and mirrors request.auth?.tenantId plus request.auth?.scopes.

registerV1Routes centralizes the v1 mount points and creates the namespace used by the auth-related routes and the scope-protected administrative surfaces.

Public methods

Method Description
registerV1Routes Registers the v1 route modules and their prefixes.

Registered route modules

Route module Prefix
authRoutes /v1/auth
tenantsRoutes /v1/tenants
creditProfilesRoutes /v1/credit-profiles
decisionsRoutes /v1/decisions
webhooksRoutes /v1/webhooks
eventsRoutes /v1/events

Authorization Scope Enforcement

apps/api/src/services/authz.ts

requireScope is the scope gate used by v1 route handlers that need explicit permission checks beyond simple authentication. It reads the caller’s scopes from request.auth and throws a 403 error when the required scope is missing.

Public methods

Method Description
requireScope Checks whether request.auth.scopes includes the requested scope and throws a forbidden error when it does not.

Scope check behavior

  • Reads request.auth?.scopes ?? []
  • Compares the array with the requested scope string using includes
  • Throws Error("forbidden")
  • Attaches statusCode = 403 to the thrown error

Scope-protected v1 surfaces

Route module Prefix Scope enforcement intent
tenantsRoutes /v1/tenants Administrative tenant operations guarded by admin:tenants.
eventsRoutes /v1/events Internal event surfaces guarded by internal:events.
sequenceDiagram
    participant Client
    participant Guard as authPlugin
    participant Route as v1 scope protected route
    participant Scope as requireScope

    Client->>Guard: Bearer request with x-request-id
    Guard-->>Route: request.auth set
    Route->>Scope: requireScope(request, scope)
    alt scope present
        Scope-->>Route: continue
        Route-->>Client: 200 response
    else scope missing
        Scope-->>Route: throws forbidden
        Route-->>Client: 403 forbidden
    end

Regional Token Exchange, Refresh, and Introspection

The US and JP route modules implement the regional authorization-code-style flow, refresh flow, and token introspection flow. In both regions, the endpoints are protected by the global auth plugin plus either requirePartnerAuth or requireAccessToken, depending on whether the route expects a partner token or an end-user access token.

US token flow types

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

UsAccessContext
Property Type Description
consentId string Consent identifier bound to the access token.
tenantId string Tenant identifier embedded in the access token.
purpose ConsentPurpose Purpose claim for the consent.
dataCategories DataCategory[] Categories carried in the access token and exposed as request.auth.scopes.
RefreshPermissions
Property Type Description
enabled boolean Controls whether refresh is allowed.
max_refresh_per_day number Daily refresh cap used by refresh limiting logic.
RefreshTokenRecord
Property Type Description
token string Stored refresh token string.
consentId string Consent associated with the refresh token.
tenantId string Tenant associated with the refresh token.
expiresAt Date Refresh token expiry timestamp.

Token claim values

  • 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

Regional token responses

Property Type Description
access_token string RS256 JWT signed with the regional private key.
refresh_token string Opaque refresh token string stored in PostgreSQL.
expires_in number Access token lifetime in seconds.
token_type string Always Bearer.
scope string Space-delimited list of consent data categories.

US authorization code exchange

{
    "title": "Exchange US Consent Token",
    "description": "Exchanges a consent identifier for a regional access token and refresh token after partner authentication",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/:consentId/token",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner-token>",
            "required": true
        },
        {
            "key": "x-request-id",
            "value": "smoke-check",
            "required": true
        },
        {
            "key": "content-type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consentId",
            "value": "cons_1234567890",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"authorization_code\": \"ok\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"access_token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example\",\n    \"refresh_token\": \"rtk_7f7d3c4d-2d19-4bb8-8d7f-4c0f2fdf7f21\",\n    \"expires_in\": 900,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions income cashflow_features\"\n}"
        },
        "404": {
            "description": "Consent not found"
        }
    }
}

US token refresh

{
    "title": "Refresh US Access Token",
    "description": "Refreshes a US access token using a stored refresh token and partner authentication",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/tokens/refresh",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner-token>",
            "required": true
        },
        {
            "key": "x-request-id",
            "value": "smoke-check",
            "required": true
        },
        {
            "key": "content-type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"refresh_token\": \"rtk_7f7d3c4d-2d19-4bb8-8d7f-4c0f2fdf7f21\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"access_token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example\",\n    \"refresh_token\": \"rtk_7f7d3c4d-2d19-4bb8-8d7f-4c0f2fdf7f21\",\n    \"expires_in\": 900,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions income cashflow_features\"\n}"
        },
        "400": {
            "description": "Refresh not allowed"
        },
        "401": {
            "description": "Consent revoked or expired"
        }
    }
}

US token introspection

{
    "title": "Introspect US Access Token",
    "description": "Validates a US access token against the regional signing keys and consent state",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/tokens/introspect",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner-token>",
            "required": true
        },
        {
            "key": "x-request-id",
            "value": "smoke-check",
            "required": true
        },
        {
            "key": "content-type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"active\": true,\n    \"expires_at\": \"2026-03-31T12:00:00.000Z\",\n    \"consent_id\": \"cons_1234567890\",\n    \"purpose\": \"PERSONAL_FINANCE\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\"\n    ]\n}"
        }
    }
}

US authorization endpoint

{
    "title": "Authorize US Consent",
    "description": "Returns the consent metadata and a fixed authorization code when the consent is active and not expired",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/us/consents/:consentId/authorize",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "x-request-id",
            "value": "smoke-check",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consentId",
            "value": "cons_1234567890",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"cons_1234567890\",\n    \"purpose\": \"PERSONAL_FINANCE\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\",\n        \"income\",\n        \"cashflow_features\"\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": "Consent not found"
        },
        "409": {
            "description": "Consent revoked or expired"
        }
    }
}

US token flow execution rules

[!NOTE] The body field authorization_code is validated by schema but never read by exchangeConsentToken. The handler exchanges based on consentId and partner authentication.

  • requirePartnerAuth rejects access-token mode with 401 TOKEN_NOT_ALLOWED.
  • requireAccessToken rejects non-access-token requests with 401 ACCESS_TOKEN_REQUIRED.
  • ensurePurpose and ensureCategory execute before data access.
  • exchangeConsentToken signs the JWT with:
    • tenantId
    • consentId
    • purpose
    • dataCategories
    • scope
  • refreshAccessToken:
    • checks refresh token ownership by tenantId
    • checks consent status and expiry
    • enforces refreshPermissions.enabled
    • enforces max_refresh_per_day
    • marks connections REAUTH_REQUIRED when the daily limit is hit
  • introspectToken:
    • verifies the JWT signature, issuer, and audience
    • checks consent revocation and consent expiry
    • returns active: false when the key is missing or verification fails

JP token flow types

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

JpAccessContext
Property Type Description
consentId string Consent identifier bound to the access token.
tenantId string Tenant identifier embedded in the access token.
purpose JpConsentPurpose Purpose claim for the consent.
dataCategories JpDataCategory[] Categories carried in the access token and exposed as request.auth.scopes.
JpRefreshPermissions
Property Type Description
enabled boolean Controls whether refresh is allowed.
max_refresh_per_day number Daily refresh cap used by refresh limiting logic.
JpEvidenceSnapshot
Property Type Description
evidenceRef string Snapshot identifier.
consentId string Consent associated with the evidence snapshot.
computedAt Date Snapshot computation timestamp.
featureSet "JP_CASHFLOW_V1" Feature set label for JP evidence.
features Record<string, number> Computed feature values.

JP authorization code exchange

{
    "title": "Exchange JP Consent Token",
    "description": "Exchanges a consent identifier for a JP regional access token and refresh token after partner authentication",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/consents/:consentId/token",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner-token>",
            "required": true
        },
        {
            "key": "x-request-id",
            "value": "smoke-check",
            "required": true
        },
        {
            "key": "content-type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consentId",
            "value": "cons_1234567890",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"authorization_code\": \"ok\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"access_token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example\",\n    \"refresh_token\": \"rtk_7f7d3c4d-2d19-4bb8-8d7f-4c0f2fdf7f21\",\n    \"expires_in\": 900,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions income cashflow_features\"\n}"
        },
        "404": {
            "description": "Consent not found"
        }
    }
}

JP token refresh

{
    "title": "Refresh JP Access Token",
    "description": "Refreshes a JP access token using a stored refresh token and partner authentication",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/tokens/refresh",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner-token>",
            "required": true
        },
        {
            "key": "x-request-id",
            "value": "smoke-check",
            "required": true
        },
        {
            "key": "content-type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"refresh_token\": \"rtk_7f7d3c4d-2d19-4bb8-8d7f-4c0f2fdf7f21\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"access_token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example\",\n    \"refresh_token\": \"rtk_7f7d3c4d-2d19-4bb8-8d7f-4c0f2fdf7f21\",\n    \"expires_in\": 900,\n    \"token_type\": \"Bearer\",\n    \"scope\": \"accounts balances transactions income cashflow_features\"\n}"
        },
        "400": {
            "description": "Refresh not allowed"
        },
        "401": {
            "description": "Consent revoked or expired"
        }
    }
}

JP token introspection

{
    "title": "Introspect JP Access Token",
    "description": "Validates a JP access token against the regional signing keys and consent state",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/tokens/introspect",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <partner-token>",
            "required": true
        },
        {
            "key": "x-request-id",
            "value": "smoke-check",
            "required": true
        },
        {
            "key": "content-type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"active\": true,\n    \"expires_at\": \"2026-03-31T12:00:00.000Z\",\n    \"consent_id\": \"cons_1234567890\",\n    \"purpose\": \"PERSONAL_FINANCE\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\"\n    ]\n}"
        }
    }
}

JP authorization endpoint

{
    "title": "Authorize JP Consent",
    "description": "Returns the consent metadata and a fixed authorization code when the consent is active and not expired",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/jp/consents/:consentId/authorize",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "x-request-id",
            "value": "smoke-check",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "consentId",
            "value": "cons_1234567890",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"cons_1234567890\",\n    \"purpose\": \"PERSONAL_FINANCE\",\n    \"data_categories\": [\n        \"accounts\",\n        \"balances\",\n        \"transactions\",\n        \"income\",\n        \"cashflow_features\"\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": "Consent not found"
        },
        "409": {
            "description": "Consent revoked or expired"
        }
    }
}

JP token flow execution rules

[!NOTE] The JP token exchange handler follows the same request-body pattern as the US version: authorization_code is required by schema but is not consumed by exchangeJpConsentToken.

  • requirePartnerAuth rejects access-token mode with 401 TOKEN_NOT_ALLOWED.
  • requireAccessToken rejects non-access-token requests with 401 ACCESS_TOKEN_REQUIRED.
  • exchangeJpConsentToken signs the JWT with the same claim shape as the US flow, using JP consent state.
  • refreshJpAccessToken enforces refresh limits and consent status checks before issuing a new access token.
  • introspectJpToken validates the JWT signature, issuer, audience, and consent state before returning active: true.
sequenceDiagram
    participant Partner
    participant Guard as authPlugin
    participant Route as US or JP route
    participant Flow as exchange refresh introspect
    participant DB as Prisma PostgreSQL
    participant JWT as jose

    Partner->>Guard: Bearer request with x-request-id
    Guard-->>Route: request.auth plus usAccess or jpAccess
    Route->>Route: requirePartnerAuth or requireAccessToken
    Route->>Flow: consentId or token
    Flow->>DB: read or write consent and refresh records
    Flow->>JWT: sign or verify token
    JWT-->>Flow: token or claims
    Flow-->>Route: response payload
    Route-->>Partner: JSON response

Token Service Deployment Boundary

services/token-service/Dockerfile

This Dockerfile packages token-service as a standalone Node 18 Alpine image. It installs production dependencies only, copies src, sets NODE_ENV=production, exposes port 8081, and starts the service with node src/index.js.

Build step Value Effect
Base image node:18-alpine Lightweight runtime for token-service.
Working directory /app Container root for the service.
Dependency install npm ci --omit=dev Installs only production dependencies.
Source copy COPY src ./src Bakes the runtime source into the image.
Environment NODE_ENV=production Production runtime mode.
Exposed port 8081 Dedicated listening port for the service.
Command node src/index.js Launches the token-service process.

This boundary matters because the visible regional token exchange, refresh, and introspection flows live in apps/api/src/routes/us/index.ts and apps/api/src/routes/jp/index.ts, while this Dockerfile defines a separate deployable artifact for token-service.

Operational Verification Scripts

scripts/check-all-api-paths.sh

This smoke script validates the auth boundary end to end in a local environment. It seeds dev auth, confirms the public endpoints, creates consents with a partner API key, exchanges consent tokens, exercises access-token routes, refreshes tokens, and introspects tokens.

Step Auth behavior verified
Seed dev auth Creates a usable API key for partner-authenticated requests.
Public checks Confirms healthz, readyz, and openapi.json remain public.
Consent creation Uses Authorization: Bearer ${API_KEY} plus x-request-id.
Token exchange Uses partner auth on `/api/v1/us
Data access Uses the returned access token on /data/* routes.
Refresh Uses partner auth on `/api/v1/us
Introspection Uses partner auth on `/api/v1/us

scripts/test-use-cases.sh

This script exercises the same auth boundary from user-case flows. It creates a consent, exchanges it for tokens, calls introspection and refresh with partner headers, then calls data routes with access headers.

Flow Header mode Purpose
Consent creation Partner header Create a consent record.
Token exchange Partner header Receive access and refresh tokens.
Receipt lookup Partner header Validate consent state.
Introspection Partner header Confirm the access token is accepted by the regional introspection endpoint.
Refresh Partner header Confirm refresh token rotation and renewal.
Data access Access header Confirm access-token-only routes accept the regional token.

Error Handling

Auth plugin errors

Status Code Trigger
400 invalid_request Missing or empty x-request-id.
401 unauthorized No valid Bearer token can be resolved.

Route-level auth and authorization errors

Status Code Trigger
401 TOKEN_NOT_ALLOWED Access-token mode used on a partner-only route.
401 ACCESS_TOKEN_REQUIRED Partner token or unresolved token used on an access-token route.
403 forbidden requireScope rejected a missing scope.
404 CONSENT_NOT_FOUND / not_found Consent or resource lookup failed.
409 consent_revoked Consent was revoked or expired before authorize or token exchange.
400 REFRESH_LIMIT_EXCEEDED / PROVIDER_UNAVAILABLE Refresh flow hit its daily cap or the upstream refresh path failed.

Behavioral notes

  • requireScope throws, rather than sending a reply directly.
  • requirePartnerAuth rejects any request that already resolved as request.usAccess or request.jpAccess.
  • requireAccessToken only accepts requests that resolved as access-token mode.
  • Regional token introspection returns active: false when public key retrieval fails, JWT verification fails, or consent state no longer permits access.

Dependencies

Dependency Role
fastify Request lifecycle and route registration.
fastify-plugin Wraps the auth plugin for Fastify decoration and hook registration.
zod Route schemas for body, params, querystring, and responses.
@lita/auth API key resolution and JWT verification used by the auth plugin.
@lita/db Consent, refresh token, and counter persistence for US and JP flows.
jose RS256 signing and verification for regional access tokens.
@lita/webhooks Webhook emission during consent activation, refresh limit handling, and revoke flows.
services/token-service/Dockerfile Separate deployment boundary for token-service runtime packaging.

Testing Considerations

  • Confirm every protected call includes x-request-id.
  • Verify partner-only routes reject access tokens with TOKEN_NOT_ALLOWED.
  • Verify access-token routes reject partner tokens with ACCESS_TOKEN_REQUIRED.
  • Verify requireScope blocks requests missing admin:tenants and internal:events.
  • Verify regional token introspection returns inactive for revoked or expired consent.
  • Verify refresh limit handling updates connection status and returns the refresh-limit error path.
  • Verify POST /api/v1/auth/token/introspect reflects the current request auth context rather than the submitted token string.

Key Classes Reference

Class Responsibility
auth.ts Defines the v1 auth token introspection endpoint.
index.ts Registers the v1 route modules and their prefixes.
authz.ts Enforces scope membership through requireScope.
auth.ts Implements the global auth plugin and request resolution order.
index.ts Implements the US regional token and consent routes.
index.ts Implements the JP regional token and consent routes.
Dockerfile Packages the token-service runtime as a separate container image.