Credit Scoring and Decisions Domain - Decision Events, Webhook Fan-Out, and Async Completion Flow

docs/docs-api.md · apps/api/src/routes/v1/events.ts · apps/api/src/routes/v1/webhooks.ts · apps/worker/src/index.ts

Overview

This domain turns scoring and compliance milestones into webhook-driven integration points. Internal event ingestion accepts scoped events for audit capture, tenant webhook registration controls where notifications are delivered, and the regional scoring surfaces emit features.computed, score.completed, and decision.completed events as evidence snapshots and decisions become available.

The operational model is split between request-time API handlers and background delivery. The API layer creates webhook delivery records and tags them for tenants, while apps/worker/src/index.ts continuously pulls queued deliveries, signs each request, posts it to the subscriber’s HTTPS endpoint, and records failures for compliance review.

Architecture Overview

flowchart TB
  subgraph InternalApi [Internal API Surface]
    EventsRoute[v1 events route]
    WebhooksRoute[v1 webhooks routes]
  end

  subgraph RegionalSurfaces [Regional scoring surfaces]
    USCompute[US feature compute]
    JPCompute[JP feature compute]
    ScoreRead[Score readback]
    StatusRead[Job status readback]
  end

  subgraph WebhookDelivery [Webhook delivery pipeline]
    EndpointRegistry[Webhook endpoint registry]
    DeliveryQueue[Webhook delivery records]
    Worker[Worker process]
  end

  subgraph ExternalSystems [External systems]
    TenantEndpoint[Registered HTTPS endpoint]
    InternalProducer[Internal event producer]
  end

  InternalProducer -->|POST event payload| EventsRoute
  EventsRoute -->|audit event only| AuditLog[Audit event log]

  WebhooksRoute -->|create and list endpoints| EndpointRegistry
  WebhooksRoute -->|enqueue test delivery| DeliveryQueue

  USCompute -->|enqueue features.computed and score.completed| DeliveryQueue
  JPCompute -->|enqueue features.computed and score.completed| DeliveryQueue
  ScoreRead -->|emit decision.completed| DeliveryQueue

  DeliveryQueue --> Worker
  Worker -->|signed POST| TenantEndpoint
  TenantEndpoint -->|verify signature| TenantVerifier[Webhook verification helpers]

Event Semantics

Documented webhook catalog

The webhook reference in docs/docs-api.md defines the tenant-facing event catalog:

Event Fires When
consent.activated Applicant completes the redirect flow and consent transitions to ACTIVE
consent.expired Consent passes its expiry date without activation or renewal
consent.revoked Consent is explicitly revoked via DELETE /consents/{id}
data.updated New or updated financial data is received for an active consent
features.computed Feature computation pipeline completes successfully
score.completed Score computation completes. Score and evidence_ref are now available
kyc.updated KYC/AML screening result changes, including from manual review outcomes

Observed emitters in the provided code

Event Where it is emitted Payload fields
consent.activated Regional token exchange flow consent_id, status: "ACTIVE"
connection.created Regional token exchange flow consent_id
consent.revoked Regional revoke flow consent_id, status
connection.degraded ensureConnection helper path consent_id, connection_id
connection.refreshed After touchConnection / touchJpConnection consent_id, connection_id
connection.reauth_required Refresh-token limit branch reason: "refresh_limit_exceeded"
features.computed Regional compute flow consent_id, job_id, evidence_ref
score.completed Regional compute flow consent_id, evidence_ref
decision.completed Regional score readback flow consent_id, evidence_ref, decision, approved_limit, reasons

Component Structure

Internal Event Ingestion

Note: decision.completed is emitted by the regional score endpoints, but it is not listed in the webhook catalog in docs/docs-api.md. Note: The documented score.completed semantics say the score is available when the event fires, but the shown regional code emits score.completed with consent_id and evidence_ref only. The numeric score is returned separately by GET /{region}/consents/{consentId}/score.

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

