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.

test(sweep): pin the embed gate, IRL analytics/drops, avatar attachments and voice contracts

nirholas7caacb0042b2
diff --git a/tests/api/embed-gate-create.test.js b/tests/api/embed-gate-create.test.js
new file mode 100644
index 000000000..f49d5b13e
--- /dev/null
+++ b/tests/api/embed-gate-create.test.js
@@ -0,0 +1,212 @@
+// Tests for POST /api/embed/gate-create, the endpoint that turns an asset you
+// own into a holder-only embed.
+//
+// Two rules carry the weight here. First, only the owner may put a gate on an
+// asset: a gate created by anyone else would be a stranger paywalling someone
+// else's avatar. Second, the response must not contain the glbUrl, because the
+// point of gating is that the model is handed out by api/embed/resolve.js and
+// only against a proven holding.
+//
+// The gate config is coin-agnostic plumbing: `mint` is a runtime parameter so
+// any community can gate with its own SPL token, and it defaults to $THREE when
+// the caller does not name one. Both behaviours are pinned below.
+//
+// Only the database and the session lookup are stubbed. The gate normalization,
+// the asset resolver and the snippet the caller pastes are all the real thing.
+
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+
+beforeAll(() => {
+ process.env.JWT_SECRET = 'test-jwt-secret-embed-gate-create-0123456789';
+ process.env.S3_PUBLIC_DOMAIN = 'assets.test.three.ws';
+});
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const getSessionUserMock = vi.fn();
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+ hasScope: vi.fn(() => true),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ embedGateCreateIp: vi.fn(async () => ({ success: true, limit: 20, remaining: 19, reset: 0 })),
+ },
+ clientIp: () => '203.0.113.11',
+}));
+
+const handler = (await import('../../api/embed/gate-create.js')).default;
+const { DEFAULT_GATE_MINT } = await import('../../api/_lib/embed-gate.js');
+
+const OWNER = 'user_owner_1';
+const AVATAR_ID = '8e3f1c22-0000-4000-8000-0000000000c1';
+const ASSET = `avatar:${AVATAR_ID}`;
+
+const avatarRow = {
+ id: AVATAR_ID,
+ name: 'Nova',
+ description: 'A public avatar',
+ storage_key: 'avatars/nova.glb',
+ thumbnail_key: 'avatars/nova.jpg',
+};
+
+/** `owner` is the row checkAssetOwnership reads; `avatar` is what the resolver
+ * reads. They are separate queries against the same table, so they are stubbed
+ * by the columns each selects. */
+function stubDb({ avatar = [avatarRow], owner = [{ owner_id: OWNER }], inserted = [] } = {}) {
+ sqlMock.mockImplementation((strings) => {
+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/insert into embed_gates/i.test(text)) return Promise.resolve(inserted);
+ if (/update embed_gates/i.test(text)) return Promise.resolve([]);
+ if (/select owner_id from avatars/i.test(text)) return Promise.resolve(owner);
+ if (/from\s+avatars/i.test(text)) return Promise.resolve(avatar);
+ return Promise.resolve([]);
+ });
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk) this.body += chunk;
+ },
+ };
+}
+
+async function post(body) {
+ const req = {
+ method: 'POST',
+ url: '/api/embed/gate-create',
+ headers: { 'content-type': 'application/json' },
+ rawBody: Buffer.from(JSON.stringify(body)),
+ body,
+ on(event, cb) {
+ if (event === 'data') {
+ queueMicrotask(() => {
+ cb(Buffer.from(JSON.stringify(body)));
+ this._endCb?.();
+ });
+ } else if (event === 'end') {
+ this._endCb = cb;
+ }
+ },
+ destroy() {},
+ };
+ const res = mkRes();
+ await handler(req, res);
+ return { res, json: res.body ? JSON.parse(res.body) : null };
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ getSessionUserMock.mockReset();
+});
+
+describe('authorization', () => {
+ it('401s a caller with no session and no bearer token', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ stubDb();
+ const { res, json } = await post({ assetId: ASSET, gate: { minAmount: 5000 } });
+
+ expect(res.statusCode).toBe(401);
+ expect(json.error).toBe('unauthorized');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('403s a signed-in caller who does not own the asset', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'user_someone_else' });
+ stubDb();
+ const { res, json } = await post({ assetId: ASSET, gate: { minAmount: 5000 } });
+
+ expect(res.statusCode).toBe(403);
+ expect(json.error).toBe('not_owner');
+ });
+
+ it('404s an asset that does not exist', async () => {
+ getSessionUserMock.mockResolvedValue({ id: OWNER });
+ stubDb({ avatar: [], owner: [] });
+ const { res, json } = await post({ assetId: ASSET, gate: { minAmount: 5000 } });
+
+ expect(res.statusCode).toBe(404);
+ expect(json.error).toBe('not_found');
+ });
+});
+
+describe('creating a gate', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: OWNER });
+ });
+
+ it('defaults to $THREE and returns a paste-ready snippet', async () => {
+ stubDb();
+ const { res, json } = await post({ assetId: ASSET, gate: { minAmount: 5000 } });
+
+ expect(res.statusCode).toBe(201);
+ expect(json.gate).toEqual({ mint: DEFAULT_GATE_MINT, minAmount: 5000, chain: 'solana' });
+ expect(json.gateId).toMatch(/^[A-Za-z0-9]{12}$/);
+ expect(json.embed.snippet).toContain(json.assetId);
+ expect(json.embed.snippet).toContain('/embed/v1.js');
+ // The whole point of gating: this response is not a way around it.
+ expect(JSON.stringify(json)).not.toContain('avatars/nova.glb');
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+
+ it('accepts a runtime mint, so a community can gate with its own token', async () => {
+ stubDb();
+ const mint = 'THREEsynthetic1111111111111111111111111111';
+ const { res, json } = await post({ assetId: ASSET, gate: { mint, minAmount: 1 } });
+
+ expect(res.statusCode).toBe(201);
+ expect(json.gate.mint).toBe(mint);
+ });
+
+ it('rejects a non-positive threshold instead of creating an open gate', async () => {
+ stubDb();
+ const { res, json } = await post({ assetId: ASSET, gate: { minAmount: 0 } });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('validation_error');
+ });
+
+ it('rejects a chain other than solana, the home chain for gating', async () => {
+ stubDb();
+ const { res, json } = await post({
+ assetId: ASSET,
+ gate: { minAmount: 5000, chain: 'ethereum' },
+ });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('validation_error');
+ });
+
+ it('rejects an assetId that is not one of the documented specs', async () => {
+ stubDb();
+ const { res, json } = await post({ assetId: 'not-an-asset-ref', gate: { minAmount: 5000 } });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('validation_error');
+ });
+
+ it('rejects a body with no gate at all', async () => {
+ stubDb();
+ const { res, json } = await post({ assetId: ASSET });
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('validation_error');
+ });
+});
diff --git a/tests/api/embed-gate-verify.test.js b/tests/api/embed-gate-verify.test.js
new file mode 100644
index 000000000..1e538684a
--- /dev/null
+++ b/tests/api/embed-gate-verify.test.js
@@ -0,0 +1,313 @@
+// Tests for POST /api/embed/gate-verify, the two-phase wallet proof that mints
+// the access token api/embed/resolve.js accepts in place of a chain read.
+//
+// This endpoint is the whole security boundary of a token-gated embed: whoever
+// gets a token past it sees the model. So what is pinned here is every way the
+// proof can be forged or replayed, and the rule that a balance the caller
+// claims counts for nothing.
+//
+// The signatures are real ed25519 signatures from a real keypair, verified by
+// the real api/_lib/siws.js. Only the database rows and the chain read are
+// stubbed: one because there is no Postgres in a unit test, the other because
+// hitting mainnet from the suite would make the tests flaky and slow. The
+// stubbed balance is the value a real RPC read returned, which is exactly the
+// input the gate decision is defined over.
+
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+import { ed25519 } from '@noble/curves/ed25519.js';
+import bs58 from 'bs58';
+
+beforeAll(() => {
+ process.env.JWT_SECRET = 'test-jwt-secret-embed-gate-verify-0123456789';
+});
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ embedGateVerifyIp: vi.fn(async () => ({ success: true, limit: 30, remaining: 29, reset: 0 })),
+ embedGateVerifyWallet: vi.fn(async () => ({ success: true, limit: 10, remaining: 9, reset: 0 })),
+ },
+ clientIp: () => '203.0.113.9',
+}));
+
+const balanceMock = vi.fn();
+vi.mock('../../api/_lib/embed-gate.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, getSplTokenBalance: (...a) => balanceMock(...a) };
+});
+
+const handler = (await import('../../api/embed/gate-verify.js')).default;
+const { verifyEmbedGateToken } = await import('../../api/_lib/embed-gate-token.js');
+const { DEFAULT_GATE_MINT } = await import('../../api/_lib/embed-gate.js');
+
+// A real keypair: the wallet address IS the public key, so a signature that
+// verifies here is one a wallet could have produced.
+const SECRET = ed25519.utils.randomSecretKey();
+const PUBLIC = ed25519.getPublicKey(SECRET);
+const WALLET = bs58.encode(PUBLIC);
+const OTHER_SECRET = ed25519.utils.randomSecretKey();
+const OTHER_WALLET = bs58.encode(ed25519.getPublicKey(OTHER_SECRET));
+
+const ASSET = 'avatar:8e3f1c22-0000-4000-8000-0000000000c1';
+const GATE_ID = 'gate_0000000000000042';
+const NONCE = 'A1b2C3d4E5f6G7h8';
+
+const gateRow = {
+ id: GATE_ID,
+ asset_id: ASSET,
+ owner_user_id: 'user_1',
+ chain: 'solana',
+ mint: DEFAULT_GATE_MINT,
+ min_amount: 5000,
+};
+
+function nonceRow(overrides = {}) {
+ return {
+ nonce: NONCE,
+ gate_id: GATE_ID,
+ address: WALLET,
+ expires_at: new Date(Date.now() + 60_000).toISOString(),
+ consumed_at: null,
+ ...overrides,
+ };
+}
+
+function signedMessage(nonce = NONCE, wallet = WALLET, secret = SECRET) {
+ const message = [
+ 'three.ws token-gated embed verification.',
+ '',
+ `Asset: ${ASSET}`,
+ `Wallet: ${wallet}`,
+ `Nonce: ${nonce}`,
+ `Issued At: ${new Date().toISOString()}`,
+ ].join('\n');
+ const signature = bs58.encode(ed25519.sign(new TextEncoder().encode(message), secret));
+ return { message, signature };
+}
+
+/** Route each query by the statement it is, so the handler's read order stays
+ * an implementation detail. `burn` is the conditional update that consumes a
+ * nonce, and returning [] from it is a lost race with a concurrent caller. */
+function stubDb({ gate = [gateRow], nonce = [nonceRow()], burn = [{ nonce: NONCE }], insert = [] } = {}) {
+ sqlMock.mockImplementation((strings) => {
+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/insert into embed_gate_nonces/i.test(text)) return Promise.resolve(insert);
+ if (/update embed_gate_nonces/i.test(text)) return Promise.resolve(burn);
+ if (/from embed_gate_nonces/i.test(text)) return Promise.resolve(nonce);
+ if (/from embed_gates/i.test(text)) return Promise.resolve(gate);
+ return Promise.resolve([]);
+ });
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk) this.body += chunk;
+ },
+ };
+}
+
+async function post(body) {
+ const req = {
+ method: 'POST',
+ url: '/api/embed/gate-verify',
+ headers: { 'content-type': 'application/json' },
+ rawBody: Buffer.from(JSON.stringify(body)),
+ body,
+ on(event, cb) {
+ if (event === 'data') {
+ queueMicrotask(() => {
+ cb(Buffer.from(JSON.stringify(body)));
+ this._endCb?.();
+ });
+ } else if (event === 'end') {
+ this._endCb = cb;
+ }
+ },
+ destroy() {},
+ };
+ const res = mkRes();
+ await handler(req, res);
+ return { res, json: res.body ? JSON.parse(res.body) : null };
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ balanceMock.mockReset();
+});
+
+describe('phase 1: nonce issue', () => {
+ it('returns a signable message carrying the gate terms', async () => {
+ stubDb();
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET });
+
+ expect(res.statusCode).toBe(200);
+ expect(json.message).toContain(`Asset: ${ASSET}`);
+ expect(json.message).toMatch(/^Nonce: .+$/m);
+ expect(json.gate).toEqual({ mint: DEFAULT_GATE_MINT, minAmount: 5000 });
+ expect(json.chain).toBe('solana');
+ // A nonce is one-time state, so nothing about this may be cached.
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+
+ it('404s an asset that is not gated at all', async () => {
+ stubDb({ gate: [] });
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET });
+ expect(res.statusCode).toBe(404);
+ expect(json.error).toBe('not_found');
+ });
+});
+
+describe('phase 2: proof of ownership', () => {
+ it('mints an access token when a real signature clears the threshold', async () => {
+ stubDb();
+ balanceMock.mockResolvedValue(9000);
+ const { message, signature } = signedMessage();
+
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET, signature, message });
+
+ expect(res.statusCode).toBe(200);
+ expect(json.allowed).toBe(true);
+ expect(json.amount).toBe(9000);
+ // The token must be one resolve.js will actually accept for this gate.
+ const claim = await verifyEmbedGateToken(json.accessToken, { assetId: ASSET, gateId: GATE_ID });
+ expect(claim).toBeTruthy();
+ expect(claim.wallet).toBe(WALLET);
+ expect(claim.amount).toBe(9000);
+ });
+
+ it('refuses a wallet that does not hold enough, and mints nothing', async () => {
+ stubDb();
+ balanceMock.mockResolvedValue(10);
+ const { message, signature } = signedMessage();
+
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET, signature, message });
+
+ expect(res.statusCode).toBe(200);
+ expect(json.allowed).toBe(false);
+ expect(json.accessToken).toBeUndefined();
+ expect(json.reason).toMatch(/insufficient balance/i);
+ });
+
+ it('reads the balance on chain rather than believing the caller', async () => {
+ stubDb();
+ balanceMock.mockResolvedValue(0);
+ const { message, signature } = signedMessage();
+
+ const { json } = await post({
+ assetId: ASSET,
+ walletAddress: WALLET,
+ signature,
+ message,
+ amount: 999999,
+ balance: 999999,
+ });
+
+ expect(json.allowed).toBe(false);
+ expect(balanceMock).toHaveBeenCalledWith(WALLET, DEFAULT_GATE_MINT);
+ });
+
+ it('rejects a signature made by a different key', async () => {
+ stubDb();
+ balanceMock.mockResolvedValue(9000);
+ // Signed by the other keypair, presented as this wallet.
+ const { message } = signedMessage();
+ const forged = bs58.encode(ed25519.sign(new TextEncoder().encode(message), OTHER_SECRET));
+
+ const { res, json } = await post({
+ assetId: ASSET,
+ walletAddress: WALLET,
+ signature: forged,
+ message,
+ });
+
+ expect(res.statusCode).toBe(401);
+ expect(json.error).toBe('invalid_signature');
+ expect(balanceMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a nonce issued to a different wallet', async () => {
+ stubDb({ nonce: [nonceRow({ address: OTHER_WALLET })] });
+ balanceMock.mockResolvedValue(9000);
+ const { message, signature } = signedMessage();
+
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET, signature, message });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('invalid_nonce');
+ expect(balanceMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a nonce that was already consumed', async () => {
+ stubDb({ nonce: [nonceRow({ consumed_at: new Date().toISOString() })] });
+ const { message, signature } = signedMessage();
+
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET, signature, message });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('nonce_reused');
+ });
+
+ it('rejects an expired nonce', async () => {
+ stubDb({ nonce: [nonceRow({ expires_at: new Date(Date.now() - 1000).toISOString() })] });
+ const { message, signature } = signedMessage();
+
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET, signature, message });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('nonce_expired');
+ });
+
+ it('loses the race rather than issuing two tokens for one nonce', async () => {
+ // The conditional burn matched no row: a concurrent caller consumed it
+ // between the read and the update.
+ stubDb({ burn: [] });
+ balanceMock.mockResolvedValue(9000);
+ const { message, signature } = signedMessage();
+
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET, signature, message });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('nonce_reused');
+ expect(balanceMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a message with no nonce in it', async () => {
+ stubDb();
+ const message = `three.ws token-gated embed verification.\n\nAsset: ${ASSET}\nWallet: ${WALLET}`;
+ const signature = bs58.encode(ed25519.sign(new TextEncoder().encode(message), SECRET));
+
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET, signature, message });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('invalid_message');
+ });
+
+ it('answers a chain read that failed without granting access', async () => {
+ stubDb();
+ balanceMock.mockRejectedValue(new Error('rpc unavailable'));
+ const { message, signature } = signedMessage();
+
+ const { res, json } = await post({ assetId: ASSET, walletAddress: WALLET, signature, message });
+
+ expect(res.statusCode).toBe(200);
+ expect(json.allowed).toBe(false);
+ expect(json.accessToken).toBeUndefined();
+ expect(json.reason).toMatch(/rpc unavailable/i);
+ });
+});
diff --git a/tests/api/embed-resolve.test.js b/tests/api/embed-resolve.test.js
new file mode 100644
index 000000000..6e61cb052
--- /dev/null
+++ b/tests/api/embed-resolve.test.js
@@ -0,0 +1,240 @@
+// Tests for GET /api/embed/resolve, the endpoint every 3D embed on the public
+// internet calls to find out what to render.
+//
+// What it pins is the one decision that has to be right every single time: a
+// token-gated asset must never hand back its glbUrl to a caller who has not
+// proved the holding. The lock is enforced here, on the read path, rather than
+// in the widget, so a caller with curl gets the same answer as the browser.
+//
+// Everything below the database seam is the real implementation: the real
+// asset resolver, the real gate reader, and the real HMAC token module, so a
+// token that unlocks in this test is a token the production verifier minted
+// the same way. Only `sql` is stubbed, standing in for rows the endpoint would
+// have read from Postgres.
+
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+
+beforeAll(() => {
+ process.env.JWT_SECRET = 'test-jwt-secret-embed-resolve-0123456789';
+ // The avatar branch builds its glbUrl through api/_lib/r2.js, which requires
+ // the asset host to be configured rather than guessing one.
+ process.env.S3_PUBLIC_DOMAIN = 'assets.test.three.ws';
+});
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: true, limit: 240, remaining: 239, reset: 0 })) },
+ clientIp: () => '203.0.113.7',
+}));
+
+const handler = (await import('../../api/embed/resolve.js')).default;
+const { signEmbedGateToken } = await import('../../api/_lib/embed-gate-token.js');
+const { DEFAULT_GATE_MINT } = await import('../../api/_lib/embed-gate.js');
+
+const AVATAR_ID = '8e3f1c22-0000-4000-8000-0000000000c1';
+const ASSET = `avatar:${AVATAR_ID}`;
+const GATE_ID = 'gate_0000000000000001';
+
+const avatarRow = {
+ id: AVATAR_ID,
+ name: 'Nova',
+ description: 'A public avatar',
+ storage_key: 'avatars/nova.glb',
+ thumbnail_key: 'avatars/nova.jpg',
+};
+
+const gateRow = {
+ id: GATE_ID,
+ asset_id: ASSET,
+ owner_user_id: 'user_1',
+ chain: 'solana',
+ mint: DEFAULT_GATE_MINT,
+ min_amount: 5000,
+ created_at: new Date().toISOString(),
+};
+
+/** Answer each query by the table it names, so the order of reads inside the
+ * handler is free to change without rewriting the fixtures. */
+function stubRows({ avatar = [avatarRow], gate = [] } = {}) {
+ sqlMock.mockImplementation((strings) => {
+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/from\s+avatars/i.test(text)) return Promise.resolve(avatar);
+ if (/from\s+embed_gates/i.test(text)) return Promise.resolve(gate);
+ return Promise.resolve([]);
+ });
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ ended: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ this.ended = true;
+ if (chunk) this.body += chunk;
+ },
+ };
+}
+
+async function get(query) {
+ const req = { method: 'GET', url: `/api/embed/resolve?${query}`, headers: {} };
+ const res = mkRes();
+ await handler(req, res);
+ return { res, json: res.body ? JSON.parse(res.body) : null };
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+});
+
+describe('an ungated asset', () => {
+ it('returns the render payload and lets the edge cache it', async () => {
+ stubRows();
+ const { res, json } = await get(`id=${encodeURIComponent(ASSET)}`);
+
+ expect(res.statusCode).toBe(200);
+ expect(json.name).toBe('Nova');
+ expect(json.glbUrl).toBeTruthy();
+ expect(json.gated).toBeUndefined();
+ // Cross-origin by design: the embed runs on someone else's page.
+ expect(res.getHeader('access-control-allow-origin')).toBe('*');
+ expect(res.getHeader('cache-control')).toMatch(/public/);
+ });
+
+ it('404s an id that resolves to nothing', async () => {
+ stubRows({ avatar: [] });
+ const { res, json } = await get(`id=${encodeURIComponent(ASSET)}`);
+ expect(res.statusCode).toBe(404);
+ expect(json.error).toBe('not_found');
+ });
+});
+
+describe('a gated asset without a valid token', () => {
+ it('withholds the glbUrl and returns the gate terms instead', async () => {
+ stubRows({ gate: [gateRow] });
+ const { res, json } = await get(`id=${encodeURIComponent(ASSET)}`);
+
+ expect(res.statusCode).toBe(200);
+ expect(json.locked).toBe(true);
+ expect(json.glbUrl).toBeUndefined();
+ // The whole payload, not just the top level: a nested copy would leak it.
+ expect(JSON.stringify(json)).not.toContain('avatars/nova.glb');
+ expect(json.gate).toMatchObject({ gateId: GATE_ID, mint: DEFAULT_GATE_MINT, minAmount: 5000 });
+ // The teaser stays, so a visitor can see what the holding would unlock.
+ expect(json.name).toBe('Nova');
+ expect(json.poster).toBeTruthy();
+ });
+
+ it('never lets a locked or unlocked answer be cached and reused', async () => {
+ stubRows({ gate: [gateRow] });
+ const locked = await get(`id=${encodeURIComponent(ASSET)}`);
+ expect(locked.res.getHeader('cache-control')).toBe('private, no-store');
+
+ const token = await signEmbedGateToken({
+ gateId: GATE_ID,
+ assetId: ASSET,
+ wallet: 'ThreeWsSyntheticTestWallet1111111111111111',
+ mint: DEFAULT_GATE_MINT,
+ minAmount: 5000,
+ amount: 9000,
+ });
+ stubRows({ gate: [gateRow] });
+ const unlocked = await get(`id=${encodeURIComponent(ASSET)}&gate_token=${token}`);
+ expect(unlocked.res.getHeader('cache-control')).toBe('private, no-store');
+ });
+
+ it('stays locked for a garbage token rather than erroring', async () => {
+ stubRows({ gate: [gateRow] });
+ const { res, json } = await get(`id=${encodeURIComponent(ASSET)}&gate_token=eg1.nope.nope`);
+ expect(res.statusCode).toBe(200);
+ expect(json.locked).toBe(true);
+ expect(json.glbUrl).toBeUndefined();
+ });
+
+ it('rejects a token minted for a different gate on the same asset', async () => {
+ const token = await signEmbedGateToken({
+ gateId: 'gate_some_superseded_id',
+ assetId: ASSET,
+ wallet: 'ThreeWsSyntheticTestWallet1111111111111111',
+ mint: DEFAULT_GATE_MINT,
+ minAmount: 5000,
+ amount: 9000,
+ });
+ stubRows({ gate: [gateRow] });
+ const { json } = await get(`id=${encodeURIComponent(ASSET)}&gate_token=${token}`);
+ expect(json.locked).toBe(true);
+ expect(json.glbUrl).toBeUndefined();
+ });
+
+ it('rejects a token minted for a different asset', async () => {
+ const token = await signEmbedGateToken({
+ gateId: GATE_ID,
+ assetId: 'avatar:11111111-0000-4000-8000-000000000001',
+ wallet: 'ThreeWsSyntheticTestWallet1111111111111111',
+ mint: DEFAULT_GATE_MINT,
+ minAmount: 5000,
+ amount: 9000,
+ });
+ stubRows({ gate: [gateRow] });
+ const { json } = await get(`id=${encodeURIComponent(ASSET)}&gate_token=${token}`);
+ expect(json.locked).toBe(true);
+ });
+});
+
+describe('a gated asset with a valid token', () => {
+ it('unlocks the real glbUrl and says so', async () => {
+ const token = await signEmbedGateToken({
+ gateId: GATE_ID,
+ assetId: ASSET,
+ wallet: 'ThreeWsSyntheticTestWallet1111111111111111',
+ mint: DEFAULT_GATE_MINT,
+ minAmount: 5000,
+ amount: 9000,
+ });
+ stubRows({ gate: [gateRow] });
+ const { res, json } = await get(`id=${encodeURIComponent(ASSET)}&gate_token=${token}`);
+
+ expect(res.statusCode).toBe(200);
+ expect(json.gated).toBe(true);
+ expect(json.unlocked).toBe(true);
+ expect(json.locked).toBeUndefined();
+ expect(json.glbUrl).toContain('avatars/nova.glb');
+ });
+});
+
+describe('input validation', () => {
+ it('400s a missing id before touching the database', async () => {
+ stubRows();
+ const { res, json } = await get('');
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('validation_error');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('400s an id that is not one of the documented specs', async () => {
+ stubRows();
+ const { res } = await get('id=javascript:alert(1)');
+ expect(res.statusCode).toBe(400);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('405s a method other than GET', async () => {
+ const req = { method: 'POST', url: '/api/embed/resolve?id=x', headers: {} };
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/tests/api/irl-analytics-endpoint.test.js b/tests/api/irl-analytics-endpoint.test.js
new file mode 100644
index 000000000..f7d88eb23
--- /dev/null
+++ b/tests/api/irl-analytics-endpoint.test.js
@@ -0,0 +1,114 @@
+// GET /api/irl/analytics: the ops-gated /irl usage rollup.
+//
+// tests/irl-analytics.test.js covers the rollup queries themselves; this file
+// covers the endpoint around them: the CORS decision, the ops authorization gate,
+// the method gate, and the degrade contract when the summary can't be read.
+//
+// The CORS case is the regression fence. cors() takes `origins` as null (the
+// first-party allow-list), '*', or an array of patterns. This handler passed the
+// string 'same', which reached `allowed.some(...)` and threw a TypeError, so every
+// request that carried an Origin header - the browser preflight included - came
+// back as a 500 instead of a CORS decision.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+let summaryImpl = async () => ({
+ windows: { '24h': { pins_placed: 3 } },
+ placement_modes_30d: { 'gyro-gps': 3 },
+ daily_series_30d: [{ day: '2026-08-13', pins_placed: 3, nearby_fetches: 1 }],
+ generated_at: '2026-08-13T00:00:00.000Z',
+});
+vi.mock('../../api/_lib/irl-analytics.js', () => ({
+ getIrlAnalyticsSummary: () => summaryImpl(),
+}));
+
+let authOk = true;
+vi.mock('../../api/_lib/ops-auth.js', () => ({
+ authorizeOps: vi.fn(async () => (authOk ? { ok: true, actor: 'ops-secret' } : { ok: false, actor: '' })),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { default: handler } = await import('../../api/irl/analytics.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+
+async function call(method = 'GET', headers = {}) {
+ const res = makeRes();
+ await handler({ url: '/api/irl/analytics', method, headers: { host: 'x', ...headers }, query: {} }, res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch { /* non-JSON body */ }
+ return { res, body: parsed };
+}
+
+beforeEach(() => {
+ authOk = true;
+ summaryImpl = async () => ({
+ windows: { '24h': { pins_placed: 3 } },
+ placement_modes_30d: { 'gyro-gps': 3 },
+ daily_series_30d: [{ day: '2026-08-13', pins_placed: 3, nearby_fetches: 1 }],
+ generated_at: '2026-08-13T00:00:00.000Z',
+ });
+});
+
+describe('CORS', () => {
+ it('answers a preflight that carries an Origin with 204, never a 500', async () => {
+ const { res } = await call('OPTIONS', { origin: 'https://evil.example.com' });
+ expect(res.statusCode).toBe(204);
+ });
+
+ it('does not hand a cross-origin caller an allow-origin header', async () => {
+ const { res } = await call('GET', { origin: 'https://evil.example.com' });
+ expect(res.getHeader('access-control-allow-origin')).toBeUndefined();
+ expect(res.statusCode).toBe(200); // authorized in this suite; the CORS header is the assertion
+ });
+});
+
+describe('gates', () => {
+ it('401s an unauthorized caller', async () => {
+ authOk = false;
+ const { res, body } = await call('GET');
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('405s a non-GET method', async () => {
+ const { res, body } = await call('POST');
+ expect(res.statusCode).toBe(405);
+ expect(body.error).toBe('method_not_allowed');
+ });
+
+ it('serves the real rollup to an authorized caller', async () => {
+ const { res, body } = await call('GET');
+ expect(res.statusCode).toBe(200);
+ expect(body.windows['24h'].pins_placed).toBe(3);
+ expect(body.daily_series_30d).toHaveLength(1);
+ });
+});
+
+describe('degrade contract', () => {
+ it('serves an empty rollup with a note, and LOGS the reason', async () => {
+ summaryImpl = async () => { throw new Error('relation "irl_events" does not exist'); };
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { res, body } = await call('GET');
+ expect(res.statusCode).toBe(200);
+ expect(body.windows).toEqual({});
+ expect(body.note).toMatch(/analytics_unavailable/);
+ // An unlogged degrade is indistinguishable from "no usage yet". That is how a
+ // broken query survived unnoticed behind a wall of zeros.
+ expect(logged).toHaveBeenCalled();
+ logged.mockRestore();
+ });
+});
diff --git a/tests/api/irl-drops-handler.test.js b/tests/api/irl-drops-handler.test.js
new file mode 100644
index 000000000..ab736f3df
--- /dev/null
+++ b/tests/api/irl-drops-handler.test.js
@@ -0,0 +1,178 @@
+// GET/POST /api/irl/drops: the request boundary of the IRL Money Drops endpoint.
+//
+// tests/irl-drops.test.js covers the custody primitive itself (public projection,
+// atomics math, quiz hashing, presence proof). This file covers the HTTP edge the
+// handler owns: path parsing, id validation, method handling, and the auth /
+// presence refusals that must happen BEFORE anything touches an escrow. Nothing
+// here signs, funds, or releases: every custody call is mocked, so a probe of the
+// claim path exercises its validation, never a settlement.
+//
+// The id guard is the regression fence. `irl_drops.id` is a UUID column, so
+// `/api/irl/drops/not-a-uuid` used to reach getDropRow(), where Postgres refused
+// the cast (`invalid input syntax for type uuid`) and a malformed URL came back as
+// a 500 instead of a 4xx.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Custody + chain modules are mocked wholesale; this suite never moves value.
+const getDropRowMock = vi.fn(async () => null);
+const nearbyDropsMock = vi.fn(async () => []);
+const myDropsMock = vi.fn(async () => []);
+const myClaimsMock = vi.fn(async () => []);
+const createDropMock = vi.fn(async () => { throw Object.assign(new Error('not reached'), { status: 400 }); });
+
+vi.mock('../../api/_lib/irl-drops.js', () => ({
+ getDropRow: (...a) => getDropRowMock(...a),
+ nearbyDrops: (...a) => nearbyDropsMock(...a),
+ myDrops: (...a) => myDropsMock(...a),
+ myClaims: (...a) => myClaimsMock(...a),
+ createDrop: (...a) => createDropMock(...a),
+ confirmFunding: vi.fn(),
+ reserveClaim: vi.fn(),
+ failClaim: vi.fn(),
+ confirmClaim: vi.fn(),
+ releaseFromEscrow: vi.fn(),
+ markRefunding: vi.fn(),
+ sweepRefund: vi.fn(),
+ recordRefundTx: vi.fn(),
+ hasChatSignal: vi.fn(async () => false),
+ verifyQuiz: vi.fn(async () => false),
+ haversineM: () => 0,
+ atomicsToAmount: (v) => String(v),
+ toPublicDrop: (row) => ({ ...row }),
+ BASE58_RE: /^[1-9A-HJ-NP-Za-km-z]{32,44}$/,
+}));
+
+vi.mock('../../api/_lib/agent-pumpfun.js', () => ({
+ solanaConnection: vi.fn(),
+ loadAgentForSigning: vi.fn(async () => ({ error: { status: 403, code: 'forbidden', msg: 'no' } })),
+}));
+vi.mock('../../api/_lib/execution-engine.js', () => ({ submitProtected: vi.fn() }));
+vi.mock('../../api/_lib/agent-trade-guards.js', () => ({
+ enforceSpendLimit: vi.fn(),
+ lamportsToUsd: vi.fn(async () => 0),
+ SpendLimitError: class SpendLimitError extends Error {},
+}));
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+let sessionUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => sessionUser) }));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ publicIp: vi.fn(async () => ({ success: true })),
+ irlNearbyIp: vi.fn(async () => ({ success: true })),
+ irlPinIp: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: () => '127.0.0.1',
+ limitFailClosedRead: vi.fn(async () => ({ success: true })),
+}));
+
+// Presence enforcement off by default (the dev/preview contract); the claim path
+// verifies the token itself, so it is asserted through verifyFixToken.
+let fixIsEnforced = false;
+let fixVerdict = { ok: false, reason: 'missing' };
+vi.mock('../../api/_lib/irl-presence.js', () => ({
+ fixEnforced: () => fixIsEnforced,
+ verifyFixToken: vi.fn(async () => fixVerdict),
+}));
+
+const { default: handler } = await import('../../api/irl/drops.js');
+
+const DROP_ID = '11111111-1111-4111-8111-111111111111';
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+
+async function call(method, url, { body, headers = {} } = {}) {
+ const res = makeRes();
+ const req = { url, method, headers: { host: 'x', ...headers }, query: {}, body };
+ if (body !== undefined) {
+ // readJson() reads the raw body and requires the JSON content type, exactly as
+ // the server hands it over in production.
+ req.rawBody = Buffer.from(JSON.stringify(body));
+ req.headers['content-type'] = 'application/json';
+ }
+ await handler(req, res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch { /* non-JSON body */ }
+ return { res, body: parsed };
+}
+
+beforeEach(() => {
+ sessionUser = null;
+ fixIsEnforced = false;
+ fixVerdict = { ok: false, reason: 'missing' };
+ getDropRowMock.mockClear().mockResolvedValue(null);
+ nearbyDropsMock.mockClear().mockResolvedValue([]);
+});
+
+describe('drop id validation', () => {
+ it('400s a non-UUID drop id on a read, without querying for the row', async () => {
+ const { res, body } = await call('GET', '/api/irl/drops/not-a-uuid');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('bad_request');
+ expect(getDropRowMock).not.toHaveBeenCalled();
+ });
+
+ it('400s a non-UUID drop id on an action path too', async () => {
+ const { res } = await call('POST', '/api/irl/drops/xyz/claim', { body: { lat: 1, lng: 1 } });
+ expect(res.statusCode).toBe(400);
+ expect(getDropRowMock).not.toHaveBeenCalled();
+ });
+
+ it('404s a well-formed id that names no drop', async () => {
+ const { res, body } = await call('GET', `/api/irl/drops/${DROP_ID}`);
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ expect(getDropRowMock).toHaveBeenCalledWith(DROP_ID);
+ });
+});
+
+describe('nearby read', () => {
+ it('400s without coordinates', async () => {
+ const { res, body } = await call('GET', '/api/irl/drops');
+ expect(res.statusCode).toBe(400);
+ expect(body.error_description).toMatch(/lat and lng/i);
+ });
+
+ it('401s when presence is enforced and no valid fix token is presented', async () => {
+ fixIsEnforced = true;
+ const { res, body } = await call('GET', '/api/irl/drops?lat=37.7749&lng=-122.4194');
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('fix_required');
+ expect(nearbyDropsMock).not.toHaveBeenCalled();
+ });
+
+ it('caps the radius at the server ceiling rather than trusting the caller', async () => {
+ await call('GET', '/api/irl/drops?lat=37.7749&lng=-122.4194&radius=100000');
+ expect(nearbyDropsMock).toHaveBeenCalledWith(expect.objectContaining({ radiusM: 80 }));
+ });
+});
+
+describe('write paths refuse before any custody work', () => {
+ it('401s a create from a caller with neither a session nor a device token', async () => {
+ const { res, body } = await call('POST', '/api/irl/drops', { body: { amount: 1, lat: 1, lng: 1 } });
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('auth_required');
+ expect(createDropMock).not.toHaveBeenCalled();
+ });
+
+ it('405s an unsupported method', async () => {
+ const { res } = await call('PUT', '/api/irl/drops');
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/tests/api/irl-interactions.test.js b/tests/api/irl-interactions.test.js
index b702fbe1d..5b8d46e82 100644
--- a/tests/api/irl-interactions.test.js
+++ b/tests/api/irl-interactions.test.js
@@ -78,6 +78,12 @@ vi.mock('../../api/_lib/settlement-verify.js', () => ({
const { default: handler } = await import('../../api/irl/interactions.js');
+// `irl_pins.id` / `irl_interactions.pin_id` are UUID columns, so every fixture id
+// here is a real UUID: the handler rejects anything else at the boundary rather
+// than letting Postgres fail the cast and turn a bad request into a 500.
+const PIN_ID = '11111111-1111-4111-8111-111111111111';
+const MISSING_PIN_ID = '22222222-2222-4222-8222-222222222222';
+
// A real Solana settlement signature (base58, 43–88 chars) and the $THREE mint —
// the only signature/mint a `pay` row is allowed to carry.
const SOL_SIG = '5'.repeat(64);
@@ -120,7 +126,7 @@ beforeEach(() => {
replyOrigRow = null;
sessionUser = null;
pinRow = {
- id: 'pin-1',
+ id: PIN_ID,
agent_id: 'agent-1',
lat: 40.7128,
lng: -74.006,
@@ -135,15 +141,33 @@ describe('POST — validation + ownership resolution', () => {
expect(res.statusCode).toBe(400);
});
+ // A non-UUID id reached the pin lookup unchecked and Postgres killed the query
+ // with `invalid input syntax for type uuid`, so a malformed request came back as
+ // a 500. It is a bad request, and it never touches the database.
+ it('400s a malformed pinId instead of letting the UUID cast 500 the request', async () => {
+ const { res, body } = await post({ pinId: 'not-a-uuid', type: 'view' });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/invalid pinId/i);
+ const queried = sqlMock.mock.calls.some(([s]) =>
+ /FROM irl_pins/i.test(Array.isArray(s) ? s.join(' ') : String(s)));
+ expect(queried).toBe(false);
+ });
+
+ it('400s a malformed pinId on the public count read too', async () => {
+ const { res, body } = await call('GET', { query: { pinId: "1' OR '1'='1" } });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/invalid pinId/i);
+ });
+
it('404s when the pin is missing / expired / hidden', async () => {
pinRow = null;
- const { res, body } = await post({ pinId: 'gone', type: 'tap' });
+ const { res, body } = await post({ pinId: MISSING_PIN_ID, type: 'tap' });
expect(res.statusCode).toBe(404);
expect(body.error).toMatch(/not found/i);
});
it('logs a tap and never trusts a caller-supplied owner — uses the pin', async () => {
- const { res } = await post({ pinId: 'pin-1', type: 'tap', deviceToken: 'dev-A' });
+ const { res } = await post({ pinId: PIN_ID, type: 'tap', deviceToken: 'dev-A' });
expect(res.statusCode).toBe(201);
// agent_id taken from the pin (values[1]), not the body.
expect(lastInsert.values[1]).toBe('agent-1');
@@ -153,7 +177,7 @@ describe('POST — validation + ownership resolution', () => {
describe('POST — view de-dupe', () => {
it('collapses a repeat view from the same device within the window', async () => {
viewDupeRow = { id: 'ix-existing' };
- const { res, body } = await post({ pinId: 'pin-1', type: 'view', deviceToken: 'dev-A' });
+ const { res, body } = await post({ pinId: PIN_ID, type: 'view', deviceToken: 'dev-A' });
expect(res.statusCode).toBe(200);
expect(body.deduped).toBe(true);
expect(lastInsert).toBeNull(); // no new row written
@@ -161,7 +185,7 @@ describe('POST — view de-dupe', () => {
it("doesn't log the owner viewing their own pin", async () => {
sessionUser = { id: 'owner-uuid' };
- const { res, body } = await post({ pinId: 'pin-1', type: 'view' });
+ const { res, body } = await post({ pinId: PIN_ID, type: 'view' });
expect(res.statusCode).toBe(200);
expect(body.self).toBe(true);
expect(lastInsert).toBeNull();
@@ -170,7 +194,7 @@ describe('POST — view de-dupe', () => {
describe('POST — pay is only recorded with a verified settlement', () => {
it('400s a pay with no signature', async () => {
- const { res, body } = await post({ pinId: 'pin-1', type: 'pay', amount: 50000, currencyMint: THREE_MINT });
+ const { res, body } = await post({ pinId: PIN_ID, type: 'pay', amount: 50000, currencyMint: THREE_MINT });
expect(res.statusCode).toBe(400);
expect(body.error).toMatch(/signature/i);
expect(lastInsert).toBeNull();
@@ -178,7 +202,7 @@ describe('POST — pay is only recorded with a verified settlement', () => {
it('400s a pay whose mint is neither $THREE nor USDC', async () => {
const { res, body } = await post({
- pinId: 'pin-1', type: 'pay', amount: 50000,
+ pinId: PIN_ID, type: 'pay', amount: 50000,
currencyMint: 'SomeOtherMint1111111111111111111111111111111', signature: SOL_SIG,
});
expect(res.statusCode).toBe(400);
@@ -188,7 +212,7 @@ describe('POST — pay is only recorded with a verified settlement', () => {
it('records a verified $THREE pay and notifies the owner + ops', async () => {
const { res } = await post({
- pinId: 'pin-1', type: 'pay', amount: 50000, currencyMint: THREE_MINT, signature: SOL_SIG,
+ pinId: PIN_ID, type: 'pay', amount: 50000, currencyMint: THREE_MINT, signature: SOL_SIG,
});
expect(res.statusCode).toBe(201);
expect(insertedPayload().signature).toBe(SOL_SIG);
@@ -199,7 +223,7 @@ describe('POST — pay is only recorded with a verified settlement', () => {
it('holds a pay at 202 while the settlement is not yet visible on-chain', async () => {
settlementProof = { status: 'pending' };
const { res, body } = await post({
- pinId: 'pin-1', type: 'pay', amount: 50000, currencyMint: THREE_MINT, signature: SOL_SIG,
+ pinId: PIN_ID, type: 'pay', amount: 50000, currencyMint: THREE_MINT, signature: SOL_SIG,
});
expect(res.statusCode).toBe(202);
expect(body.pending).toBe(true);
@@ -213,7 +237,7 @@ describe('POST — pay is only recorded with a verified settlement', () => {
it('de-dupes a pay by signature (one settlement → one row)', async () => {
paySigDupeRow = { id: 'ix-paid' };
const { res, body } = await post({
- pinId: 'pin-1', type: 'pay', amount: 50000, currencyMint: THREE_MINT, signature: SOL_SIG,
+ pinId: PIN_ID, type: 'pay', amount: 50000, currencyMint: THREE_MINT, signature: SOL_SIG,
});
expect(res.statusCode).toBe(200);
expect(body.deduped).toBe(true);
@@ -223,7 +247,7 @@ describe('POST — pay is only recorded with a verified settlement', () => {
describe('POST — messages + owner replies', () => {
it('a visitor message notifies the owner', async () => {
- const { res } = await post({ pinId: 'pin-1', type: 'message', message: 'is this the meetup?', deviceToken: 'dev-A' });
+ const { res } = await post({ pinId: PIN_ID, type: 'message', message: 'is this the meetup?', deviceToken: 'dev-A' });
expect(res.statusCode).toBe(201);
expect(notifyMock).toHaveBeenCalledWith('owner-uuid', 'irl_interaction', expect.objectContaining({ kind: 'message' }));
// not an owner reply → no from:'owner' stamp, stays unread (seen_at null).
@@ -233,7 +257,7 @@ describe('POST — messages + owner replies', () => {
it("a visitor can't forge an owner reply via payload.from", async () => {
const { res } = await post({
- pinId: 'pin-1', type: 'message', message: 'totally the owner', deviceToken: 'dev-A',
+ pinId: PIN_ID, type: 'message', message: 'totally the owner', deviceToken: 'dev-A',
payload: { from: 'owner' },
});
expect(res.statusCode).toBe(201);
@@ -245,7 +269,7 @@ describe('POST — messages + owner replies', () => {
sessionUser = { id: 'owner-uuid' };
replyOrigRow = { viewer_user_id: 'visitor-uuid' };
const { res, body } = await post({
- pinId: 'pin-1', type: 'message', message: 'yes! see you there',
+ pinId: PIN_ID, type: 'message', message: 'yes! see you there',
replyTo: '11111111-1111-1111-1111-111111111111',
});
expect(res.statusCode).toBe(201);
@@ -253,7 +277,7 @@ describe('POST — messages + owner replies', () => {
expect(insertedSeenAt()).not.toBeNull(); // authored → already seen
// The owner is never self-notified; the signed-in visitor is.
expect(notifyMock).not.toHaveBeenCalledWith('owner-uuid', expect.anything(), expect.anything());
- expect(notifyMock).toHaveBeenCalledWith('visitor-uuid', 'irl_reply', expect.objectContaining({ pin_id: 'pin-1' }));
+ expect(notifyMock).toHaveBeenCalledWith('visitor-uuid', 'irl_reply', expect.objectContaining({ pin_id: PIN_ID }));
expect(body.notified).toBe(true);
});
@@ -261,7 +285,7 @@ describe('POST — messages + owner replies', () => {
sessionUser = { id: 'owner-uuid' };
replyOrigRow = { viewer_user_id: null }; // visitor was anonymous
const { res, body } = await post({
- pinId: 'pin-1', type: 'message', message: 'thanks for stopping by',
+ pinId: PIN_ID, type: 'message', message: 'thanks for stopping by',
replyTo: '11111111-1111-1111-1111-111111111111',
});
expect(res.statusCode).toBe(201);
@@ -286,14 +310,14 @@ describe('POST — payload serialization boundary (no uncaught 500)', () => {
throw new TypeError('Converting circular structure to JSON');
},
};
- const { res, body } = await post({ pinId: 'pin-1', type: 'tap', payload: hostile, deviceToken: 'dev-A' });
+ const { res, body } = await post({ pinId: PIN_ID, type: 'tap', payload: hostile, deviceToken: 'dev-A' });
expect(res.statusCode).toBe(400);
expect(body.error).toMatch(/serializable/i);
expect(lastInsert).toBeNull(); // no row written when serialization fails
});
it('records a normal payload object as serialized JSONB', async () => {
- const { res } = await post({ pinId: 'pin-1', type: 'tap', payload: { note: 'hi' }, deviceToken: 'dev-A' });
+ const { res } = await post({ pinId: PIN_ID, type: 'tap', payload: { note: 'hi' }, deviceToken: 'dev-A' });
expect(res.statusCode).toBe(201);
// values[10] is the serialized payload text the INSERT binds to the ::jsonb cast.
expect(typeof lastInsert.values[10]).toBe('string');
@@ -316,14 +340,14 @@ describe('POST — view_count increment is logged, not swallowed', () => {
}
return Promise.resolve([]);
});
- const { res } = await post({ pinId: 'pin-1', type: 'view', deviceToken: 'dev-fresh' });
+ const { res } = await post({ pinId: PIN_ID, type: 'view', deviceToken: 'dev-fresh' });
expect(res.statusCode).toBe(201);
// The rejection is async fire-and-forget — let the microtask queue drain.
await Promise.resolve();
await Promise.resolve();
expect(warn).toHaveBeenCalledWith(
'[irl/interactions] view_count increment failed',
- expect.objectContaining({ pinId: 'pin-1', reason: 'db down' }),
+ expect.objectContaining({ pinId: PIN_ID, reason: 'db down' }),
);
warn.mockRestore();
sqlMock.mockClear();
diff --git a/tests/api/irl-pins-hardening.test.js b/tests/api/irl-pins-hardening.test.js
index 467fe95a5..6fce18b89 100644
--- a/tests/api/irl-pins-hardening.test.js
+++ b/tests/api/irl-pins-hardening.test.js
@@ -154,10 +154,18 @@ beforeEach(() => {
// ── Pure helpers ─────────────────────────────────────────────────────────────
describe('isValidPinId', () => {
- it('accepts a canonical UUID + conservative opaque ids', () => {
+ it('accepts a canonical UUID', () => {
expect(isValidPinId(UUID)).toBe(true);
- expect(isValidPinId('pin-1')).toBe(true); // url/path-safe opaque id
- expect(isValidPinId('del_1')).toBe(true);
+ expect(isValidPinId(UUID.toUpperCase())).toBe(true);
+ });
+ // `irl_pins.id` is a UUID COLUMN. A "URL-safe opaque id" used to be accepted
+ // here, which handed non-UUID text straight to Postgres: the query died with
+ // `invalid input syntax for type uuid` and the caller saw a 500 where this
+ // guard exists to produce a 400. Anything that is not a UUID is rejected.
+ it('rejects url-safe-but-not-UUID ids that the UUID column cannot cast', () => {
+ expect(isValidPinId('pin-1')).toBe(false);
+ expect(isValidPinId('del_1')).toBe(false);
+ expect(isValidPinId('not-a-uuid')).toBe(false);
});
it('rejects empty / non-string / oversized / dangerous-shaped ids', () => {
expect(isValidPinId('')).toBe(false);
diff --git a/tests/api/irl-pins-moderation.test.js b/tests/api/irl-pins-moderation.test.js
index 1b7e99138..0cdd6d6be 100644
--- a/tests/api/irl-pins-moderation.test.js
+++ b/tests/api/irl-pins-moderation.test.js
@@ -105,6 +105,17 @@ describe('POST /api/irl/pins — content gate', () => {
expect(body.message).toMatch(/\$THREE/);
});
+ // A ticker longer than ten characters used to slip past the guard entirely: the
+ // cashtag pattern capped the ticker at nine trailing characters and then demanded
+ // a word boundary, which can never fall mid-word, so the whole cashtag went
+ // unmatched and the caption was treated as clean.
+ it('422s an off-brand cashtag whose ticker is longer than ten characters', async () => {
+ const { res, body } = await post({ ...BASE, caption: 'buy $SOMETHINGELSE now' });
+ expect(res.statusCode).toBe(422);
+ expect(body.error).toBe('content');
+ expect(body.field).toBe('caption');
+ });
+
it('allows a caption that references $THREE', async () => {
const { res } = await post({ ...BASE, caption: 'powered by $THREE' });
expect(res.statusCode).toBe(201);
diff --git a/tests/api/irl-report.test.js b/tests/api/irl-report.test.js
index 586348de4..20f8a198d 100644
--- a/tests/api/irl-report.test.js
+++ b/tests/api/irl-report.test.js
@@ -72,9 +72,9 @@ function makeRes() {
end(body) { this.writableEnded = true; this._body = body; },
};
}
-async function report(body) {
+async function report(body, headers = {}) {
const res = makeRes();
- await handler({ url: '/api/irl/report', method: 'POST', headers: { host: 'x' }, query: {}, body }, res);
+ await handler({ url: '/api/irl/report', method: 'POST', headers: { host: 'x', ...headers }, query: {}, body }, res);
let parsed = null;
try { parsed = JSON.parse(res._body); } catch {}
return { res, body: parsed };
@@ -159,6 +159,22 @@ describe('POST /api/irl/report', () => {
expect(inserted).toBe(false);
});
+ // H2 transport: the device credential rides the `x-irl-device` HEADER, with the
+ // body as the fallback. This path used to read `body.deviceToken` only, so a
+ // header-only client lost BOTH device-keyed protections at once: the owner became
+ // an "independent" reporter of their own pin, and the per-device dedup fell back
+ // to the coarse per-IP identity.
+ it('honours the x-irl-device header for the owner self-report', async () => {
+ const { res, body } = await report({ pinId: PIN_A, reason: 'spam' }, { 'x-irl-device': 'owner-dev' });
+ expect(res.statusCode).toBe(200);
+ expect(body.self).toBe(true);
+ });
+
+ it('dedupes a header-only reporter by device, not by IP', async () => {
+ await report({ pinId: PIN_A, reason: 'spam' }, { 'x-irl-device': 'visitor-dev' });
+ expect(lastInsert.reporterToken).toBe('visitor-dev');
+ });
+
it('ignores an authenticated owner self-report', async () => {
pinRow = { id: PIN_A, user_id: OWNER, device_token: null, hidden_at: null };
sessionUser = { id: OWNER };
diff --git a/tests/avatar-appearance-attachments.test.js b/tests/avatar-appearance-attachments.test.js
new file mode 100644
index 000000000..82a5375e6
--- /dev/null
+++ b/tests/avatar-appearance-attachments.test.js
@@ -0,0 +1,112 @@
+// Tests for custom bone-mounted attachments on the avatar appearance record.
+//
+// `appearance.accessories` names entries in the curated preset catalog. Scene
+// Composer attaches forged GLBs that are in no catalog, so they persist through
+// `appearance.attachments`, each carrying its own bone + URL. Two things have to
+// hold for that to be safe and to actually work:
+//
+// 1. The API accepts the shape the studio writes, and rejects a URL on a host
+// we do not serve assets from. A stored attachment is fetched by every
+// browser that renders the avatar, including viewers who do not own it.
+// 2. The runtime turns a stored entry back into the preset shape the
+// load-and-attach path already understands, with ids that cannot collide
+// with a catalog preset.
+//
+// Before this contract existed the studio PATCHed a top-level `accessories`
+// array, which zod stripped as an unknown key: the request answered 200 and
+// stored nothing. The last case here is the regression guard for that.
+
+import { describe, it, expect } from 'vitest';
+
+import { avatarAppearance } from '../api/_lib/validate.js';
+import { isTrustedAttachmentUrl, validateAppearance } from '../api/_lib/accessories.js';
+
+const CDN = 'https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev';
+
+describe('appearance.attachments schema', () => {
+ it('accepts a bone-mounted forged prop on a three.ws asset host', () => {
+ const res = avatarAppearance.safeParse({
+ attachments: [{ bone: 'mixamorig:Head', url: `${CDN}/forge/anon/crown.glb`, name: 'Horned crown' }],
+ });
+ expect(res.success).toBe(true);
+ expect(res.data.attachments).toHaveLength(1);
+ expect(res.data.attachments[0].bone).toBe('mixamorig:Head');
+ });
+
+ it('keeps attachments alongside the rest of the appearance document', () => {
+ const res = avatarAppearance.safeParse({
+ colors: { skin: '#c99a70' },
+ hidden: ['hair'],
+ attachments: [{ bone: 'mixamorig:RightHand', url: `${CDN}/forge/anon/staff.glb` }],
+ });
+ expect(res.success).toBe(true);
+ expect(res.data.colors.skin).toBe('#c99a70');
+ expect(res.data.attachments[0].bone).toBe('mixamorig:RightHand');
+ });
+
+ it('rejects a URL on a host we do not serve assets from', () => {
+ const res = avatarAppearance.safeParse({
+ attachments: [{ bone: 'mixamorig:Head', url: 'https://evil.example.com/payload.glb' }],
+ });
+ expect(res.success).toBe(false);
+ expect(JSON.stringify(res.error.issues)).toMatch(/asset host/);
+ });
+
+ it('rejects more attachments than the studio may save', () => {
+ const many = Array.from({ length: 9 }, (_, i) => ({
+ bone: 'mixamorig:Head',
+ url: `${CDN}/forge/anon/prop-${i}.glb`,
+ }));
+ expect(avatarAppearance.safeParse({ attachments: many }).success).toBe(false);
+ });
+
+ it('rejects an entry with no bone to hang on', () => {
+ const res = avatarAppearance.safeParse({
+ attachments: [{ url: `${CDN}/forge/anon/crown.glb` }],
+ });
+ expect(res.success).toBe(false);
+ });
+});
+
+describe('isTrustedAttachmentUrl', () => {
+ it('allows our own asset hosts and same-origin paths', () => {
+ expect(isTrustedAttachmentUrl(`${CDN}/forge/anon/crown.glb`)).toBe(true);
+ expect(isTrustedAttachmentUrl('https://three.ws/accessories/hat-beanie.glb')).toBe(true);
+ expect(isTrustedAttachmentUrl('/accessories/hat-beanie.glb')).toBe(true);
+ });
+
+ it('refuses http, protocol-relative and lookalike hosts', () => {
+ expect(isTrustedAttachmentUrl('http://three.ws/x.glb')).toBe(false);
+ expect(isTrustedAttachmentUrl('//evil.example.com/x.glb')).toBe(false);
+ expect(isTrustedAttachmentUrl('https://three.ws.evil.com/x.glb')).toBe(false);
+ expect(isTrustedAttachmentUrl('https://notr2.dev.evil.com/x.glb')).toBe(false);
+ expect(isTrustedAttachmentUrl(null)).toBe(false);
+ });
+});
+
+describe('validateAppearance', () => {
+ it('names the offending URL so the studio can show it', () => {
+ const err = validateAppearance({
+ attachments: [{ bone: 'Head', url: 'https://evil.example.com/x.glb' }],
+ });
+ expect(err).toMatch(/evil\.example\.com/);
+ });
+
+ it('passes a well-formed outfit', () => {
+ expect(
+ validateAppearance({ attachments: [{ bone: 'Head', url: `${CDN}/forge/anon/crown.glb` }] }),
+ ).toBeNull();
+ });
+});
+
+describe('the shape Scene Composer used to send', () => {
+ it('is no longer silently dropped: a bare accessories array of objects fails', () => {
+ // The old payload put objects in `accessories`, which the catalog field
+ // types as preset-id strings. It has to fail loudly rather than parse to
+ // an empty document that stores nothing.
+ const res = avatarAppearance.safeParse({
+ accessories: [{ bone: 'mixamorig:Head', glbUrl: `${CDN}/forge/anon/crown.glb`, name: 'Crown' }],
+ });
+ expect(res.success).toBe(false);
+ });
+});
diff --git a/tests/irl-analytics.test.js b/tests/irl-analytics.test.js
index cc2232a6b..678189783 100644
--- a/tests/irl-analytics.test.js
+++ b/tests/irl-analytics.test.js
@@ -145,4 +145,27 @@ describe('getIrlAnalyticsSummary', () => {
expect(Array.isArray(summary.daily_series_30d)).toBe(true);
expect(typeof summary.generated_at).toBe('string');
});
+
+ // The 30-day series joins two per-day sub-selects onto a generate_series. Both
+ // sides expose a column called `day`, so every reference to the series column has
+ // to be qualified: an unqualified one made Postgres reject the whole query with
+ // `column reference "day" is ambiguous`, and because the endpoint degrades a
+ // failed summary into an empty 200, the rollup silently served zeros forever.
+ it('qualifies every reference to the daily-series column so the join is unambiguous', async () => {
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]);
+ await getIrlAnalyticsSummary();
+
+ const series = sqlMock.mock.calls
+ .map(([strings]) => (Array.isArray(strings) ? strings.join(' ') : String(strings)))
+ .find((q) => /generate_series/.test(q));
+ expect(series).toBeTruthy();
+ // The series carries its own column alias and both joins reference it.
+ expect(series).toMatch(/generate_series\([^)]*\)\s+AS\s+d\(day\)/i);
+ expect(series).toMatch(/ON p\.day = d\.day/i);
+ expect(series).toMatch(/ON n\.day = d\.day/i);
+ // No bare `day` survives on either side of a join condition or the ordering.
+ expect(series).not.toMatch(/=\s*day\b/);
+ expect(series).not.toMatch(/ORDER BY\s+day\b/i);
+ });
});