Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(cz): expire claim nonces, close the double-redeem race, and ship the cz_claims migration

nirholas78ce0193b5e8
diff --git a/api/_lib/migrations/20260812140000_cz_claims.sql b/api/_lib/migrations/20260812140000_cz_claims.sql
new file mode 100644
index 000000000..68b161b89
--- /dev/null
+++ b/api/_lib/migrations/20260812140000_cz_claims.sql
@@ -0,0 +1,30 @@
+-- Migration: the CZ agent claim ledger backing /api/cz/claim.
+--
+-- The handler has always required this table, but it only ever existed as a
+-- comment at the top of api/cz/claim.js telling a human to "run once before
+-- deploy". Nobody ran it, so every real call to the endpoint (GET to mint a
+-- nonce, POST to redeem it) died with a 500 on `relation "cz_claims" does not
+-- exist` while the malformed-input paths kept returning tidy 400s, which made
+-- the surface look healthy from the outside.
+--
+-- One row per issued nonce. The row is minted `pending` by the GET, and the
+-- POST flips it to `claimed` only after the ECDSA signature over
+-- "Claim CZ Agent\n\nNonce: <nonce>" recovers to the same address the nonce
+-- was issued for. `nonce` is unique so a replay can never resolve to two rows,
+-- and the status flip is conditional on `status = 'pending'` in the handler so
+-- two concurrent POSTs on one nonce cannot both win.
+
+CREATE TABLE IF NOT EXISTS cz_claims (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ address TEXT NOT NULL, -- lowercased 0x EOA the nonce was issued to
+ nonce TEXT NOT NULL UNIQUE, -- 16 random bytes, hex
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'claimed')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ claimed_at TIMESTAMPTZ
+);
+
+-- "has this address already claimed?" and the per-address audit trail.
+CREATE INDEX IF NOT EXISTS cz_claims_address_idx ON cz_claims (address);
+-- Sweeping expired pending nonces (the handler treats anything older than its
+-- TTL as dead) and reading the claim feed newest-first.
+CREATE INDEX IF NOT EXISTS cz_claims_created_at_idx ON cz_claims (created_at DESC);
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 702758e3d..ffa1d1817 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -559,6 +559,15 @@ export const limits = {
// scripted wallet-mint spam per IP.
agentCreateIp: (ip) =>
getLimiter('agent:create:ip', { limit: 20, window: '10 m', critical: true, degradeToMemory: true }).limit(ip),
+ // CZ agent claim (/api/cz/claim). The GET mints a nonce row, the POST
+ // redeems it against one ECDSA signature; a real claim is two calls, so 10
+ // per hour leaves room for a wallet rejection and a retry while capping how
+ // many rows one IP can write into cz_claims. `local` because the handler
+ // writes nothing of value on the GET (a random nonce that is useless without
+ // the matching signature) and the money buckets need the shared Redis
+ // allowance more; per-instance is also exactly what this endpoint's previous
+ // hand-rolled in-memory bucket gave, so it is not a regression.
+ czClaimIp: (ip) => getLimiter('cz:claim:ip', { limit: 10, window: '1 h', local: true }).limit(ip),
// CAPTCHA-verified login bucket. When a user solves the Altcha proof-of-work
// puzzle (api/auth/captcha.js) they receive a signed bypass token that routes
// their login through this separate bucket instead of authIp. It is intentionally
diff --git a/api/cz/claim.js b/api/cz/claim.js
index 2f8774b5e..ede86a890 100644
--- a/api/cz/claim.js
+++ b/api/cz/claim.js
@@ -1,21 +1,18 @@
-// POST /api/cz/claim — verify ECDSA signature, record claim intent, return on-chain tx payload
-// GET /api/cz/claim?address=0x... — issue a fresh nonce for signing
+// POST /api/cz/claim verify an ECDSA signature, record the
+// claim, return the on-chain tx payload
+// GET /api/cz/claim?address=0x... issue a fresh nonce to sign
//
-// Requires this table (run once before deploy):
-// create table if not exists cz_claims (
-// id uuid primary key default gen_random_uuid(),
-// address text not null,
-// nonce text not null unique,
-// status text not null default 'pending', -- pending | claimed
-// created_at timestamptz not null default now(),
-// claimed_at timestamptz
-// );
+// Backed by the `cz_claims` table (api/_lib/migrations/20260812140000_cz_claims.sql).
+// One row per issued nonce: minted `pending` by the GET, flipped to `claimed`
+// by the POST once the signature recovers to the address the nonce was issued
+// for. Nonces expire after NONCE_TTL_MS so an abandoned one cannot be redeemed
+// weeks later from a browser history entry or a proxy log.
import { randomBytes } from 'crypto';
import { verifyMessage, Interface } from 'ethers';
import { sql } from '../_lib/db.js';
import { cors, json, error, wrap, readJson, rateLimited } from '../_lib/http.js';
-import { clientIp } from '../_lib/rate-limit.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
import { env } from '../_lib/env.js';
const CZ_AGENT_ID = env.CZ_AGENT_ID || 'cz-preview';
@@ -24,24 +21,16 @@ const CZ_AGENT_NAME = env.CZ_AGENT_NAME || 'CZ Agent';
// Frontend skips the on-chain tx when the address is empty/zero.
const REGISTRY_CONTRACT = env.CZ_REGISTRY_CONTRACT || '0x0000000000000000000000000000000000000000';
+// A nonce only has to survive the round trip from "connect wallet" to "approve
+// the signature in the wallet popup". Fifteen minutes covers a slow human on a
+// hardware wallet and still bounds how long a leaked nonce is worth anything.
+const NONCE_TTL_MS = 15 * 60 * 1000;
+
const _iface = new Interface(['function transferAgent(string agentId, address newOwner)']);
function encodeTransferAgent(agentId, newOwner) {
return _iface.encodeFunctionData('transferAgent', [agentId, newOwner]);
}
-// Inline sliding-window rate limiter: 5 requests / hour per IP.
-// Using in-memory here because this is a one-shot flow with minimal traffic.
-const _buckets = new Map();
-function checkRate(ip) {
- const now = Date.now();
- const window = 60 * 60 * 1000;
- const kept = (_buckets.get(ip) || []).filter((t) => t > now - window);
- if (kept.length >= 5) return { success: false, limit: 5, remaining: 0, reset: kept[0] + window };
- kept.push(now);
- _buckets.set(ip, kept);
- return { success: true, limit: 5, remaining: 5 - kept.length, reset: now + window };
-}
-
function claimMessage(nonce) {
return `Claim CZ Agent\n\nNonce: ${nonce}`;
}
@@ -51,7 +40,7 @@ export default wrap(async (req, res) => {
const ip = clientIp(req);
- // ── GET: issue nonce ──────────────────────────────────────────────────────
+ // GET: issue nonce
if (req.method === 'GET') {
const address = new URL(req.url, 'http://x').searchParams.get('address') || '';
if (!/^0x[0-9a-fA-F]{40}$/.test(address))
@@ -62,19 +51,18 @@ export default wrap(async (req, res) => {
'address must be a 0x-prefixed Ethereum address',
);
- const rl = checkRate(ip);
- if (!rl.success)
- return rateLimited(res, rl, 'too many requests — try again in an hour');
+ const rl = await limits.czClaimIp(ip);
+ if (!rl.success) return rateLimited(res, rl, 'too many requests, try again in an hour');
const nonce = randomBytes(16).toString('hex');
await sql`
insert into cz_claims (address, nonce, status)
values (${address.toLowerCase()}, ${nonce}, 'pending')
`;
- return json(res, 200, { nonce });
+ return json(res, 200, { nonce, expiresInSeconds: NONCE_TTL_MS / 1000 });
}
- // ── POST: verify signature and record claim ───────────────────────────────
+ // POST: verify signature and record claim
if (req.method === 'POST') {
let body;
try {
@@ -91,19 +79,22 @@ export default wrap(async (req, res) => {
'validation_error',
'signerAddress, signature, and nonce are required',
);
+ if (typeof signerAddress !== 'string' || typeof signature !== 'string' || typeof nonce !== 'string')
+ return error(res, 400, 'validation_error', 'signerAddress, signature, and nonce must be strings');
if (!/^0x[0-9a-fA-F]{40}$/.test(signerAddress))
return error(res, 400, 'validation_error', 'invalid signerAddress format');
- const rl = checkRate(ip);
- if (!rl.success)
- return rateLimited(res, rl, 'too many requests — try again in an hour');
+ const rl = await limits.czClaimIp(ip);
+ if (!rl.success) return rateLimited(res, rl, 'too many requests, try again in an hour');
const rows = await sql`
- select id, address, status from cz_claims where nonce = ${nonce} limit 1
+ select id, address, status, created_at from cz_claims where nonce = ${nonce} limit 1
`;
const row = rows[0];
if (!row) return error(res, 400, 'invalid_nonce', 'nonce not found');
if (row.status !== 'pending') return error(res, 409, 'conflict', 'nonce already used');
+ if (Date.now() - new Date(row.created_at).getTime() > NONCE_TTL_MS)
+ return error(res, 400, 'nonce_expired', 'nonce expired, request a new one');
if (row.address !== signerAddress.toLowerCase())
return error(res, 403, 'forbidden', 'address does not match nonce');
@@ -116,21 +107,24 @@ export default wrap(async (req, res) => {
if (recovered.toLowerCase() !== signerAddress.toLowerCase())
return error(res, 403, 'forbidden', 'signature does not match signer address');
- await sql`
- update cz_claims set status = 'claimed', claimed_at = now() where id = ${row.id}
+ // Conditional on `pending` so two POSTs racing on the same nonce cannot
+ // both be told they won the claim: exactly one update returns a row.
+ const claimed = await sql`
+ update cz_claims set status = 'claimed', claimed_at = now()
+ where id = ${row.id} and status = 'pending'
+ returning id
`;
-
- const txPayload = {
- to: REGISTRY_CONTRACT,
- data: encodeTransferAgent(CZ_AGENT_ID, signerAddress),
- value: '0x0',
- };
+ if (!claimed[0]) return error(res, 409, 'conflict', 'nonce already used');
return json(res, 200, {
ok: true,
agentId: CZ_AGENT_ID,
agentName: CZ_AGENT_NAME,
- txPayload,
+ txPayload: {
+ to: REGISTRY_CONTRACT,
+ data: encodeTransferAgent(CZ_AGENT_ID, signerAddress),
+ value: '0x0',
+ },
});
}
diff --git a/tests/cz-claim.test.js b/tests/cz-claim.test.js
new file mode 100644
index 000000000..cf924c46e
--- /dev/null
+++ b/tests/cz-claim.test.js
@@ -0,0 +1,259 @@
+// The HTTP contract of the CZ agent claim (api/cz/claim.js).
+//
+// The endpoint hands ownership of a pre-registered agent to whoever proves
+// control of an address, so the whole surface is the signature check. Three
+// properties are load-bearing:
+//
+// 1. The nonce is bound to the address it was issued to. A signature that is
+// valid on its own but was made by another key, or redeemed against a
+// nonce issued to a different address, must not claim the agent.
+// 2. A nonce is single-use and short-lived. The status flip is conditional on
+// `pending` so a replay (or two concurrent POSTs) cannot both win, and a
+// nonce older than the TTL is dead even though its row is still `pending`.
+// 3. The returned tx payload encodes transferAgent(agentId, signer) for the
+// address that actually signed, never for an address supplied in the body
+// without proof.
+//
+// The signatures here are real secp256k1 personal_sign signatures produced by
+// ethers, the same library the handler verifies with; only the database rows
+// and the rate limiter are stubbed.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+import { Wallet, Interface } from 'ethers';
+
+const sqlState = { queue: [], calls: [] };
+const rateState = { success: true };
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ text: strings.join('?'), values });
+ return sqlState.queue.length ? sqlState.queue.shift() : [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ czClaimIp: vi.fn(async () =>
+ rateState.success
+ ? { success: true, limit: 10, remaining: 9, reset: Date.now() + 3_600_000 }
+ : { success: false, limit: 10, remaining: 0, reset: Date.now() + 3_600_000 },
+ ),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const handler = (await import('../api/cz/claim.js')).default;
+
+const claimMessage = (nonce) => `Claim CZ Agent\n\nNonce: ${nonce}`;
+const NONCE = 'a1b2c3d4e5f60718293a4b5c6d7e8f90';
+
+function call({ method = 'GET', url = '/api/cz/claim', body } = {}) {
+ const raw = body === undefined ? Buffer.from('') : Buffer.from(JSON.stringify(body));
+ const req = Readable.from([raw]);
+ req.method = method;
+ req.url = url;
+ req.headers = { host: 'localhost', 'content-type': 'application/json' };
+ const res = {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+ return handler(req, res).then(() => ({
+ status: res.statusCode,
+ headers: res.headers,
+ payload: res.body ? JSON.parse(res.body) : null,
+ }));
+}
+
+const pendingRow = (address, over = {}) => [{
+ id: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc',
+ address: address.toLowerCase(),
+ status: 'pending',
+ created_at: new Date().toISOString(),
+ ...over,
+}];
+
+let wallet;
+let other;
+
+beforeEach(async () => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ rateState.success = true;
+ wallet = Wallet.createRandom();
+ other = Wallet.createRandom();
+});
+
+describe('GET /api/cz/claim (nonce issuance)', () => {
+ it('issues a hex nonce with its lifetime for a well-formed address', async () => {
+ const r = await call({ url: `/api/cz/claim?address=${wallet.address}` });
+ expect(r.status).toBe(200);
+ expect(r.payload.nonce).toMatch(/^[0-9a-f]{32}$/);
+ expect(r.payload.expiresInSeconds).toBe(900);
+ // The row is stored lowercased so the POST comparison is case-insensitive.
+ expect(sqlState.calls[0].values[0]).toBe(wallet.address.toLowerCase());
+ expect(sqlState.calls[0].values[1]).toBe(r.payload.nonce);
+ });
+
+ it('rejects a non-address and writes nothing', async () => {
+ const r = await call({ url: '/api/cz/claim?address=not-an-address' });
+ expect(r.status).toBe(400);
+ expect(r.payload.error).toBe('validation_error');
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('surfaces the limiter as a 429 with a retry budget', async () => {
+ rateState.success = false;
+ const r = await call({ url: `/api/cz/claim?address=${wallet.address}` });
+ expect(r.status).toBe(429);
+ expect(r.payload.error).toBe('rate_limited');
+ expect(Number(r.headers['retry-after'])).toBeGreaterThan(0);
+ expect(sqlState.calls).toHaveLength(0);
+ });
+});
+
+describe('POST /api/cz/claim (signature redemption)', () => {
+ it('claims the agent and returns transferAgent calldata for the signer', async () => {
+ sqlState.queue.push(pendingRow(wallet.address), [{ id: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' }]);
+ const signature = await wallet.signMessage(claimMessage(NONCE));
+
+ const r = await call({
+ method: 'POST',
+ body: { signerAddress: wallet.address, signature, nonce: NONCE },
+ });
+
+ expect(r.status).toBe(200);
+ expect(r.payload.ok).toBe(true);
+ expect(r.payload.agentId).toBe('cz-preview');
+
+ const iface = new Interface(['function transferAgent(string agentId, address newOwner)']);
+ const decoded = iface.decodeFunctionData('transferAgent', r.payload.txPayload.data);
+ expect(decoded[0]).toBe('cz-preview');
+ expect(decoded[1].toLowerCase()).toBe(wallet.address.toLowerCase());
+ expect(r.payload.txPayload.value).toBe('0x0');
+
+ // The status flip is guarded on `pending`, which is what makes the nonce
+ // single-use under concurrency rather than merely in sequence.
+ expect(sqlState.calls[1].text).toContain("status = 'pending'");
+ });
+
+ it('refuses a signature produced by a different key', async () => {
+ sqlState.queue.push(pendingRow(wallet.address));
+ const signature = await other.signMessage(claimMessage(NONCE));
+
+ const r = await call({
+ method: 'POST',
+ body: { signerAddress: wallet.address, signature, nonce: NONCE },
+ });
+
+ expect(r.status).toBe(403);
+ expect(r.payload.error).toBe('forbidden');
+ // Only the lookup ran: nothing was marked claimed.
+ expect(sqlState.calls).toHaveLength(1);
+ });
+
+ it('refuses a nonce issued to another address', async () => {
+ sqlState.queue.push(pendingRow(other.address));
+ const signature = await wallet.signMessage(claimMessage(NONCE));
+
+ const r = await call({
+ method: 'POST',
+ body: { signerAddress: wallet.address, signature, nonce: NONCE },
+ });
+
+ expect(r.status).toBe(403);
+ expect(sqlState.calls).toHaveLength(1);
+ });
+
+ it('refuses a nonce that has already been redeemed', async () => {
+ sqlState.queue.push(pendingRow(wallet.address, { status: 'claimed' }));
+ const signature = await wallet.signMessage(claimMessage(NONCE));
+
+ const r = await call({
+ method: 'POST',
+ body: { signerAddress: wallet.address, signature, nonce: NONCE },
+ });
+
+ expect(r.status).toBe(409);
+ expect(r.payload.error).toBe('conflict');
+ });
+
+ it('loses the race when a concurrent POST flipped the row first', async () => {
+ // Row still reads `pending`, but the conditional update matches nothing.
+ sqlState.queue.push(pendingRow(wallet.address), []);
+ const signature = await wallet.signMessage(claimMessage(NONCE));
+
+ const r = await call({
+ method: 'POST',
+ body: { signerAddress: wallet.address, signature, nonce: NONCE },
+ });
+
+ expect(r.status).toBe(409);
+ expect(r.payload.error).toBe('conflict');
+ });
+
+ it('refuses a nonce older than its TTL', async () => {
+ const stale = new Date(Date.now() - 30 * 60 * 1000).toISOString();
+ sqlState.queue.push(pendingRow(wallet.address, { created_at: stale }));
+ const signature = await wallet.signMessage(claimMessage(NONCE));
+
+ const r = await call({
+ method: 'POST',
+ body: { signerAddress: wallet.address, signature, nonce: NONCE },
+ });
+
+ expect(r.status).toBe(400);
+ expect(r.payload.error).toBe('nonce_expired');
+ expect(sqlState.calls).toHaveLength(1);
+ });
+
+ it('reports an unknown nonce without leaking whether one exists', async () => {
+ sqlState.queue.push([]);
+ const r = await call({
+ method: 'POST',
+ body: { signerAddress: wallet.address, signature: '0xdead', nonce: NONCE },
+ });
+ expect(r.status).toBe(400);
+ expect(r.payload.error).toBe('invalid_nonce');
+ });
+
+ it('rejects unparseable signature bytes as a 400, not a crash', async () => {
+ sqlState.queue.push(pendingRow(wallet.address));
+ const r = await call({
+ method: 'POST',
+ body: { signerAddress: wallet.address, signature: '0xdeadbeef', nonce: NONCE },
+ });
+ expect(r.status).toBe(400);
+ expect(r.payload.error).toBe('invalid_signature');
+ });
+
+ it('rejects non-string fields instead of coercing them into the query', async () => {
+ const r = await call({
+ method: 'POST',
+ body: { signerAddress: wallet.address, signature: ['0x1'], nonce: { $ne: null } },
+ });
+ expect(r.status).toBe(400);
+ expect(r.payload.error).toBe('validation_error');
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('requires every field', async () => {
+ const r = await call({ method: 'POST', body: { signerAddress: wallet.address } });
+ expect(r.status).toBe(400);
+ expect(r.payload.error_description).toContain('required');
+ });
+});
+
+describe('other methods', () => {
+ it('answers an unsupported method with 405 and an allow header', async () => {
+ const r = await call({ method: 'PUT' });
+ expect(r.status).toBe(405);
+ expect(r.headers.allow).toBe('GET, POST, OPTIONS');
+ });
+});