The eventsRoutes plugin exposes a single ingestion endpoint for internal callers. The handler validates that the caller has the internal:events scope, writes the payload to the audit trail with request.logAuditEvent, and returns 202 Accepted with { accepted: true }.

Request Model

Property Type Description
type string Internal event type name
payload record<string, unknown> Arbitrary event payload forwarded into the audit entry

Response Model

Property Type Description
accepted boolean true when the event has been accepted for ingestion

Execution Path

  1. requireScope(request, "internal:events") gates the handler.
  2. request.logAuditEvent records event.ingest.
  3. The handler returns 202 with accepted: true.

Webhook Endpoint Registry and Fan-Out

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

The webhooksRoutes plugin manages tenant webhook endpoints and a test fan-out path. The routes require request.tenantId; if it is missing, the handler throws Error("missing tenant") before any persistence or enqueue call.

Request and Response Models

Model Property Type Description
endpointSchema url string HTTPS endpoint URL to register
endpointSchema events string[] Event names subscribed to by the endpoint
Create response id string Registered webhook endpoint identifier
Create response url string Registered endpoint URL
Create response events string[] Events attached to the endpoint
testSchema eventType string Event name used for the test fan-out
testSchema payload record<string, unknown> Test payload delivered to each registered endpoint
Test response queued number Number of webhook deliveries enqueued

Endpoint Behavior

Method Description
POST /endpoints Creates a tenant webhook endpoint, records webhook.endpoint.create, and returns the stored endpoint
GET /endpoints Returns all webhook endpoints for the current tenant
POST /test Loads the tenant endpoints and enqueues one delivery per endpoint for the supplied event type and payload, then records webhook.test

Fan-Out Behavior

The test route performs explicit fan-out:

  1. listWebhookEndpoints(request.tenantId) loads all tenant endpoints.
  2. enqueueWebhookDelivery(request.tenantId, endpoint.id, body.eventType, body.payload) is called once per endpoint.
  3. request.logAuditEvent records the batch with targetId: "batch" and a count of queued deliveries.

Regional Completion and Decision Surfaces

docs/docs-api.md · apps/api/src/routes/us/index.ts · apps/api/src/routes/jp/index.ts

The regional docs describe the async scoring sequence:

  1. Create a consent.
  2. Wait for consent.activated.
  3. Call POST /{region}/features/compute.
  4. Wait for score.completed or poll GET /{region}/status/{job_id}.
  5. Fetch the score from GET /{region}/consents/{consentId}/score.

The route implementations show two compute patterns:

  • Partner-auth mode when consent_id is included in the request body. The handler creates an evidence snapshot, writes a job record with status: "COMPLETE", and returns 202 Accepted.
  • Access-token mode when consent_id is not in the body. The handler returns the computed evidence reference and feature vector directly with 200 OK.

Documented Async Flow

Step Endpoint Result
Create consent POST /{region}/consents Returns redirect URL and PENDING consent
Activate consent POST /{region}/consents/{consentId}/token Moves consent to ACTIVE and emits consent.activated
Compute features POST /{region}/features/compute Creates evidence snapshot and emits features.computed and score.completed
Poll completion GET /{region}/status/{job_id} Returns PROCESSING, COMPLETE, or FAILED
Read score GET /{region}/consents/{consentId}/score Returns score data and emits decision.completed

Webhook Signature Verification Helpers

Note: In partner-auth mode, the handler stores the job as COMPLETE immediately, but the HTTP response still reports status: "PROCESSING" and estimated_completion_ms: 0. The polling endpoint therefore reflects the stored job state rather than a deferred compute job.

The webhook consumer guidance in docs/docs-api.md requires verification of X-Lita-Signature before processing payloads. The repository includes matching helpers in the official SDKs:

File Helper
sdks/node/src/webhooks.ts constructEvent
sdks/java/src/main/java/com/joinlita/Webhooks.java constructEvent
sdks/python/lita/webhooks.py construct_event

These helpers verify the raw body against the sha256= HMAC signature before deserializing the payload.

Webhook Delivery Worker

