# Reusable KYC by Oathstone — Integration Guide

> **Verify once. Use everywhere.**  
> Add RKYC to any site in under 10 minutes.  
> No API keys. No registration. No admin intervention.

---

## What you're installing

RKYC lets users with an Oathstone Passport skip your registration and login forms entirely. When a verified user visits your site:

1. The Oathstone Chrome extension reads your `/.well-known/rkyc.md` file
2. A one-tap popup asks the user to approve the fields you declared
3. The extension fills your form, bypasses CAPTCHA, and submits
4. Your server receives an ES256 JWT — not PII
5. You verify the JWT using Oathstone's public key and create a session

**What you get:** instant onboarding, no manual KYC review, no GDPR liability for PII, automatic silent re-login for returning users.

---

## Prerequisites

- A web server that can serve static files (for `rkyc.md`)
- The Oathstone Chrome extension loaded in Developer Mode (for testing)

---

## Step 1 — Publish `/.well-known/rkyc.md`

Create this file at the root of your public directory. The extension reads it automatically on every page load.

```
your-project/
  public/
    .well-known/
      rkyc.md     ← create this
```

**Minimal version** (copy this to start):

```markdown
---
rkyc: "1.0"
site: "https://yoursite.com"
site_name: "Your Site"
contact: "developers@yoursite.com"
registration_endpoint: "https://yoursite.com/api/rkyc/register"
reauth_endpoint: "https://yoursite.com/api/rkyc/reauth"
---

## Required Fields

| Field           | Scope          | Required |
|-----------------|----------------|----------|
| first_name      | identity.basic | yes      |
| last_name       | identity.basic | yes      |
| email           | identity.basic | yes      |
| identity_status | identity.basic | yes      |

## CAPTCHA Policy

none
```

**Full version with all options:**

```markdown
---
rkyc: "1.0"
site: "https://yoursite.com"
site_name: "Your Site Name"
contact: "developers@yoursite.com"
registration_endpoint: "https://yoursite.com/api/rkyc/register"
reauth_endpoint: "https://yoursite.com/api/rkyc/reauth"
sovereign_ads: false
---

## Supported Flows

- **passport-relay** — Full handshake via Oathstone Passport or Chrome extension.
- **autonomous-fill** — Oathstone agent fills forms directly.
- **attestation-only** — Server-to-server via JWT verification.

## Required Fields

| Field           | Scope               | Required |
|-----------------|---------------------|----------|
| first_name      | identity.basic      | yes      |
| last_name       | identity.basic      | yes      |
| email           | identity.basic      | yes      |
| identity_status | identity.basic      | yes      |
| phone           | identity.full       | no       |
| dob             | identity.full       | no       |
| country         | identity.full       | no       |

## Scopes

- `identity.basic` — first_name, last_name, email, identity_status
- `identity.full` — + phone, gender, dob, country
- `identity.government` — + credential type hash (no raw value)
- `identity.biometric` — + liveness_verified boolean only

## CAPTCHA Policy

none — Oathstone does not use CAPTCHAs for users with an active Passport session.
```

**Framework paths:**

| Framework | Where to put the file |
|---|---|
| Next.js | `public/.well-known/rkyc.md` |
| Vite / React | `public/.well-known/rkyc.md` |
| SvelteKit | `static/.well-known/rkyc.md` |
| Nuxt | `public/.well-known/rkyc.md` |
| Express | serve from `express.static('public')` |
| Plain HTML | any directory served at your domain root |

**Verify it's live:**
```bash
curl https://yoursite.com/.well-known/rkyc.md
# Should return your markdown with HTTP 200
```

---

## Step 2 — Add the WebMCP script tag

Add this to your HTML `<head>` or just before `</body>`:

```html
<script src="https://business.oathstone.cloud/oathstone-webmcp.js" defer></script>
```

This registers 13 browser-native WebMCP tools:

| Tool | What it does |
|---|---|
| `request_kyc_access` | Triggers the one-tap approval popup |
| `bypass_captcha` | Hides CAPTCHA for verified users |
| `prefill_form` | Fills registration form fields from Passport |
| `fill_login_form` | Fills email + password for silent re-login |
| `submit_registration` | Submits the form after fill |
| `place_ad` | Renders a sovereign retargeting ad |
| `personalize_page` | Shows "Welcome back, [Name]" UI |
| `check_verification_status` | Returns whether user is verified |
| `get_page_signals` | Detects form type, CAPTCHA presence |
| `detect_login_page` | Checks if current page is a login form |
| `update_password_field` | Updates password field for rotation |
| `get_intent_signals` | Reads Shopify product metadata |
| `read_rkyc_file` | Fetches and parses your rkyc.md |

**For React/Next.js**, add it to your layout:

```tsx
// app/layout.tsx
export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <script src="https://business.oathstone.cloud/oathstone-webmcp.js" defer />
      </body>
    </html>
  );
}
```

---

## Step 3 — Verify tokens on your server

When a user approves the RKYC popup, the extension POSTs an ES256 JWT to your `registration_endpoint`. Verify it server-side using one of these methods — **no API key required for any of them**.

