KYC and Identity Verification Domain

Overview

This frontend domain provides the edge routes and review surface used to start and inspect identity verification for applicant review. The POST /api/kyc route loads the target application from backend candidate URLs, derives Plaid prefill data from the application record, and starts an identity verification session. The GET /api/kyc/[verificationId] route loads verification status from backend candidate URLs and returns the verification record in a normalized wrapper.

The AML page in frontend/app/aml/page.tsx is the reviewer-facing status screen for compliance review. It presents a fixed AML outcome summary, highlights the major review dimensions, and routes back to /dashboard. Together, these pieces let reviewer flows initiate KYC, fetch verification state on demand, and present AML context without the browser talking directly to backend services.

Architecture Overview

flowchart TB
    subgraph FrontendAppRouter [Frontend App Router]
        AMLPage[AML page]
        KycCreate[KYC POST route]
        KycStatus[KYC status route]
        AppMatcher[Application identifier matcher]
        PrefillBuilder[Prefill payload builder]
        BackNav[Dashboard navigation]
    end

    subgraph BackendServices [Backend Services]
        AppsApi[Applications API]
        VerifCreate[Identity verification create endpoint]
        VerifStatus[Identity verification status endpoint]
    end

    Reviewer[Reviewer]

    Reviewer --> AMLPage
    AMLPage --> BackNav
    BackNav --> Reviewer

    Reviewer --> KycCreate
    Reviewer --> KycStatus

    KycCreate --> AppMatcher
    AppMatcher --> AppsApi
    KycCreate --> PrefillBuilder
    PrefillBuilder --> VerifCreate

    KycStatus --> VerifStatus

Frontend KYC Creation Route

frontend/app/api/kyc/route.ts

This route is the entry point for starting a KYC session. It validates the incoming body, requires an auth token, looks up the application by ID variants, builds the Plaid prefill payload, and then calls the backend verification endpoint until one candidate succeeds.

Request Validation

Field Type Description
applicationId `string \ number`

The route rejects malformed JSON with 400 Invalid request payload, rejects missing IDs with 400 Application id is required, and rejects requests without an auth token with 401 Authentication required.

Prefill Derivation

buildPrefillPayload turns a backend application record into the payload expected by the verification service. It reads the application fields directly, then falls back to metadata when the direct values are missing.

Prefill extraction order:

  • email from application.email
  • phone from application.phone, normalized to digits while preserving a leading +
  • first_name and last_name from application.full_name, with Applicant as the fallback name seed
  • dob_year, dob_month, dob_day from application.date_of_birth or metadata.date_of_birth
  • street, city, region, postal_code, country from direct metadata keys and nested metadata.address
  • country falls back to US

If email, phone, or required address fields are missing, the route fails before calling the verification endpoint.

Create KYC Verification

{
    "title": "Create KYC Verification",
    "description": "Loads the selected application, builds Plaid prefill data, and requests a new link token and verification payload from the backend verification service.",
    "method": "POST",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/kyc",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"applicationId\": 4821\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "KYC session started",
            "body": "{\n    \"linkToken\": \"link-sandbox-9a12b3c4d5e6f7a8\",\n    \"verification\": [],\n    \"applicant\": {\n        \"id\": 4821,\n        \"email\": \"[email protected]\",\n        \"phone\": \"+14155550123\",\n        \"fullName\": \"Ethan Martin\",\n        \"dateOfBirth\": \"1990-08-15\",\n        \"address\": {\n            \"street\": \"1180 Market St\",\n            \"city\": \"San Francisco\",\n            \"region\": \"CA\",\n            \"postalCode\": \"94102\",\n            \"country\": \"US\"\n        }\n    }\n}"
        },
        "400": {
            "description": "Invalid request payload, missing application id, or incomplete application data",
            "body": "{\n    \"detail\": \"Application id is required\"\n}"
        },
        "401": {
            "description": "Authentication token is missing",
            "body": "{\n    \"detail\": \"Authentication required\"\n}"
        },
        "404": {
            "description": "Application was not found",
            "body": "{\n    \"detail\": \"Application not found\"\n}"
        },
        "502": {
            "description": "Backend applications service or verification service was unavailable",
            "body": "{\n    \"detail\": \"Plaid verification endpoint is not available\"\n}"
        }
    }
}

Route Support Functions

Method Description Returns
readString Converts strings, numbers, and booleans into a trimmed string value. string
normalisePhone Removes non-numeric characters from a phone number while keeping a leading +. string
splitName Splits a display name into first and last name parts. { first: string; last: string }
parseDateParts Parses a date string into year, month, and day segments. { year: number; month: number; day: number }
extractFromMetadata Reads the first non-empty string value from the supplied metadata keys. string
resolveAddress Resolves address fields from direct metadata keys, nested metadata.address, and application.country. { street: string; city: string; region: string; postalCode: string; country: string }
buildPrefillPayload Builds the Plaid prefill payload and enforces required email, phone, date of birth, and address data. PrefillPayload
findApplicationById Matches the requested ID against collectApplicationIdentifiers values. `BackendApplication \
callBackendWithPrefill Tries backend verification candidates until one returns a valid link token and verification payload. `{ link_token: string; verification: Record<string, unknown> } \

