User Consent Management Domain
Overview
This domain turns consent activity into auditable operational data. It captures internal consent events, rolls them up into daily cohorts, classifies stale sessions as timeouts, and pushes consent lifecycle changes to partner webhook endpoints. The same telemetry also feeds compliance reporting, monitoring, and model-governance signals used to detect drift and retraining pressure.
It is centered on the US API consent lifecycle and the analytics schema under analytics.*. The visible code records session state, event ingestion history, daily metrics, webhook delivery attempts, and response-level access logs so that consent behavior can be traced from intake through terminal outcomes.
Architecture Overview
flowchart TD
subgraph Ingress[Ingress and Jobs]
InternalRoutes[registerInternalAnalyticsRoutes]
DailyJob[runDailyPsuConsentMetricsJob]
TimeoutJob[runPsuConsentTimeoutWatchdog]
DriftJob[runDailyFeatureDriftCheck]
end
subgraph ConsentCore[Consent and Audit Core]
ApplyEvent[applyConsentEvent]
ConsentSvc[createConsent revokeConsent getConsentReceipt ensureConsentActive]
WebhookSvc[dispatchWebhook]
AuditSvc[registerAuditLogger]
ModelGov[runFeatureDriftDetection evaluateRetrainingTriggers]
end
subgraph Storage[PostgreSQL and Prisma]
Sessions[analytics psu consent sessions]
Events[analytics psu consent events]
Daily[analytics psu consent daily metrics]
WebhookData[webhook endpoints and deliveries]
AuditLog[access log]
end
subgraph External[External Systems]
InternalAuth[Internal auth]
PartnerEndpoint[Partner webhook endpoint]
Scheduler[Cron and process argv]
end
Scheduler --> DailyJob
Scheduler --> TimeoutJob
Scheduler --> DriftJob
InternalRoutes --> InternalAuth
InternalRoutes --> ApplyEvent
InternalRoutes --> Sessions
InternalRoutes --> Events
DailyJob --> Daily
TimeoutJob --> ApplyEvent
TimeoutJob --> Sessions
ConsentSvc --> WebhookSvc
WebhookSvc --> WebhookData
WebhookSvc --> PartnerEndpoint
AuditSvc --> AuditLog
DriftJob --> ModelGov
Component Structure
1. Consent Analytics Routes
services/us-api/src/routes/internalAnalytics.ts
These routes ingest consent lifecycle events and expose daily consent telemetry for internal consumers. Both handlers are wrapped with requireInternalAuth, so the request is rejected before the handler executes unless the internal auth middleware passes.
Public Methods
| Method | Description |
|---|---|
registerInternalAnalyticsRoutes |
Registers the internal event-ingestion and telemetry-query routes on a FastifyInstance. |
Request Models
eventSchema
| Property | Type | Description | ||
|---|---|---|---|---|
psu_id |
string |
PSU identifier attached to the consent session. | ||
consent_session_id |
string |
Session identifier used to correlate all consent events. | ||
product |
string |
Product label stored with the session. | ||
country |
string |
Country code associated with the session. | ||
provider |
string |
Provider name used for the session. | ||
institution_id |
`string \ | null \ | undefined` | Optional institution identifier. |
timestamp |
string |
ISO-8601 timestamp validated with z.string().datetime(). |
||
failure_reason |
`string \ | null \ | undefined` | Optional failure reason attached to terminal events. |
event_name |
ConsentEventNames |
Event name constrained to the consent analytics allowlist. |
metricsQuerySchema
| Property | Type | Description | |
|---|---|---|---|
start_date |
string |
Inclusive cohort start date in YYYY-MM-DD format. |
|
end_date |
string |
Inclusive cohort end date in YYYY-MM-DD format. |
|
product |
`string \ | undefined` | Optional product filter. |
country |
`string \ | undefined` | Optional country filter. |
provider |
`string \ | undefined` | Optional provider filter. |
institution_id |
`string \ | undefined` | Optional institution filter. |
API Integration
Ingest Consent Event
{
"title": "Ingest Consent Event",
"description": "Validates an internal PSU consent event and forwards it to the consent analytics ingestion pipeline",
"method": "POST",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/internal/analytics/events",
"headers": [],
"queryParams": [],
"pathParams": [],
"bodyType": "json",
"requestBody": "{\n \"psu_id\": \"psu_123\",\n \"consent_session_id\": \"sess_123\",\n \"product\": \"product_a\",\n \"country\": \"US\",\n \"provider\": \"provider_a\",\n \"institution_id\": null,\n \"timestamp\": \"2024-01-01T00:05:00.000Z\",\n \"failure_reason\": null,\n \"event_name\": \"consent_completed\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Success",
"body": "{\n \"status\": \"stored\"\n}"
},
"400": {
"description": "Invalid body",
"body": "{\n \"error\": {\n \"code\": \"INVALID_BODY\",\n \"message\": \"Invalid request body\"\n },\n \"request_id\": \"req_123\"\n}"
},
"409": {
"description": "Dimension mismatch",
"body": "{\n \"status\": \"dimension_mismatch\"\n}"
}
}
}
Get PSU Consent Metrics
{
"title": "Get PSU Consent Metrics",
"description": "Returns daily cohort rollups, funnel metrics, failure breakdowns, and latency metrics for consent analytics",
"method": "GET",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/internal/analytics/psu-consent/metrics",
"headers": [],
"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_123",
"required": false
}
],
"pathParams": [],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Success",
"body": "{\n \"daily\": [],\n \"funnel\": [],\n \"failures\": [],\n \"latency\": []\n}"
},
"400": {
"description": "Invalid query",
"body": "{\n \"error\": {\n \"code\": \"INVALID_QUERY\",\n \"message\": \"start_date must be <= end_date\"\n },\n \"request_id\": \"req_123\"\n}"
}
}
}
Event Ingestion Semantics
applyConsentEvent(pool, parsed.data)is the only mutation path in the handler.- A
dimension_mismatchresult is translated into HTTP409. - All other statuses are returned directly as
{ status: result.status }. - The route validates body shape before any database write occurs.
2. Webhook Delivery Service
services/us-api/src/webhooks/webhookService.ts
This service dispatches consent lifecycle events to active partner webhook endpoints. It discovers enabled subscriptions, writes a delivery record before sending, signs the payload, and updates the delivery status after the HTTP attempt.
Public Methods
| Method | Description |
|---|---|
dispatchWebhook |
Loads matching webhook endpoints for a partner and sends the event payload to each endpoint. |
Request and Delivery Models
WebhookEvent
| Property | Type | Description |
|---|---|---|
event |
string |
Logical webhook event name. |
payload |
Record<string, unknown> |
Event payload delivered to the partner endpoint. |
Webhook endpoint fields used by dispatchWebhook
| Property | Type | Description |
|---|---|---|
id |
string |
Endpoint identifier used for delivery records. |
partnerId |
string |
Partner owner used for filtering. |
active |
boolean |
Endpoint must be active to receive the event. |
events |
string[] |
Subscription list checked with has: event.event. |
url |
string |
Destination URL for the HTTP POST. |
secret |
string |
Secret used to compute the webhook signature. |
Webhook delivery fields written by the service
| Property | Type | Description |
|---|---|---|
id |
string |
Generated delivery identifier. |
webhookId |
string |
References the subscribed endpoint. |
eventType |
string |
Event name stored in the delivery row. |
payload |
Record<string, unknown> |
Stored event payload. |
status |
string |
Set to PENDING, DELIVERED, or FAILED. |
attemptCount |
number |
Set to 1 for the current attempt. |
lastAttemptAt |
Date |
Timestamp of the attempt update. |
Delivery Semantics
- The service filters endpoints by
partnerId,active: true, and event subscription. - Each matching endpoint gets a
webhookDeliveryrow before the outbound request begins. - The outgoing request includes:
Content-Type: application/jsonX-Webhook-SignatureIdempotency-Key
- The body posted to the partner is
{ event, data }. - A non-OK HTTP response marks the delivery as
FAILEDbut does not throw. - A network or fetch failure marks the delivery as
FAILEDand throwsApiError(502, 'PROVIDER_UNAVAILABLE', 'Webhook dispatch failed').
Consent Lifecycle Hooks
[!NOTE] The published US API contract states webhook delivery is signed, retried, deduplicated, and at-least-once. The visible
dispatchWebhookimplementation persists one delivery row, performs a singlefetchattempt, and storesattemptCount: 1; no retry loop is present in this file.
The visible consent flow emits webhook events from two paths:
exchangeTokenemitsconsent_activatedafter a pending consent becomesACTIVE.revokeConsentemitsconsent_revokedafter the consent record is markedREVOKED.
Both flows catch and ignore webhook delivery failures so the core consent mutation still completes.
Sequence of a Successful Delivery
sequenceDiagram
participant S as Consent Service
participant W as dispatchWebhook
participant P as Prisma
participant E as Partner Endpoint
S->>W: event and partnerId
W->>P: findMany webhookEndpoint
P-->>W: active matching endpoints
W->>P: create webhookDelivery PENDING
W->>E: POST event data with signature
E-->>W: 200 OK
W->>P: update webhookDelivery DELIVERED
3. Consent Lifecycle and Receipt Service
services/us-api/src/services/consentService.ts
This service owns consent creation, revocation, receipt materialization, and the active-consent check used by downstream access control. It also emits the consent audit trail by writing consent log rows.
Public Methods
| Method | Description |
|---|---|
createConsent |
Creates a new consent in PENDING_USER_ACTION and writes a CREATED consent log entry. |
revokeConsent |
Marks the consent REVOKED, revokes active tokens, disconnects linked connections, writes a REVOKED log entry, and attempts a revocation webhook. |
getConsentReceipt |
Returns the consent receipt payload used for audit and compliance review. |
ensureConsentActive |
Validates that the consent exists, is ACTIVE, and is not expired. |
Request and Response Models
CreateConsentPayload
| Property | Type | Description | |
|---|---|---|---|
user |
{ country: 'US'; user_reference?: string } |
User identity envelope. | |
purpose |
Purpose |
Declared purpose of the consent. | |
data_categories |
DataCategory[] |
Granted data scope. | |
access_duration_days |
`number \ | undefined` | Relative expiry window used when expires_at is absent. |
expires_at |
`string \ | undefined` | Absolute expiry timestamp. |
refresh_permissions |
`{ enabled: boolean; max_refresh_per_day: number } \ | undefined` | Refresh policy for the consent. |
consent_disclosure_version |
string |
Disclosure version captured with the consent. |
Consent receipt response
| Property | Type | Description |
|---|---|---|
consent_id |
string |
Consent identifier. |
status |
string |
Current consent status. |
purpose |
string |
Stored consent purpose. |
data_categories |
string[] |
Granted data categories. |
consent_disclosure_version |
string |
Disclosure version captured at creation. |
expires_at |
string |
ISO timestamp for expiry. |
created_at |
string |
ISO timestamp for creation. |
Receipt and Audit Expectations
createConsentwrites a consent record and aconsentLogrow withaction: 'CREATED'.revokeConsentwritesaction: 'REVOKED'and updates all related tokens and connections before attempting webhook delivery.getConsentReceiptis read-only and returns the stored receipt fields needed for audits.ensureConsentActiveraisesApiError(409, 'CONSENT_REVOKED')for missing, revoked, or expired consent.
Consent Lifecycle Flow
sequenceDiagram
participant P as Partner
participant C as Consent Service
participant D as Prisma
participant W as dispatchWebhook
P->>C: createConsent payload
C->>D: insert consent
C->>D: insert consentLog CREATED
C-->>P: consent record
P->>C: revokeConsent consentId
C->>D: mark consent REVOKED
C->>D: revoke tokens and connections
C->>D: insert consentLog REVOKED
C->>W: consent_revoked
W-->>C: delivery result or error
C-->>P: consentId
API Integration
Create Consent
{
"title": "Create Consent",
"description": "Creates a new US consent and returns a user authorization link",
"method": "POST",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/api/v1/us/consents",
"headers": [
{
"key": "Authorization",
"value": "Bearer <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\": null,\n \"refresh_permissions\": {\n \"enabled\": true,\n \"max_refresh_per_day\": 4\n },\n \"consent_disclosure_version\": \"v1\"\n}",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Success",
"body": "{\n \"consent_id\": \"consent_123\",\n \"status\": \"PENDING_USER_ACTION\",\n \"expires_at\": \"2024-12-31T00:00:00Z\",\n \"auth\": {\n \"link_url\": \"https://link.lita.com/us/consent_123\"\n }\n}"
}
}
}
Get Consent Receipt
{
"title": "Get Consent Receipt",
"description": "Returns the stored consent receipt for audit and compliance review",
"method": "GET",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/api/v1/us/consents/{consent_id}/receipt",
"headers": [
{
"key": "Authorization",
"value": "Bearer <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": "Success",
"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\": \"2024-12-31T00:00:00.000Z\",\n \"created_at\": \"2024-01-01T00:00:00.000Z\"\n}"
}
}
}
Revoke Consent
{
"title": "Revoke Consent",
"description": "Immediately revokes the consent, linked tokens, and linked connections",
"method": "POST",
"baseUrl": "<UsApiBaseUrl>",
"endpoint": "/api/v1/us/consents/{consent_id}/revoke",
"headers": [
{
"key": "Authorization",
"value": "Bearer <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": "Success",
"body": "{\n \"consentId\": \"consent_123\"\n}"
}
}
}
4. Audit Logging Service
services/us-api/src/middleware/auditLogger.ts
This middleware captures request-level audit entries after the response is sent. It uses the partner identity, consent identity, route, and final status code to build an access-log row.
Public Methods
| Method | Description |
|---|---|
registerAuditLogger |
Registers an onResponse hook that persists access log entries. |
Audit Record Fields
| Property | Type | Description | |
|---|---|---|---|
id |
string |
Generated access log identifier. | |
requestId |
string |
Value read from x-request-id. |
|
partnerId |
`string \ | null` | Populated from request.partnerId when available. |
consentId |
`string \ | null` | Populated from request.accessClaims?.consent_id when available. |
route |
string |
Route URL or raw request URL. | |
statusCode |
number |
Final response status code. |
Lifecycle Behavior
- The hook executes after the response is generated.
- If Prisma initialization fails, audit logging is disabled globally for the process and a single warning is emitted.
- Other persistence failures are logged as warnings without blocking the response.
5. Consent Analytics Jobs
services/us-api/src/jobs/dailyPsuConsentMetrics.ts
services/us-api/src/jobs/psuConsentTimeoutWatchdog.ts
services/us-api/src/jobs/featureDriftJob.ts
These jobs keep consent telemetry current. One job produces daily cohort rollups, one classifies stale sessions as timeouts, and one runs feature-drift detection on consent-derived evidence snapshots.
Public Methods
| Method | Description |
|---|---|
runDailyPsuConsentMetricsJob |
Resolves the job date and lookback window, then calls refreshDailyMetricsForRange. |
runPsuConsentTimeoutWatchdog |
Finds open consent sessions and emits synthetic timeout events for rows that have passed their deadline. |
runDailyFeatureDriftCheck |
Runs feature-drift detection against the US_CASHFLOW_V1 feature set. |
Job Configuration
| Environment Variable | Default | Description |
|---|---|---|
LOOKBACK_DAYS |
7 |
Number of days passed to the daily metrics refresh. |
RUN_DATE |
current date | Override date used by the daily metrics job, expected in YYYY-MM-DD. |
DEFAULT_TIMEOUT_MINUTES |
15 |
Fallback timeout for sessions without a provider-specific timeout. |
PROVIDER_TIMEOUT_MINUTES |
{} |
JSON map of provider name to timeout minutes. |
psuConsentTimeoutWatchdog.ts Behavior
parseProviderTimeoutMap()returns an empty map when the environment value is missing, invalid JSON, non-object, ornull.resolveDefaultTimeoutMinutes()returns15when the env var is missing or not numeric.- The watchdog selects rows where
final_status IS NULLandstarted_at IS NOT NULL. - Each row gets a deadline of
started_at + timeoutMinutes. - Expired sessions emit a synthetic consent event:
event_name: 'consent_timeout'failure_reason: 'timeout'timestamp: now.toISOString()
featureDriftJob.ts Behavior
- Calls
runFeatureDriftDetectionwith:featureSet: 'US_CASHFLOW_V1'schemaVersion: GLOBAL_CREDIT_FEATURE_SCHEMA_VERSIONsampleLimit: 500baselineLabel: 'training-baseline'
Model Governance Hooks
services/us-api/src/services/modelGovernanceService.ts
| Method | Description |
|---|---|
ensureFeatureSchemaVersion |
Creates the feature schema version record if it does not already exist. |
runFeatureDriftDetection |
Loads the baseline and live snapshots, computes drift statistics, and persists a featureDriftReport. |
evaluateRetrainingTriggers |
Evaluates AUC and drift thresholds and creates a pending retrain trigger when the thresholds are breached. |
recordModelLineage |
Creates a model artifact and active deployment record when model lineage does not yet exist. |
Drift and retraining inputs
| Type | Property | Description |
|---|---|---|
DriftInput |
featureSet |
Feature set identifier to evaluate. |
DriftInput |
schemaVersion |
Feature schema version used for baseline matching. |
DriftInput |
sampleLimit |
Optional number of snapshots to sample. |
DriftInput |
baselineLabel |
Optional baseline selector; defaults to training-baseline. |
PerformanceThresholds |
aucMin |
Minimum acceptable AUC. |
PerformanceThresholds |
driftScoreMax |
Maximum acceptable drift score. |
Daily Cohort Rollup Semantics
The visible tests confirm that daily rollups are cohort-based on started_at date, not on the terminal event date. That means the metrics job summarizes sessions by the day they began, then counts terminal outcomes for that cohort.
Sequence of a Timeout Classification
sequenceDiagram
participant C as Cron
participant W as runPsuConsentTimeoutWatchdog
participant P as Postgres
participant A as applyConsentEvent
C->>W: run
W->>P: select open sessions
P-->>W: rows with started_at and no final_status
loop each expired row
W->>A: consent_timeout event
A->>P: update session and append event
P-->>A: persisted
end
W-->>C: completed
Sequence of a Daily Rollup
sequenceDiagram
participant C as Cron
participant J as runDailyPsuConsentMetricsJob
participant R as refreshDailyMetricsForRange
participant P as Postgres
C->>J: run
J->>R: runDate and lookbackDays
R->>P: aggregate sessions by started_at date
P-->>R: cohort totals
R-->>J: metrics refreshed
J-->>C: completed
6. Consent Analytics Storage
services/us-api/src/migrations/001_create_psu_consent_analytics.sql
The migration creates the analytics schema used by the ingestion and rollup paths. The visible code reads and writes the following tables and fields.
| Table | Purpose | Observed fields in code |
|---|---|---|
analytics.psu_consent_sessions |
Stores the session-level state machine for each consent session. | consent_session_id, psu_id, product, country, provider, institution_id, started_at, final_status, failure_reason, timeout_at |
analytics.psu_consent_events |
Stores ingested consent events and supports idempotency checks. | psu_id, consent_session_id, product, country, provider, institution_id, timestamp, event_name, failure_reason |
analytics.psu_consent_daily_metrics |
Stores daily cohort rollups by session start date. | date, sessions_started, sessions_completed, sessions_failed |
State and Event Rules Verified by Tests
- Duplicate events are idempotent.
- The first terminal event wins even if a later terminal event arrives.
- Step timestamps are first-write-wins through
COALESCE. - Timeout events set
final_statustotimeoutand populatetimeout_at.
7. Published US API Contract
documents/us-api-v1.md
This document defines the public consent contract that the consent services and telemetry support. It is the source for the consent receipt and webhook semantics referenced by this section.
Relevant documented endpoints
POST /api/v1/us/consentsGET /api/v1/us/consents/{consent_id}/receiptPOST /api/v1/us/consents/{consent_id}/revokePOST /api/v1/us/webhooksGET /api/v1/us/webhooksDELETE /api/v1/us/webhooks/{webhook_id}
Supported webhook events listed in the contract
consent_activatedconsent_revokedconnection_reauth_requiredconnection_refreshedconnection_degradeddecision_completed
Contract guarantees
- Consent receipts are available for audit and compliance review.
- Webhook delivery is described as signed, retried, deduplicated, and at-least-once.
- Consent access is revoked when consent is revoked or expires.
8. Test Coverage
services/us-api/test/psuConsentAnalytics.test.ts
services/us-api/test/flows.test.ts
The test suite validates the consent telemetry pipeline end to end using pg-mem and mocked Fastify middleware.
psuConsentAnalytics.test.ts scenarios
| Scenario | Behavior asserted |
|---|---|
| Duplicate event ingestion | applyConsentEvent does not update twice for the same event. |
| First terminal wins | A later terminal event does not overwrite the first terminal result. |
| First-write-wins timestamps | consent_start does not replace an earlier started_at. |
| Daily metrics aggregation | Rollups count sessions by started_at date. |
| Timeout watchdog | A stale session gets final_status: timeout and a populated timeout_at. |
flows.test.ts scenarios
| Scenario | Behavior asserted |
|---|---|
| Consent creation | POST /api/v1/us/consents succeeds with the mocked Prisma path. |
| Consent revocation | POST /api/v1/us/consents/consent_1/revoke succeeds. |
| Refresh limit enforcement | POST /api/v1/us/tokens/refresh returns 429 when the daily limit is reached. |
| Category gating | GET /api/v1/us/data/accounts returns 403 when the consent scope omits ACCOUNTS. |
9. State Management
Consent Lifecycle States
| State | Description |
|---|---|
PENDING_USER_ACTION |
Consent has been created and is waiting for user authorization. |
ACTIVE |
Consent is usable for downstream access and webhook emission. |
REVOKED |
Consent has been invalidated and cannot be used further. |
Consent Session Final States
| State | Description |
|---|---|
completed |
Terminal successful session outcome. |
failed |
Terminal failure outcome recorded by ingestion. |
timeout |
Synthetic terminal outcome emitted by the watchdog. |
null |
Session still open and eligible for timeout classification. |
Delivery States
| State | Description |
|---|---|
PENDING |
Delivery row created before the outbound HTTP attempt. |
DELIVERED |
Partner endpoint returned an OK response. |
FAILED |
Partner endpoint returned a non-OK response or the fetch failed. |
Retraining Signal States
| State | Description |
|---|---|
PENDING |
evaluateRetrainingTriggers created a retrain trigger that still needs action. |
Transition Rules
PENDING_USER_ACTIONbecomesACTIVEthrough token exchange.ACTIVEbecomesREVOKEDthrough revocation.- Open sessions transition to
timeoutonly when the watchdog emitsconsent_timeout. - The first terminal consent event is retained as the final state.
PENDINGwebhook deliveries move toDELIVEREDorFAILEDafter the HTTP attempt.- Retraining triggers are created only when either AUC or drift thresholds are breached.
10. Integration Points
applyConsentEventreceives all internal consent analytics events.refreshDailyMetricsForRangepowers daily cohort rollups.fetchDailyMetrics,fetchFunnelMetrics,fetchFailureBreakdown, andfetchLatencyMetricsback the internal metrics query.dispatchWebhookemits consent lifecycle events to partner endpoints.registerAuditLoggercaptures response-level audit trails for consent-related traffic.runFeatureDriftDetectionandevaluateRetrainingTriggersturn consent-derived evidence into model-monitoring signals.documents/us-api-v1.mddefines the externally visible consent and webhook contract that this domain supports.
11. Analytics and Telemetry
This domain records telemetry at multiple layers:
- Internal consent events via
analytics.psu_consent_events - Session outcomes via
analytics.psu_consent_sessions - Daily rollups via
analytics.psu_consent_daily_metrics - Outbound webhook attempts via
webhookDelivery - Request/response audit trails via
accessLog - Consent lifecycle actions via
consentLogwithCREATED,TOKEN_ISSUED, andREVOKED
12. Error Handling
| Location | Error condition | Behavior |
|---|---|---|
registerInternalAnalyticsRoutes |
Invalid event body | Throws ApiError(400, 'INVALID_BODY', ...). |
registerInternalAnalyticsRoutes |
Invalid query or inverted date range | Throws ApiError(400, 'INVALID_QUERY', ...). |
registerInternalAnalyticsRoutes |
Dimension mismatch from event ingest | Returns 409 with { status: 'dimension_mismatch' }. |
ensureConsentActive |
Missing, revoked, or expired consent | Throws ApiError(409, 'CONSENT_REVOKED'). |
revokeConsent |
Consent not found | Throws ApiError(404, 'NOT_FOUND'). |
dispatchWebhook |
Partner fetch failure | Marks delivery failed and throws ApiError(502, 'PROVIDER_UNAVAILABLE', 'Webhook dispatch failed'). |
dispatchWebhook |
Partner HTTP non-OK response | Marks delivery failed and continues without throwing. |
registerAuditLogger |
Prisma initialization error | Disables audit logging globally and emits one warning. |
runDailyPsuConsentMetricsJob |
Invalid RUN_DATE |
Throws RUN_DATE must be YYYY-MM-DD. |
runPsuConsentTimeoutWatchdog |
Invalid provider timeout JSON | Falls back to defaults and continues. |
13. Caching Strategy
The consent analytics and watchdog code paths shown here are database-driven and recompute from persisted rows on each run. The only stateful runtime behavior visible in this section is process-level control flow such as audit-log disablement after Prisma initialization failure and job configuration via environment variables.
14. Dependencies
fastifyfor the internal route registration.zodfor request/query validation.pgfor job-level database access.- Prisma for consent, token, connection, webhook, access-log, and model-governance persistence.
- Native
cryptofor consent IDs, delivery IDs, and log IDs. fetchfor outbound webhook delivery and partner calls.pg-meminpsuConsentAnalytics.test.tsfor in-memory validation of the migration and analytics behavior.jestfor route and analytics flow tests.
Key Classes Reference
| Class | Responsibility |
|---|---|
internalAnalytics.ts |
Internal consent event ingestion and consent metrics query endpoints. |
webhookService.ts |
Signed outbound webhook delivery and delivery-state tracking. |
consentService.ts |
Consent creation, revocation, receipt generation, and active-consent checks. |
auditLogger.ts |
Response-level access logging for compliance and traceability. |
dailyPsuConsentMetrics.ts |
Daily cohort rollup job entrypoint. |
psuConsentTimeoutWatchdog.ts |
Stale-session timeout classification job entrypoint. |
featureDriftJob.ts |
Consent-evidence drift monitoring job entrypoint. |
modelGovernanceService.ts |
Feature schema versioning, drift detection, retraining trigger evaluation, and model lineage. |
001_create_psu_consent_analytics.sql |
Analytics schema creation for sessions, events, and daily metrics. |
psuConsentAnalytics.test.ts |
Validation of idempotency, terminal-state rules, rollups, and timeout behavior. |
flows.test.ts |
Consent lifecycle and access-control flow validation. |
us-api-v1.md |
Published consent, receipt, webhook, and delivery contract. |