### Option A — Local JWT verification (recommended)

Fetch the public key once, verify every token locally. Zero dependency on Oathstone after the initial fetch.

```javascript
import { createRemoteJWKSet, jwtVerify } from "jose"; // npm i jose

const JWKS = createRemoteJWKSet(
  new URL("https://enduring-salmon-903.convex.site/.well-known/rkyc-jwks.json")
);

async function verifyRkycToken(jwt, siteOrigin) {
  const { payload } = await jwtVerify(jwt, JWKS, {
    issuer: "https://business.oathstone.cloud",
    audience: siteOrigin, // must match YOUR site's origin exactly
  });
  // payload.sub            = site-scoped nullifier (your safe user ID)
  // payload.approvedFields = ["first_name", "last_name", "email", ...]
  // payload.scope          = "identity.basic"
  return payload;
}
```

### Option B — Server-side verify (no JWT library)

```javascript
const res = await fetch(
  "https://enduring-salmon-903.convex.site/api/rkyc/verify-jwt",
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ jwt, siteOrigin: "https://yoursite.com" }),
  }
);
const { success, approvedFields, nullifier } = await res.json();
```

### Option C — On-chain verification (trustless, no Oathstone servers)

```javascript
import { createPublicClient, http } from "viem";
import { celo } from "viem/chains";

const client = createPublicClient({ chain: celo, transport: http() });
const registry = await fetch(
  "https://enduring-salmon-903.convex.site/.well-known/rkyc-registry.json"
).then(r => r.json());

const verified = await client.readContract({
  address: registry.contractAddress,
  abi: registry.abi,
  functionName: "isVerified",
  args: ["0x" + nullifierFromJwt], // jwt.payload.sub
});
// verified = true/false — Celo only, no Oathstone dependency
```

---

## Framework examples

### Next.js App Router

```typescript
// app/api/rkyc/register/route.ts
import { NextRequest, NextResponse } from "next/server";
import { createRemoteJWKSet, jwtVerify } from "jose"; // npm i jose

const JWKS = createRemoteJWKSet(
  new URL("https://enduring-salmon-903.convex.site/.well-known/rkyc-jwks.json")
);

export async function POST(req: NextRequest) {
  const { jwt } = await req.json();
  const siteOrigin = req.headers.get("origin") ?? "https://yoursite.com";

  try {
    const { payload } = await jwtVerify(jwt, JWKS, {
      issuer: "https://business.oathstone.cloud",
      audience: siteOrigin,
    });
    // payload.sub = your user's ID — safe to store, no PII
    // Create your session here (cookie, DB record, etc.)
    return NextResponse.json({ success: true });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 401 });
  }
}
```

### Express / Node.js

```javascript
const { createRemoteJWKSet, jwtVerify } = require("jose"); // npm i jose

const JWKS = createRemoteJWKSet(
  new URL("https://enduring-salmon-903.convex.site/.well-known/rkyc-jwks.json")
);

app.post("/api/rkyc/register", async (req, res) => {
  const { jwt } = req.body;
  const siteOrigin = req.headers.origin;

  try {
    const { payload } = await jwtVerify(jwt, JWKS, {
      issuer: "https://business.oathstone.cloud",
      audience: siteOrigin,
    });
    // payload.sub = user ID, payload.approvedFields = verified field names
    req.session.userId = payload.sub;
    res.json({ success: true });
  } catch (err) {
    res.status(401).json({ error: err.message });
  }
});
```

### Convex

```typescript
// convex/http.ts — add to your httpRouter
http.route({
  path: "/api/rkyc/register",
  method: "POST",
  handler: httpAction(async (ctx, req) => {
    const origin = req.headers.get("Origin");
    const headers = {
      "Access-Control-Allow-Origin": origin ?? "*",
      "Content-Type": "application/json",
    };
    const { jwt } = await req.json() as any;

    // Verify using Oathstone's public JWKS endpoint
    const verifyRes = await fetch(
      "https://enduring-salmon-903.convex.site/api/rkyc/verify-jwt",
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ jwt, siteOrigin: origin }),
      }
    );
    const result = await verifyRes.json();

    if (!result.success) {
      return new Response(JSON.stringify({ error: result.error }), { status: 401, headers });
    }

    // result.nullifier = safe user ID (site-scoped, no PII)
    // Store in your DB, create a session, etc.
    return new Response(JSON.stringify({ success: true }), { status: 200, headers });
  }),
});
```

Add to `convex/schema.ts` to store verified sessions:

```typescript
rkycSessions: defineTable({
  nullifier: v.string(),           // site-scoped user ID from jwt.sub
  approvedFields: v.array(v.string()),
  siteOrigin: v.string(),
  verifiedAt: v.number(),
  expiresAt: v.number(),
}).index("by_nullifier", ["nullifier"]),
```

---

## Step 4 — No API key, no registration

RKYC tokens are standard ES256 JWTs. You verify them the same way you'd verify a Google or Apple sign-in token — using the public key.

**No registration. No seed script. No admin contact.**

Public endpoints (fetch these — no auth needed):

