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
fix(referral): stop blaming the referral code when the visit beacon cannot read the body
nirholas9194946f1260
diff --git a/api/referral/visit.js b/api/referral/visit.jsindex 6a901ba6d..d91888626 100644--- a/api/referral/visit.js+++ b/api/referral/visit.js@@ -1,4 +1,4 @@-// POST /api/referral/visit — record a referral-link visit (top of the viral funnel).+// POST /api/referral/visit: record a referral-link visit (top of the viral funnel).//// A share link carries `?ref=CODE`. public/referral-capture.js parks the code for// later signup attribution AND fires a beacon here so we can measure the FULL@@ -29,7 +29,19 @@ export default wrap(async (req, res) => {const rl = await limits.referralVisitIp(ip);if (!rl.success) return rateLimited(res, rl);- const body = await readJson(req).catch(() => null);+ // A body we could not read at all is a different failure from a code we read+ // and rejected. Collapsing both into `invalid_code` sends an integrator hunting+ // through their referral code when the real fault is their content-type header+ // (readJson requires application/json) or an oversized payload.+ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ const status = err?.status === 415 || err?.status === 413 ? err.status : 400;+ const code = { 415: 'unsupported_media_type', 413: 'payload_too_large' }[status] || 'bad_request';+ return error(res, status, code, err?.message || 'unreadable request body');+ }+const code = normalizeReferralCode(body?.code);if (!code) return error(res, 400, 'invalid_code', 'malformed referral code');@@ -38,7 +50,7 @@ export default wrap(async (req, res) => {// UTC day so the dedup window is stable regardless of server timezone.const day = new Date().toISOString().slice(0, 10);- // Resolve the referrer at write time when the code is live — lets the funnel+ // Resolve the referrer at write time when the code is live, which lets the funnel// roll up by referrer without re-joining on every read.const [referrer] = await sql`select id from usersdiff --git a/prompts/swarm-100/api-referral-01.md b/prompts/swarm-100/api-referral-01.mddeleted file mode 100644index 3dc21f24a..000000000--- a/prompts/swarm-100/api-referral-01.md+++ /dev/null@@ -1,101 +0,0 @@-# API audit: api/referral batch 01 (1 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/referral/visit.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-referral-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/tests/referral-visit-endpoint.test.js b/tests/referral-visit-endpoint.test.jsnew file mode 100644index 000000000..f9bdb51ba--- /dev/null+++ b/tests/referral-visit-endpoint.test.js@@ -0,0 +1,249 @@+/**+ * Referral visit beacon (api/referral/visit.js): the write side of the share+ * funnel, and the only public unauthenticated writer into referral_visits.+ *+ * tests/referral-funnel.test.js pins the read side, so the counts it reports+ * were only ever as trustworthy as the rows this handler writes, which nothing+ * covered. Four behaviours carry the funnel and each fails silently if it+ * regresses (the endpoint answers 200 either way, so no alert would fire):+ * the referrer resolved at write time, the unknown-code row that keeps dead+ * links visible, the once-per-visitor-per-day dedup, and the usage event that+ * fires only on a genuinely new visit.+ *+ * We drive the REAL wrapped handler and mock only the I/O boundary (DB, rate+ * limiter, usage buffer) so the handler's own branching runs unchanged.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const H = vi.hoisted(() => ({+ /** Rows the `users` lookup returns; empty means the code matches nobody. */+ referrerRows: [],+ /** Rows the insert's RETURNING clause yields; empty means ON CONFLICT DO NOTHING fired. */+ insertRows: [{ id: '1' }],+ /** Every insert the handler issued, as { code, referrerId, visitorHash, day }. */+ inserts: [],+ /** Every recordEvent() payload. */+ events: [],+ /** Rate limiter verdict. */+ rl: { success: true, limit: 60, remaining: 59, reset: Date.now() + 1000 },+ /** IPs the limiter was asked about, so the per-IP keying is observable. */+ rlCalls: [],+}));++vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => false, drain: async () => {} }));++vi.mock('../api/_lib/db.js', () => {+ const sql = (strings, ...vals) => {+ if (!Array.isArray(strings)) return Promise.resolve({ __frag: true });+ const q = strings.join(' ').toLowerCase();+ if (q.includes('from users')) return Promise.resolve(H.referrerRows);+ if (q.includes('insert into referral_visits')) {+ const [code, referrerId, visitorHash, day] = vals;+ H.inserts.push({ code, referrerId, visitorHash, day });+ return Promise.resolve(H.insertRows);+ }+ return Promise.resolve([]);+ };+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };+});++vi.mock('../api/_lib/rate-limit.js', () => ({+ clientIp: (req) => req.headers['x-forwarded-for'] || '1.2.3.4',+ limits: {+ referralVisitIp: async (ip) => {+ H.rlCalls.push(ip);+ return H.rl;+ },+ },+}));++vi.mock('../api/_lib/usage.js', () => ({+ recordEvent: (evt) => { H.events.push(evt); },+}));++const handler = (await import('../api/referral/visit.js')).default;++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ ended: false,+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },+ end(b) { this.body = b; this.ended = true; },+ get headersSent() { return this.ended; },+ get writableEnded() { return this.ended; },+ };+}++async function visit(body, { method = 'POST', contentType = 'application/json', headers = {} } = {}) {+ const req = {+ method,+ url: '/api/referral/visit',+ headers: { 'content-type': contentType, 'user-agent': 'QA/1.0', ...headers },+ query: {},+ ...(body === undefined ? {} : { body }),+ };+ const res = makeRes();+ await handler(req, res);+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null, headers: res.headers };+}++beforeEach(() => {+ H.referrerRows = [];+ H.insertRows = [{ id: '1' }];+ H.inserts = [];+ H.events = [];+ H.rl = { success: true, limit: 60, remaining: 59, reset: Date.now() + 1000 };+ H.rlCalls = [];+});++describe('referral visit: the recorded row', () => {+ it('resolves the referrer at write time and records the visit', async () => {+ H.referrerRows = [{ id: 'referrer-1' }];++ const r = await visit({ code: 'ADA99' });++ expect(r.status).toBe(200);+ expect(r.body).toEqual({ ok: true });+ expect(H.inserts).toHaveLength(1);+ expect(H.inserts[0].code).toBe('ADA99');+ expect(H.inserts[0].referrerId).toBe('referrer-1');+ });++ it('uppercases a lowercase code so a shared link is matched case-insensitively', async () => {+ H.referrerRows = [{ id: 'referrer-1' }];++ await visit({ code: 'ada99' });++ expect(H.inserts[0].code).toBe('ADA99');+ });++ it('records an unknown code with no referrer, so dead-link traffic stays visible', async () => {+ H.referrerRows = [];++ const r = await visit({ code: 'NOSUCHCODE' });++ expect(r.status).toBe(200);+ expect(H.inserts).toHaveLength(1);+ expect(H.inserts[0].referrerId).toBeNull();+ expect(H.events[0].meta.has_referrer).toBe(false);+ });++ it('stores only a hash of the visitor, never the raw ip or user agent', async () => {+ await visit({ code: 'ADA99' }, { headers: { 'x-forwarded-for': '203.0.113.7' } });++ const { visitorHash } = H.inserts[0];+ expect(visitorHash).toMatch(/^[0-9a-f]{64}$/);+ expect(visitorHash).not.toContain('203.0.113.7');+ expect(visitorHash).not.toContain('QA/1.0');+ });++ it('stamps the UTC day so the dedup window does not move with the server timezone', async () => {+ await visit({ code: 'ADA99' });++ expect(H.inserts[0].day).toBe(new Date().toISOString().slice(0, 10));+ });++ it('separates visitors by ip, so two people on one link are two visits', async () => {+ await visit({ code: 'ADA99' }, { headers: { 'x-forwarded-for': '203.0.113.7' } });+ await visit({ code: 'ADA99' }, { headers: { 'x-forwarded-for': '198.51.100.4' } });++ expect(H.inserts[0].visitorHash).not.toBe(H.inserts[1].visitorHash);+ });+});++describe('referral visit: dedup replay', () => {+ it('answers 200 without counting a usage event when the row already existed', async () => {+ // ON CONFLICT DO NOTHING returns no row: the visitor already counted today.+ H.insertRows = [];++ const r = await visit({ code: 'ADA99' });++ expect(r.status).toBe(200);+ expect(r.body).toEqual({ ok: true });+ expect(H.events).toHaveLength(0);+ });++ it('counts a usage event exactly once, on the insert that actually landed', async () => {+ H.referrerRows = [{ id: 'referrer-1' }];+ await visit({ code: 'ADA99' });+ H.insertRows = [];+ await visit({ code: 'ADA99' });++ expect(H.events).toHaveLength(1);+ expect(H.events[0]).toMatchObject({ userId: 'referrer-1', kind: 'referral_visit' });+ });+});++describe('referral visit: rejected requests never reach the database', () => {+ it('400s a malformed code rather than mangling it into a valid one', async () => {+ const r = await visit({ code: 'my-code' });++ expect(r.status).toBe(400);+ expect(r.body.error).toBe('invalid_code');+ expect(H.inserts).toHaveLength(0);+ });++ it('400s a missing code', async () => {+ const r = await visit({});++ expect(r.status).toBe(400);+ expect(r.body.error).toBe('invalid_code');+ expect(H.inserts).toHaveLength(0);+ });++ it('400s a code that is not a string', async () => {+ const r = await visit({ code: { nested: true } });++ expect(r.status).toBe(400);+ expect(r.body.error).toBe('invalid_code');+ });++ it('415s a non-JSON content type instead of blaming the referral code', async () => {+ // The old catch-all reported `invalid_code` here, sending integrators to+ // debug a code that was never read.+ const r = await visit({ code: 'ADA99' }, { contentType: 'application/x-www-form-urlencoded' });++ expect(r.status).toBe(415);+ expect(r.body.error).toBe('unsupported_media_type');+ expect(H.inserts).toHaveLength(0);+ });++ it('405s a GET, since the beacon is POST only', async () => {+ const r = await visit(undefined, { method: 'GET' });++ expect(r.status).toBe(405);+ expect(H.inserts).toHaveLength(0);+ });++ it('204s a preflight without touching the database', async () => {+ const r = await visit(undefined, { method: 'OPTIONS' });++ expect(r.status).toBe(204);+ expect(H.inserts).toHaveLength(0);+ });+});++describe('referral visit: rate limiting', () => {+ it('429s over the per-ip limit, before the body is read or a row is written', async () => {+ H.rl = { success: false, limit: 60, remaining: 0, reset: Date.now() + 60_000 };++ const r = await visit({ code: 'ADA99' });++ expect(r.status).toBe(429);+ expect(r.body.error).toBe('rate_limited');+ expect(r.headers['retry-after']).toBeTruthy();+ expect(H.inserts).toHaveLength(0);+ });++ it('keys the limiter on the caller ip, so one flooder cannot mute everyone', async () => {+ await visit({ code: 'ADA99' }, { headers: { 'x-forwarded-for': '203.0.113.7' } });+ await visit({ code: 'ADA99' }, { headers: { 'x-forwarded-for': '198.51.100.4' } });++ expect(H.rlCalls).toEqual(['203.0.113.7', '198.51.100.4']);+ });+});