Consent Management Domain Revocation, Scope Enforcement, and Evidence Retention Across Services
Overview
This domain is the control plane for consented access in the US and consent-based Lita flows. It defines how a consent is created, activated, revoked, expired, and audited, and how that state is enforced when data is fetched or reused elsewhere in the platform.
Two documentation layers define the contract: documents/lita-consent-data-api.md describes the broader consent-based access model and retention posture, while documents/us-api-v1.md tightens the US-specific rules around purpose, permitted categories, connections, scoped tokens, receipts, and revocation. The runtime enforcement is split across the US API service, the US data gateway, Redis-backed token/session checks, and the relational schema in platform/database/migrations/002_customer_api_tables.sql.
Architecture Overview
flowchart TB
subgraph Specs[Spec Documents]
ConsentSpec[documents lita consent data api]
UsSpec[documents us api v1]
end
subgraph UsApi[US API Service]
ConsentService[consentService ts]
TokenService[tokenService ts]
ConnectionService[connectionService ts]
FeatureService[featureService ts]
ScoringService[scoringService ts]
ModelGov[modelGovernanceService ts]
end
subgraph Gateway[US Data Gateway]
GatewayAuth[auth go]
GatewayHandlers[handlers go]
Provider[provider go]
end
subgraph Storage[Persistence and Session State]
CustomerTables[002 customer api tables sql]
RedisSession[Redis session keys]
end
ConsentSpec --> ConsentService
UsSpec --> ConsentService
UsSpec --> TokenService
UsSpec --> GatewayHandlers
ConsentService --> CustomerTables
TokenService --> CustomerTables
ConnectionService --> CustomerTables
FeatureService --> CustomerTables
ScoringService --> CustomerTables
ModelGov --> CustomerTables
GatewayHandlers --> GatewayAuth
GatewayHandlers --> Provider
GatewayAuth --> RedisSession
GatewayHandlers --> CustomerTables
Contract and Enforcement Map
| Layer |
File |
Responsibility |
| Consent contract |
documents/lita-consent-data-api.md |
Consent-based access rules, retention posture, access credential scoping |
| US contract |
documents/us-api-v1.md |
Purpose enforcement, data categories, consent receipts, revocation, token behavior |
| US runtime |
services/us-api/src/services/*.ts |
Consent state transitions, token issuance and refresh, evidence snapshots, replay, connection state |
| Gateway runtime |
services/us-data-gateway/internal/handlers/handlers.go |
Bearer token auth, category enforcement, consent expiry and status checks, provider dispatch |
| Session revocation |
services/us-data-gateway/internal/auth/auth.go |
RS256 verification and Redis session revocation gate |
| Persistence |
platform/database/migrations/002_customer_api_tables.sql |
Relational backing for consent, token, connection, log, and evidence state |
Component Structure
1. Specification Layer
documents/lita-consent-data-api.md
[!IMPORTANT]
Revocation is not a single code path. The US API marks the consent revoked, invalidates tokens, disconnects associated connections, and writes a consent log entry. The Go data gateway separately blocks requests when token claims do not match the requested category or when the consent row is inactive or expired. Evidence retention is handled independently through immutable evidence snapshots and decision records.
This document defines the platform-wide consent-based access model.
- Access is scoped to consent and can be revoked when consent expires, consent is revoked, or credentials are revoked for security reasons.
- The document states that Lita retains consent records and access logs for audit and compliance purposes.
- It also states that Lita does not impose artificial retention limits on delivered data.
documents/us-api-v1.md
This document specializes the model for the US API.
- Consent is bound to
purpose and data_categories.
- Consent grants may include refresh permissions and disclosure versioning.
- Access tokens are short-lived JWTs signed with RS256.
- Consent revocation immediately invalidates associated tokens and connections.
- Receipt metadata is retained for audit and compliance review.
Key contract values visible in the docs
- Purposes:
RENTAL_SCREENING, LENDING_UNDERWRITING, ACCOUNT_OPENING, INCOME_VERIFICATION, FRAUD_PREVENTION, GENERAL_PERSONAL_FINANCE
- Data categories:
IDENTITY_BASIC, ACCOUNTS, BALANCES, TRANSACTIONS, INCOME, EMPLOYMENT, CASHFLOW_FEATURES, DEVICE_RISK, WATCHLIST_SCREENING
- Connection statuses:
ACTIVE, REAUTH_REQUIRED, DEGRADED, DISCONNECTED
2. US API Consent Service
services/us-api/src/services/consentService.ts
This service owns consent creation, revocation, and receipt projection. It writes the source of truth for consent state, then fans out to token and connection invalidation when revocation happens.
Data Models
CreateConsentPayload
| Property |
Type |
Description |
user |
{ country: 'US'; user_reference?: string } |
User identity scope for the consent |
purpose |
Purpose |
Required US purpose |
data_categories |
DataCategory[] |
Allowed categories for the consent |
access_duration_days |
`number |
undefined` |
expires_at |
`string |
undefined` |
refresh_permissions |
`{ enabled: boolean; max_refresh_per_day: number } |
undefined` |
consent_disclosure_version |
string |
Disclosure version captured with the consent |
Public Methods
| Method |
Description |
createConsent |
Creates a consent row, writes a consent log entry, and sets initial status to PENDING_USER_ACTION |
revokeConsent |
Marks the consent revoked, revokes active tokens, disconnects related connections, writes a revocation log entry, and attempts webhook delivery |
getConsentReceipt |
Returns audit metadata for the consent, including purpose, categories, disclosure version, expiry, and creation time |
ensureConsentActive |
Rejects requests when the consent is not ACTIVE or has expired |
Revocation behavior
prisma.consent.update sets status: 'REVOKED'
prisma.token.updateMany sets revokedAt on all active tokens
prisma.connection.updateMany sets status: 'DISCONNECTED'
prisma.consentLog.create records REVOKED
dispatchWebhook sends consent_revoked and is wrapped in a best-effort try/catch
3. Token Service
services/us-api/src/services/tokenService.ts
[!NOTE]
revokeConsent finishes the database updates before attempting webhook delivery. If webhook dispatch fails, the revocation remains committed and the failure is intentionally ignored.
This service issues and refreshes scoped JWT access tokens and maintains the refresh token state that allows or blocks renewal.
Data Models
TokenPair
| Property |
Type |
Description |
access_token |
string |
RS256 JWT access token |
refresh_token |
string |
Rotating refresh token returned alongside the access token |
expires_in |
number |
Access token lifetime in seconds |
scope |
{ purpose: Purpose; data_categories: DataCategory[] } |
Scope carried by the issued credential pair |
Public Methods
| Method |
Description |
exchangeToken |
Activates a pending consent if needed and issues a token pair, optionally validating link_token |
refreshToken |
Validates the refresh token hash, checks consent status and expiry, enforces refresh limits, and issues a new token pair |
introspectToken |
Validates JWT claims and refresh-state presence, then reports active scope and expiry |
Enforcement behavior
exchangeToken rejects a mismatched link_token with LEGAL_RESTRICTION
exchangeToken rejects revoked consents with CONSENT_REVOKED
refreshToken rejects invalid refresh tokens with LEGAL_RESTRICTION
refreshToken rejects inactive or expired consents with CONSENT_REVOKED
enforceRefreshLimit blocks excess daily refreshes with REFRESH_LIMIT_EXCEEDED
issueTokens stores token metadata with accessJti, refreshTokenHash, and expiresAt
Token invalidation path
- Revocation sets
revokedAt on active tokens
- Refresh lookups require
revokedAt: null
- Introspection also requires a matching token row with
revokedAt: null
4. Connection Service
services/us-api/src/services/connectionService.ts
This service normalizes connection state and gives the US API a way to re-open or re-check linked institution sessions.
Public Methods
| Method |
Description |
ensureConnectionsReady |
Reads all connections for a consent and returns ACTIVE, DEGRADED, or throws REAUTH_REQUIRED |
recordConnectionRefresh |
Marks all connections for a consent as refreshed and ACTIVE |
Behavior
- If no connection rows exist, the consent is treated as
ACTIVE
- A
REAUTH_REQUIRED connection raises an ApiError with the same code and an optional reauth_link
- Any
DEGRADED connection downgrades the returned status to DEGRADED
recordConnectionRefresh updates lastRefreshedAt and resets status to ACTIVE
5. Evidence Snapshot and Scoring Services
services/us-api/src/services/featureService.ts
This service computes cashflow features and persists an immutable evidence snapshot for later replay.
Data Models
CashflowFeatures
| Property |
Type |
Description |
income_monthly_avg_usd |
number |
Mean monthly income derived from the income response |
income_stability_index |
number |
Normalized stability metric |
nsf_overdraft_count_180d |
number |
Overdraft count in the lookback window |
balance_min_30d_usd |
number |
Minimum current balance across accounts |
rent_payment_detected |
boolean |
Flag derived from transaction categories |
debt_payment_ratio_est |
number |
Debt payment ratio estimate |
Public Methods
| Method |
Description |
computeCashflow |
Builds normalized cashflow features, migrates them to the global schema, and stores an evidenceSnapshot row |
fetchEvidence |
Loads a stored evidence snapshot by evidenceRef |
Evidence retention behavior
evidence_ref is generated with the prefix evd_us_
- Snapshots include:
consentId
featureSet
features
inputsDigest
lookbackDays
schemaVersion
metadata
metadata carries:
income_method
source_feature_set
source_features
migration_notes
services/us-api/src/services/scoringService.ts
This service validates decisions, persists scored outcomes, and replays decisions from stored evidence.
Data Models
DecisionPayload
| Property |
Type |
Description |
applicant_reference |
`string |
undefined` |
purpose |
string |
Declared decision purpose |
product_type |
`string |
undefined` |
score |
`number |
undefined` |
decision |
string |
APPROVE, REVIEW, or DENY |
approved_limit |
`number |
undefined` |
model |
object |
Model identity and lineage metadata |
reasons |
`{ code: string; description?: string }[] |
undefined` |
evidence_ref |
string |
Evidence snapshot reference |
consent_id |
string |
Consent tied to the decision |
consent_text_version |
string |
Captured consent text version |
connection_status |
string |
Connection state at decision time |
features |
Record<string, unknown> |
Feature payload used to make the decision |
Public Methods
| Method |
Description |
validateDecision |
Enforces deny-reason rules and the deny-reason allowlist |
storeDecision |
Loads the evidence snapshot, optionally records model lineage, and persists the decision |
replayDecision |
Reuses stored evidence to replay scoring and return an audit payload |
Evidence and lineage behavior
storeDecision requires a valid evidence_ref
- The decision row stores:
consentId
evidenceRef
payload
modelArtifactId
schemaVersion
replayDecision loads the evidence snapshot and the most recent stored decision for that evidence
- If
config.scoringCallbackUrl is configured, replay posts the evidence and feature payload to the callback and stores the returned decision again
Deny reason allowlist
INSUFFICIENT_INCOME
INCOME_INSTABILITY
RECENT_OVERDRAFTS
LOW_MIN_BALANCE
HIGH_CASHFLOW_VOLATILITY
INSUFFICIENT_HISTORY
UNVERIFIED_ACCOUNT
INCONSISTENT_IDENTITY_SIGNALS
HIGH_RISK_DEVICE_SIGNAL
6. US Data Gateway
services/us-data-gateway/internal/handlers/handlers.go
The gateway serves consent-scoped financial data and gates each request with RS256 verification, Redis session state, consent status, expiry, and category checks.
Data Models
Handler
| Property |
Type |
Description |
DB |
*pgxpool.Pool |
PostgreSQL connection pool used to read consent state |
Provider |
provider.Provider |
Data provider used to fetch accounts, balances, transactions, and income |
Auth |
auth.TokenVerifier |
JWT and session revocation verifier |
consentRecord
| Property |
Type |
Description |
ID |
string |
Consent identifier |
Status |
string |
Consent status read from the database |
ExpiresAt |
time.Time |
Consent expiry time |
Categories |
[]string |
Category scope for the consent |
apiError
| Property |
Type |
Description |
Status |
int |
HTTP status returned to the client |
Code |
string |
JSON error code |
Public Methods
| Method |
Description |
Accounts |
Returns tokenized account data when the token covers ACCOUNTS and the consent is active |
Balances |
Returns balance data when the token covers BALANCES and the consent is active |
Transactions |
Returns historical transactions when the token covers TRANSACTIONS and the consent is active |
TransactionsSync |
Returns cursor-based transaction sync data when the token covers TRANSACTIONS and the consent is active |
Income |
Returns income data when the token covers INCOME and the consent is active |
Enforcement order inside each handler
authorize validates Authorization: Bearer ...
TokenVerifier.Verify validates RS256 and Redis revocation state
- The handler logs
X-Request-Id and consent_id
contains(claims.Categories, ...) enforces the requested category
ensureConsentActive checks consent status and expiry
- The provider fetch method is called only after scope and consent checks pass
services/us-data-gateway/internal/auth/auth.go
[!NOTE]
ensureConsentActive returns CONSENT_REVOKED for both non-ACTIVE records and expired records. The gateway does not expose a separate expiry-specific error code.
This service verifies bearer tokens, validates the JWT algorithm, and consults Redis for session revocation.
Data Models
Claims
| Property |
Type |
Description |
ConsentID |
string |
Consent identifier carried in the JWT claim cid |
Purpose |
string |
Purpose claim carried in pur |
Categories |
[]string |
Category list carried in cat |
RegisteredClaims |
jwt.RegisteredClaims |
Embedded standard JWT claims, including the token ID used by Redis lookups |
TokenVerifier
| Property |
Type |
Description |
PublicKey |
*rsa.PublicKey |
RS256 verification key |
Redis |
*redis.Client |
Session store used for revocation checks |
Public Methods
| Method |
Description |
Verify |
Parses the JWT, validates RS256, reads the Redis session, and rejects revoked sessions |
Redis revocation gate
- Session keys are read with
session:<claims.ID>
session["revoked"] == "true" causes verification failure
- The gateway rejects the request before any handler-specific logic runs
services/us-data-gateway/internal/provider/provider.go
This is the provider contract used by the gateway to retrieve data after consent, scope, and status checks pass.
Data Models
Account
| Property |
Type |
Description |
AccountToken |
string |
Tokenized account identifier |
Name |
string |
Account display name |
Type |
string |
Account type |
Mask |
string |
Masked account suffix |
Balance
| Property |
Type |
Description |
AccountToken |
string |
Tokenized account identifier |
Available |
float64 |
Available balance |
Current |
float64 |
Current balance |
Currency |
string |
ISO currency code |
Transaction
| Property |
Type |
Description |
TransactionID |
string |
Transaction identifier |
AccountToken |
string |
Tokenized account identifier |
Amount |
float64 |
Transaction amount |
Currency |
string |
ISO currency code |
PostedAt |
string |
Posting timestamp |
MerchantName |
string |
Merchant display name |
MerchantCategory |
string |
Merchant category |
TransactionRemoval
| Property |
Type |
Description |
TransactionID |
string |
Identifier of a removed transaction |
TransactionSync
| Property |
Type |
Description |
Added |
[]Transaction |
Added transactions |
Modified |
[]Transaction |
Modified transactions |
Removed |
[]TransactionRemoval |
Removed transactions |
NextCursor |
string |
Cursor for the next sync page |
Income
| Property |
Type |
Description |
IncomeID |
string |
Income identifier |
Amount |
float64 |
Income amount |
Currency |
string |
ISO currency code |
PayDate |
string |
Payment date |
Public Methods
| Method |
Description |
FetchAccounts |
Returns tokenized account records for a consent |
FetchBalances |
Returns balances for a consent |
FetchTransactions |
Returns dated transaction history for a consent |
FetchTransactionsSync |
Returns cursor-based sync data for a consent |
FetchIncome |
Returns income records for a consent |
services/us-data-gateway/cmd/us-data-gateway/main.go
The gateway mounts the consent-scoped endpoints to the HTTP server.
| Mounted path |
Handler |
/api/v1/us/data/accounts |
Accounts |
/api/v1/us/data/balances |
Balances |
/api/v1/us/data/transactions |
Transactions |
/api/v1/us/data/transactions/sync |
TransactionsSync |
/api/v1/us/data/income |
Income |
7. Persistence Schema
platform/database/migrations/002_customer_api_tables.sql
This migration is the relational backing for the consent management domain.
- It stores the consent state read and written by the US API and the gateway.
- It backs token revocation, connection status changes, consent receipts, consent logs, refresh counts, evidence snapshots, and decision history.
- The runtime uses it as the source of truth for cross-service enforcement, while Redis is used only for session revocation checks in the gateway.
State Management
Consent lifecycle
| State |
Meaning |
PENDING_USER_ACTION |
Consent exists but has not yet been activated |
ACTIVE |
Consent can be used for access and refresh flows |
REVOKED |
Consent is no longer valid and blocks token and data access |
Connection lifecycle
| State |
Meaning |
ACTIVE |
Connection can be used |
REAUTH_REQUIRED |
User must reauthenticate before data access resumes |
DEGRADED |
Partial or stale access is available |
DISCONNECTED |
Connection is closed after revocation |
Token lifecycle
| State |
Meaning |
issued |
Access token has been created and persisted |
revokedAt != null |
Access token is no longer valid |
expired |
Token has passed its JWT or database expiry window |
Evidence lifecycle
| State |
Meaning |
stored |
Snapshot or decision payload has been persisted |
immutable |
Evidence is retained for later audit and replay |
replayed |
Evidence has been reused to reconstruct a decision path |
Feature Flows
1. Consent Revocation Propagation
sequenceDiagram
participant Partner as Partner Client
participant ConsentService as consentService ts
participant DB as Customer Tables
participant TokenService as tokenService ts
participant ConnectionService as connectionService ts
participant Webhook as Webhook Delivery
participant Gateway as US Data Gateway
Partner->>ConsentService: revokeConsent
ConsentService->>DB: update consent status to REVOKED
ConsentService->>DB: update tokens revokedAt
ConsentService->>DB: update connections status DISCONNECTED
ConsentService->>DB: write consentLog REVOKED
ConsentService->>Webhook: dispatchWebhook consent_revoked
Webhook-->>ConsentService: best effort result or error ignored
Partner->>Gateway: data request with old access token
Gateway->>Gateway: verify token and session state
Gateway->>DB: ensureConsentActive lookup
Gateway-->>Partner: CONSENT_REVOKED
What happens
- The US API changes the consent row to
REVOKED.
- Active access tokens are invalidated by setting
revokedAt.
- Related connections are disconnected.
- A revocation log is written.
- Webhook delivery is attempted but does not block the revocation commit.
- The gateway blocks subsequent data requests because the consent row is no longer active.
2. Scoped Data Access
sequenceDiagram
participant Client as Partner Client
participant GatewayAuth as auth ts
participant Redis as Redis
participant Gateway as Handler
participant DB as Customer Tables
participant Provider as Data Provider
Client->>Gateway: GET accounts with Bearer token
Gateway->>GatewayAuth: Verify
GatewayAuth->>Redis: HGetAll session token id
Redis-->>GatewayAuth: session state
GatewayAuth-->>Gateway: claims or error
Gateway->>Gateway: check requested category
Gateway->>DB: ensureConsentActive lookup
DB-->>Gateway: consent row
Gateway->>Provider: FetchAccounts
Provider-->>Gateway: accounts
Gateway-->>Client: JSON accounts response
What happens
- The JWT is verified with RS256.
- Redis session state is consulted to catch security revocations.
- The gateway enforces the requested category from token claims.
- The consent row must still be
ACTIVE and unexpired.
- Only then does the provider fetch run.
3. Evidence Snapshot and Replay
sequenceDiagram
participant Client as Partner Client
participant FeatureService as featureService ts
participant Provider as Mock Provider
participant DB as Customer Tables
participant ScoringService as scoringService ts
participant ModelGov as modelGovernanceService ts
Client->>FeatureService: computeCashflow
FeatureService->>Provider: balances transactions income
Provider-->>FeatureService: raw inputs
FeatureService->>DB: store evidenceSnapshot
FeatureService-->>Client: evidence_ref and features
Client->>ScoringService: storeDecision
ScoringService->>DB: fetch evidenceSnapshot
ScoringService->>ModelGov: recordModelLineage when model is provided
ScoringService->>DB: create decision row
ScoringService-->>Client: decision_id
Client->>ScoringService: replayDecision
ScoringService->>DB: load evidenceSnapshot and prior decision
ScoringService-->>Client: replay payload with audit metadata
What happens
- Evidence is stored separately from the decision payload.
- The decision references the evidence snapshot by
evidence_ref.
- Replay uses the stored evidence rather than rebuilding the input state from scratch.
API Integration
US Consent Creation
Create US Consent
{
"title": "Create US Consent",
"description": "Creates a new US consent and returns the user authorization link",
"method": "POST",
"baseUrl": "<USApiBaseUrl>",
"endpoint": "/api/v1/us/consents",
"headers": [
{
"key": "Authorization",
"value": "Bearer <PARTNER_TOKEN>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<uuid>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"user\": {\n \"country\": \"US\",\n \"user_reference\": \"user_123\"\n },\n \"purpose\": \"LENDING_UNDERWRITING\",\n \"data_categories\": [\n \"ACCOUNTS\",\n \"BALANCES\"\n ],\n \"access_duration_days\": 365,\n \"expires_at\": \"2025-12-31T00:00:00Z\",\n \"refresh_permissions\": {\n \"enabled\": true,\n \"max_refresh_per_day\": 4\n },\n \"consent_disclosure_version\": \"v1\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Consent created",
"body": "{\n \"consent_id\": \"consent_123\",\n \"status\": \"PENDING_USER_ACTION\",\n \"expires_at\": \"2025-12-31T00:00:00Z\",\n \"auth\": {\n \"link_url\": \"https://link.lita.com/us/consent_123\"\n }\n}"
}
}
}
Consent Receipt
Get US Consent Receipt
{
"title": "Get US Consent Receipt",
"description": "Returns consent metadata for audit and compliance review",
"method": "GET",
"baseUrl": "<USApiBaseUrl>",
"endpoint": "/api/v1/us/consents/{consent_id}/receipt",
"headers": [
{
"key": "Authorization",
"value": "Bearer <PARTNER_TOKEN>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<uuid>",
"required": true
}
],
"queryParams": [],
"pathParams": [
{
"key": "consent_id",
"value": "consent_123",
"required": true
}
],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Receipt returned",
"body": "{\n \"consent_id\": \"consent_123\",\n \"status\": \"ACTIVE\",\n \"purpose\": \"LENDING_UNDERWRITING\",\n \"data_categories\": [\n \"ACCOUNTS\",\n \"BALANCES\"\n ],\n \"consent_disclosure_version\": \"v1\",\n \"expires_at\": \"2025-12-31T00:00:00Z\",\n \"created_at\": \"2025-01-01T00:00:00Z\"\n}"
}
}
}
Consent Revocation
Revoke US Consent
{
"title": "Revoke US Consent",
"description": "Immediately revokes the consent, invalidates tokens, disconnects connections, and records revocation evidence",
"method": "POST",
"baseUrl": "<USApiBaseUrl>",
"endpoint": "/api/v1/us/consents/{consent_id}/revoke",
"headers": [
{
"key": "Authorization",
"value": "Bearer <PARTNER_TOKEN>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<uuid>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [
{
"key": "consent_id",
"value": "consent_123",
"required": true
}
],
"bodyType": "json",
"requestBody": "[]",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Consent revoked",
"body": "{\n \"consentId\": \"consent_123\"\n}"
}
}
}
Token Exchange
Exchange Consent Token
{
"title": "Exchange Consent Token",
"description": "Activates a pending consent when needed and issues short-lived access and refresh tokens",
"method": "POST",
"baseUrl": "<USApiBaseUrl>",
"endpoint": "/api/v1/us/consents/{consent_id}/token",
"headers": [
{
"key": "Authorization",
"value": "Bearer <PARTNER_TOKEN>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<uuid>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [
{
"key": "consent_id",
"value": "consent_123",
"required": true
}
],
"bodyType": "json",
"requestBody": "{\n \"link_token\": \"linktok_consent_123\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Token pair issued",
"body": "{\n \"access_token\": \"eyJhbGciOiJSUzI1NiIs...\",\n \"refresh_token\": \"rtk_us_7e6c8c0e0f1f2a7d1b4d3f2a\",\n \"expires_in\": 3600,\n \"scope\": {\n \"purpose\": \"LENDING_UNDERWRITING\",\n \"data_categories\": [\n \"ACCOUNTS\",\n \"BALANCES\"\n ]\n }\n}"
}
}
}
Refresh Token
Refresh Consent Token
{
"title": "Refresh Consent Token",
"description": "Issues new access credentials when the refresh token is valid and the consent is still active",
"method": "POST",
"baseUrl": "<USApiBaseUrl>",
"endpoint": "/api/v1/us/tokens/refresh",
"headers": [
{
"key": "Authorization",
"value": "Bearer <PARTNER_TOKEN>",
"required": true
},
{
"key": "X-Request-Id",
"value": "<uuid>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"refresh_token\": \"rtk_us_7e6c8c0e0f1f2a7d1b4d3f2a\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "New token pair issued",
"body": "{\n \"access_token\": \"eyJhbGciOiJSUzI1NiIs...\",\n \"refresh_token\": \"rtk_us_89ab1c2d3e4f5a6b7c8d9e0f\",\n \"expires_in\": 3600,\n \"scope\": {\n \"purpose\": \"LENDING_UNDERWRITING\",\n \"data_categories\": [\n \"ACCOUNTS\",\n \"BALANCES\"\n ]\n }\n}"
}
}
}
US Data Gateway Endpoints
Get US Accounts
{
"title": "Get US Accounts",
"description": "Returns tokenized accounts after category, token, and consent checks pass",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/accounts",
"headers": [
{
"key": "Authorization",
"value": "Bearer <ACCESS_TOKEN>",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Accounts returned",
"body": "{\n \"accounts\": [\n {\n \"account_token\": \"acct_tok_1\",\n \"name\": \"Checking\",\n \"type\": \"depository\",\n \"mask\": \"1234\"\n },\n {\n \"account_token\": \"acct_tok_2\",\n \"name\": \"Savings\",\n \"type\": \"depository\",\n \"mask\": \"5678\"\n }\n ]\n}"
}
}
}
Get US Balances
{
"title": "Get US Balances",
"description": "Returns balance data when the token scope includes BALANCES",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/balances",
"headers": [
{
"key": "Authorization",
"value": "Bearer <ACCESS_TOKEN>",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Balances returned",
"body": "{\n \"balances\": [\n {\n \"account_token\": \"acct_tok_1\",\n \"available\": 1200,\n \"current\": 1500,\n \"currency\": \"USD\"\n },\n {\n \"account_token\": \"acct_tok_2\",\n \"available\": 3000,\n \"current\": 3200,\n \"currency\": \"USD\"\n }\n ]\n}"
}
}
}
Get US Transactions
{
"title": "Get US Transactions",
"description": "Returns dated transaction history when the token scope includes TRANSACTIONS",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/transactions",
"headers": [
{
"key": "Authorization",
"value": "Bearer <ACCESS_TOKEN>",
"required": true
}
],
"queryParams": [
{
"key": "from",
"value": "2024-10-01",
"required": false
},
{
"key": "to",
"value": "2024-10-31",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Transactions returned",
"body": "{\n \"transactions\": [\n {\n \"transaction_id\": \"txn_1\",\n \"account_token\": \"acct_tok_1\",\n \"amount\": 1200,\n \"currency\": \"USD\",\n \"posted_at\": \"2024-10-01T00:00:00Z\",\n \"merchant_name\": \"Rent Co\",\n \"merchant_category\": \"RENT\"\n },\n {\n \"transaction_id\": \"txn_2\",\n \"account_token\": \"acct_tok_1\",\n \"amount\": 85,\n \"currency\": \"USD\",\n \"posted_at\": \"2024-10-02T00:00:00Z\",\n \"merchant_name\": \"Card\",\n \"merchant_category\": \"DEBT\"\n }\n ]\n}"
}
}
}
Get US Transactions Sync
{
"title": "Get US Transactions Sync",
"description": "Returns cursor-based incremental transaction changes",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/transactions/sync",
"headers": [
{
"key": "Authorization",
"value": "Bearer <ACCESS_TOKEN>",
"required": true
}
],
"queryParams": [
{
"key": "cursor",
"value": "cursor_001",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Transaction sync returned",
"body": "{\n \"added\": [\n {\n \"transaction_id\": \"txn_3\",\n \"account_token\": \"acct_tok_2\",\n \"amount\": 45,\n \"currency\": \"USD\",\n \"posted_at\": \"2024-10-03T00:00:00Z\",\n \"merchant_name\": \"Coffee\",\n \"merchant_category\": \"FOOD\"\n }\n ],\n \"modified\": [\n {\n \"transaction_id\": \"txn_2\",\n \"account_token\": \"acct_tok_1\",\n \"amount\": 90,\n \"currency\": \"USD\",\n \"posted_at\": \"2024-10-02T00:00:00Z\",\n \"merchant_name\": \"Card\",\n \"merchant_category\": \"DEBT\"\n }\n ],\n \"removed\": [\n {\n \"transaction_id\": \"txn_9\"\n }\n ],\n \"next_cursor\": \"cursor_002\"\n}"
}
}
}
Get US Income
{
"title": "Get US Income",
"description": "Returns income records after consent scope and status checks pass",
"method": "GET",
"baseUrl": "<USDataGatewayBaseUrl>",
"endpoint": "/api/v1/us/data/income",
"headers": [
{
"key": "Authorization",
"value": "Bearer <ACCESS_TOKEN>",
"required": true
}
],
"queryParams": [
{
"key": "lookback_days",
"value": "180",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Income returned",
"body": "{\n \"income\": [\n {\n \"income_id\": \"inc_1\",\n \"amount\": 4200,\n \"currency\": \"USD\",\n \"pay_date\": \"2024-10-01\"\n },\n {\n \"income_id\": \"inc_2\",\n \"amount\": 4300,\n \"currency\": \"USD\",\n \"pay_date\": \"2024-10-15\"\n }\n ]\n}"
}
}
}
Error Handling
The domain uses explicit error codes rather than ambiguous failures.
US API and gateway error codes
| Code |
Source |
Meaning |
CONSENT_REVOKED |
US API and Go gateway |
Consent is inactive, revoked, or expired |
CATEGORY_NOT_ALLOWED |
Go gateway |
Token scope does not cover the requested category |
REFRESH_LIMIT_EXCEEDED |
US API token service |
Daily refresh limit has been reached |
REAUTH_REQUIRED |
US API connection service |
A linked institution requires reauthentication |
LEGAL_RESTRICTION |
US API token and scoring services |
Token or decision rule violated a policy gate |
PROVIDER_UNAVAILABLE |
US API scoring service |
Callback replay target failed |
NOT_FOUND |
US API services |
The requested consent or evidence record was missing |
TOKEN_REQUIRED |
Go gateway |
Bearer token was missing |
INTERNAL_ERROR |
Go gateway |
Non-typed server error normalized by writeError |
Go gateway error shape
{
"error": "CATEGORY_NOT_ALLOWED"
}
Error propagation pattern
- The Go gateway converts typed errors into JSON with an
error field.
- The US API throws typed
ApiError instances for consent, token, and scoring failures.
- Missing records are returned as
NOT_FOUND.
- Revocation and expiry are enforced before provider calls and before replay.
Caching Strategy
Redis session store
| Key |
Usage |
Invalidation trigger |
session:<claims.ID> |
Session revocation marker used by TokenVerifier.Verify |
Security revocation or explicit session revocation |
Database-backed state used as the source of truth
| Table role |
Usage |
Invalidated by |
| Consent rows |
Consent status and expiry |
revokeConsent and natural expiration |
| Token rows |
Access and refresh state |
revokeConsent, refresh failure paths, expiry |
| Connection rows |
Connection state |
revokeConsent, reauthentication refresh flows |
| Refresh events |
Daily refresh cap tracking |
Day boundary rollover |
| Evidence snapshots |
Immutable replay source |
Never invalidated by normal revocation |
| Decision rows |
Persisted scoring result |
Never invalidated by normal revocation |
Dependencies
External packages and runtime services
prisma for US API persistence
jsonwebtoken for RS256 access token signing and verification
redis for gateway session revocation checks
pgxpool for PostgreSQL access in the gateway
pg for SQL-backed jobs and analytics
fastify for the US API HTTP layer
net/http and log for the Go gateway
Service dependencies
- US API consent and token services depend on shared consent tables
- The gateway depends on token claims produced by the US API
- Evidence snapshots and decision rows depend on the consent and feature services
- Revocation propagation depends on both database updates and gateway-side session checks
Testing Considerations
Consent and token lifecycle
- Consent creation persists
PENDING_USER_ACTION
- Revocation marks consent
REVOKED
- Revocation invalidates active tokens and disconnects related connections
- Refresh is blocked once the daily limit is reached
- Refresh is blocked when the consent is inactive or expired
Scope enforcement
- Requests without the correct category claim return
CATEGORY_NOT_ALLOWED
- Requests with a valid token but a revoked consent return
CONSENT_REVOKED
- Gateway auth rejects missing bearer tokens with
TOKEN_REQUIRED
Gateway error mapping
services/us-data-gateway/internal/handlers/handlers_test.go verifies:
ErrCategoryNotAllowed returns 403
ErrConsentRevoked returns 409
US API flow tests
services/us-api/test/flows.test.ts covers:
- Consent creation
- Consent revocation
- Refresh limit enforcement
- Category gating on account access
Key Classes Reference
| Class |
Responsibility |
consentService.ts |
Creates, revokes, and audits consent state |
tokenService.ts |
Issues, refreshes, and introspects consent-scoped JWTs |
connectionService.ts |
Tracks connection readiness and reauthentication state |
featureService.ts |
Computes cashflow features and stores evidence snapshots |
scoringService.ts |
Validates, persists, and replays scoring decisions |
modelGovernanceService.ts |
Records model lineage and monitors drift or retraining triggers |
auth.go |
Verifies JWTs and Redis session revocation state |
handlers.go |
Enforces category scope and consent status before data access |
provider.go |
Defines the gateway data retrieval contract |
main.go |
Mounts the US data gateway HTTP routes |
002_customer_api_tables.sql |
Persists consent, token, connection, log, and evidence state |