```
GET https://enduring-salmon-903.convex.site/.well-known/rkyc-jwks.json
    → Public key for local JWT verification (cache 24h)

GET https://enduring-salmon-903.convex.site/.well-known/rkyc-registry.json
    → Celo RKYCRegistry contract address + ABI

POST https://enduring-salmon-903.convex.site/api/rkyc/verify-jwt
     body: { jwt, siteOrigin }
    → Server-side JWT verification (no API key)

GET https://enduring-salmon-903.convex.site/api/rkyc/check-onchain?nullifier=<hex>
    → On-chain nullifier lookup
```

The JWT `aud` claim is set to your site's origin — a token issued for `shoesite.com` is cryptographically invalid on any other site.

---

## Step 5 — Test locally

1. Start your dev server
2. Load the Oathstone extension in Chrome (`chrome://extensions` → Developer mode → Load unpacked → select the `extension/` folder from the zip)
3. Pair the extension at [business.oathstone.cloud/admin/passport/pair](https://business.oathstone.cloud/admin/passport/pair)
4. Navigate to your registration page
5. The extension fires: `get_page_signals()` → `read_rkyc_file()` → `request_kyc_access()`

**Debug commands:**
```bash
# Verify rkyc.md is reachable
curl http://localhost:3000/.well-known/rkyc.md

# Verify JWKS is reachable
curl https://enduring-salmon-903.convex.site/.well-known/rkyc-jwks.json

# Test JWT verification with a dummy token
curl -X POST https://enduring-salmon-903.convex.site/api/rkyc/verify-jwt \
  -H "Content-Type: application/json" \
  -d '{"jwt":"invalid","siteOrigin":"http://localhost:3000"}'
# Expected: { "success": false, "error": "Malformed JWT." }
```

Open DevTools → Console and look for `[PageAgent]` and `[BG]` log prefixes from the extension.

---

## JWT token reference

The token your server receives from the extension:

```json
{
  "iss": "https://business.oathstone.cloud",
  "sub": "<site-scoped-nullifier>",
  "aud": "https://yoursite.com",
  "exp": 1234568790,
  "approvedFields": ["first_name", "last_name", "email", "identity_status"],
  "scope": "identity.basic"
}
```

- `sub` — `sha256(passportNullifierHash|siteOrigin)`. Safe to use as user ID. Different on every partner site — no cross-site tracking.
- `aud` — your site's origin. Token is rejected by any other site's verification.
- `approvedFields` — field names only, no values. No PII transmitted.
- Expires 15 minutes after issuance. The extension refreshes automatically.

---

## The rkyc.md frontmatter reference

| Field | Required | Description |
|---|---|---|
| `rkyc` | yes | Protocol version. Use `"1.0"` |
| `site` | yes | Your site's full origin URL |
| `site_name` | yes | Human-readable name shown in the approval popup |
| `contact` | yes | Email for integration issues |
| `registration_endpoint` | yes | Where the extension POSTs the JWT after approval |
| `reauth_endpoint` | yes | Where the extension POSTs for silent re-login |
| `sovereign_ads` | no | `true` to opt into sovereign retargeting ads |

---

## Security

- Always verify the JWT signature using the JWKS endpoint. Never trust the payload without it.
- Check the `aud` claim — it must match your site's exact origin.
- `sub` is safe to store as a user ID. It's derived per-site and cannot track users across sites.
- No PII in the JWT. No PII on Oathstone's servers.
- On-chain verification is optional but fully trustless — zero Oathstone dependency.

---

## Troubleshooting

**Extension not detecting my form**  
→ Check `oathstone-webmcp.js` is loading (no console errors)  
→ Verify `/.well-known/rkyc.md` returns HTTP 200  
→ Ensure form inputs have `name` attributes matching field names (`first_name`, `email`, etc.)

**JWT verification failing**  
→ Check JWKS is reachable: `curl https://enduring-salmon-903.convex.site/.well-known/rkyc-jwks.json`  
→ Tokens expire after 15 minutes — check server clock  
→ Verify the `aud` claim exactly matches your origin (scheme + host + port, e.g. `https://yoursite.com`)

**rkyc.md returning 404**  
→ Next.js: file must be at `public/.well-known/rkyc.md`  
→ SvelteKit: use `static/` not `public/`  
→ Some static hosts strip dotfiles — check your deployment config

**CAPTCHA not being bypassed**  
→ Set `CAPTCHA Policy: none` in your rkyc.md  
→ The CAPTCHA element must have class `.g-recaptcha`, attribute `[data-sitekey]`, or "captcha" in its class name

---

## Links

- [Live demo](https://business.oathstone.cloud/social-store)
- [RKYC landing page](https://business.oathstone.cloud/reusable-kyc)
- [Reference rkyc.md](https://business.oathstone.cloud/.well-known/rkyc.md)
- [JWKS](https://enduring-salmon-903.convex.site/.well-known/rkyc-jwks.json)
- [Extension download](https://business.oathstone.cloud/oathstone-extension.zip)

---

*Reusable KYC by Oathstone — Sovereign identity infrastructure for the open web.*  
*Built on Celo. Zero PII stored.*