apps/worker/src/index.ts

The worker process continuously polls the webhook delivery table and performs background delivery. It is responsible for signing outgoing webhook requests, retrying transient failures, and writing compliance/audit records when a delivery fails.

Module Properties

Property Type Description
POLL_INTERVAL_MS number Fixed interval between polling cycles

Worker Functions

Method Description
processDelivery Loads a delivery and its endpoint, signs the raw payload, posts it to the subscriber, and updates delivery status
pollDeliveries Pulls up to 10 pending or retrying deliveries whose retry window has elapsed and hands them to processDelivery
run Runs the infinite polling loop with POLL_INTERVAL_MS delays

Delivery State

Field Type Description
status pending · retrying · delivered · failed Delivery lifecycle state used by the worker
attempts number Delivery retry count
lastError string Last failure message captured from the worker
nextRetryAt Date Next retry time for retryable deliveries
payloadJson unknown Stored webhook payload body
endpoint.secret string Shared secret used to sign the outbound request
endpoint.url string Subscriber HTTPS URL

Delivery Lifecycle

  1. pollDeliveries() loads up to 10 rows where status is pending or retrying.
  2. processDelivery() serializes payloadJson and generates a timestamped signature with signWebhook.
  3. The worker sends POST with Content-Type: application/json, X-Lita-Signature, and X-Lita-Timestamp.
  4. On success, the delivery row is marked delivered.
  5. On failure, attempts increments, status becomes retrying until the fifth failure, and recordAuditEvent writes webhook.delivery.failed.

Retry Rules

  • Retry delay is linear: attempts * 60_000.
  • Deliveries reach failed after 5 attempts.
  • Polling continues even when a cycle throws; the worker logs the error and keeps running.

API Integration

Ingest Internal Event

Ingest Internal Event

{
    "title": "Ingest Internal Event",
    "description": "Accepts an internal event payload, requires the internal:events scope, writes an audit event, and returns accepted: true",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/events",
    "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    \"type\": \"score.completed\",\n    \"payload\": {\n        \"event_id\": \"evt_9uVwX0yZ1aB2\",\n        \"consent_id\": \"con_8kXpL9mR2nQv\",\n        \"evidence_ref\": \"ev_5sKjL2mN8pQr\",\n        \"region\": \"us\"\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "202": {
            "description": "Accepted",
            "body": "{\n    \"accepted\": true\n}"
        }
    }
}

Register Webhook Endpoint

Register Webhook Endpoint

{
    "title": "Register Webhook Endpoint",
    "description": "Creates a tenant webhook endpoint and records a webhook.endpoint.create audit event",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/webhooks/endpoints",
    "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    \"url\": \"https://webhooks.partner.example/lita\",\n    \"events\": [\n        \"consent.activated\",\n        \"features.computed\",\n        \"score.completed\",\n        \"decision.completed\"\n    ]\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Created",
            "body": "{\n    \"id\": \"weh_6sKjL2mN8pQr\",\n    \"url\": \"https://webhooks.partner.example/lita\",\n    \"events\": [\n        \"consent.activated\",\n        \"features.computed\",\n        \"score.completed\",\n        \"decision.completed\"\n    ]\n}"
        }
    }
}

List Webhook Endpoints

List Webhook Endpoints

{
    "title": "List Webhook Endpoints",
    "description": "Returns the tenant's registered webhook endpoints",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/webhooks/endpoints",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<uuid>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "[\n    {\n        \"id\": \"weh_6sKjL2mN8pQr\",\n        \"url\": \"https://webhooks.partner.example/lita\",\n        \"events\": [\n            \"consent.activated\",\n            \"features.computed\",\n            \"score.completed\"\n        ]\n    }\n]"
        }
    }
}

Test Webhook Fan-Out

Test Webhook Fan-Out

