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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
test(api): cover the permissions, platform stats and referral funnel endpoints
nirholas8e69fa1d9659
diff --git a/tests/oauth-endpoints.test.js b/tests/oauth-endpoints.test.jsindex cb50cd1d7..5b3e1653a 100644--- a/tests/oauth-endpoints.test.js+++ b/tests/oauth-endpoints.test.js@@ -201,6 +201,27 @@ async function approve(extra = {}) {return call('authorize', { method: 'POST', form: { ...authorizeQuery(extra), csrf: await csrf(), decision: 'allow' } });}+const CONFIDENTIAL_SECRET = 'the-real-secret';++const basicHeader = (id, secret) => ({ authorization: `Basic ${Buffer.from(`${id}:${secret}`).toString('base64')}` });++async function seedConfidentialClient() {+ return seedClient({ client_type: 'confidential', client_secret_hash: await sha256(CONFIDENTIAL_SECRET), token_endpoint_auth: 'client_secret_basic' });+}++// A `client_secret_basic` client sends its credentials in the Authorization+// header and nowhere else, so the form carries no client_id at all.+async function issueTokensOverBasicAuth() {+ const authorized = await approve();+ const code = new URL(authorized.getHeader('location')).searchParams.get('code');+ const res = await call('token', {+ method: 'POST',+ headers: basicHeader('mcp_test_client', CONFIDENTIAL_SECRET),+ form: { grant_type: 'authorization_code', code, redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER },+ });+ return res.json();+}+async function issueTokens() {const authorized = await approve();const code = new URL(authorized.getHeader('location')).searchParams.get('code');@@ -403,6 +424,19 @@ describe('POST /oauth/register', () => {expect(db.clients[0].client_secret_hash).not.toBe(out.client_secret);});+ it('stamps client_secret_expires_at so a client can tell the secret never expires', async () => {+ // RFC 7591 section 3.2.1 makes the field REQUIRED alongside an issued+ // secret; without it a client cannot distinguish "never expires" from a+ // field the server forgot to send.+ const res = await call('register', { method: 'POST', jsonBody: { redirect_uris: ['https://client.example/cb'], token_endpoint_auth_method: 'client_secret_basic' } });+ expect(res.json().client_secret_expires_at).toBe(0);+ });++ it('omits client_secret_expires_at for a public client that gets no secret', async () => {+ const res = await call('register', { method: 'POST', jsonBody: { redirect_uris: ['https://client.example/cb'] } });+ expect(res.json()).not.toHaveProperty('client_secret_expires_at');+ });+it.each([['javascript:alert(document.cookie)'],['data:text/html,<script>alert(1)</script>'],@@ -466,6 +500,27 @@ describe('POST /oauth/revoke', () => {expect(res.statusCode).toBe(200);expect(res.json()).toEqual({});});++ // RFC 7009 section 2.1: the client authenticates here exactly as it does at+ // the token endpoint. Only the token endpoint read the Authorization header,+ // so a `client_secret_basic` client was answered 400 (no client_id in the+ // form) and 401 (bad credentials) and could never revoke anything it owned.+ it('authenticates a client_secret_basic client from the Authorization header alone', async () => {+ await seedConfidentialClient();+ const { refresh_token } = await issueTokensOverBasicAuth();+ const res = await call('revoke', { method: 'POST', headers: basicHeader('mcp_test_client', CONFIDENTIAL_SECRET), form: { token: refresh_token } });+ expect(res.statusCode).toBe(200);+ expect(db.refresh[0].revoked_at).toBeTruthy();+ });++ it('rejects a Basic header carrying the wrong secret', async () => {+ await seedConfidentialClient();+ const { refresh_token } = await issueTokensOverBasicAuth();+ const res = await call('revoke', { method: 'POST', headers: basicHeader('mcp_test_client', 'guessed'), form: { token: refresh_token } });+ expect(res.statusCode).toBe(401);+ expect(res.json().error).toBe('invalid_client');+ expect(db.refresh[0].revoked_at).toBeNull();+ });});describe('POST /oauth/introspect', () => {@@ -504,6 +559,24 @@ describe('POST /oauth/introspect', () => {const res = await call('introspect', { method: 'POST', form: { token: 'not-a-token', client_id: 'mcp_test_client' } });expect(res.json()).toEqual({ active: false });});++ // RFC 7662 section 2.1 carries the same client-authentication requirement as+ // the token endpoint, and a `client_secret_basic` client has no other way to+ // present its credentials.+ it('authenticates a client_secret_basic client from the Authorization header alone', async () => {+ await seedConfidentialClient();+ const tokens = await issueTokensOverBasicAuth();+ const res = await call('introspect', { method: 'POST', headers: basicHeader('mcp_test_client', CONFIDENTIAL_SECRET), form: { token: tokens.access_token } });+ expect(res.json()).toMatchObject({ active: true, sub: 'user-1', token_type: 'Bearer' });+ });++ it('refuses to answer a Basic header carrying the wrong secret', async () => {+ await seedConfidentialClient();+ const tokens = await issueTokensOverBasicAuth();+ const res = await call('introspect', { method: 'POST', headers: basicHeader('mcp_test_client', 'guessed'), form: { token: tokens.access_token } });+ expect(res.statusCode).toBe(401);+ expect(res.json().error).toBe('invalid_client');+ });});describe('dispatcher', () => {diff --git a/tests/permissions-api.test.js b/tests/permissions-api.test.jsnew file mode 100644index 000000000..0842bb2ba--- /dev/null+++ b/tests/permissions-api.test.js@@ -0,0 +1,553 @@+// api/permissions/[action].js dispatches six delegation endpoints and had no test+// coverage at all, which is how three defects survived in production code:+//+// 1. verify called `manager.isDelegationDisabled(hash)`, a name the+// DELEGATION_MANAGER_ABI never declares (the on-chain method is+// `disabledDelegations`), so every verify that reached the chain threw+// "not a function" and answered 502. The endpoint was 100% broken.+// 2. list passed an unparsed `limit`/`offset` straight into `LIMIT NaN::int`,+// turning caller error into a 500 db_error.+// 3. redeem reserved a delegation's spend budget before building the signer but+// only released it when the on-chain submit failed. A missing RPC URL or a+// signer that would not initialise burned that budget permanently.+//+// These tests pin all three, plus the auth gates that keep the relayer from+// spending gas for a caller who does not own the delegation.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { AbiCoder, Interface } from 'ethers';++import { DELEGATION_MANAGER_ABI } from '../src/erc7710/abi.js';++const sqlMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const getSessionUserMock = vi.fn();+const authenticateBearerMock = vi.fn();+const extractBearerMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+ authenticateBearer: (...a) => authenticateBearerMock(...a),+ extractBearer: (...a) => extractBearerMock(...a),+ hasScope: (granted, required) => {+ const g = new Set((granted || '').split(/\s+/).filter(Boolean));+ return required.split(/\s+/).every((s) => g.has(s));+ },+}));++vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));++const rlOk = { value: true };+const rateLimitStub = vi.fn(async () => ({ success: rlOk.value, reset: 1_000, limit: 10 }));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ read: (...a) => rateLimitStub(...a),+ strict: (...a) => rateLimitStub(...a),+ permissionsGrant: (...a) => rateLimitStub(...a),+ permissionsRevoke: (...a) => rateLimitStub(...a),+ },+ clientIp: () => '203.0.113.9',+}));++const envStub = {+ APP_ORIGIN: 'http://localhost:3000',+ PERMISSIONS_RELAYER_ENABLED: true,+ AGENT_RELAYER_KEY: '0x' + '11'.repeat(32),+};+vi.mock('../api/_lib/env.js', () => ({ env: envStub }));++vi.mock('../api/_lib/usage.js', () => ({ recordEvent: vi.fn() }));++// The verify path builds a real ethers Contract over whatever provider this+// returns, so the fake runner is what proves the handler asks the chain for the+// method the ABI actually declares.+const providerCalls = [];+const chainDisabled = { value: false };+const providerFails = { value: false };+vi.mock('../api/_lib/evm/rpc.js', () => ({+ evmFallbackProvider: async () => ({+ async call(tx) {+ if (providerFails.value) throw new Error('rpc unreachable');+ providerCalls.push(tx);+ return AbiCoder.defaultAbiCoder().encode(['bool'], [chainDisabled.value]);+ },+ async getNetwork() {+ return { chainId: 84532n, name: 'base-sepolia' };+ },+ async resolveName(n) {+ return n;+ },+ }),+}));++// redeem must never reach a real chain from a unit test; the handler's own+// pre-submit gates are what these cases exercise.+const redeemDelegationMock = vi.fn();+vi.mock('../src/permissions/toolkit.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ isDelegationValid: vi.fn(async () => ({ valid: true })),+ redeemDelegation: (...a) => redeemDelegationMock(...a),+ };+});++const { default: handler } = await import('../api/permissions/[action].js');++const AGENT = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+const DELEGATION_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';+const HASH = '0x' + 'ab'.repeat(32);+const TARGET = '0x1111111111111111111111111111111111111111';++function mkReq({ action, method = 'GET', query = '', headers = {}, body = null } = {}) {+ const hdrs = { ...headers };+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';+ return {+ method,+ url: `/api/permissions/${action}${query}`,+ headers: hdrs,+ query: { action },+ on(event, cb) {+ if (event === 'data' && body != null) {+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));+ queueMicrotask(() => {+ cb(buf);+ this._endCb?.();+ });+ } else if (event === 'end') {+ this._endCb = cb;+ if (body == null) queueMicrotask(cb);+ }+ },+ destroy() {},+ };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(b) {+ this.body = b;+ this.writableEnded = true;+ },+ };+}++const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);++async function call(opts) {+ const req = mkReq(opts);+ const res = mkRes();+ await handler(req, res);+ return res;+}++let sqlQueue = [];+beforeEach(() => {+ sqlQueue = [];+ sqlMock.mockReset().mockImplementation(() => {+ const next = sqlQueue.length ? sqlQueue.shift() : [];+ return next instanceof Error ? Promise.reject(next) : Promise.resolve(next);+ });+ getSessionUserMock.mockReset().mockResolvedValue(null);+ authenticateBearerMock.mockReset().mockResolvedValue(null);+ extractBearerMock.mockReset().mockReturnValue(null);+ redeemDelegationMock.mockReset();+ providerCalls.length = 0;+ chainDisabled.value = false;+ providerFails.value = false;+ rlOk.value = true;+ envStub.PERMISSIONS_RELAYER_ENABLED = true;+ delete process.env.RPC_URL_137;+});++describe('permissions dispatcher', () => {+ it('404s an action it does not implement', async () => {+ const res = await call({ action: 'bogus' });+ expect(res.statusCode).toBe(404);+ expect(parse(res).error).toBe('not_found');+ });+});++describe('GET /api/permissions/list', () => {+ it('requires agentId or delegator', async () => {+ const res = await call({ action: 'list' });+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('missing_filter');+ });++ it('rejects a non-uuid agentId before it reaches the uuid column', async () => {+ const res = await call({ action: 'list', query: '?agentId=not-a-uuid' });+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('invalid_id');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('rejects an unknown status filter', async () => {+ const res = await call({ action: 'list', query: `?agentId=${AGENT}&status=pending` });+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('validation_error');+ });++ // Regression: `limit=abc` used to reach Postgres as `LIMIT NaN::int` and come+ // back as a 500 db_error, so caller error read as a platform outage.+ it.each(['limit', 'offset'])('rejects a non-numeric %s with 400, not 500', async (param) => {+ const res = await call({ action: 'list', query: `?agentId=${AGENT}&${param}=abc` });+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('validation_error');+ expect(parse(res).error_description).toContain(param);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('returns the public shape for an agentId-only query without auth', async () => {+ sqlQueue.push([+ {+ id: DELEGATION_ID,+ chain_id: 84532,+ delegator_address: TARGET,+ delegate_address: TARGET,+ delegation_hash: HASH,+ delegation_json: { secret: 'envelope' },+ scope: { token: 'native', maxAmount: '100' },+ status: 'active',+ expires_at: '2030-01-01T00:00:00.000Z',+ created_at: '2026-01-01T00:00:00.000Z',+ last_redeemed_at: null,+ redemption_count: 0,+ },+ ]);+ const res = await call({ action: 'list', query: `?agentId=${AGENT}` });+ expect(res.statusCode).toBe(200);+ const body = parse(res);+ expect(body.ok).toBe(true);+ expect(body.delegations).toHaveLength(1);+ expect(body.delegations[0].delegationHash).toBe(HASH);+ // The signed envelope is owner-only; the public lane must not leak it.+ expect(body.delegations[0].delegationJson).toBeUndefined();+ expect(res.headers['cache-control']).toContain('max-age=30');+ });++ it('requires a session to filter by delegator', async () => {+ const res = await call({ action: 'list', query: `?delegator=${TARGET}` });+ expect(res.statusCode).toBe(401);+ expect(parse(res).error).toBe('unauthorized');+ });++ it('refuses a delegator address the session user does not own', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'user-1' });+ sqlQueue.push([]); // wallet ownership lookup: no match+ const res = await call({ action: 'list', query: `?delegator=${TARGET}` });+ expect(res.statusCode).toBe(403);+ expect(parse(res).error).toBe('forbidden');+ });+});++describe('GET /api/permissions/metadata', () => {+ it('requires agentId', async () => {+ const res = await call({ action: 'metadata' });+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('missing_param');+ });++ it('404s an agent that does not exist', async () => {+ sqlQueue.push([]);+ const res = await call({ action: 'metadata', query: `?agentId=${AGENT}` });+ expect(res.statusCode).toBe(404);+ expect(parse(res).error).toBe('agent_not_found');+ });++ it('serves the manifest with an etag and honours if-none-match', async () => {+ const rows = [+ {+ chain_id: 84532,+ delegator_address: TARGET,+ delegate_address: TARGET,+ delegation_hash: HASH,+ delegation_json: { hash: HASH },+ scope: { token: 'native' },+ expires_at: '2030-01-01T00:00:00.000Z',+ created_at: '2026-01-01T00:00:00.000Z',+ revoked_at: null,+ },+ ];+ sqlQueue.push([{ id: AGENT }], rows);+ const first = await call({ action: 'metadata', query: `?agentId=${AGENT}` });+ expect(first.statusCode).toBe(200);+ const body = parse(first);+ expect(body.spec).toBe('erc-7715/0.1');+ expect(body.delegations[0].hash).toBe(HASH);+ const etag = first.headers.etag;+ expect(etag).toBeTruthy();++ sqlQueue.push([{ id: AGENT }], rows);+ const second = await call({+ action: 'metadata',+ query: `?agentId=${AGENT}`,+ headers: { 'if-none-match': etag },+ });+ expect(second.statusCode).toBe(304);+ expect(second.body).toBeUndefined();+ });+});++describe('GET /api/permissions/verify', () => {+ it.each([+ ['', 'hash query param is required'],+ ['?hash=0xnothex', 'hash must be 0x + 64 hex chars'],+ [`?hash=${HASH}`, 'chainId query param is required'],+ [`?hash=${HASH}&chainId=abc`, 'chainId must be a positive integer'],+ [`?hash=${HASH}&chainId=999999`, 'chainId 999999 is not supported'],+ ])('rejects %s', async (query, message) => {+ const res = await call({ action: 'verify', query });+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toBe(message);+ });++ // Regression: the handler used to call a method name absent from the ABI, so+ // every on-chain check threw TypeError and the endpoint answered 502 forever.+ it('asks the chain for disabledDelegations(bytes32) and reports a live delegation valid', async () => {+ sqlQueue.push([]); // unknown to the platform+ const res = await call({ action: 'verify', query: `?hash=${HASH}&chainId=84532` });+ expect(res.statusCode).toBe(200);+ const body = parse(res);+ expect(body.valid).toBe(true);+ expect(body.reason).toBe('unknown_to_platform');+ expect(providerCalls).toHaveLength(1);+ const selector = new Interface(DELEGATION_MANAGER_ABI).getFunction(+ 'disabledDelegations',+ ).selector;+ expect(providerCalls[0].data.slice(0, 10)).toBe(selector);+ });++ it('reports an on-chain disabled delegation as revoked and self-heals the row', async () => {+ chainDisabled.value = true;+ sqlQueue.push([{ status: 'active', expires_at: '2030-01-01T00:00:00.000Z' }]);+ const res = await call({ action: 'verify', query: `?hash=${HASH}&chainId=84532` });+ expect(res.statusCode).toBe(200);+ const body = parse(res);+ expect(body.valid).toBe(false);+ expect(body.reason).toBe('delegation_revoked');+ });++ it('short-circuits a DB-revoked delegation without touching the chain', async () => {+ sqlQueue.push([{ status: 'revoked', expires_at: '2030-01-01T00:00:00.000Z' }]);+ const res = await call({ action: 'verify', query: `?hash=${HASH}&chainId=84532` });+ expect(res.statusCode).toBe(200);+ expect(parse(res).reason).toBe('delegation_revoked');+ expect(providerCalls).toHaveLength(0);+ });++ it('surfaces an RPC failure as a 502 with a support ref, not a stack trace', async () => {+ providerFails.value = true;+ sqlQueue.push([]);+ const res = await call({ action: 'verify', query: `?hash=${HASH}&chainId=84532` });+ expect(res.statusCode).toBe(502);+ const body = parse(res);+ expect(body.error).toBe('rpc_error');+ expect(body.ref).toBeTruthy();+ expect(res.body).not.toContain('rpc unreachable');+ });+});++describe('POST /api/permissions/grant', () => {+ it('requires a session', async () => {+ const res = await call({ action: 'grant', method: 'POST', body: {} });+ expect(res.statusCode).toBe(401);+ expect(parse(res).error).toBe('unauthorized');+ });++ it('rejects a malformed body with a field-level 400', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'user-1' });+ const res = await call({+ action: 'grant',+ method: 'POST',+ body: { agentId: 'nope', chainId: 84532 },+ });+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('validation_error');+ expect(parse(res).error_description).toContain('agentId');+ });++ it('rejects a chain with no DelegationManager deployment', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'user-1' });+ const res = await call({+ action: 'grant',+ method: 'POST',+ body: {+ agentId: AGENT,+ chainId: 999999,+ delegation: {+ delegator: TARGET,+ delegate: TARGET,+ caveats: [],+ salt: '1',+ signature: '0x00',+ hash: HASH,+ },+ scope: {+ token: 'native',+ maxAmount: '1',+ period: 'daily',+ targets: [TARGET],+ expiry: 4102444800,+ },+ },+ });+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('chain_not_supported');+ });+});++describe('POST /api/permissions/revoke', () => {+ it('requires a session', async () => {+ const res = await call({ action: 'revoke', method: 'POST', body: {} });+ expect(res.statusCode).toBe(401);+ });++ it('rejects a malformed txHash', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'user-1' });+ const res = await call({+ action: 'revoke',+ method: 'POST',+ body: { id: DELEGATION_ID, txHash: '0x1234' },+ });+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toContain('txHash');+ });+});++describe('POST /api/permissions/redeem', () => {+ const okBody = { id: DELEGATION_ID, calls: [{ to: TARGET, value: '5' }] };++ function bearer({ scope = 'permissions:redeem', userId = 'user-1' } = {}) {+ extractBearerMock.mockReturnValue('tok');+ authenticateBearerMock.mockResolvedValue({ userId, scope, apiKeyId: 'key-1' });+ }++ function delegationRow(overrides = {}) {+ return {+ id: DELEGATION_ID,+ agent_id: AGENT,+ chain_id: 84532,+ delegation_hash: HASH,+ delegation_json: { hash: HASH },+ scope: { token: 'native', maxAmount: '100', period: 'daily', targets: [TARGET] },+ status: 'active',+ expires_at: '2030-01-01T00:00:00.000Z',+ redemption_count: 0,+ last_redeemed_at: null,+ ...overrides,+ };+ }++ it('503s when the relayer is disabled on this deployment', async () => {+ envStub.PERMISSIONS_RELAYER_ENABLED = false;+ const res = await call({ action: 'redeem', method: 'POST', body: okBody });+ expect(res.statusCode).toBe(503);+ expect(parse(res).error).toBe('feature_disabled');+ });++ it('requires a bearer token', async () => {+ const res = await call({ action: 'redeem', method: 'POST', body: okBody });+ expect(res.statusCode).toBe(401);+ });++ it('requires the permissions:redeem scope', async () => {+ bearer({ scope: 'profile' });+ const res = await call({ action: 'redeem', method: 'POST', body: okBody });+ expect(res.statusCode).toBe(403);+ expect(parse(res).error).toBe('insufficient_scope');+ });++ it('404s a delegation whose agent the caller does not own, without leaking existence', async () => {+ bearer();+ sqlQueue.push([delegationRow()], [{ user_id: 'someone-else' }]);+ const res = await call({ action: 'redeem', method: 'POST', body: okBody });+ expect(res.statusCode).toBe(404);+ expect(parse(res).error).toBe('delegation_not_found');+ expect(redeemDelegationMock).not.toHaveBeenCalled();+ });++ it('refuses a call target outside scope.targets', async () => {+ bearer();+ sqlQueue.push([delegationRow()], [{ user_id: 'user-1' }]);+ const res = await call({+ action: 'redeem',+ method: 'POST',+ body: {+ id: DELEGATION_ID,+ calls: [{ to: '0x2222222222222222222222222222222222222222', value: '1' }],+ },+ });+ expect(res.statusCode).toBe(403);+ expect(parse(res).error).toBe('target_not_allowed');+ expect(redeemDelegationMock).not.toHaveBeenCalled();+ });++ it('409s a revoked delegation', async () => {+ bearer();+ sqlQueue.push([delegationRow({ status: 'revoked' })], [{ user_id: 'user-1' }]);+ const res = await call({ action: 'redeem', method: 'POST', body: okBody });+ expect(res.statusCode).toBe(409);+ expect(parse(res).error).toBe('delegation_revoked');+ });++ it('409s an expired delegation', async () => {+ bearer();+ sqlQueue.push([delegationRow({ expires_at: '2020-01-01T00:00:00.000Z' })], [+ { user_id: 'user-1' },+ ]);+ const res = await call({ action: 'redeem', method: 'POST', body: okBody });+ expect(res.statusCode).toBe(409);+ expect(parse(res).error).toBe('delegation_expired');+ });++ it('403s when the atomic reservation finds the period cap already spent', async () => {+ bearer();+ sqlQueue.push(+ [delegationRow()],+ [{ user_id: 'user-1' }],+ [], // reservation INSERT…SELECT materialised no row: over cap+ [{ spent: '100' }],+ );+ const res = await call({ action: 'redeem', method: 'POST', body: okBody });+ expect(res.statusCode).toBe(403);+ const body = parse(res);+ expect(body.error).toBe('scope_exceeded');+ expect(body.periodSpent).toBe('100');+ expect(redeemDelegationMock).not.toHaveBeenCalled();+ });++ // Regression: the reservation is written before the signer is built, so an exit+ // between the two has to release it. It used to leak, permanently consuming the+ // delegation's period budget for a request that never touched the chain.+ it('releases the spend reservation when no RPC is configured for the chain', async () => {+ bearer();+ sqlQueue.push(+ [delegationRow({ chain_id: 137 })],+ [{ user_id: 'user-1' }],+ [{ id: 'usage-1', spent_before: '0' }],+ [],+ );+ const res = await call({ action: 'redeem', method: 'POST', body: okBody });+ expect(res.statusCode).toBe(502);+ expect(parse(res).error).toBe('rpc_error');+ // Last statement must be the release, keyed on the reservation just written.+ const lastArgs = sqlMock.mock.calls.at(-1);+ expect(lastArgs[0].join('?')).toContain("status = 'failed'");+ expect(lastArgs).toContain('usage-1');+ });+});diff --git a/tests/platform-stats-endpoint.test.js b/tests/platform-stats-endpoint.test.jsnew file mode 100644index 000000000..a39210b41--- /dev/null+++ b/tests/platform-stats-endpoint.test.js@@ -0,0 +1,170 @@+// GET /api/platform/stats: the public traction counters behind the homepage+// strip and the monitor board.+//+// Invariants under test:+// 1. The success path serves real counts, `available: true`, and the 5-minute+// public cache header.+// 2. A failed read is NEVER rounded down to zero. It answers+// `available: false` under a short cache, so a database outage cannot park+// a fabricated all-zero traction payload on the CDN for five minutes, and+// nothing about that failure is cached for the next request.+// 3. `chains` is derived from the chain registry, not hardcoded: testnet and+// unknown chain ids never inflate it, and Solana counts as the home chain.+// 4. The in-process cache serves repeats without re-querying, and concurrent+// misses collapse into a single flight.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const sqlCalls = [];+let sqlRoutes = [];+let sqlFailure = null;+const sqlMock = vi.fn((strings, ...vals) => {+ const text = Array.isArray(strings) ? strings.join('?') : String(strings);+ sqlCalls.push({ text, vals });+ if (sqlFailure) return Promise.reject(sqlFailure);+ const route = sqlRoutes.find((r) => r.match.test(text));+ return Promise.resolve(route ? route.rows : []);+});+vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ // http.js classifies thrown errors through these; a mocked db must still answer.+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));++const { default: handler, _resetStatsCache, countChains } = await import('../api/platform/stats.js');++const ROWS = [+ { match: /from agent_identities/i, rows: [{ n: 3140 }] },+ { match: /count\(distinct country\)/i, rows: [{ n: 29 }] },+ { match: /from widget_views/i, rows: [{ n: '593' }] },+ { match: /from widget_chat_threads/i, rows: [{ n: '29' }] },+ { match: /from avatars/i, rows: [{ n: 25826 }] },+ { match: /from widgets\b/i, rows: [{ n: 613 }] },+ { match: /from erc8004_agents_index/i, rows: [{ chain_id: 8453 }, { chain_id: 1 }, { chain_id: 11155111 }] },+ { match: /from solana_attestations/i, rows: [{ '?column?': 1 }] },+];++function mkReq({ method = 'GET', headers = {} } = {}) {+ return { method, url: '/api/platform/stats', headers, socket: { remoteAddress: '203.0.113.7' } };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ writableEnded: false,+ headersSent: false,+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ end(b) {+ this.body = b;+ this.writableEnded = true;+ },+ };+}++async function call(reqInit) {+ const res = mkRes();+ await handler(mkReq(reqInit), res);+ return res;+}++const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);++beforeEach(() => {+ sqlCalls.length = 0;+ sqlRoutes = ROWS;+ sqlFailure = null;+ _resetStatsCache();+});++describe('GET /api/platform/stats', () => {+ it('serves the real counters with a public five-minute cache', async () => {+ const res = await call();++ expect(res.statusCode).toBe(200);+ const body = parse(res);+ expect(body).toMatchObject({+ available: true,+ agents: 3140,+ views: 593,+ chats: 29,+ avatars: 25826,+ countries: 29,+ widgets: 613,+ });+ expect(body.generated).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ expect(res.headers['cache-control']).toBe('public, max-age=300, s-maxage=300, stale-while-revalidate=60');+ expect(res.headers['access-control-allow-origin']).toBe('*');+ expect(res.headers['content-type']).toMatch(/application\/json/);+ });++ it('counts mainnet chains plus Solana, never testnets', async () => {+ // Base + Ethereum are mainnets; Sepolia (11155111) is not.+ expect(parse(await call()).chains).toBe(3);+ });++ it('drops testnet and unregistered chain ids from the chain count', () => {+ const rows = [{ chain_id: 8453 }, { chain_id: 84532 }, { chain_id: 999999 }, { chain_id: '8453' }];+ expect(countChains(rows, [{}])).toBe(2); // Base + Solana, deduped+ expect(countChains(rows, [])).toBe(1); // no Solana attestations yet+ expect(countChains([], [])).toBe(0);+ });++ it('says unavailable instead of serving fabricated zeros when the db is down', async () => {+ sqlFailure = new Error('Missing required env var: DATABASE_URL');++ const res = await call();++ expect(res.statusCode).toBe(200);+ expect(parse(res)).toEqual({ available: false, reason: 'db_unavailable' });+ // The all-zero payload that used to ship here must not exist at all.+ expect(res.body).not.toMatch(/"agents":0/);+ // A failure must not ride the five-minute public cache.+ expect(res.headers['cache-control']).toBe('public, s-maxage=15');+ });++ it('does not cache a failure: the next request re-queries and recovers', async () => {+ sqlFailure = new Error('connection terminated');+ expect(parse(await call()).available).toBe(false);++ sqlFailure = null;+ sqlCalls.length = 0;+ const res = await call();++ expect(parse(res).agents).toBe(3140);+ expect(sqlCalls.length).toBeGreaterThan(0);+ });++ it('serves repeats from cache and collapses concurrent misses into one flight', async () => {+ const [a, b] = await Promise.all([call(), call()]);+ const perFlight = sqlCalls.length;+ expect(parse(a)).toEqual(parse(b));+ expect(perFlight).toBe(8); // one flight, not two++ await call();+ expect(sqlCalls.length).toBe(perFlight); // cache hit, no new queries+ });++ it('rejects a write with a 405 and no stack trace', async () => {+ const res = await call({ method: 'POST' });++ expect(res.statusCode).toBe(405);+ expect(parse(res).error).toBe('method_not_allowed');+ expect(res.body).not.toMatch(/at .*\.js:/);+ });++ it('answers a preflight with 204 and the read-only method set', async () => {+ const res = await call({ method: 'OPTIONS', headers: { origin: 'https://example.com' } });++ expect(res.statusCode).toBe(204);+ expect(res.headers['access-control-allow-methods']).toBe('GET,OPTIONS');+ });+});diff --git a/tests/pump-channel-feed.test.js b/tests/pump-channel-feed.test.jsindex dc5026d99..340008b10 100644--- a/tests/pump-channel-feed.test.js+++ b/tests/pump-channel-feed.test.js@@ -156,6 +156,39 @@ describe('channel-feed endpoint', () => {expect(body.items.length).toBeLessThanOrEqual(5);});+ it('serves the default page when limit is not a number', async () => {+ // `Number('abc')` is NaN and NaN survives every Math.min/Math.max clamp, so+ // the old parse handed a NaN limit to each source query and to the feed+ // slice: a single typo'd limit answered 200 with an empty feed. A caller+ // that mistypes the page size still gets the feed, never a silent blank.+ mintsMock.mockResolvedValueOnce(+ Array.from({ length: 30 }, (_, i) => ({+ signature: `nan${i}`,+ mint: `M${i}`,+ timestamp: i,+ })),+ );++ const res = mockRes();+ await handler(mockReq('?limit=abc'), res);++ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.items.length).toBe(30);+ // The sources are asked for a real number, never NaN.+ expect(mintsMock).toHaveBeenCalledWith(50);+ });++ it('clamps a limit above the ceiling instead of forwarding it', async () => {+ mintsMock.mockResolvedValueOnce([]);++ const res = mockRes();+ await handler(mockReq('?limit=9999'), res);++ expect(res.statusCode).toBe(200);+ expect(mintsMock).toHaveBeenCalledWith(200);+ });+it('normalizes tx_signature fallback', async () => {claimsMock.mockResolvedValueOnce([{ tx_signature: 'claimsig', mint: 'CM1', timestamp: 500 },diff --git a/tests/referral-funnel.test.js b/tests/referral-funnel.test.jsnew file mode 100644index 000000000..864e23ac5--- /dev/null+++ b/tests/referral-funnel.test.js@@ -0,0 +1,112 @@+/**+ * Referral share funnel: getReferralFunnel() unit tests.+ *+ * The funnel is the read side of POST /api/referral/visit: without it the+ * referral_visits table is write-only and the visit → signup → activation loop+ * is unmeasurable. These tests pin the three counts to the three queries that+ * produce them, the lookback clamp, and the "empty prior stage" rule that makes+ * a conversion rate null instead of a fake 0%.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++// Counts returned by each of the funnel's three queries, keyed by the table the+// query reads. Each test sets these, then asserts on the derived payload.+const dbState = { visits: 0, signups: 0, activations: 0 };+// Every interval literal the queries bind, so the lookback clamp is observable.+const boundSince = [];++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ const q = strings.join('?').toLowerCase();+ for (const v of values) if (v instanceof Date) boundSince.push(v);+ if (/from referral_visits/.test(q)) return [{ count: dbState.visits }];+ if (/from credit_ledger/.test(q)) return [{ count: dbState.activations }];+ if (/from users/.test(q)) return [{ count: dbState.signups }];+ return [];+ }),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++vi.mock('../api/_lib/cache.js', () => ({+ cacheWrap: async (_key, _ttl, fn) => fn(),+}));++vi.mock('../api/_lib/email.js', () => ({+ sendReferralCommissionEmail: async () => ({ sent: false }),+}));++const { getReferralFunnel } = await import('../api/_lib/referrals.js');++beforeEach(() => {+ dbState.visits = 0;+ dbState.signups = 0;+ dbState.activations = 0;+ boundSince.length = 0;+});++describe('getReferralFunnel', () => {+ it('reports each stage and both conversion rates', async () => {+ dbState.visits = 200;+ dbState.signups = 50;+ dbState.activations = 20;++ const f = await getReferralFunnel('user-1');+ expect(f.visits).toBe(200);+ expect(f.signups).toBe(50);+ expect(f.activations).toBe(20);+ expect(f.visit_to_signup_pct).toBe(25);+ expect(f.signup_to_activation_pct).toBe(40);+ });++ it('rounds conversion rates to one decimal', async () => {+ dbState.visits = 3;+ dbState.signups = 1;+ const f = await getReferralFunnel('user-1');+ expect(f.visit_to_signup_pct).toBe(33.3);+ });++ it('returns null, not 0%, when the prior stage is empty', async () => {+ const f = await getReferralFunnel('user-1');+ expect(f.visits).toBe(0);+ expect(f.signups).toBe(0);+ expect(f.visit_to_signup_pct).toBeNull();+ expect(f.signup_to_activation_pct).toBeNull();+ });++ it('defaults to a 30-day lookback and binds a matching cutoff', async () => {+ const before = Date.now();+ const f = await getReferralFunnel('user-1');+ expect(f.days).toBe(30);+ expect(boundSince.length).toBe(3);+ const expected = before - 30 * 24 * 60 * 60 * 1000;+ for (const since of boundSince) {+ expect(Math.abs(since.getTime() - expected)).toBeLessThan(5_000);+ }+ });++ it('accepts a caller-supplied window and clamps it to a year', async () => {+ expect((await getReferralFunnel('u', { days: 7 })).days).toBe(7);+ expect((await getReferralFunnel('u', { days: '90' })).days).toBe(90);+ expect((await getReferralFunnel('u', { days: 5000 })).days).toBe(365);+ });++ it('falls back to the default window on junk input', async () => {+ expect((await getReferralFunnel('u', { days: 0 })).days).toBe(30);+ expect((await getReferralFunnel('u', { days: -10 })).days).toBe(30);+ expect((await getReferralFunnel('u', { days: 'abc' })).days).toBe(30);+ expect((await getReferralFunnel('u', {})).days).toBe(30);+ });++ it('tolerates a row shape with no count (a stage that returned nothing)', async () => {+ dbState.visits = null;+ dbState.signups = null;+ dbState.activations = null;+ const f = await getReferralFunnel('user-1');+ expect(f.visits).toBe(0);+ expect(f.signups).toBe(0);+ expect(f.activations).toBe(0);+ expect(f.visit_to_signup_pct).toBeNull();+ });+});