KYC and Identity Verification Domain - AML, KYC, and Residence Permit OCR Flows in the Frontend Edge

Overview

This section covers the frontend-facing identity verification surface in Dwilar/lita-ehousing: the AML assessment page, the KYC proxy routes, and the residence-permit OCR proxy that expands evidence intake beyond bank-link data. The user-visible entry point is frontend/app/aml/page.tsx, which renders a completed AML risk assessment view and provides navigation back into the main product flow.

The verification path is split across edge routes. frontend/app/api/kyc/route.ts prepares a Plaid-style identity-verification payload from backend application data, while frontend/app/api/kyc/[verificationId]/route.ts retrieves verification status by ID. frontend/app/api/v1/application/residence-permit/ocr/route.ts accepts either an uploaded document or a file_url and forwards it to the backend OCR service. The standalone document_ai_ocr script provides Google Cloud Document AI OCR support for non-bank identity evidence, such as residence permits and other uploaded documents.

Architecture Overview

flowchart TB
    User[User]
    AMLPage[AML Risk Assessment Page]
    KycProxy[api kyc POST]
    VerificationStatusProxy[api kyc verificationId GET]
    ResidencePermitOcrProxy[api v1 application residence permit ocr POST]
    AppLookup[Application lookup and identifier matching]
    BackendApplications[Backend applications API]
    BackendVerification[Backend identity verification API]
    BackendResidencePermitOcr[Backend residence permit OCR API]
    DocumentAIOcr[build_client]
    GoogleDocumentAI[Google Cloud Document AI]

    User --> AMLPage
    User --> KycProxy
    User --> VerificationStatusProxy
    User --> ResidencePermitOcrProxy

    KycProxy --> AppLookup
    AppLookup --> BackendApplications
    KycProxy --> BackendVerification
    VerificationStatusProxy --> BackendVerification
    ResidencePermitOcrProxy --> BackendResidencePermitOcr

    DocumentAIOcr --> GoogleDocumentAI

Component Structure

1. Presentation Layer

AML Risk Assessment Page (frontend/app/aml/page.tsx)

This page is the human-facing AML entry point in the frontend edge. It renders a fixed “AML Risk Assessment” view with a “Low Risk Profile” summary, three compliance cards, and a back-navigation button to /dashboard.

The page is driven by local content constants rather than API state. The visible assessment content is organized through complianceHighlights and transactionMetrics, and the component uses useRouter() only for navigation.

Key module data