{
    "title": "Test Webhook Fan-Out",
    "description": "Loads all tenant webhook endpoints and enqueues one delivery per endpoint for the supplied event",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/webhooks/test",
    "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    \"eventType\": \"score.completed\",\n    \"payload\": {\n        \"event_id\": \"evt_9uVwX0yZ1aB2\",\n        \"event_type\": \"score.completed\",\n        \"created_at\": \"2026-03-31T09:05:12Z\",\n        \"region\": \"us\",\n        \"data\": {\n            \"consent_id\": \"con_8kXpL9mR2nQv\",\n            \"applicant_id\": \"app_clean\",\n            \"evidence_ref\": \"ev_5sKjL2mN8pQr\"\n        }\n    }\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"queued\": 2\n}"
        }
    }
}

Trigger Feature Computation

Trigger Feature Computation

{
    "title": "Trigger Feature Computation",
    "description": "Starts regional feature computation. The handler supports two flows: a partner-auth branch that returns 202 with a queued job and an access-token branch that returns the evidence snapshot and computed feature vector directly",
    "method": "POST",
    "baseUrl": "<LitaApiBaseUrl>",
    "endpoint": "/{region}/features/compute",
    "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": [
        {
            "key": "region",
            "value": "us",
            "required": true
        }
    ],
    "bodyType": "json",
    "requestBody": "{\n    \"consent_id\": \"con_8kXpL9mR2nQv\",\n    \"feature_set\": \"US_CASHFLOW_V1\",\n    \"as_of\": \"2026-03-31T09:05:12Z\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Direct response branch",
            "body": "{\n    \"evidence_ref\": \"ev_5sKjL2mN8pQr\",\n    \"features\": {\n        \"monthly_income\": 5200,\n        \"avg_balance\": 3400,\n        \"overdraft_count\": 0,\n        \"cashflow_surplus\": 1850,\n        \"cashflow_inflow\": 6800,\n        \"cashflow_outflow\": 4950,\n        \"cashflow_net\": 1850\n    }\n}"
        },
        "202": {
            "description": "Accepted",
            "body": "{\n    \"job_id\": \"job_7tYuI8oP3qRs\",\n    \"status\": \"PROCESSING\",\n    \"consent_id\": \"con_8kXpL9mR2nQv\",\n    \"estimated_completion_ms\": 0\n}"
        }
    }
}

Poll Job Status

Poll Job Status

{
    "title": "Poll Job Status",
    "description": "Returns the current state of the regional in-memory job record used by the async completion flow",
    "method": "GET",
    "baseUrl": "<LitaApiBaseUrl>",
    "endpoint": "/{region}/status/{job_id}",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<uuid>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "region",
            "value": "us",
            "required": true
        },
        {
            "key": "job_id",
            "value": "job_7tYuI8oP3qRs",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"job_id\": \"job_7tYuI8oP3qRs\",\n    \"status\": \"COMPLETE\",\n    \"consent_id\": \"con_8kXpL9mR2nQv\",\n    \"completed_at\": \"2026-03-31T09:05:12Z\",\n    \"error\": null\n}"
        }
    }
}

Read Completed Score

Read Completed Score

{
    "title": "Read Completed Score",
    "description": "Fetches the computed score after the webhook-driven completion flow has produced evidence snapshots",
    "method": "GET",
    "baseUrl": "<LitaApiBaseUrl>",
    "endpoint": "/{region}/consents/{consentId}/score",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<uuid>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "region",
            "value": "us",
            "required": true
        },
        {
            "key": "consentId",
            "value": "con_8kXpL9mR2nQv",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"consent_id\": \"con_8kXpL9mR2nQv\",\n    \"applicant_id\": \"app_clean\",\n    \"score\": 820,\n    \"score_range\": {\n        \"min\": 300,\n        \"max\": 850\n    },\n    \"decision\": \"APPROVE\",\n    \"score_factors\": [\n        \"NO_DELINQUENCIES\",\n        \"HIGH_INCOME_STABILITY\",\n        \"LOW_OBLIGATION_RATIO\"\n    ],\n    \"evidence_ref\": \"ev_5sKjL2mN8pQr\",\n    \"scored_at\": \"2026-03-31T09:05:12Z\",\n    \"model_version\": \"1.2.0\"\n}"
        }
    }
}

