# UseOneID Integration Instructions for AI Coding Assistants
> **Target:** Cursor, Claude Code, Windsurf, GitHub Copilot, v0, ChatGPT, Antigravity
> **Official NPM Packages:** `@useoneid/react` (UI SDK) | `@useoneid/cli` (`npx @useoneid/cli init` / `doctor` / `webhooks trigger`) | `@useoneid/mcp-server` (AI Agents)
> **Coverage:** Global (190+ countries — ICAO 9303 Passports, National IDs, Driver's Licenses, Multi-Currency KYT & Global KYB)
> **Domain:** https://useoneid.com | API Base: https://useoneid.com/api/v1

Server calls authenticate with the secret key: `Authorization: Bearer sk_sandbox_...` or `sk_live_...`. A `pk_` key and a `client_id` do not authorize a server request. A `client_id` alone opens a sandbox session. Sandbox acceptance does not create a production identity. `POST /api/v1/verify/lookup-user` returns a masked name and tier, not a government-attested profile. Government registry checks stay unavailable until the external provider is configured. Live session status is `GET /api/v1/verify/sessions/{session_id}` (and `POST /api/v1/verify/sessions/cancel` records user cancellation reasons). First-time corporate KYB is `POST /api/v1/verify/kyb` and 1-Click Reusable KYB is `POST /api/v1/verify/rkyb`. Optional region-specific Tier-3 banking verification (e.g. Nigeria BVN linking) is `POST /api/v1/consumer/bvn/link`. Shared risk is `POST /api/v1/risk/events` and `GET /api/v1/risk/score`. Global multi-currency KYT Transaction Monitoring & Network Trust Shield is `POST /api/v1/transactions/monitor` and `GET /api/v1/transactions/alerts`. Proof of Personhood (Human-vs-AI) is `POST /api/v1/verify/human`. Verified Business Trust Seal is `GET /api/v1/trust-seal/{clientId}` (public verification page at `/verify/seal/{clientId}`). Consumer emergency identity freeze with network-wide partner webhook broadcast is `POST /api/v1/consumer/freeze`.

When the user asks to **"Integrate UseOneID"** or **"Add 1-Click Identity / KYC / KYB / KYT / AI Agent Authority"**, execute the following workflow automatically:

---

## 0. Mandatory First Step for AI Coding Agents (Study the Host Application First)

Before writing code, **scan and understand the host application's codebase** (routes, auth/signup flows, onboarding forms, checkout/payout/transfer endpoints, business/vendor onboarding, contract signing, bot-sensitive flows, and existing webhook handlers). Then **integrate UseOneID across every relevant touchpoint — not just a single login button**:

| Touchpoint Found in Host App | UseOneID Integration to Wire |
|---|---|
| **Signup, Login, KYC, Profile Onboarding, Forms** | `POST /api/v1/verify/lookup-user` (<50ms check; includes `documentExpired`, `reuseEligible`, and optional `accepted_poa_types` such as `["utility_bill"]` for 1-step incremental POA top-up) → `flow=reuse` (2-sec 1-Click Biometrics) or `flow=fkyc` (Full First-Time KYC with automatic pre-flight Layer 1 binary/EXIF anti-tampering forensics returning `422 DOCUMENT_TAMPERING_DETECTED` on edited files) via `<UseOneIDButton />` or `<UseOneIDLookup />` + RS256 JWKS verification (`jose`). If all primary government IDs on file are expired, `POST /api/v1/verify/complete` returns `422 DOCUMENT_EXPIRED` (`requires_renewal: true`) and `initiate` routes to renewal. |
| **Transfers, Payouts, Withdrawals, High-Value Checkout** | `POST /api/v1/transactions/monitor` (Global KYT + Network Trust Shield) + honor `decision` (`allow` / `step_up` via `step_up_url` / `hold` / `block`) |
| **Merchant, Seller, Landlord, or B2B Onboarding** | `POST /api/v1/verify/kyb` (first-time) or `POST /api/v1/verify/rkyb` (1-Click Reuse) + embed `GET /api/v1/trust-seal/{clientId}` badge |
| **Bank Statements, Payslips, Utility Bills, Invoices** | `POST /api/v1/verify/document-forensics` (PDF binary forensics, EXIF/XMP editor fingerprints, cross-account recycled SHA-256 check & Production Vision AI financial math reconciliation; returns RS256 `forensics_token` and `authentic` / `suspicious` / `forged` verdict; `$0.45` in Production, free in Sandbox) |
| **Leases, Contracts, Terms, Escrow Agreements** | `POST /api/v1/partner/signatures` (SHA-256 + RSA-2048 seal — ESIGN, UETA, eIDAS, UK ECA & international e-signature standards) |
| **Promos, Waitlists, Reviews, Airdrops, Voting** | `POST /api/v1/verify/human` (Proof of Personhood — stops bots & Sybil farms using `uniqueness_hash`) |
| **Chargebacks, Fraud Reports, Account Disputes** | `POST /api/v1/risk/events` & `GET /api/v1/risk/score` (shared cross-network fraud shield) |
| **AI Agents / Autonomous Tool Execution** | Public W3C `did:web` root at `GET /.well-known/did.json` (`did:web:useoneid.com`). Consumer 1-click consent page `GET /kya/authorize?client_id=...&agent_name=...&spending_limit=...&scopes=...&redirect_uri=...` (mints an isolated per-user KYA passport + `agent_did` + portable W3C Verifiable Credential 2.0 with PIN confirmation), or server-to-server `POST /api/v1/kya/bind` (`duration_days` 1–365 or `0` for never-expires-until-revoked; sub-agent delegation via `parent_agent_id` / `subject_token`, max depth 3; returns `kya_token` + `verifiable_credential`), `POST /api/v1/kya/verify` (live spending-cap & revocation check; `$0.02` in Production via `kya_live_authorization`, free in Sandbox), `POST /api/v1/kya/revoke` (`cascade: false` to revoke only that agent), or `@useoneid/mcp-server`. **`agent_id` must be globally unique — duplicates return `409 Conflict`.** |
| **Real-Time Security & Lifecycle Sync (Required)** | Create an HMAC-SHA256 webhook endpoint (Section 5 below) handling `identity.verified`, `kyb.approved`, `identity.frozen`, `identity.unfrozen`, `identity.risk_escalated`, `transaction.flagged`, `identity.consent_revoked`, `signature.completed`, `signature.declined`, `document.expiring`, and `document.expired` |

### Credential Rules (Do Not Mix These Up)
- **Frontend (`client_id` / `NEXT_PUBLIC_USEONEID_CLIENT_ID`):** MUST be the Partner **Client ID (`cid_...`)** from Partner Settings (`/partner/settings`). **NEVER** pass `pk_...` or `sk_...` as `client_id`.
- **Backend (`USEONEID_SECRET_KEY`):** MUST be `sk_sandbox_...` or `sk_live_...` sent via `Authorization: Bearer <key>`. Never expose in browser code.
- **Webhook Secret (`USEONEID_WEBHOOK_SECRET`):** Used to verify the `x-useoneid-signature` HMAC-SHA256 header.

---

## 1. Front-End Integration (React / Next.js / TypeScript)

### Option A: Install via Official NPM Package (Recommended)

Run the standard install:
```bash
npm install @useoneid/react
```

#### Mount the `<UseOneIDButton />` on Login, Signup, or Checkout:
```tsx
"use client";

import React from "react";
import { UseOneIDButton } from "@useoneid/react";

export default function LoginPage() {
  const handleSuccess = async (identityPayload: { token: string; user: any }) => {
    console.log("Verified User Profile:", identityPayload.user);
    // Send cryptographically signed token to your backend
    const res = await fetch("/api/auth/useoneid", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ token: identityPayload.token }),
    });
    if (res.ok) window.location.href = "/dashboard";
  };

  return (
    <div className="max-w-md mx-auto p-6 space-y-4">
      <UseOneIDButton
        clientId={process.env.NEXT_PUBLIC_USEONEID_CLIENT_ID || "cid_sandbox_demo"}
        redirectUri={typeof window !== "undefined" ? window.location.origin : "https://yourapp.com"}
        onSuccess={handleSuccess}
        text="Continue with UseOneID"
        theme="light" // "light" | "dark" | "brand"
      />
    </div>
  );
}
```

---

### Option B: Zero-Dependency Standalone Component
If the user prefers not to install packages from NPM, create `components/UseOneIDButton.tsx` directly:

```tsx
"use client";

import React from "react";

export interface UseOneIDButtonProps {
  clientId?: string;
  redirectUri?: string;
  onSuccess: (payload: { token: string; user: { id: string; email: string; name: string; tier: string } }) => void;
  onError?: (error: string) => void;
  theme?: "light" | "dark" | "brand";
  text?: string;
  mode?: "popup" | "redirect";
  className?: string;
}

export function UseOneIDButton({
  clientId = process.env.NEXT_PUBLIC_USEONEID_CLIENT_ID || "cid_sandbox_demo",
  redirectUri,
  onSuccess,
  onError,
  theme = "light",
  text = "Continue with UseOneID",
  mode = "popup",
  className = "",
}: UseOneIDButtonProps) {
  const handleClick = () => {
    // Default to production deployment or local development environment
    const authBase = process.env.NEXT_PUBLIC_USEONEID_AUTH_URL || "https://useoneid.com";
    const effectiveRedirectUri = redirectUri || (typeof window !== "undefined" ? window.location.origin : "");
    const authUrl = `${authBase}/oauth/authorize?client_id=${encodeURIComponent(clientId)}&response_type=token&scope=openid+profile+email+kyc${effectiveRedirectUri ? `&redirect_uri=${encodeURIComponent(effectiveRedirectUri)}` : ""}`;

    if (mode === "redirect") {
      window.location.href = authUrl;
      return;
    }

    // Popup handshake. Opens the consent window.
    const popup = window.open(authUrl, "useoneid_auth", "width=500,height=720,menubar=no,toolbar=no");
    
    // Fallback if popup was blocked by browser
    if (!popup || popup.closed || typeof popup.closed === "undefined") {
      window.location.href = authUrl;
      return;
    }

    const listener = (event: MessageEvent) => {
      if (event.origin !== authBase) {
        return;
      }
      if (event.data?.type === "USEONEID_AUTH_SUCCESS") {
        window.removeEventListener("message", listener);
        if (popup && !popup.closed) popup.close();
        onSuccess(event.data.payload);
      } else if (event.data?.type === "USEONEID_AUTH_ERROR") {
        window.removeEventListener("message", listener);
        if (popup && !popup.closed) popup.close();
        onError?.(event.data.error || "Authentication cancelled");
      }
    };
    window.addEventListener("message", listener);
  };

  const themeStyles = {
    light: "bg-white text-neutral-800 border border-neutral-200 hover:bg-neutral-50 shadow-sm",
    dark: "bg-neutral-900 text-white border border-neutral-800 hover:bg-neutral-800 shadow-sm",
    brand: "bg-[#1EA06E] text-white border border-[#168a5c] hover:bg-[#168a5c] shadow-sm",
  }[theme];

  return (
    <button
      type="button"
      onClick={handleClick}
      aria-label={text}
      className={`w-full py-3 px-4 rounded-[4px] flex items-center justify-center gap-2.5 font-sans font-bold text-sm transition-all cursor-pointer select-none active:scale-[0.99] ${themeStyles} ${className}`}
    >
      <div className="w-6 h-6 rounded-[4px] bg-white border border-neutral-200 flex items-center justify-center shrink-0 p-0.5 overflow-hidden">
        <img
          src="https://useoneid.com/favicon.png"
          alt="UseOneID"
          className="w-full h-full object-contain"
        />
      </div>
      <span>{text}</span>
    </button>
  );
}
```

---

## 2. 1-Click Account Lookup for Forms & Onboarding (Marketplaces, FinTech, PropTech, SaaS)

Query multiple candidate identifiers (email, phone, global passport, national ID) in a single high-speed call (<50ms):

```typescript
// Query one or more candidate identifiers in a single REST call:
const res = await fetch("https://useoneid.com/api/v1/verify/lookup-user", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    email: "user@example.com",
    phone: "+14155550199",
    passportNumber: "P12345678", // Optional: Global ICAO 9303 Passport (190+ countries)
    nin: "12345678901",          // Optional: National ID / NIN (where applicable)
  }),
});
const { found, user } = await res.json();

if (found) {
  // Existing User: Launch directly to 2-second 3D Face Biometric Scan!
  const authUrl = "https://useoneid.com/oauth/authorize?" + new URLSearchParams({
    client_id: "your_client_id",
    login_hint: "buyer@example.com",
    flow: "reuse", // Skips input & welcome screens directly to Face Biometrics
  });
} else {
  // First-Time User: Launch directly into Onboarding with prefilled contact details
  const authUrl = "https://useoneid.com/oauth/authorize?" + new URLSearchParams({
    client_id: "your_client_id",
    login_hint: "buyer@example.com",
    flow: "fkyc", // Bypasses 1-Click toggle directly to ID & face enrolment
  });
}
```

Pre-fill application forms (name, verified ID status, address, KYC tier) with verified data in 1 click using React:

```tsx
"use client";

import React, { useState } from "react";
import { UseOneIDLookup } from "@useoneid/react";

export default function TenantApplicationForm() {
  const [formData, setFormData] = useState({ fullName: "", email: "", phone: "", address: "" });

  const handleFill = (verifiedData: any) => {
    setFormData({
      fullName: verifiedData.fullName,
      email: verifiedData.email,
      phone: verifiedData.phone,
      address: verifiedData.address,
    });
  };

  return (
    <form className="space-y-4">
      <div className="flex justify-between items-center">
        <label className="text-sm font-bold">Personal Details</label>
        <UseOneIDLookup onFill={handleFill} />
      </div>

      <input
        value={formData.fullName}
        onChange={(e) => setFormData({ ...formData, fullName: e.target.value })}
        placeholder="Full Name"
        className="w-full p-2 border rounded"
      />
      <input
        value={formData.email}
        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
        placeholder="Email"
        className="w-full p-2 border rounded"
      />
      <input
        value={formData.phone}
        onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
        placeholder="Phone Number"
        className="w-full p-2 border rounded"
      />
    </form>
  );
}
```

---

## 3. High-Value / High-Risk Biometric Step-Up & Digital Signatures

### A. High-Value Biometric Step-Up (Transfers > $1,000, Lease Execution)
Mandate live 3D Face Biometric authentication (bypassing PIN) for sensitive transactions:
```tsx
<UseOneIDButton
  clientId={process.env.NEXT_PUBLIC_USEONEID_CLIENT_ID}
  redirectUri={typeof window !== "undefined" ? window.location.origin : "https://yourapp.com"}
  scope="openid profile kyc biometric_step_up"
  text="Authorize Large Transfer"
  onSuccess={(payload) => {
    console.log("Biometrically verified token:", payload.token);
  }}
/>
```

### B. Digital Signatures & Non-Repudiation API (Global: ESIGN, UETA, eIDAS, UK ECA & Evidence Act §84)
Record legally binding digital agreements with SHA-256 + RSA-2048 seals, or send a `"Pending"` request directly to the signer's UseOneID Consumer App (`/consumer/signature`) with an automatic email alert so they can **Review & Sign** (PIN or Live Face) or **Decline**:
```typescript
const res = await fetch("https://useoneid.com/api/v1/partner/signatures", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.USEONEID_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    document_title: "Residential Tenancy Agreement",
    signer_email: "tenant@example.com",
    document_content: "Terms of tenancy agreement...",
    // Optional: pass "Pending" to send to the signer's UseOneID app for interactive signing or decline.
    // Omit (defaults to "Completed") to seal immediately after your app captures consent.
    status: "Pending",
  }),
});
const { signature } = await res.json();
console.log("Signature ID:", signature.id, "Status:", signature.status, "SHA-256:", signature.sha256_hash);
// Listen for `signature.completed` and `signature.declined` webhooks (Section 5D),
// or poll GET https://useoneid.com/api/v1/partner/signatures?status=Completed|Pending|Declined
```

---

## 4. Back-End RS256 Token Verification (Standard `jose` Library)

Install standard `jose`:
```bash
npm install jose
```

### Route Handler (`app/api/auth/useoneid/route.ts` or Express / Supabase Edge Function)
```typescript
import { NextRequest, NextResponse } from "next/server";
import * as jose from "jose";

export async function POST(req: NextRequest) {
  try {
    const { token } = await req.json();

    // Stateless RS256 JWKS verification against UseOneID Edge Enclave
    const JWKS = jose.createRemoteJWKSet(
      new URL("https://useoneid.com/.well-known/jwks.json")
    );

    const { payload } = await jose.jwtVerify(token, JWKS, {
      issuer: ["https://auth.useoneid.com", "https://useoneid.com"],
      audience: process.env.USEONEID_CLIENT_ID,
    });

    return NextResponse.json({
      success: true,
      user: {
        id: payload.sub,
        email: payload.email,
        name: payload.name,
        tier: payload.kyc_tier,
      },
    });
  } catch (err: any) {
    return NextResponse.json({ error: "Invalid identity signature", details: err.message }, { status: 401 });
  }
}
```

---

## 5. Additional Platform APIs (Wire Wherever Relevant in the Host App)

### A. Real-Time KYT Transaction Monitoring & Closed-Loop Step-Up
Call before executing payouts, withdrawals, or high-value transfers:
```typescript
const res = await fetch("https://useoneid.com/api/v1/transactions/monitor", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.USEONEID_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    transaction_id: tx.id,
    user_id: user.useoneidSub,
    amount: tx.amount,
    currency: tx.currency, // USD, EUR, GBP, CAD, NGN, KES, ZAR, GHS, etc.
    direction: "outbound",
    country: user.country || "US", // ISO 3166-1 alpha-2 (e.g. US, GB, DE, NG, KE, ZA)
    counterparty_id: tx.recipientAccountOrWallet,
    receiver_user_id: tx.receiverUseOneIdSub, // optional: enables 2-hop & 3-hop circular wash detection
    device_fingerprint: req.headers["x-device-fingerprint"], // optional: enables shared-device collusion detection
    shadow_mode: false, // set true to test AML rules silently without blocking live traffic
    channel: "bank_transfer",
  }),
});
const { decision, shadow_decision, risk_score, step_up_url, decision_token } = await res.json();
// Shadow-Node Merge (call when an external counterparty later verifies on UseOneID):
// POST https://useoneid.com/api/v1/transactions/shadow-merge { user_id, identifiers: [email, phone, bankAccount] }
// decision === "allow" -> proceed
// decision === "step_up" -> open step_up_url for 2-second 3D face biometric step-up
// decision === "hold" | "block" -> pause payout & alert compliance
```

### B. Proof of Personhood (Human-vs-AI Anti-Bot Gate)
```typescript
const res = await fetch("https://useoneid.com/api/v1/verify/human", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.USEONEID_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    user_id: user.useoneidSub,
    action_scope: "promo_claim",
    require_biometric: true,
  }),
});
const { is_human, uniqueness_hash, proof_token } = await res.json();
```

### C. Corporate KYB, 1-Click RKYB & Verified Business Trust Seal
```typescript
// First-time KYB: POST /api/v1/verify/kyb | 1-Click Reusable KYB: POST /api/v1/verify/rkyb
// Public Trust Seal: GET https://useoneid.com/api/v1/trust-seal/{clientId}
```

### D. HMAC-SHA256 Webhook Receiver (`/api/webhooks/useoneid`)
Always scaffold a verified webhook route so the host app reacts in real time to freezes, risk escalations, KYC/KYB completions, and KYT alerts:
```typescript
import crypto from "crypto";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  const rawBody = await req.text();
  const signature = req.headers.get("x-useoneid-signature") || "";
  const secret = process.env.USEONEID_WEBHOOK_SECRET || "";

  const expected = "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
  const valid =
    signature.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));

  if (!valid) {
    return NextResponse.json({ error: "Invalid webhook signature" }, { status: 401 });
  }

  const payload = JSON.parse(rawBody);
  const { event, data } = payload;
  switch (event) {
    case "identity.verified":
      // Mark user as KYC verified in host DB
      break;
    case "kyb.approved":
      // Activate merchant/business account in host DB
      break;
    case "identity.frozen":
      // Immediately pause withdrawals, high-risk actions & active sessions for data.user_id
      break;
    case "identity.unfrozen":
      // Lift temporary freeze hold for data.user_id
      break;
    case "identity.risk_escalated":
    case "transaction.flagged":
      // Trigger step-up authentication or compliance review
      break;
    case "identity.consent_revoked":
      // Stop syncing profile attributes for data.user_sub
      break;
    case "signature.completed":
      // Mark contract/agreement as signed using payload.signature (id, sha256_hash, rsa_signature, signed_at)
      break;
    case "signature.declined":
      // Mark contract/agreement as declined by signer (payload.signature.id, payload.signature.reason) and pause deal/escrow
      break;
  }

  return NextResponse.json({ received: true }, { status: 200 });
}
```

---

## 6. Vanilla HTML / Webflow / Shopify CDN Embed
For non-React websites:

```html
<!-- In <head> or before </body> -->
<script src="https://useoneid.com/sdk/v1/useoneid.js" async></script>

<!-- In your form or login card -->
<div 
  id="useoneid-auth-button"
  data-client-id="cid_sandbox_demo"
  data-text="Continue with UseOneID"
  data-theme="light">
</div>

<script>
  window.addEventListener("useoneid:success", function(event) {
    console.log("Verified Identity:", event.detail.user);
    // Submit form or send token to backend
  });
</script>
```

---

## 7. Autonomous AI Agent Authority (KYA™ Protocol)

When the user asks to integrate AI Agent Spending Caps, Delegation, or Model Context Protocol (MCP):

### Python (LangChain / CrewAI / AutoGen)
```python
import os
import requests

# Stateless KYA™ binding via official REST gateway
response = requests.post(
    "https://useoneid.com/api/v1/kya/bind",
    headers={"Authorization": f"Bearer {os.getenv('USEONEID_API_KEY')}"},
    json={
        "client_id": os.getenv("USEONEID_CLIENT_ID"),
        "human_sub": "usr_987654",
        "agent_id": "agt_procure_v1",
        "spending_limit": "1000_USD",
        "allowed_actions": ["escrow:transact", "contracts:review"]
    }
)
passport = response.json()
```

### Model Context Protocol (MCP) Setup
Add to `~/.cursor/mcp.json` or Claude Desktop `claude_desktop_config.json`:
```json
{
  "mcpServers": {
    "useoneid-kya": {
      "command": "npx",
      "args": ["-y", "@useoneid/mcp-server@latest"],
      "env": {
        "USEONEID_API_URL": "https://useoneid.com",
        "USEONEID_API_KEY": "sk_live_your_secret_key"
      }
    }
  }
}
```

---

## 8. Zero-Friction Setup Instructions to User

After writing the code, the AI Assistant should prompt the user:
> *"I've integrated UseOneID across your app's identity, security, and webhook touchpoints! To complete setup:*
> 1. *Copy your **Partner Client ID (`cid_...`)** from https://useoneid.com/partner/settings (do NOT use `pk_...` as `client_id`) and set `NEXT_PUBLIC_USEONEID_CLIENT_ID=cid_...`.*
> 2. *Copy your **Secret API Key (`sk_sandbox_...` or `sk_live_...`)** from https://useoneid.com/partner/api-keys and set `USEONEID_SECRET_KEY=sk_...` on your backend.*
> 3. *Register your webhook URL (`https://yourdomain.com/api/webhooks/useoneid`) in Partner Settings / API Keys and set `USEONEID_WEBHOOK_SECRET=whsec_...`."*