Name Type Description
AssessmentStatus `"match" \ "no-match" \
complianceHighlights Array of objects Three AML summary cards: watchlist screening, transaction patterns, and documentation.
transactionMetrics Array of objects AML transaction mix cards covering domestic transfers, international transfers, cash deposits, and cash withdrawals.

Visible UI behaviors

  • Renders the AML summary as a completed assessment.
  • Provides a back button that routes to /dashboard.
  • Presents a “Powered by Google AML” brand label in the header.
  • Displays a static summary, not a live polling or streaming view.

Application Identifier Matching Helper (frontend/app/api/applications/[id]/route.ts)

This helper is imported by the KYC proxy to resolve an application from backend data using multiple identifier forms.

Method Description
collectApplicationIdentifiers Collects normalized identifiers from application.id, application.identifier, and metadata keys that indicate identifiers, references, or IDs.

KYC Verification Proxy Route (frontend/app/api/kyc/route.ts)

This route is the identity-verification start point at the frontend edge. It accepts a JSON payload containing applicationId, authenticates the request, loads backend applications, resolves the correct application record, builds a prefixed verification payload, and then calls the backend verification service.

The route is careful about application selection and payload assembly:

  • requestSchema accepts applicationId as either a string or number and converts it to a trimmed string.
  • extractAuthToken must succeed before the route will continue.
  • fetchApplicationsFromBackend loads the applicant pool.
  • findApplicationById compares the requested ID against all identifiers returned by collectApplicationIdentifiers.
  • buildPrefillPayload validates that the application includes email, phone, name, date of birth, and address components before verification starts.

Public and route-level methods

Method Description
POST Validates the request, loads the target application, builds the prefill payload, and starts identity verification through the backend verification endpoint.

Supporting functions used by the route

Method Description
readString Normalizes scalar values into trimmed strings.
normalisePhone Strips non-digits while preserving a leading + when present.
splitName Splits a full name into first and last name parts.
parseDateParts Splits a date of birth into year, month, and day values.
extractFromMetadata Reads a string value from a set of metadata keys.
resolveAddress Builds a normalized address from direct metadata fields and nested metadata.address.
buildPrefillPayload Assembles the backend verification payload from application fields.
findApplicationById Finds the target application by matching collected identifiers.
callBackendWithPrefill Iterates backend base URL candidates and starts verification with the first successful endpoint.

Prefill payload model

Property Type Description
email string Applicant email used by the verification service.
phone string Normalized applicant phone number.
first_name string First name derived from the application full name.
last_name string Last name derived from the application full name, or Applicant when unavailable.
dob_year number Year parsed from the application date of birth.
dob_month number Month parsed from the application date of birth.
dob_day number Day parsed from the application date of birth.
street string Address line extracted from application metadata.
city string City extracted from application metadata.
region string Region or state extracted from application metadata.
postal_code string Postal code extracted from application metadata.
country string Country extracted from metadata or defaulted from the application record.

Response payload model

Property Type Description
linkToken string Link token returned by the backend verification service.
verification Record<string, unknown> Verification object returned by the backend service.
applicant.id `string \ number`
applicant.email string Applicant email.
applicant.phone string Applicant phone.
applicant.fullName string Applicant full name.
applicant.dateOfBirth string Applicant date of birth.
applicant.address.street string Street address.
applicant.address.city string City.
applicant.address.region string Region or state.
applicant.address.postalCode string Postal code.
applicant.address.country string Country.

KYC Verification Status Proxy Route (frontend/app/api/kyc/[verificationId]/route.ts)

This route retrieves a previously created identity-verification status by verification ID. It validates the route parameter, resolves backend API base URLs, and tries each candidate until one returns a successful JSON payload.

Public and route-level methods

Method Description
GET Validates verificationId, fetches the current verification payload from the backend, and returns it wrapped in a verification object.

Supporting functions used by the route

Method Description
callBackend Tries each backend base URL candidate and requests verification status for the supplied ID.

Response payload model

Property Type Description
verification Record<string, unknown> Raw verification-status payload returned by the backend.

Residence Permit OCR Proxy Route (frontend/app/api/v1/application/residence-permit/ocr/route.ts)

This route extends identity evidence intake beyond bank-link flows. It accepts document input as either a file upload or a file_url, forwards the request to the backend OCR service, and returns the backend response status and body as-is.

The request path is designed to be flexible:

  • If file is present, it is forwarded as a File.
  • If file_url is present, it is forwarded as a trimmed string.
  • If neither is present, the route returns a 400 error.

The route also normalizes the backend base URL by trimming trailing slashes from environment values before sending the request.

Public and route-level methods

Method Description
POST Validates file or file_url, forwards the OCR request to the backend service, and returns the backend response unchanged.

Supporting functions used by the route

Method Description
sanitizeBaseUrl Trims and normalizes backend URL environment values.

Google Cloud Document AI OCR Script (document_ai_ocr/main.py, document_ai_ocr/README.md, document_ai_ocr/requirements.txt)

This standalone OCR script supports document processing outside the bank-link workflow. The README describes a minimal OCR runner for Google Cloud Document AI using Application Default Credentials, and the Python code selects a regional processor endpoint automatically.

Public and route-level methods

Method Description
build_client Creates a DocumentProcessorServiceClient, using the default endpoint for us and a regional endpoint for other locations.

Package dependency

Package Constraint Purpose
google-cloud-documentai >=2.30.0 Google Cloud Document AI client library used by build_client.

Runtime setup documented in README.md

  • Enable the Document AI API in Google Cloud.
  • Create an OCR processor and copy its processor ID.
  • Install dependencies with pip install -r requirements.txt.
  • Authenticate with Application Default Credentials.
  • Set GOOGLE_CLOUD_PROJECT, DOCUMENT_AI_LOCATION, and DOCUMENT_AI_PROCESSOR_ID.
  • Run the script against PDF, PNG, or JPEG files.

Documented output behavior

  • Prints extracted text.
  • Prints page count.
  • Prints detected languages per page when available.
  • Prints table counts per page and JSON table data when available.

API Integration

Start KYC Verification

{
    "title": "Start KYC Verification",
    "description": "Validates an application id, loads backend applications, builds a Plaid-style prefill payload, and starts identity verification through 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\": 12345\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Verification started successfully.",
            "body": "{\n    \"linkToken\": \"link-sandbox-8f4a91c1\",\n    \"verification\": [],\n    \"applicant\": {\n        \"id\": \"12345\",\n        \"email\": \"[email protected]\",\n        \"phone\": \"+14155550123\",\n        \"fullName\": \"Jane Doe\",\n        \"dateOfBirth\": \"1990-04-12\",\n        \"address\": {\n            \"street\": \"123 Main St\",\n            \"city\": \"Austin\",\n            \"region\": \"TX\",\n            \"postalCode\": \"78701\",\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 is required.",
            "body": "{\n    \"detail\": \"Authentication required\"\n}"
        },
        "404": {
            "description": "The application could not be found.",
            "body": "{\n    \"detail\": \"Application not found\"\n}"
        },
        "502": {
            "description": "The backend verification service or application lookup failed.",
            "body": "{\n    \"detail\": \"Failed to start Plaid identity verification\"\n}"
        }
    }
}

Get KYC Verification Status

{
    "title": "Get KYC Verification Status",
    "description": "Retrieves a previously created identity-verification payload from the backend using the supplied verification id and returns it inside a verification wrapper.",
    "method": "GET",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/kyc/{verificationId}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "verificationId",
            "value": "verif_12345",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Verification payload loaded successfully.",
            "body": "{\n    \"verification\": []\n}"
        },
        "400": {
            "description": "The verification id is invalid.",
            "body": "{\n    \"detail\": \"Invalid verification id\"\n}"
        },
        "404": {
            "description": "The backend did not return a matching verification payload.",
            "body": "{\n    \"detail\": \"Verification not found\"\n}"
        },
        "502": {
            "description": "The backend verification status lookup failed.",
            "body": "{\n    \"detail\": \"Failed to load verification status\"\n}"
        }
    }
}

Submit Residence Permit for OCR

{
    "title": "Submit Residence Permit for OCR",
    "description": "Accepts either an uploaded file or a file_url, forwards the OCR request to the backend service, and returns the backend body and status unchanged.",
    "method": "POST",
    "baseUrl": "<FrontendAppBaseUrl>",
    "endpoint": "/api/v1/application/residence-permit/ocr",
    "headers": [
        {
            "key": "Content-Type",
            "value": "multipart/form-data",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "formData",
    "requestBody": "{\n    \"file\": \"<binary residence permit file>\",\n    \"file_url\": \"https://storage.example.com/residence-permit.pdf\"\n}",
    "formData": [
        {
            "key": "file",
            "value": "<binary residence permit file>",
            "required": false
        },
        {
            "key": "file_url",
            "value": "https://storage.example.com/residence-permit.pdf",
            "required": false
        }
    ],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "OCR completed successfully and the backend payload was forwarded unchanged.",
            "body": "[]"
        },
        "400": {
            "description": "Neither file nor file_url was supplied.",
            "body": "{\n    \"detail\": \"Either file or file_url is required.\"\n}"
        },
        "502": {
            "description": "The backend OCR service returned an error or could not be reached.",
            "body": "{\n    \"detail\": \"Failed to parse OCR response.\"\n}"
        }
    }
}
{
    "title": "Create Link Token Identity Verification",
    "description": "Backend identity-verification endpoint invoked by the frontend KYC proxy after application prefill data is assembled.",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/create_link_token_id_verification",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"phone\": \"+14155550123\",\n    \"first_name\": \"Jane\",\n    \"last_name\": \"Doe\",\n    \"dob_year\": 1990,\n    \"dob_month\": 4,\n    \"dob_day\": 12,\n    \"street\": \"123 Main St\",\n    \"city\": \"Austin\",\n    \"region\": \"TX\",\n    \"postal_code\": \"78701\",\n    \"country\": \"US\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Link token created and verification payload returned.",
            "body": "{\n    \"link_token\": \"link-sandbox-8f4a91c1\",\n    \"verification\": []\n}"
        }
    }
}

Get Identity Verification Status

{
    "title": "Get Identity Verification Status",
    "description": "Backend verification status endpoint invoked by the frontend KYC status proxy.",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/identity_verification_status/{verificationId}",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "verificationId",
            "value": "verif_12345",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Verification status payload returned by the backend.",
            "body": "[]"
        }
    }
}

Feature Flows

1. Start Identity Verification

sequenceDiagram
    participant U as User
    participant A as AMLPage
    participant K as POST api kyc
    participant L as collectApplicationIdentifiers
    participant F as fetchApplicationsFromBackend
    participant B as buildPrefillPayload
    participant V as BackendVerification
    participant U2 as UI

    U->>A: Open AML assessment
    U->>K: Submit applicationId
    K->>K: extractAuthToken
    K->>F: Load backend applications
    K->>L: Match application identifiers
    K->>B: Build verification payload
    K->>V: POST create_link_token_id_verification
    V-->>K: link_token and verification
    K-->>U2: Return linkToken, verification, applicant

The KYC proxy first authenticates the request, then loads backend applications and resolves the target application by identifier. After the application is found, the route assembles the prefill payload from the stored application fields and starts identity verification by calling the backend verification service.

2. Poll Verification Status

sequenceDiagram
    participant U as User
    participant S as GET api kyc verificationId
    participant V as BackendVerification
    participant UI as UI

    U->>S: Request verificationId
    S->>V: GET identity_verification_status
    V-->>S: Verification payload
    S-->>UI: Return verification wrapper

The verification-status route is a thin lookup proxy. It validates the route parameter, tries backend base URL candidates, and returns the backend verification payload wrapped under verification.

3. Submit Residence Permit for OCR

sequenceDiagram
    participant U as User
    participant O as POST api v1 application residence permit ocr
    participant B as BackendOCR
    participant R as UI

    U->>O: Submit file or file_url
    O->>O: Validate multipart form data
    O->>B: Forward OCR request
    B-->>O: OCR payload
    O-->>R: Return backend body and status

This OCR flow accepts either a binary upload or a URL. That makes it suitable for residence permits and other non-bank identity evidence, which is not captured by bank-link connectivity alone.

4. Google Cloud Document AI OCR Client Creation

sequenceDiagram
    participant C as build_client
    participant P as DocumentProcessorServiceClient
    participant G as Google Cloud Document AI

    C->>C: Read location
    alt location is us
        C->>P: Create default client
    else regional location
        C->>P: Create client with regional endpoint
    end
    P-->>G: Ready to process OCR requests

The Python script centralizes regional endpoint selection. When the location is us, the default client is used; otherwise the client targets {location}-documentai.googleapis.com.

State Management

AML Assessment View State

  • AssessmentStatus: match, no-match, pending
  • The page renders a fixed assessment result, not a dynamic polling screen.

KYC Request State

  • The POST route builds request-scoped state from:
    • authenticated request headers,
    • backend application lookup results,
    • resolved applicant identifiers,
    • prefill payload validation,
    • backend verification response.

OCR Submission State

  • The OCR proxy branches on the presence of file and file_url.
  • It forwards whichever inputs are present and rejects requests that contain neither.

Error Handling

KYC Verification Proxy

  • Returns 400 when the body is invalid or applicationId is missing.
  • Returns 401 when the request is unauthenticated.
  • Returns 404 when the application cannot be matched and the backend did not fail.
  • Returns 502 when the backend application lookup fails, the verification endpoint is unavailable, or the backend verification call throws.
  • Propagates backend 401 and 403 responses directly when application loading fails with authorization errors.

Verification Status Proxy

  • Returns 400 for an invalid verificationId.
  • Returns 404 when the backend returns no status payload.
  • Returns 502 for backend lookup failures.

Residence Permit OCR Proxy

  • Returns 400 if neither file nor file_url is supplied.
  • Parses upstream JSON when possible.
  • Falls back to response.text() if the upstream response is not JSON.
  • Returns the upstream HTTP status unchanged.

Document AI OCR Script

  • The documented setup depends on valid ADC credentials and the required environment variables.
  • The client constructor selects a regional endpoint from the supplied location value.

Dependencies

Dependency Where Used Role
next/server frontend/app/api/kyc/route.ts, frontend/app/api/kyc/[verificationId]/route.ts, frontend/app/api/v1/application/residence-permit/ocr/route.ts Next.js route handlers and responses.
next/headers KYC proxy routes Reads incoming request headers for auth and backend URL resolution.
zod KYC proxy routes Validates applicationId and verificationId.
@/app/api/applications/common KYC and application lookup flow Auth extraction, backend fetch helpers, and backend URL resolution.
@/app/api/applications/[id]/route KYC application matching Identifier collection for application lookup.
google-cloud-documentai document_ai_ocr/main.py OCR client for Google Cloud Document AI.
ClientOptions document_ai_ocr/main.py Sets the regional API endpoint for non-us locations.
GOOGLE_APPLICATION_CREDENTIALS document_ai_ocr/README.md Service-account credential path for ADC.
GOOGLE_CLOUD_PROJECT document_ai_ocr/README.md Google Cloud project ID for OCR execution.
DOCUMENT_AI_LOCATION document_ai_ocr/README.md, document_ai_ocr/main.py Controls regional Document AI endpoint selection.
DOCUMENT_AI_PROCESSOR_ID document_ai_ocr/README.md Document AI processor identifier.

Testing Considerations

  • Verify that applicationId values supplied as strings and numbers both validate through the KYC proxy.
  • Verify that missing auth headers return 401 from POST /api/kyc.
  • Verify that applications with missing email, phone, or address fields are rejected before verification starts.
  • Verify that GET /api/kyc/{verificationId} returns 400 for empty or invalid IDs.
  • Verify that POST /api/v1/application/residence-permit/ocr rejects requests with no file and no file_url.
  • Verify that a file_url is trimmed before being forwarded to the backend OCR service.
  • Verify that non-JSON OCR responses are returned as { "detail": "<text>" }.
  • Verify that build_client("us") uses the default Document AI client and that non-us locations set the regional endpoint.

Key Classes Reference

Class Responsibility
page.tsx Renders the AML risk assessment entry point and back-navigation in the frontend.
route.ts Handles KYC initiation, KYC status lookup, and residence-permit OCR proxying.
[verificationId]/route.ts Retrieves verification status for a specific identity-verification record.
[id]/route.ts Provides application identifier collection used by KYC application matching.
main.py Builds the Google Cloud Document AI OCR client with region-aware endpoint selection.
README.md Documents OCR setup, environment variables, supported file types, and runtime behavior.
requirements.txt Declares the Python OCR dependency on google-cloud-documentai.