Audit and Compliance Tracking

Note: The delivery worker adds X-Lita-Timestamp to outbound webhook requests. The consumer-facing verification guidance in docs/docs-api.md only names X-Lita-Signature, so consumers must validate against the raw body exactly as delivered.

The shown code writes audit records at each control point that matters for traceability:

Action Where it is written Target
event.ingest apps/api/src/routes/v1/events.ts Event
webhook.endpoint.create apps/api/src/routes/v1/webhooks.ts WebhookEndpoint
webhook.test apps/api/src/routes/v1/webhooks.ts WebhookDelivery batch
webhook.delivery.failed apps/worker/src/index.ts WebhookDelivery

The worker also writes compliance-oriented audit rows through recordAuditEvent, which captures tenant, actor, target, and the failure metadata when delivery retries fail.

State Management

Regional Job Records

The regional compute handlers write an in-memory job record with the following fields:

Field Type Description
jobId string Generated job identifier
status PROCESSING · COMPLETE · FAILED Job lifecycle value returned by the polling endpoint
consentId string Consent associated with the job
completedAt string ISO timestamp written when the job is completed
error string Optional failure message

Webhook Delivery States

State Meaning
pending Delivery is ready for the worker to send
retrying A previous attempt failed and the delivery is waiting for its next retry window
delivered The subscriber returned a successful HTTP status
failed The worker has exhausted the retry limit

The webhook and score flow depends on the consent state described in docs/docs-api.md:

PENDING, ACTIVE, REVOKED, EXPIRED

Error Handling

Internal Event Ingestion

  • requireScope(request, "internal:events") blocks the handler before any audit write when the caller lacks the required scope.

Webhook Endpoint Registry

  • Both POST /endpoints and GET /endpoints throw Error("missing tenant") when request.tenantId is absent.
  • The POST /test fan-out follows the same tenant guard before enqueuing any delivery.

Worker Delivery

  • Missing delivery rows are ignored.
  • Any non-2xx response or fetch failure is treated as a delivery error.
  • Failure updates set lastError, nextRetryAt, and either retrying or failed depending on the attempt count.
  • Audit rows are written for failed deliveries.

Regional Completion Flow

  • GET /{region}/consents/{consentId}/score returns 422 when the consent is not ACTIVE or when the evidence snapshot is not ready.
  • The score endpoint returns 502 when the scoring provider is unavailable.
  • The score endpoint returns 400 when a DENY decision has no reason codes.

Integration Points

  • @lita/webhooks provides endpoint storage, webhook enqueueing, and signing.
  • @lita/compliance provides recordAuditEvent for delivery failure compliance logging.
  • @lita/db provides the prisma.webhookDelivery store used by the worker.
  • docs/docs-api.md defines the tenant-facing event catalog and webhook signature contract.
  • sdks/node/src/webhooks.ts, sdks/java/src/main/java/com/joinlita/Webhooks.java, and sdks/python/lita/webhooks.py provide consumer-side signature verification helpers.

Testing Considerations

  • Validate POST /api/v1/events rejects callers without internal:events.
  • Confirm webhook endpoint creation records webhook.endpoint.create and returns the stored endpoint.
  • Confirm POST /api/v1/webhooks/test queues exactly one delivery per registered endpoint.
  • Verify processDelivery signs payloads with the endpoint secret and posts the raw JSON body.
  • Verify failed deliveries increment attempts, set nextRetryAt, and write webhook.delivery.failed.
  • Verify score.completed and decision.completed are emitted from the regional score flow as side effects of evidence creation and decision readback.

Key Classes Reference

Class Responsibility
events.ts Internal event ingestion with audit-only acceptance
webhooks.ts Tenant webhook endpoint management and test fan-out
index.ts Background webhook delivery polling, signing, retry, and compliance logging
docs-api.md Event catalog, webhook payload contract, and async completion guidance