Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ KERNEL_API_KEY=
# Local links are written to .data/credential-requests.json.
# Replace FileCollectionRequestStore with your database in production.
COLLECTION_REQUEST_TTL_MINUTES=15

# Card capture (/cards/add) calls the Kernel API from the browser. Override the
# API origin here only when targeting a non-production Kernel API.
# NEXT_PUBLIC_KERNEL_API_BASE_URL=https://api.onkernel.com
45 changes: 42 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# Customer-hosted credential collection
# Customer-hosted credential and card collection

A runnable Next.js example for collecting credentials with [`@onkernel/vault-react`](https://www.npmjs.com/package/@onkernel/vault-react). The browser renders Kernel's unstyled credential form while a same-origin backend keeps the Kernel API key private and maps one-time bearer capabilities to vault items.
A runnable Next.js example for collecting credentials and payment cards on your own domain with [`@onkernel/vault-react`](https://www.npmjs.com/package/@onkernel/vault-react) 0.5.0 or newer. The browser renders Kernel's unstyled forms while a same-origin backend keeps the Kernel API key private.

It includes two flows that share the same backend pieces:
- **`/cards/add`**: a branded card enrollment page for a Kernel wallet. See [Card capture](#card-capture).

The credential flows share the same backend pieces:

- **`/credentials/collect`**: the page sends entered values to this backend, which forwards them to Kernel as `value`.
- **`/credentials/collect-encrypted`**: the page encrypts values in the browser to the vault's public key, this backend forwards the ciphertext as `encrypted_value`, and only Kernel can decrypt it. Use this when plaintext must never reach your backend, proxies, or request logs. See [Encrypted values](#encrypted-values).
Expand Down Expand Up @@ -53,6 +55,7 @@ The fragment is not sent in page requests or referrers. The page sends it only i
- `app/credentials/collect-encrypted` and `app/api/credential-requests/current-encrypted` are the encrypted flow. `lib/encrypted-submission.ts` turns a `CredentialForm` submission into `encrypted_value` fields with [`jose`](https://github.com/panva/jose).
- `lib/request-store.ts` defines the durable `CollectionRequestStore` boundary.
- `scripts/create-request.ts` creates a short-lived link without persisting the raw token.
- `app/cards/add` and `scripts/create-card-link.ts` are the card capture flow. `lib/capture-token.ts` reads the capture token from the fragment.

Successful submissions mark the mapping consumed. Kernel writes include both the rendered version and immutable item ID, so a stale form or a deleted-and-recreated key cannot redirect a write.

Expand All @@ -72,6 +75,42 @@ The encrypted route rejects plaintext `value` strings, so a misconfigured page c

Requires `@onkernel/sdk` 0.122.0 or newer and HTTPS (WebCrypto needs a secure context; `localhost` also works). The page's JavaScript still sees raw values before encrypting them, so keep the collection route free of third-party scripts. If your backend already holds plaintext, use the default flow.

## Card capture

`/cards/add` renders `KernelCardCapture` for one Kernel wallet payment method. Card details are entered in the card vault's own iframes (VGS or Evervault, depending on your organization), so this page, its backend, and Kernel never receive the card number. Unlike the credential flows, the component calls the Kernel API directly from the browser with the capture token; there is no backend route.

Requires `KERNEL_API_KEY` in `.env.local`. There is no mock mode. Create a link:

```sh
bun run create-card-link -- <vault-name> [wallet-key]
```

The script upserts the vault and a `provider: "kernel"` wallet (`card-wallet` by default), runs `add_payment_method`, and prints:

```text
https://app.example.com/cards/add#token=<payment-method-id>.<secret>
```

A capture link lasts 30 minutes, and a wallet can have at most 3 open enrollment links. The page reads the token from the fragment, removes it from the address bar, and renders the form.

Styling has three layers, all in `app/cards/add/card-capture-page.tsx` and `app/globals.css`:

1. Page CSS styles the surrounding form through the component's class hooks (`credential-title`, `credential-primary`, `card-field`, ...) under `className`.
2. `fieldCss` styles the VGS inputs inside their iframes.
3. `evervaultTheme` styles Evervault's iframe, which renders its own labels, inputs, and errors. Page CSS and `fieldCss` can't reach it.

Pass both `fieldCss` and `evervaultTheme`; the component uses the one that matches the card vault. Override all customer-facing copy with `labels`; the defaults mention Kernel.

Your CSP must allow the card vault and the Kernel API:

```text
script-src 'self' 'nonce-<per-request-nonce>' https://js.verygoodvault.com https://js.evervault.com;
frame-src https://js.verygoodvault.com https://ui-components.evervault.com;
connect-src 'self' https://api.onkernel.com https://keys.evervault.com;
```

If the card vault's script or iframe doesn't load within 30 seconds, for example because the CSP blocks it, the component shows a retry button. `onComplete` means Kernel stored the card; confirm the payment method is `active` from your backend before treating it as ready. See [Embedded Card Capture](https://kernel.sh/docs/integrations/wallets/embedded-card-capture) for every prop, class hook, and error code.

## Use a production store

`FileCollectionRequestStore` is intentionally local-only. Its atomic file replacement prevents torn files, but it does not coordinate multiple processes and most serverless filesystems are ephemeral.
Expand Down
94 changes: 94 additions & 0 deletions app/cards/add/card-capture-page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
'use client';

import { useEffect, useState } from 'react';
import { KernelCardCapture } from '@onkernel/vault-react';
import { readCaptureToken } from '@/lib/capture-token';

// Kernel stores a card with VGS or Evervault, depending on the organization.
// Both render in the provider's own iframes, which page CSS can't reach:
// fieldCss styles the VGS inputs and evervaultTheme styles Evervault's. The
// component uses whichever matches the card vault.
const fieldCss = {
'font-family': 'ui-sans-serif, system-ui, sans-serif',
'font-size': '16px',
color: '#111827',
'&::placeholder': { color: '#9ca3af' },
'&.invalid.touched': { color: '#b91c1c' },
};

const evervaultTheme = {
styles: {
body: { fontFamily: 'ui-sans-serif, system-ui, sans-serif', color: '#111827' },
'[ev-component=card]': { gap: 20 },
label: { display: 'block', marginBottom: 8, fontSize: 16, fontWeight: 600 },
input: {
height: 42,
padding: '0 12px',
border: '1px solid #9ca3af',
borderRadius: 8,
background: '#ffffff',
color: '#111827',
fontSize: 16,
'&::placeholder': { color: '#9ca3af' },
'&:focus': { borderColor: '#111827', boxShadow: '0 0 0 3px rgb(17 24 39 / 12%)', outline: 'none' },
},
'.field[ev-valid=false] input': { borderColor: '#b91c1c' },
'.error': { marginTop: 6, fontSize: 14, color: '#b91c1c' },
},
};

const labels = {
title: 'Add a payment card',
description:
'Your assistant uses this card for purchases you approve. Card details go straight to a secure card vault; we never see your card number.',
completeTitle: 'Card added',
completeDescription: 'Your assistant can now request purchases with this card.',
number: 'Card number',
expiry: 'Expiry',
expirationPlaceholder: 'MM / YY',
cvc: 'CVC',
email: 'Email',
emailHint: 'The card network may use it to verify you.',
submit: 'Save card',
submitting: 'Saving…',
retry: 'Try again',
checkAgain: 'Check again',
missingToken: 'This link is incomplete. Open the full link you were sent.',
};

export function CardCapturePage() {
const [token, setToken] = useState<string | null>();

useEffect(() => {
// The token travels in the fragment, so it never reaches a server log or a
// referrer. Read it, then remove it from the address bar. An empty fragment
// keeps the token already read: Strict Mode runs this effect twice, and the
// second run sees the fragment the first one cleared. Opening another link
// in this tab changes only the fragment, so read again on hashchange;
// KernelCardCapture starts over when its token changes.
const read = () => {
const hash = window.location.hash;
setToken((current) => (hash ? readCaptureToken(hash) : (current ?? null)));
if (hash) window.history.replaceState(null, '', window.location.pathname);
};
read();
window.addEventListener('hashchange', read);
return () => window.removeEventListener('hashchange', read);
}, []);

if (token === undefined) return null;
return (
<KernelCardCapture
token={token ?? ''}
baseUrl={process.env.NEXT_PUBLIC_KERNEL_API_BASE_URL}
className="customer-card-capture"
fieldCss={fieldCss}
evervaultTheme={evervaultTheme}
labels={labels}
onComplete={() => {
// Confirm the payment method is active from your backend before
// treating the card as ready.
}}
/>
);
}
12 changes: 12 additions & 0 deletions app/cards/add/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { CardCapturePage } from './card-capture-page';

export default function Page() {
return (
<main className="collection-shell">
<section className="collection-card">
<p className="eyebrow">Payment method</p>
<CardCapturePage />
</section>
</main>
);
}
44 changes: 44 additions & 0 deletions app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,47 @@ h1 {
color: #166534;
font-weight: 600;
}

.customer-card-capture .credential-title {
margin: 0;
font-size: 1.75rem;
line-height: 1.2;
}

.customer-card-capture .credential-header {
margin-bottom: 28px;
}

.customer-card-capture .credential-header .credential-description {
margin: 12px 0 0;
}

.customer-card-capture .credential-form {
display: grid;
gap: 20px;
}

/* VGS renders each input in an iframe that fills this container. */
.customer-card-capture .card-field {
height: 42px;
padding: 0 12px;
border: 1px solid #9ca3af;
border-radius: 6px;
background: #ffffff;
}

.customer-card-capture .card-field iframe {
width: 100%;
height: 100%;
}

.customer-card-capture .card-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}

/* Evervault's iframe holds its own labels and inputs and sizes itself. */
.customer-card-capture .evervault-card iframe {
width: 100%;
}
4 changes: 4 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export default function Home() {
Generate a one-time collection link with <code>bun run create-request</code>, then open the
printed URL. Add <code>--encrypted</code> for the flow that encrypts values in the browser.
</p>
<p className="intro">
For card enrollment, run <code>bun run create-card-link -- &lt;vault-name&gt;</code> and open the
printed <code>/cards/add</code> link.
</p>
</section>
</main>
);
Expand Down
8 changes: 4 additions & 4 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions lib/capture-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// A Kernel capture token is "<payment-method-id>.<secret>". It is a single-use
// capability for one card enrollment, not an API key.
const captureTokenPattern = /^[a-z0-9]{1,64}\.[A-Za-z0-9_-]{43}$/;

export function readCaptureToken(hash: string): string | null {
const params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);
const tokens = params.getAll('token');
if (tokens.length !== 1 || Array.from(params.keys()).some((key) => key !== 'token')) return null;
return captureTokenPattern.test(tokens[0]) ? tokens[0] : null;
}
18 changes: 9 additions & 9 deletions next.config.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import type { NextConfig } from 'next';

const collectionHeaders = [
{ key: 'Cache-Control', value: 'no-store' },
{ key: 'Referrer-Policy', value: 'no-referrer' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-Frame-Options', value: 'DENY' },
];

const nextConfig: NextConfig = {
async headers() {
return [
{
source: '/credentials/collect',
headers: [
{ key: 'Cache-Control', value: 'no-store' },
{ key: 'Referrer-Policy', value: 'no-referrer' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-Frame-Options', value: 'DENY' },
],
},
{ source: '/credentials/collect', headers: collectionHeaders },
{ source: '/cards/add', headers: collectionHeaders },
];
},
};
Expand Down
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
"typecheck": "tsc --noEmit",
"test": "bun test",
"check": "bun run typecheck && bun run test && bun run build",
"create-request": "bun run scripts/create-request.ts"
"create-request": "bun run scripts/create-request.ts",
"create-card-link": "bun run scripts/create-card-link.ts"
},
"dependencies": {
"@onkernel/sdk": "^0.122.0",
"@onkernel/vault-react": "^0.1.0",
"@onkernel/sdk": "^0.148.0",
"@onkernel/vault-react": "^0.5.0",
"jose": "^6.2.12",
"next": "^16.3.5",
"react": "^19.2.3",
Expand Down
37 changes: 37 additions & 0 deletions scripts/create-card-link.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import Kernel from '@onkernel/sdk';

// Creates a Kernel wallet if needed, adds a payment method, and prints a link
// to this app's card capture page. Card capture always talks to Kernel, so
// there is no mock mode.
const [vaultArg, walletArg = 'card-wallet'] = process.argv.slice(2);
if (!vaultArg) throw new Error('usage: bun run create-card-link -- <vault-name> [wallet-key]');

const appOrigin = new URL(required('APP_ORIGIN')).origin;
const kernel = new Kernel({
apiKey: required('KERNEL_API_KEY'),
maxRetries: 0,
...(process.env.KERNEL_API_BASE_URL ? { baseURL: process.env.KERNEL_API_BASE_URL } : {}),
});

const vault = await kernel.vaults.upsert({ name: vaultArg });
await kernel.vaults.items.upsert(walletArg, {
id_or_name: vault.id,
type: 'wallet',
spec: { provider: 'kernel' },
});
const added = await kernel.vaults.items.performOperation(walletArg, {
id_or_name: vault.id,
type: 'add_payment_method',
});
const token = added.type === 'add_payment_method' ? added.payment_method.action?.capture_token : undefined;
if (!token) throw new Error('Kernel returned no capture token; the wallet must use provider "kernel"');

const url = new URL('/cards/add', appOrigin);
url.hash = `token=${token}`;
process.stdout.write(`${url.toString()}\n`);

function required(name: string) {
const value = process.env[name];
if (!value) throw new Error(`${name} is required`);
return value;
}
23 changes: 23 additions & 0 deletions tests/capture-token.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { expect, test } from 'bun:test';
import { readCaptureToken } from '../lib/capture-token';

const token = `s36utp6h7ycc1bpm6pyv1g2p.${'a'.repeat(43)}`;

test('reads a single capture token from the fragment', () => {
expect(readCaptureToken(`#token=${token}`)).toBe(token);
expect(readCaptureToken(`token=${token}`)).toBe(token);
});

test('rejects malformed, repeated, or extra fragment parameters', () => {
for (const hash of [
'',
'#token=',
`#token=${'a'.repeat(43)}`,
`#token=ABC.${'a'.repeat(43)}`,
`#token=${token}x`,
`#token=${token}&token=${token}`,
`#token=${token}&next=/`,
]) {
expect(readCaptureToken(hash)).toBeNull();
}
});
Loading
Loading