Prefill Payload

Property Type Description
email string Applicant email address.
phone string Normalized applicant phone number.
first_name string First name derived from the applicant display name.
last_name string Last name derived from the applicant display name.
dob_year number Year parsed from the applicant date of birth.
dob_month number Month parsed from the applicant date of birth.
dob_day number Day parsed from the applicant date of birth.
street string Street address used for verification prefill.
city string City used for verification prefill.
region string State or region used for verification prefill.
postal_code string Postal code used for verification prefill.
country string Country used for verification prefill.

Verification Status Route

frontend/app/api/kyc/[verificationId]/route.ts

This route fetches the current identity verification record for a verification ID. It validates the path parameter, resolves backend candidates, skips the current request origin, and continues through candidates until one returns a non-404 result.

Path Validation

Field Type Description
verificationId string Required path parameter. The route rejects empty values with 400 Invalid verification id.

The route does not attach request body data and does not require a JSON body. It returns 404 Verification not found when no candidate returns a status record, and 502 Failed to load verification status when the lookup fails with a backend or network error.

Get KYC Verification Status

{
    "title": "Get KYC Verification Status",
    "description": "Fetches the latest identity verification record for a verification id by trying the configured backend candidates in order.",
    "method": "GET",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/kyc/{verificationId}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "verificationId",
            "value": "ver_123456",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Verification status found",
            "body": "{\n    \"verification\": []\n}"
        },
        "400": {
            "description": "Invalid verification id",
            "body": "{\n    \"detail\": \"Invalid verification id\"\n}"
        },
        "404": {
            "description": "No backend candidate returned a verification record",
            "body": "{\n    \"detail\": \"Verification not found\"\n}"
        },
        "502": {
            "description": "Backend verification status lookup failed",
            "body": "{\n    \"detail\": \"Failed to load verification status\"\n}"
        }
    }
}

Route Support Functions

