diff --git a/.env.example b/.env.example
index 547d400..882c760 100644
--- a/.env.example
+++ b/.env.example
@@ -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
diff --git a/README.md b/README.md
index ff63bb0..d3222c5 100644
--- a/README.md
+++ b/README.md
@@ -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).
@@ -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.
@@ -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 -- [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=.
+```
+
+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-' 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.
diff --git a/app/cards/add/card-capture-page.tsx b/app/cards/add/card-capture-page.tsx
new file mode 100644
index 0000000..e192f03
--- /dev/null
+++ b/app/cards/add/card-capture-page.tsx
@@ -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();
+
+ 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 (
+ {
+ // Confirm the payment method is active from your backend before
+ // treating the card as ready.
+ }}
+ />
+ );
+}
diff --git a/app/cards/add/page.tsx b/app/cards/add/page.tsx
new file mode 100644
index 0000000..7e57580
--- /dev/null
+++ b/app/cards/add/page.tsx
@@ -0,0 +1,12 @@
+import { CardCapturePage } from './card-capture-page';
+
+export default function Page() {
+ return (
+
+
+
+ );
+}
diff --git a/app/globals.css b/app/globals.css
index 93bcb30..c00f85d 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -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%;
+}
diff --git a/app/page.tsx b/app/page.tsx
index 3f2f292..aa029bf 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -8,6 +8,10 @@ export default function Home() {
Generate a one-time collection link with bun run create-request, then open the
printed URL. Add --encrypted for the flow that encrypts values in the browser.
+
+ For card enrollment, run bun run create-card-link -- <vault-name> and open the
+ printed /cards/add link.
+
);
diff --git a/bun.lock b/bun.lock
index d01a6c9..2ef17d1 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,8 +5,8 @@
"": {
"name": "vault-react-example",
"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",
@@ -99,9 +99,9 @@
"@next/swc-win32-x64-msvc": ["@next/swc-win32-x64-msvc@16.3.5", "", { "os": "win32", "cpu": "x64" }, "sha512-LNdCHzgLFc+UeqMS84LzXPaeBRKyqDN9OMyFAr1OrB0XrNw78IRrEVtZvvA7245W/HsaoeVOQX9jPjPk8jojwA=="],
- "@onkernel/sdk": ["@onkernel/sdk@0.122.0", "", {}, "sha512-cHjduH6Ssfs29Q/vetvvc4jACIDDTd/OVJ0p3frLXFJQ9mloLgKygyAilBrJBuXNtgeUsd9fhgXfVsTpDzhZGA=="],
+ "@onkernel/sdk": ["@onkernel/sdk@0.148.0", "", {}, "sha512-e58SYGkmQoKMTKYv8SNpzbO4uE9Bhz/7dv6iyW8V1dq/m9V7CHNa8L3o9peP2arbaQdyqWCt5kljxKrK5XnlOw=="],
- "@onkernel/vault-react": ["@onkernel/vault-react@0.1.0", "", { "peerDependencies": { "react": ">=18", "react-dom": ">=18" } }, "sha512-XogSCQ3GhtU9Q0TeIFt+pdfKOQVRZHLwKE6Uvj1YvH5CLwaF2q45KgM4jnMmUvrOXamq/of0xh3ECPPtOF/xgA=="],
+ "@onkernel/vault-react": ["@onkernel/vault-react@0.5.0", "", { "peerDependencies": { "react": ">=18", "react-dom": ">=18" } }, "sha512-hm1UvjjcoKdWHpiRxCJ3hmI/xXLDHhBTmHhgwJbgC6rAfDlOcNXbkgTVatxu9IxzgENCMiQRGgqNei18VHv6mg=="],
"@swc/helpers": ["@swc/helpers@0.5.23", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw=="],
diff --git a/lib/capture-token.ts b/lib/capture-token.ts
new file mode 100644
index 0000000..50b0bd4
--- /dev/null
+++ b/lib/capture-token.ts
@@ -0,0 +1,10 @@
+// A Kernel capture token is ".". 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;
+}
diff --git a/next.config.ts b/next.config.ts
index a697d19..1bbf2cf 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -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 },
];
},
};
diff --git a/package.json b/package.json
index 0298e26..5434fd2 100644
--- a/package.json
+++ b/package.json
@@ -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",
diff --git a/scripts/create-card-link.ts b/scripts/create-card-link.ts
new file mode 100644
index 0000000..70ef8f9
--- /dev/null
+++ b/scripts/create-card-link.ts
@@ -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 -- [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;
+}
diff --git a/tests/capture-token.test.ts b/tests/capture-token.test.ts
new file mode 100644
index 0000000..5feec3a
--- /dev/null
+++ b/tests/capture-token.test.ts
@@ -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();
+ }
+});
diff --git a/tests/card-capture-page.test.tsx b/tests/card-capture-page.test.tsx
new file mode 100644
index 0000000..58cb23e
--- /dev/null
+++ b/tests/card-capture-page.test.tsx
@@ -0,0 +1,106 @@
+import './setup';
+import { afterEach, beforeEach, expect, mock, test } from 'bun:test';
+
+const { act } = await import('react');
+const { createRoot } = await import('react-dom/client');
+const { CardCapturePage } = await import('../app/cards/add/card-capture-page');
+const token = `s36utp6h7ycc1bpm6pyv1g2p.${'a'.repeat(43)}`;
+let container: HTMLDivElement;
+let root: ReturnType;
+let originalFetch: typeof fetch;
+
+beforeEach(() => {
+ originalFetch = globalThis.fetch;
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ globalThis.fetch = originalFetch;
+});
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+test('sends the fragment token to Kernel and clears it from the address bar', async () => {
+ window.location.href = `https://app.example.com/cards/add#token=${token}`;
+ const fetchMock = mock(async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ Response.json({ status: 'completed' }),
+ );
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ await act(async () => root.render());
+ await act(settle);
+
+ expect(window.location.hash).toBe('');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [input, init] = fetchMock.mock.calls[0];
+ expect(String(input)).toBe('https://api.onkernel.com/vault/card-captures/current');
+ expect(new Headers(init?.headers).get('Authorization')).toBe(`Bearer ${token}`);
+ expect(container.textContent).toContain('Card added');
+});
+
+test('explains an incomplete link without calling Kernel', async () => {
+ window.location.href = 'https://app.example.com/cards/add#token=not-a-token';
+ const fetchMock = mock(async () => Response.json({}));
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ await act(async () => root.render());
+ await act(settle);
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(container.textContent).toContain('This link is incomplete');
+});
+
+test('keeps the token when Strict Mode runs the mount effect twice', async () => {
+ window.location.href = `https://app.example.com/cards/add#token=${token}`;
+ const fetchMock = mock(async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ Response.json({ status: 'completed' }),
+ );
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+ const { StrictMode } = await import('react');
+
+ await act(async () =>
+ root.render(
+
+
+ ,
+ ),
+ );
+ await act(settle);
+
+ expect(container.textContent).not.toContain('This link is incomplete');
+ expect(container.textContent).toContain('Card added');
+ const authorizations = fetchMock.mock.calls.map(([, init]) =>
+ new Headers(init?.headers).get('Authorization'),
+ );
+ expect(authorizations.length).toBeGreaterThan(0);
+ expect(new Set(authorizations)).toEqual(new Set([`Bearer ${token}`]));
+});
+
+test('switches to a new link opened in the same tab', async () => {
+ const second = `s36utp6h7ycc1bpm6pyv1g2q.${'b'.repeat(43)}`;
+ window.location.href = `https://app.example.com/cards/add#token=${token}`;
+ const fetchMock = mock(async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ Response.json({ status: 'completed' }),
+ );
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ await act(async () => root.render());
+ await act(settle);
+ fetchMock.mockClear();
+
+ await act(async () => {
+ window.location.hash = `token=${second}`;
+ window.dispatchEvent(new HashChangeEvent('hashchange'));
+ });
+ await act(settle);
+
+ expect(window.location.hash).toBe('');
+ expect(fetchMock).toHaveBeenCalled();
+ for (const [, init] of fetchMock.mock.calls) {
+ expect(new Headers(init?.headers).get('Authorization')).toBe(`Bearer ${second}`);
+ }
+});