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(custody): return 400 for an out-of-range anchor epoch and read latest from one row

nirholas2e12a2f88813
diff --git a/api/_lib/custody-proof.js b/api/_lib/custody-proof.js
index 0432d1a49..642027f09 100644
--- a/api/_lib/custody-proof.js
+++ b/api/_lib/custody-proof.js
@@ -353,6 +353,18 @@ export async function getAnchorRef(epoch) {
return epochRowToPublic(row);
}
+/**
+ * Public anchor reference for the newest epoch. One row, one query: the anchor
+ * endpoint used to answer `?epoch=latest` out of getPublicIntegrity(), which
+ * also runs a full-table aggregate and a 12-row recent list it then discards.
+ */
+export async function getLatestAnchorRef() {
+ const [row] = await sql`
+ SELECT * FROM custody_attestation_epochs ORDER BY epoch DESC LIMIT 1
+ `;
+ return epochRowToPublic(row);
+}
+
/**
* Owner-gated inclusion proof for one agent's wallet at the latest epoch in which
* it was attested. Returns the leaf's public fields, the Merkle path to the root,
diff --git a/api/custody/anchor.js b/api/custody/anchor.js
index 526b7bd9d..9d67ec889 100644
--- a/api/custody/anchor.js
+++ b/api/custody/anchor.js
@@ -1,12 +1,19 @@
-// GET /api/custody/anchor?epoch=N — public anchor reference for one epoch: the
-// Merkle root, the on-chain anchor tx signature, and the network it was committed
-// on. Lets a verifier cross-check the root it computed against what the platform
-// recorded — though the authoritative check reads the root straight off-chain.
+// GET /api/custody/anchor?epoch=N : public anchor reference for one epoch. It
+// carries the Merkle root, the on-chain anchor tx signature, and the network it
+// was committed on. Lets a verifier cross-check the root it computed against
+// what the platform recorded, though the authoritative check reads the root
+// straight off-chain.
//
// Returns only public epoch metadata; no per-wallet leaves.
import { cors, json, method, error, serverError } from '../_lib/http.js';
-import { getAnchorRef, getPublicIntegrity } from '../_lib/custody-proof.js';
+import { getAnchorRef, getLatestAnchorRef } from '../_lib/custody-proof.js';
+
+// Epochs are a bigint column starting at 1. Bound the accepted input to 18
+// digits so an oversized number is a client error here rather than a Postgres
+// "out of range for type bigint" that surfaces as a 500 (which is what
+// ?epoch=99999999999999999999999999 used to return).
+const EPOCH_RE = /^\d{1,18}$/;
export default async function handler(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -16,11 +23,11 @@ export default async function handler(req, res) {
const epochRaw = url.searchParams.get('epoch');
let ref;
if (epochRaw == null || epochRaw === '' || epochRaw === 'latest') {
- ref = (await getPublicIntegrity()).latest;
- } else if (/^\d+$/.test(epochRaw)) {
- ref = await getAnchorRef(epochRaw);
+ ref = await getLatestAnchorRef();
+ } else if (EPOCH_RE.test(epochRaw) && Number(epochRaw) >= 1) {
+ ref = await getAnchorRef(Number(epochRaw));
} else {
- return error(res, 400, 'bad_request', 'epoch must be a positive integer or "latest"');
+ return error(res, 400, 'bad_request', 'epoch must be a positive integer (1 to 18 digits) or "latest"');
}
if (!ref) return error(res, 404, 'not_found', 'no such epoch');
res.setHeader('cache-control', 'public, s-maxage=60, stale-while-revalidate=300');
diff --git a/api/custody/integrity.js b/api/custody/integrity.js
index 958c83046..9613602f9 100644
--- a/api/custody/integrity.js
+++ b/api/custody/integrity.js
@@ -1,6 +1,6 @@
-// GET /api/custody/integrity — public, no-auth aggregate for the Proof-of-Custody
+// GET /api/custody/integrity : public, no-auth aggregate for the Proof-of-Custody
// integrity page. Returns the latest attestation epoch, its Merkle root, the
-// on-chain anchor tx, the wallet count, and aggregate SOL — never any per-wallet
+// on-chain anchor tx, the wallet count, and aggregate SOL. Never any per-wallet
// private data. The public face of "our custody is provable".
import { cors, json, method, serverError } from '../_lib/http.js';
@@ -11,7 +11,7 @@ export default async function handler(req, res) {
if (!method(req, res, ['GET'])) return;
try {
const data = await getPublicIntegrity();
- // Public aggregate — safe to CDN-cache briefly so the integrity page stays
+ // Public aggregate, safe to CDN-cache briefly so the integrity page stays
// snappy without hammering the DB. New epochs land at most every few hours.
res.setHeader('cache-control', 'public, s-maxage=60, stale-while-revalidate=300');
return json(res, 200, { data });
diff --git a/tests/custody-public-endpoints.test.js b/tests/custody-public-endpoints.test.js
new file mode 100644
index 000000000..fb43dd1fc
--- /dev/null
+++ b/tests/custody-public-endpoints.test.js
@@ -0,0 +1,159 @@
+// The two public, no-auth Proof-of-Custody reads:
+// GET /api/custody/integrity (api/custody/integrity.js)
+// GET /api/custody/anchor (api/custody/anchor.js)
+//
+// Both are the outward face of "our custody is provable", so they are exercised
+// here at the handler boundary: the success path shapes real epoch rows, and the
+// failure paths (bad epoch input, unknown epoch, DB fault) answer a JSON error
+// with the right status instead of leaking a stack or 500-ing on client input.
+//
+// The prover beneath them is covered by tests/custody-proof-epoch.test.js; here
+// custody-proof.js is mocked at the module seam so no DB or RPC is touched.
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const EPOCH_7 = {
+ epoch: 7,
+ network: 'mainnet',
+ anchor_network: 'devnet',
+ merkle_root: 'a'.repeat(64),
+ wallet_count: 3,
+ total_lamports: '1500000000',
+ total_sol: 1.5,
+ anchor_sig: 'sig7',
+ anchor_explorer: 'https://explorer.solana.com/tx/sig7?cluster=devnet',
+ anchor_status: 'anchored',
+ created_at: '2026-08-12T00:00:00Z',
+ anchored_at: '2026-08-12T00:00:05Z',
+};
+
+const getPublicIntegrity = vi.fn(async () => ({
+ latest: EPOCH_7,
+ epochs_total: 7,
+ epochs_anchored: 7,
+ since: '2026-06-23T00:00:00Z',
+ recent: [EPOCH_7],
+}));
+const getAnchorRef = vi.fn(async (epoch) => (Number(epoch) === 7 ? EPOCH_7 : null));
+const getLatestAnchorRef = vi.fn(async () => EPOCH_7);
+
+vi.mock('../api/_lib/custody-proof.js', () => ({
+ getPublicIntegrity: (...a) => getPublicIntegrity(...a),
+ getAnchorRef: (...a) => getAnchorRef(...a),
+ getLatestAnchorRef: (...a) => getLatestAnchorRef(...a),
+}));
+
+import integrityHandler from '../api/custody/integrity.js';
+import anchorHandler from '../api/custody/anchor.js';
+
+function fakeRes() {
+ const headers = {};
+ return {
+ statusCode: 200,
+ headersSent: false,
+ writableEnded: false,
+ body: null,
+ headers,
+ setHeader(k, v) { headers[k.toLowerCase()] = v; },
+ getHeader(k) { return headers[k.toLowerCase()]; },
+ end(payload) {
+ this.writableEnded = true;
+ this.body = payload ? JSON.parse(payload) : null;
+ },
+ };
+}
+
+const req = (url) => ({ method: 'GET', url, headers: {} });
+
+beforeEach(() => {
+ getPublicIntegrity.mockClear();
+ getAnchorRef.mockClear();
+ getLatestAnchorRef.mockClear();
+});
+
+describe('GET /api/custody/integrity', () => {
+ it('returns the public aggregate and marks it CDN-cacheable', async () => {
+ const res = fakeRes();
+ await integrityHandler(req('/api/custody/integrity'), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.data.latest).toMatchObject({ epoch: 7, wallet_count: 3, anchor_status: 'anchored' });
+ expect(res.body.data.epochs_total).toBe(7);
+ expect(res.headers['cache-control']).toContain('s-maxage=60');
+ });
+
+ it('answers a DB fault with a sanitized 5xx envelope, never a stack', async () => {
+ getPublicIntegrity.mockRejectedValueOnce(new Error('relation "custody_attestation_epochs" does not exist'));
+ const res = fakeRes();
+ await integrityHandler(req('/api/custody/integrity'), res);
+
+ expect(res.statusCode).toBe(500);
+ expect(res.body.error).toBe('integrity_failed');
+ expect(res.body.ref).toMatch(/^[0-9a-f]{16}$/);
+ expect(JSON.stringify(res.body)).not.toContain('custody_attestation_epochs');
+ expect(res.headers['cache-control']).toBe('no-store');
+ });
+
+ it('rejects a non-GET method with 405 + Allow', async () => {
+ const res = fakeRes();
+ await integrityHandler({ method: 'POST', url: '/api/custody/integrity', headers: {} }, res);
+
+ expect(res.statusCode).toBe(405);
+ expect(res.headers.allow).toBe('GET, HEAD');
+ expect(getPublicIntegrity).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/custody/anchor', () => {
+ it('resolves one epoch by number', async () => {
+ const res = fakeRes();
+ await anchorHandler(req('/api/custody/anchor?epoch=7'), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.data.merkle_root).toBe('a'.repeat(64));
+ expect(getAnchorRef).toHaveBeenCalledWith(7);
+ });
+
+ it('treats a missing, empty, or "latest" epoch as the newest one via a single-row read', async () => {
+ for (const url of ['/api/custody/anchor', '/api/custody/anchor?epoch=', '/api/custody/anchor?epoch=latest']) {
+ const res = fakeRes();
+ await anchorHandler(req(url), res);
+ expect(res.statusCode).toBe(200);
+ expect(res.body.data.epoch).toBe(7);
+ }
+ // The full aggregate (extra count + 12-row recent list) is never fetched here.
+ expect(getLatestAnchorRef).toHaveBeenCalledTimes(3);
+ expect(getPublicIntegrity).not.toHaveBeenCalled();
+ });
+
+ it('404s an epoch that does not exist yet', async () => {
+ const res = fakeRes();
+ await anchorHandler(req('/api/custody/anchor?epoch=999999'), res);
+
+ expect(res.statusCode).toBe(404);
+ expect(res.body.error).toBe('not_found');
+ expect(res.headers['cache-control']).toBe('no-store');
+ });
+
+ it.each(['abc', '-1', '1.5', '0', '99999999999999999999999999', '1%20OR%201=1'])(
+ '400s the malformed epoch %s without querying the database',
+ async (raw) => {
+ const res = fakeRes();
+ await anchorHandler(req(`/api/custody/anchor?epoch=${raw}`), res);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body.error).toBe('bad_request');
+ expect(getAnchorRef).not.toHaveBeenCalled();
+ expect(getLatestAnchorRef).not.toHaveBeenCalled();
+ },
+ );
+
+ it('answers a lookup fault with a sanitized 5xx envelope', async () => {
+ getAnchorRef.mockRejectedValueOnce(new Error('connection to neon.tech failed'));
+ const res = fakeRes();
+ await anchorHandler(req('/api/custody/anchor?epoch=7'), res);
+
+ expect(res.statusCode).toBe(500);
+ expect(res.body.error).toBe('anchor_lookup_failed');
+ expect(JSON.stringify(res.body)).not.toContain('neon.tech');
+ });
+});