Method Description Returns
callBackend Resolves backend candidates, requests /identity_verification_status/{verificationId}, and returns the backend JSON record if any candidate succeeds. `Record<string, unknown> \

AML Review Page

frontend/app/aml/page.tsx

This client page is the reviewer-facing AML surface. It renders a fixed compliance summary, three compliance highlight cards, and a back action that routes the user to /dashboard.

Local Content Structure

Element Type Description
complianceHighlights Array<object> Static AML highlight cards rendered in the page body.
complianceHighlights[].id string Stable card key: watchlist, transaction-patterns, documentation.
complianceHighlights[].title string Card title shown to the reviewer.
complianceHighlights[].description string Card body text explaining the AML outcome.
complianceHighlights[].icon SVG component Icon component rendered for each highlight card.

Reviewer-visible copy on the page:

  • AML Risk Assessment
  • Assessment completed on 8/15/2025
  • Low Risk Profile
  • Watchlist Screening
  • Transaction Patterns
  • Documentation

AMLPage uses useRouter() from next/navigation and wires the back button to router.push("/dashboard"). The page does not fetch remote AML data in the provided code; its content is rendered from local JSX and the complianceHighlights array.

KYC Loading and Backend Fallback Behavior

The KYC flow resolves verification data in two stages:

  1. Load the application record from backend candidate URLs.
  2. Load or start verification data from backend candidate URLs, skipping the current origin and retrying on alternate hosts.

Both KYC routes are defensive against backend routing issues. The POST route filters the current request origin out of the backend candidate list before it starts the verification call, then retries on non-404 failures until a usable response is found. The GET route follows the same multi-candidate lookup pattern for status reads and only returns a 404 after all candidates fail to produce a status record.

KYC Start Flow

sequenceDiagram
    participant ReviewUI as Review UI
    participant KycRoute as KYC POST route
    participant AppsApi as Applications API
    participant VerifApi as Verification backend

    ReviewUI->>KycRoute: POST applicationId
    KycRoute->>KycRoute: parse request and extract auth token

    alt auth token missing
        KycRoute-->>ReviewUI: 401 Authentication required
    else request invalid
        KycRoute-->>ReviewUI: 400 detail
    else auth present
        KycRoute->>AppsApi: fetch applications from candidate base URLs
        alt applications load error and no matching application
            KycRoute-->>ReviewUI: 502 detail
        else applications loaded but no matching application
            KycRoute-->>ReviewUI: 404 Application not found
        else application found
            KycRoute->>KycRoute: buildPrefillPayload
            loop backend candidates
                KycRoute->>VerifApi: POST create_link_token_id_verification
                alt response 404
                    KycRoute->>VerifApi: try next candidate
                else success
                    VerifApi-->>KycRoute: link_token and verification
                    KycRoute-->>ReviewUI: 200 linkToken verification applicant
                end
            end
        end
    end

KYC Status Lookup Flow

sequenceDiagram
    participant ReviewUI as Review UI
    participant StatusRoute as KYC status route
    participant VerifApi as Verification backend

    ReviewUI->>StatusRoute: GET verificationId
    StatusRoute->>StatusRoute: validate path parameter

    alt invalid verificationId
        StatusRoute-->>ReviewUI: 400 Invalid verification id
    else valid verificationId
        loop backend candidates
            StatusRoute->>VerifApi: GET identity_verification_status
            alt response 404
                StatusRoute->>VerifApi: try next candidate
            else success
                VerifApi-->>StatusRoute: verification record
                StatusRoute-->>ReviewUI: 200 verification
            end
        end
        alt no candidate returned a record
            StatusRoute-->>ReviewUI: 404 Verification not found
        end
    end

Status Exposure to Review Flows

Surface File Exposed Status
KYC initiation frontend/app/api/kyc/route.ts linkToken, verification, and applicant
KYC status lookup frontend/app/api/kyc/[verificationId]/route.ts verification
AML summary page frontend/app/aml/page.tsx Low Risk Profile, watchlist, transaction pattern, and documentation highlights

Data Models and Validation

POST Request Model

Property Type Description
applicationId `string \ number`

GET Path Model

Property Type Description
verificationId string Path parameter validated by paramsSchema with a minimum length of 1.

Success Response Shape for POST /api/kyc

Property Type Description
linkToken string Camel-cased link token mapped from backend link_token.
verification Record<string, unknown> Raw verification payload returned by the backend verification service.
applicant object Reviewer-facing applicant snapshot returned by the route.

applicant

Property Type Description
id `string \ number`
email string Applicant email address.
phone string Applicant phone number.
fullName string Applicant display name.
dateOfBirth `string \ undefined`
address object Prefilled address used for verification.

applicant.address

Property Type Description
street string Street address line.
city string City.
region string State or region.
postalCode string Postal or ZIP code.
country string Country code or country name, defaulting to US.

Success Response Shape for GET /api/kyc/[verificationId]

Property Type Description
verification Record<string, unknown> Raw backend status payload wrapped in a verification object.

Error Handling

Route Condition HTTP Status Response Detail
POST /api/kyc Malformed JSON body 400 Invalid request payload
POST /api/kyc Missing or empty applicationId 400 Application id is required
POST /api/kyc Missing auth token 401 Authentication required
POST /api/kyc Applications backend returns 401 or 403 same as backend Backend message is forwarded in { detail }
POST /api/kyc Application lookup fails and no application can be resolved 404 or 502 Application not found or the backend load message
POST /api/kyc Prefill cannot be built 400 Application must include an email and phone number, Application is missing required address details, or date-of-birth errors
POST /api/kyc Verification endpoint is unavailable 502 Plaid verification endpoint is not available
GET /api/kyc/[verificationId] Invalid path parameter 400 Invalid verification id
GET /api/kyc/[verificationId] No candidate returns a status record 404 Verification not found
GET /api/kyc/[verificationId] Candidate lookup throws 502 Failed to load verification status or the thrown backend message

Integration Points

[!NOTE] The POST route distinguishes between a missing application and a backend outage. If the application lookup returns nothing and the applications load also failed, the route returns 502; if the lookup succeeds but no matching application exists, it returns 404.

  • frontend/app/api/kyc/route.ts uses collectApplicationIdentifiers from frontend/app/api/applications/[id]/route.ts to resolve application IDs across direct IDs, explicit identifiers, and metadata-backed identifier fields.
  • Both KYC routes use resolveBackendApiUrlCandidates and resolveRequestOriginCandidate from frontend/app/api/applications/common to discover backend targets and avoid looping back to the current origin.
  • frontend/app/api/kyc/route.ts depends on the backend applications API to fetch the selected applicant record before verification starts.
  • frontend/app/api/kyc/route.ts depends on the backend verification creation endpoint at /create_link_token_id_verification.
  • frontend/app/api/kyc/[verificationId]/route.ts depends on the backend verification status endpoint at /identity_verification_status/{verificationId}.
  • frontend/app/aml/page.tsx integrates with the dashboard route through router.push("/dashboard").

Dependencies

  • next/headers for request header access inside route handlers.
  • next/server for NextRequest and NextResponse.
  • zod for request and path validation.
  • next/navigation for reviewer navigation in AMLPage.
  • react and client-side component rendering in frontend/app/aml/page.tsx.
  • Backend application and verification services reached through fetch from the route handlers.

Key Classes Reference

Class Responsibility
kyc/route.ts Validates KYC start requests, loads the application, derives prefill data, and starts verification.
kyc/[verificationId]/route.ts Looks up the latest verification status for a verification ID.
aml/page.tsx Renders the reviewer-facing AML assessment page and returns the user to the dashboard.