Consent Management Domain - US API Consent, Token, and Connection Service Layer
Overview
This part of the US API implements a consent-first data access model. A consent record is the root object for every token, connection, feature snapshot, and scoring decision, and the service layer scopes access by purpose and data_categories instead of treating tokens as generic credentials.
The flow is deliberately staged: consent is created in a pending state, activated through token exchange, enforced by token middleware, and used to gate connection readiness, feature generation, and scoring replay. Revocation propagates across consent, tokens, and connections, while governance services keep the feature schema and model lineage aligned with the stored evidence.
Architecture Overview
flowchart TB
subgraph USApiConsentLayer [US API Consent First Service Layer]
Client[Partner or internal client]
Middleware[Consent and auth middleware]
ConsentSvc[consentService]
TokenSvc[tokenService]
ConnectionSvc[connectionService]
FeatureSvc[featureService]
ScoringSvc[scoringService]
GovernanceSvc[modelGovernanceService]
WebhookSvc[webhookService]
MockProvider[mockProvider]
Audit[Audit logger]
end
subgraph Persistence [Prisma backed storage]
ConsentTable[consent records]
TokenTable[token records]
ConnectionTable[connection records]
EvidenceTable[evidence snapshots]
DecisionTable[decision records]
SchemaTable[feature schema versions]
DriftTable[drift reports]
RetrainTable[retrain triggers]
ModelTable[model artifacts]
AccessLogTable[access logs]
end
subgraph ExternalSystems [External systems]
PartnerWebhook[Partner webhook endpoint]
ScoringCallback[Scoring callback URL]
end
Client --> Middleware
Middleware --> ConsentSvc
Middleware --> TokenSvc
Middleware --> ConnectionSvc
Middleware --> FeatureSvc
Middleware --> ScoringSvc
ConsentSvc --> Persistence
TokenSvc --> Persistence
ConnectionSvc --> Persistence
FeatureSvc --> MockProvider
FeatureSvc --> GovernanceSvc
FeatureSvc --> Persistence
ScoringSvc --> FeatureSvc
ScoringSvc --> GovernanceSvc
ScoringSvc --> Persistence
GovernanceSvc --> Persistence
WebhookSvc --> Persistence
ConsentSvc --> WebhookSvc
TokenSvc --> WebhookSvc
WebhookSvc --> PartnerWebhook
ScoringSvc --> ScoringCallback
Audit --> AccessLogTable
Middleware --> Audit
Consent and Token Service Layer
Consent Service
services/us-api/src/services/consentService.ts
The consent service owns lifecycle creation, revocation, and receipt rendering. It creates the consent as PENDING_USER_ACTION, records consent log entries, and on revocation it cascades to tokens and connections before attempting webhook notification.
Public Methods
| Method | Description |
|---|---|
createConsent |
Creates a new US consent, persists the consent log entry, and returns the stored consent record. |
revokeConsent |
Marks the consent as REVOKED, revokes active tokens, disconnects associated connections, logs the action, and dispatches a revocation webhook. |
getConsentReceipt |
Returns the receipt view for a consent with status, scope, disclosure version, and timestamps. |
ensureConsentActive |
Enforces that the consent exists, is ACTIVE, and has not expired. |
Properties and Types
CreateConsentPayload
| Property | Type | Description |
|---|---|---|
user |
{ country: 'US'; user_reference?: string } |
User identity payload constrained to US consent creation. |
purpose |
Purpose |
Consent purpose used for scope enforcement. |
data_categories |
DataCategory[] |
Category scope granted by 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 persisted with the consent. |
Lifecycle Notes
createConsentgenerates IDs in thecst_us_namespace and writes aCREATEDconsent log entry.revokeConsentsets consent status toREVOKED, invalidates unrevoked tokens by settingrevokedAt, and disconnects all linked connections.revokeConsentsends aconsent_revokedwebhook but ignores delivery failures in that path.ensureConsentActiverejects both revoked and expired consents withCONSENT_REVOKED.
Token Service
services/us-api/src/services/tokenService.ts
The token service performs consent-to-token exchange, refresh rotation, and introspection. It binds every access token to a consent ID, purpose, and data category list, and it stores only the refresh-token hash in the database.
Public Methods
| Method | Description |
|---|---|
exchangeToken |
Validates the link token when present, activates pending consent, issues an access and refresh token pair, and emits a consent activation webhook when needed. |
refreshToken |
Validates the refresh token, checks consent state and expiration, enforces refresh limits, and issues a new token pair. |
introspectToken |
Verifies a JWT access token, checks the access JTI against stored token records, and returns active token metadata when valid. |
Properties and Types
TokenPair
| Property | Type | Description |
|---|---|---|
access_token |
string |
RS256-signed JWT access token. |
refresh_token |
string |
Opaque refresh token returned to the client. |
expires_in |
number |
Token lifetime in seconds. |
scope |
{ purpose: Purpose; data_categories: DataCategory[] } |
Scope echoed back to the client. |
Token Exchange Boundaries
- If
linkTokenis present, it must equallinktok_${consentId}. - A consent in
PENDING_USER_ACTIONis transitioned toACTIVEbefore tokens are issued. - The access token embeds
consent_id,purpose,data_categories, andjti. - Refresh tokens are hashed with SHA-256 before storage.
- Refresh activity is counted per consent per day using
refreshEvent.
Connection Service
services/us-api/src/services/connectionService.ts
The connection service models connection readiness for downstream data access. It exposes a read-time status check and a refresh operation that reactivates all consent-linked connections.
Public Methods
| Method | Description |
|---|---|
ensureConnectionsReady |
Checks connection state for a consent and returns readiness or raises REAUTH_REQUIRED. |
recordConnectionRefresh |
Marks all consent-linked connections as refreshed and sets status to ACTIVE. |
Readiness Behavior
- No connections found: returns
{ status: 'ACTIVE', reauth_link: null }. - Any connection in
REAUTH_REQUIRED: throwsREAUTH_REQUIREDand returns the storedreauthLinkin error details. - Any connection in
DEGRADED: returns{ status: 'DEGRADED', reauth_link: null }. - Otherwise: returns
{ status: 'ACTIVE', reauth_link: null }.
Feature Computation and Scoring Boundary
Feature Service
services/us-api/src/services/featureService.ts
This service derives cashflow features from provider data and persists an evidence snapshot for later scoring and governance. It bridges provider outputs, schema migration, and evidence storage.
Public Methods
| Method | Description |
|---|---|
computeCashflow |
Derives cashflow features from provider data, migrates them to the global schema, stores an evidence snapshot, and returns the resulting evidence reference. |
fetchEvidence |
Loads a previously stored evidence snapshot by ID. |
Properties and Types
CashflowFeatures
| Property | Type | Description |
|---|---|---|
income_monthly_avg_usd |
number |
Rounded monthly income average. |
income_stability_index |
number |
Normalized income stability score. |
nsf_overdraft_count_180d |
number |
Number of overdraft or NSF events in the transaction set. |
balance_min_30d_usd |
number |
Minimum balance observed across accounts. |
rent_payment_detected |
boolean |
Indicates whether a rent transaction was observed. |
debt_payment_ratio_est |
number |
Estimated debt payment ratio based on detected debt transactions. |
Computation Flow
- Pull balances, transactions, and income from
mockProvider. - Compute aggregate values for income, stability, overdraft count, minimum balance, rent detection, and debt ratio.
- Create a digest of the raw inputs for traceability.
- Migrate the derived feature object into
GlobalCreditFeatureSchemaV1. - Ensure the feature schema version exists through
modelGovernanceService. - Persist an
evidenceSnapshotwith the migrated features and metadata.
Derived Feature Notes
lookbackDaysis persisted with the evidence snapshot.- Income is averaged from the provider income rows and rounded before storage.
- The migration step records notes when input fields are missing or when the source feature set is not
US_CASHFLOW_V1.
Scoring Service
services/us-api/src/services/scoringService.ts
The scoring service is the orchestration boundary between evidence, model lineage, and decision persistence. It validates decision payloads, stores decisions with associated artifacts, and optionally replays a decision through an external scoring callback.
Public Methods
| Method | Description |
|---|---|
validateDecision |
Enforces legal restrictions for denied decisions and checks deny reason codes. |
storeDecision |
Loads evidence, resolves model lineage when present, persists the decision, and returns the generated decision ID. |
replayDecision |
Replays a decision from evidence, optionally delegating to a scoring callback, or loads the stored decision and audit envelope. |
Properties and Types
DenyReasonsAllowlist
INSUFFICIENT_INCOME, INCOME_INSTABILITY, RECENT_OVERDRAFTS, LOW_MIN_BALANCE, HIGH_CASHFLOW_VOLATILITY, INSUFFICIENT_HISTORY, UNVERIFIED_ACCOUNT, INCONSISTENT_IDENTITY_SIGNALS, HIGH_RISK_DEVICE_SIGNAL
DecisionPayload
| Property | Type | Description |
|---|---|---|
applicant_reference |
`string \ | undefined` |
purpose |
string |
Scoring purpose. |
product_type |
`string \ | undefined` |
score |
`number \ | undefined` |
decision |
string |
Decision outcome, including DENY. |
approved_limit |
`number \ | undefined` |
model |
`{ name?: string; version?: string; schema_version?: string; training_snapshot_ref?: string; hyperparameters?: Record<string, unknown>; metrics?: Record<string, unknown> } \ | undefined` |
reasons |
`{ code: string; description?: string }[] \ | undefined` |
evidence_ref |
string |
Evidence snapshot reference. |
consent_id |
string |
Consent ID bound to the decision. |
consent_text_version |
string |
Disclosure version used at decision time. |
connection_status |
string |
Connection state at decision time. |
features |
Record<string, unknown> |
Feature payload used for scoring. |
Scoring Orchestration Boundaries
validateDecisiononly enforces reason checks whendecision === 'DENY'.storeDecisioncallsrecordModelLineageonly when bothmodel.nameandmodel.versionare provided.replayDecisionusesconfig.scoringCallbackUrlwhen configured, posts the evidence ref and feature payload, and persists the returned decision payload.- When no callback URL is configured,
replayDecisionreturns the stored decision and an audit envelope derived from the evidence snapshot and model artifact.
Model Governance Service
services/us-api/src/services/modelGovernanceService.ts
This service governs feature schema registration, drift reporting, retraining trigger creation, and model lineage. It is the governance boundary used by both feature derivation and scoring orchestration.
Public Methods
| Method | Description |
|---|---|
ensureFeatureSchemaVersion |
Ensures the global credit feature schema version exists in the store. |
runFeatureDriftDetection |
Compares recent evidence snapshots against a baseline distribution and records a drift report. |
evaluateRetrainingTriggers |
Checks the latest AUC and drift report against thresholds and creates a retraining trigger when needed. |
recordModelLineage |
Creates a model artifact and an active deployment record when the artifact does not already exist. |
Properties and Types
GLOBAL_CREDIT_FEATURE_SCHEMA_VERSION
global-credit-v1
DriftInput
| Property | Type | Description |
|---|---|---|
featureSet |
string |
Feature set name used to select baseline and evidence snapshots. |
schemaVersion |
string |
Schema version used for drift comparison. |
sampleLimit |
`number \ | undefined` |
baselineLabel |
`string \ | undefined` |
PerformanceThresholds
| Property | Type | Description |
|---|---|---|
aucMin |
number |
Minimum acceptable AUC. |
driftScoreMax |
number |
Maximum acceptable drift score. |
Governance Flow
ensureFeatureSchemaVersionstores the schema definition forincome_monthly_avg_usd,income_stability_index,nsf_overdraft_count_180d,balance_min_30d_usd,rent_payment_detected, anddebt_payment_ratio_est.runFeatureDriftDetectioncomputes per-feature mean and standard deviation across recent evidence snapshots and flags z-scores with absolute value at least2.evaluateRetrainingTriggerscreates a pending retraining trigger when the latest AUC drops below0.72or the latest drift score exceeds0.3.recordModelLineagedefaults the schema version toglobal-credit-v1and creates anACTIVEmodel deployment withmetadata.sourceset todecision-ingest.
Mock Provider
services/us-api/src/providers/mockProvider.ts
The mock provider supplies deterministic account, balance, transaction, transaction sync, and income data for feature derivation. It is the current feature-source dependency used by computeCashflow.
Public Methods
| Method | Description |
|---|---|
accounts |
Returns deterministic account records for a consent ID. |
balances |
Returns balances aligned to the generated accounts. |
transactions |
Returns deterministic transaction history for a consent ID. |
transactionsSync |
Returns a sync payload with added, modified, removed entries, and a cursor. |
income |
Returns deterministic income rows and marks the method as provider. |
Properties and Types
Account
| Property | Type | Description |
|---|---|---|
account_token |
string |
Synthetic account token. |
name |
string |
Account name. |
type |
string |
Account type. |
mask |
string |
Account mask. |
Balance
| Property | Type | Description |
|---|---|---|
account_token |
string |
Synthetic account token. |
available |
number |
Available balance. |
current |
number |
Current balance. |
currency |
string |
Currency code. |
Transaction
| Property | Type | Description |
|---|---|---|
transaction_id |
string |
Synthetic transaction identifier. |
account_token |
string |
Source account token. |
amount |
number |
Transaction amount. |
currency |
string |
Currency code. |
posted_at |
string |
Posting timestamp. |
merchant_name |
string |
Merchant name. |
merchant_category |
string |
Merchant category. |
TransactionSync
| Property | Type | Description |
|---|---|---|
added |
Transaction[] |
Newly added transactions. |
modified |
Transaction[] |
Updated transactions. |
removed |
{ transaction_id: string }[] |
Removed transaction IDs. |
next_cursor |
string |
Cursor for the next sync page. |
Income
| Property | Type | Description |
|---|---|---|
income_id |
string |
Synthetic income identifier. |
amount |
number |
Income amount. |
currency |
string |
Currency code. |
pay_date |
string |
Pay date timestamp. |
IncomeResponse
| Property | Type | Description |
|---|---|---|
method |
`'provider' \ | 'inferred'` |
income |
Income[] |
Income records. |
Consent and Scope Models
Consent Scope Types
services/us-api/src/models/types.ts
These exported constants and type aliases define the domain vocabulary used by middleware, tokens, and services.
Exported Values
| Export | Type | Value Set |
|---|---|---|
PurposeValues |
readonly string[] |
RENTAL_SCREENING, LENDING_UNDERWRITING, ACCOUNT_OPENING, INCOME_VERIFICATION, FRAUD_PREVENTION, GENERAL_PERSONAL_FINANCE |
DataCategoryValues |
readonly string[] |
IDENTITY_BASIC, ACCOUNTS, BALANCES, TRANSACTIONS, INCOME, EMPLOYMENT, CASHFLOW_FEATURES, DEVICE_RISK, WATCHLIST_SCREENING |
ConnectionStatusValues |
readonly string[] |
ACTIVE, REAUTH_REQUIRED, DEGRADED, DISCONNECTED |
FeatureSet |
type |
US_CASHFLOW_V1 |
Exported Types
| Type | Description |
|---|---|
Purpose |
One of the values from PurposeValues. |
DataCategory |
One of the values from DataCategoryValues. |
ConnectionStatus |
One of the values from ConnectionStatusValues. |
TokenClaims |
JWT claim shape used by access tokens. |
TokenClaims
| Property | Type | Description |
|---|---|---|
consent_id |
string |
Consent bound to the token. |
purpose |
Purpose |
Purpose scope embedded in the token. |
data_categories |
DataCategory[] |
Category scope embedded in the token. |
jti |
string |
Token identifier used for database lookup. |
Credit Feature Schema
services/us-api/src/models/creditFeatureSchema.ts
This file defines the global feature schema and the migration function that normalizes raw feature sets into the global shape used by governance and scoring.
Exported Values
| Export | Type | Value |
|---|---|---|
GLOBAL_CREDIT_FEATURE_SCHEMA_VERSION |
string |
global-credit-v1 |
Exported Types
GlobalCreditFeatureSchemaV1
| Property | Type | Description |
|---|---|---|
schema_version |
typeof GLOBAL_CREDIT_FEATURE_SCHEMA_VERSION |
Schema version marker. |
income_monthly_avg_usd |
number |
Normalized monthly income average. |
income_stability_index |
number |
Normalized income stability score. |
nsf_overdraft_count_180d |
number |
NSF or overdraft count over 180 days. |
balance_min_30d_usd |
number |
Minimum balance over 30 days. |
rent_payment_detected |
boolean |
Rent payment indicator. |
debt_payment_ratio_est |
number |
Estimated debt payment ratio. |
FeatureMigrationResult
| Property | Type | Description |
|---|---|---|
schema_version |
typeof GLOBAL_CREDIT_FEATURE_SCHEMA_VERSION |
Schema version of the migrated features. |
features |
GlobalCreditFeatureSchemaV1 |
Migrated feature payload. |
migration_notes |
string[] |
Notes emitted during migration. |
Migration Behavior
- Unsupported
feature_setvalues add a migration note and still emit defaulted global features. - Missing numeric fields default to
0. - Missing boolean fields default to
false. - Every migrated payload is stamped with
global-credit-v1.
Supporting Middleware and Audit Boundaries
Access Token Middleware
services/us-api/src/middleware/accessToken.ts
This middleware enforces consent-scoped access at request time and stores the parsed claims on request.accessClaims.
Public Methods
| Method | Description |
|---|---|
requireAccessToken |
Extracts a bearer token or token header, verifies RS256 JWT claims, and attaches parsed access claims to the request. |
Properties and Types
AccessClaims
| Property | Type | Description |
|---|---|---|
consent_id |
string |
Consent tied to the token. |
purpose |
Purpose |
Purpose scope. |
data_categories |
DataCategory[] |
Data category scope. |
jti |
string |
JWT identifier. |
Enforcement Behavior
- Accepts
Authorization: Bearer,x-access-token, oraccess_tokenquery input. - Rejects missing, malformed, or claim-incomplete tokens with
403andINVALID_TOKENorTOKEN_REQUIRED. - Verifies signatures using
config.jwtPublicKeyandRS256.
Partner Auth Middleware
services/us-api/src/middleware/partnerAuth.ts
This middleware authenticates partner requests before consent creation and partner-scoped actions.
Public Methods
| Method | Description |
|---|---|
requirePartnerAuth |
Validates partner tokens from authorization, header, or query input against configured partner API keys. |
Request Behavior
- Accepts
Authorization: Bearer,x-partner-token,x-api-key, orpartner_token. - Stores the accepted token in
request.partnerId.
Internal Auth Middleware
services/us-api/src/middleware/internalAuth.ts
This middleware protects internal analytics routes.
Public Methods
| Method | Description |
|---|---|
requireInternalAuth |
Accepts x-internal-token or bearer auth and checks it against config.internalApiToken. |
Request ID Middleware
services/us-api/src/middleware/requestId.ts
This middleware normalizes request tracing across the consent and audit layers.
Public Methods
| Method | Description |
|---|---|
ensureRequestId |
Reuses x-request-id when present, generates one when missing, and echoes it in the response header. |
Audit Logger
services/us-api/src/middleware/auditLogger.ts
This hook persists access logs on every response unless audit logging has been disabled after a database initialization error.
Public Methods
| Method | Description |
|---|---|
registerAuditLogger |
Registers an onResponse hook that writes access logs with request ID, partner ID, consent ID, route, and status code. |
Runtime Behavior
- Uses
prisma.accessLog.createfor each response. - Disables logging after
PrismaClientInitializationErrorand emits a warning once. - Reads
x-request-id,request.partnerId,request.accessClaims?.consent_id, andrequest.routeOptions?.url.
Error Handler
services/us-api/src/middleware/errorHandler.ts
This handler converts domain errors into structured API responses.
Public Methods
| Method | Description |
|---|---|
errorHandler |
Maps ApiError instances to typed responses and converts unexpected failures to PROVIDER_UNAVAILABLE. |
API Integration
Internal Analytics Routes
services/us-api/src/routes/internalAnalytics.ts
These routes are internal-only and require requireInternalAuth before the handler runs.
Record PSU Consent Event
{
"title": "Record PSU Consent Event",
"description": "Validates and stores a PSU consent analytics event through applyConsentEvent",
"method": "POST",
"baseUrl": "<USApiBaseUrl>",
"endpoint": "/internal/analytics/events",
"headers": [
{
"key": "x-internal-token",
"value": "<internal-token>",
"required": true
},
{
"key": "Content-Type",
"value": "application/json",
"required": true
}
],
"queryParams": [],
"pathParams": [],
"bodyType": "application/json",
"requestBody": "{\n \"psu_id\": \"psu_1\",\n \"consent_session_id\": \"sess_1\",\n \"product\": \"product_a\",\n \"country\": \"US\",\n \"provider\": \"provider_a\",\n \"institution_id\": \"inst_1\",\n \"timestamp\": \"2024-01-01T00:00:00.000Z\",\n \"failure_reason\": null,\n \"event_name\": \"consent_start\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Event stored",
"body": "{\n \"status\": \"accepted\"\n}"
},
"409": {
"description": "Dimension mismatch",
"body": "{\n \"status\": \"dimension_mismatch\"\n}"
}
}
}
Get PSU Consent Metrics
{
"title": "Get PSU Consent Metrics",
"description": "Returns daily, funnel, failure, and latency metrics for PSU consent analytics",
"method": "GET",
"baseUrl": "<USApiBaseUrl>",
"endpoint": "/internal/analytics/psu-consent/metrics",
"headers": [
{
"key": "x-internal-token",
"value": "<internal-token>",
"required": true
}
],
"queryParams": [
{
"key": "start_date",
"value": "2024-01-01",
"required": true
},
{
"key": "end_date",
"value": "2024-01-31",
"required": true
},
{
"key": "product",
"value": "product_a",
"required": false
},
{
"key": "country",
"value": "US",
"required": false
},
{
"key": "provider",
"value": "provider_a",
"required": false
},
{
"key": "institution_id",
"value": "inst_1",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Aggregated metrics",
"body": "{\n \"daily\": [],\n \"funnel\": [],\n \"failures\": [],\n \"latency\": []\n}"
}
}
}
Feature Flows
Consent Creation and Token Activation
sequenceDiagram
participant Partner as Partner Client
participant ConsentSvc as consentService
participant DB as Prisma Database
participant TokenSvc as tokenService
participant WebhookSvc as webhookService
participant Webhook as Partner Webhook
Partner->>ConsentSvc: createConsent
ConsentSvc->>DB: consent create
ConsentSvc->>DB: consentLog create CREATED
ConsentSvc-->>Partner: consent record
Partner->>TokenSvc: exchangeToken
TokenSvc->>DB: consent findUnique
alt Consent pending
TokenSvc->>DB: consent update ACTIVE
end
TokenSvc->>DB: token create
TokenSvc->>DB: consentLog create TOKEN_ISSUED
alt Consent activated
TokenSvc->>WebhookSvc: dispatchWebhook consent_activated
WebhookSvc->>Webhook: POST event payload
end
TokenSvc-->>Partner: TokenPair
Connection Readiness and Refresh
sequenceDiagram
participant Client as API Client
participant Access as requireAccessToken
participant ConnSvc as connectionService
participant DB as Prisma Database
participant ClientApp as Caller
Client->>Access: Bearer token or x-access-token
Access->>Access: verify JWT and attach claims
Client->>ConnSvc: ensureConnectionsReady
ConnSvc->>DB: connection findMany by consentId
alt No connections
ConnSvc-->>ClientApp: ACTIVE
else Reauth required
ConnSvc-->>ClientApp: throw REAUTH_REQUIRED
else Degraded
ConnSvc-->>ClientApp: DEGRADED
else Ready
ConnSvc-->>ClientApp: ACTIVE
end
Client->>ConnSvc: recordConnectionRefresh
ConnSvc->>DB: connection updateMany ACTIVE and lastRefreshedAt
ConnSvc-->>ClientApp: updated
Feature Computation and Decision Replay
sequenceDiagram
participant ScoringSvc as scoringService
participant FeatureSvc as featureService
participant Mock as mockProvider
participant Gov as modelGovernanceService
participant DB as Prisma Database
participant Callback as Scoring Callback
participant Client as Caller
ScoringSvc->>FeatureSvc: fetchEvidence
FeatureSvc->>DB: evidenceSnapshot findUnique
FeatureSvc-->>ScoringSvc: snapshot
FeatureSvc->>Mock: accounts balances transactions income
FeatureSvc->>Gov: ensureFeatureSchemaVersion
Gov->>DB: featureSchemaVersion find or create
FeatureSvc->>DB: evidenceSnapshot create
ScoringSvc->>Callback: POST evidence and features
alt Callback enabled
Callback-->>ScoringSvc: decision payload
ScoringSvc->>ScoringSvc: validateDecision
ScoringSvc->>ScoringSvc: storeDecision
ScoringSvc->>DB: decision create
ScoringSvc-->>Client: decision_id and payload
else No callback configured
ScoringSvc->>DB: decision findFirst by evidenceRef
ScoringSvc-->>Client: stored decision and audit envelope
end
Model Drift and Retraining Orchestration
sequenceDiagram
participant Job as Drift Job
participant Gov as modelGovernanceService
participant DB as Prisma Database
Job->>Gov: runFeatureDriftDetection
Gov->>DB: featureDriftBaseline findFirst
Gov->>DB: evidenceSnapshot findMany
Gov->>DB: featureDriftReport create
Job->>Gov: evaluateRetrainingTriggers
Gov->>DB: modelPerformanceSnapshot findFirst
Gov->>DB: featureDriftReport findFirst
Gov->>DB: retrainTrigger create
State Management
Consent State
PENDING_USER_ACTION: created bycreateConsent.ACTIVE: set byexchangeTokenwhen the consent is first activated.REVOKED: set byrevokeConsentand treated as inactive byensureConsentActiveand token refresh.- Expired consents are treated the same as revoked for access checks.
Connection State
ACTIVE: returned when no blocking connection state is found and forced byrecordConnectionRefresh.REAUTH_REQUIRED: causesensureConnectionsReadyto throwREAUTH_REQUIREDwithreauth_link.DEGRADED: returned as a non-blocking degraded state.DISCONNECTED: set by consent revocation.
Token State
- Access tokens are tracked by
jtiintokenrecords. - Refresh-token reuse is controlled through the hashed refresh token and daily refresh-event counting.
introspectTokenreturns inactive when the JWT is malformed, expired, revoked, or missing a persisted access JTI.
Governance State
- Feature schema version is pinned to
global-credit-v1. - Drift reports are created from recent evidence snapshots against a baseline.
- Retraining triggers are created when AUC or drift thresholds are breached.
- Model lineage records create a model artifact once and reuse it on subsequent calls.
Error Handling
Domain Error Codes
| Code | Source | Behavior |
|---|---|---|
TOKEN_REQUIRED |
requireAccessToken, authorize in the Go gateway |
Returned when no access token is supplied. |
INVALID_TOKEN |
requireAccessToken, introspectToken |
Returned for malformed or unverifiable access tokens. |
PARTNER_AUTH_REQUIRED |
requirePartnerAuth |
Returned for missing or unknown partner tokens. |
REAUTH_REQUIRED |
ensureConnectionsReady |
Returned when a consent-linked connection requires reauthentication. |
CONSENT_REVOKED |
revokeConsent, ensureConsentActive, refreshToken |
Returned when consent is revoked or expired. |
LEGAL_RESTRICTION |
validateDecision, exchangeToken, refreshToken |
Returned for invalid deny reasons or refresh token misuse. |
REFRESH_LIMIT_EXCEEDED |
enforceRefreshLimit |
Returned when daily refresh use exceeds the configured cap. |
NOT_FOUND |
getConsentReceipt, fetchEvidence |
Returned when a consent or evidence snapshot is missing. |
PROVIDER_UNAVAILABLE |
errorHandler, webhook failures, callback failures |
Returned for unexpected downstream failures. |
INVALID_BODY |
registerInternalAnalyticsRoutes |
Returned when the internal event body fails schema validation. |
INVALID_QUERY |
registerInternalAnalyticsRoutes |
Returned for malformed analytics query parameters or invalid date ranges. |
Error Pattern
- Domain services raise
ApiErrorfor expected failures. errorHandlerconvertsApiErrorinto a structured{ error, request_id }response.- Unexpected errors are converted into
PROVIDER_UNAVAILABLE. - Webhook failures during revoke and token activation are intentionally swallowed in the consent flow.
Dependencies
Runtime Packages
prismafor consent, token, connection, evidence, decision, drift, retraining, and audit persistence.jsonwebtokenfor JWT signing and verification.cryptofor IDs, hashes, and signatures.fastifyfor request context and middleware integration.zodfor internal analytics request validation.fetchfor webhook delivery and optional scoring callback replay.pgfor internal analytics jobs.
External Services
- Partner webhook endpoints via
dispatchWebhook. - Optional scoring callback endpoint via
config.scoringCallbackUrl. - Internal analytics consumers protected by
config.internalApiToken. - JWT public and private keys for access-token signing and verification.
Persistence Dependencies
- Consent, consent log, token, refresh event, connection, evidence snapshot, feature schema version, feature drift baseline, feature drift report, model performance snapshot, retrain trigger, model artifact, model deployment, decision, and access log records.
Testing Considerations
| Scenario | Coverage |
|---|---|
| Consent creation | Confirms a consent can be created and returns a success response. |
| Consent revocation | Verifies revocation completes successfully for an existing consent. |
| Refresh limits | Confirms refresh requests fail with 429 when the per-day limit is reached. |
| Category gating | Verifies /api/v1/us/data/accounts is rejected when ACCOUNTS is missing from the token scope. |
| PSU analytics idempotency | Confirms duplicate consent events do not write twice. |
| First terminal wins | Verifies a later terminal event does not override an earlier terminal failure. |
| Timestamp first-write-wins | Confirms existing session timestamps are preserved. |
| Daily metrics | Verifies daily aggregation counts started, completed, and failed sessions. |
| Timeout watchdog | Confirms stale sessions are marked as timed out. |
Key Classes Reference
| Class | Responsibility |
|---|---|
consentService.ts |
Creates, revokes, and reads consent receipts; propagates revocation. |
tokenService.ts |
Exchanges, refreshes, and introspects consent-scoped access tokens. |
connectionService.ts |
Evaluates connection readiness and refreshes consent-linked connections. |
featureService.ts |
Computes cashflow features and persists evidence snapshots. |
scoringService.ts |
Validates, stores, and replays decisions against evidence. |
modelGovernanceService.ts |
Manages feature schema, drift reporting, retraining triggers, and model lineage. |
creditFeatureSchema.ts |
Defines the global credit feature schema and migration rules. |
types.ts |
Defines purpose, category, connection, and token claim scopes. |
mockProvider.ts |
Supplies deterministic account, balance, transaction, and income data for feature derivation. |
webhookService.ts |
Signs and dispatches partner webhook events. |
accessToken.ts |
Verifies access tokens and attaches consent claims to requests. |
partnerAuth.ts |
Verifies partner identity for consent-facing requests. |
internalAuth.ts |
Protects internal-only analytics endpoints. |
requestId.ts |
Normalizes request IDs for tracing and audit logging. |
auditLogger.ts |
Writes access logs after responses complete. |
errorHandler.ts |
Converts domain failures into structured API responses. |