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(irl): answer 400 for a non-uuid pin id and catch cashtags longer than ten characters
nirholasccb312ec4270
diff --git a/api/_lib/http.js b/api/_lib/http.jsindex f0afcfa93..bd8a6685e 100644--- a/api/_lib/http.js+++ b/api/_lib/http.js@@ -257,7 +257,7 @@ export function serverError(res, status, code, err, extra = {}) {if (typeof res.setHeader === 'function') res.setHeader('retry-after', '30');return json(res, 503, {error: 'service_unavailable',- error_description: 'database temporarily unavailable — retry shortly',+ error_description: 'database temporarily unavailable, retry shortly',ref,...extra,}, { 'cache-control': 'no-store' });@@ -265,7 +265,7 @@ export function serverError(res, status, code, err, extra = {}) {const ref = reportServerError(err, { code, status });return json(res, status, {error: code,- error_description: `internal error — quote ref ${ref} to support`,+ error_description: `internal error, quote ref ${ref} to support`,ref,...extra,}, { 'cache-control': 'no-store' });@@ -640,8 +640,8 @@ export function wrap(handler) {json(res, status, {error: dbDegraded ? 'service_unavailable' : 'internal_error',error_description: dbDegraded- ? 'database temporarily unavailable — retry shortly'- : `internal error — quote ref ${ref} to support`,+ ? 'database temporarily unavailable, retry shortly'+ : `internal error, quote ref ${ref} to support`,ref,}, { 'cache-control': 'no-store' });}diff --git a/api/irl/pins.js b/api/irl/pins.jsindex 2d233c7c8..b65415f61 100644--- a/api/irl/pins.js+++ b/api/irl/pins.js@@ -61,9 +61,16 @@ export function hardBlocked(text) {// `$TICKER` cashtag that isn't $THREE, or a pump.fun-style mint address (…pump)// that isn't the $THREE contract. Generic by construction so no competitor is// ever written into source; $THREE (cashtag or contract) is explicitly allowed.+//+// The cashtag match is deliberately greedy and carries NO trailing word-boundary:+// a `{1,9}` + `\b` pattern silently missed every ticker longer than ten characters+// (the boundary could never be satisfied mid-word, so the whole cashtag went+// unmatched and the caption sailed through the guard). Matching the run of ticker+// characters as far as it goes means a long ticker is caught like a short one, and+// a genuine `$THREE` still compares equal after the `$` is stripped.export function namesOffBrandCoin(text) {const t = String(text || '');- const cashtags = t.match(/\$[A-Za-z][A-Za-z0-9]{1,9}\b/g) || [];+ const cashtags = t.match(/\$[A-Za-z][A-Za-z0-9]*/g) || [];if (cashtags.some((c) => c.slice(1).toUpperCase() !== 'THREE')) return true;const tokens = t.match(/\b[1-9A-HJ-NP-Za-km-z]{32,48}\b/g) || [];if (tokens.some((m) => /pump$/.test(m) && m !== THREE_MINT)) return true;@@ -496,21 +503,23 @@ export function readVisibility(body) {return defaultsToPrivate() ? 'private' : 'public';}-// Pin ids are server-minted UUIDs (gen_random_uuid()). Validate the format at the-// top of every mutation path so an oversized / garbage id is a clean 400 and never-// reaches the DB query or a log line. The SQL is already parameterized (this is-// not the injection guard) — it's input hygiene + defense in depth, and it lets a-// "not a pin id" request fail fast with a clear message instead of a confusing 404.+// Pin ids are server-minted UUIDs (gen_random_uuid()), and `irl_pins.id` is a UUID+// COLUMN. Validate the format at the top of every mutation path so an oversized /+// garbage id is a clean 400 and never reaches the DB query or a log line. The SQL is+// already parameterized (this is not the injection guard) — it's input hygiene, and+// it lets a "not a pin id" request fail fast with a clear message.//-// A real id is a 36-char UUID; we accept that exactly, plus a conservative-// opaque-id fallback (1–64 chars, URL/path-safe alphabet only) so the guard is-// about REJECTING the dangerous shapes — control chars, whitespace, quotes,-// SQL-injection text, multi-KB blobs — rather than over-fitting to one format.+// Strict UUID, nothing else. A looser "URL-safe opaque id" fallback used to be+// accepted here on the theory that the guard should only reject *dangerous* shapes,+// but the column disagrees: Postgres rejects any non-UUID text with `invalid input+// syntax for type uuid`, which surfaced as a 500 for every well-formed-looking id+// (`PATCH {id:'pin-1'}`, `DELETE ?id=not-a-uuid`) instead of the 400 this guard+// exists to return. api/irl/report.js has always used the strict form; this matches+// it, and privacy.js (which imports this) inherits the fix.const PIN_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;-const PIN_ID_SAFE_RE = /^[A-Za-z0-9_-]{1,64}$/;export function isValidPinId(id) {if (typeof id !== 'string' || !id) return false;- return PIN_UUID_RE.test(id) || PIN_ID_SAFE_RE.test(id);+ return PIN_UUID_RE.test(id);}// Smallest signed distance between two compass bearings, 0–180°.diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex ccd9c955d..8d0ff97b1 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -733,7 +733,7 @@ async function handleDetail(req, res, id) {} else if (isDbUnavailableError(err)) {console.warn('[marketplace/detail] db unavailable:', err?.message);res.setHeader('retry-after', '30');- return error(res, 503, 'service_unavailable', 'database temporarily unavailable — retry shortly');+ return error(res, 503, 'service_unavailable', 'database temporarily unavailable, retry shortly');} else {console.error('[marketplace/detail]', err?.message || err);return error(res, 500, 'db_error', 'Failed to load agent');diff --git a/api/x402-checkout.js b/api/x402-checkout.jsindex a4e5947d3..3a27629d3 100644--- a/api/x402-checkout.js+++ b/api/x402-checkout.js@@ -106,7 +106,7 @@ function toPubkey(value, field) {// canonical mints from a local map; ataExists fails open to "missing"), so a// transient *total* failover outage — every endpoint in solanaConnection's chain// failing within this single request — used to throw straight through wrap() as an-// opaque "internal error — quote ref … to support" 500 at the modal's Authorize+// opaque "internal error, quote ref … to support" 500 at the modal's Authorize// step. Match the sibling fail-open posture: if the live fetch fails but we still// hold a cached blockhash inside the cluster's ~60-90s validity window, serve it.// Safe by construction — a blockhash only bounds how long the buyer has to land thediff --git a/tests/api/irl-share-create.test.js b/tests/api/irl-share-create.test.jsnew file mode 100644index 000000000..847e5d04a--- /dev/null+++ b/tests/api/irl-share-create.test.js@@ -0,0 +1,181 @@+// POST /api/irl/share (api/irl/share.js) — minting a permanent, unfurlable link+// for an AR capture the owner just took.+//+// Drives the real handler against an in-memory fake `sql` and a stubbed object+// store. The ownership check, the visibility gate, and the id validation are all+// REAL, so a regression in any of them fails here.+//+// Regression pinned: a pinId that is not a UUID used to reach Postgres through+// the `${pinId}::uuid` cast and come back as `invalid input syntax for type+// uuid`, which the boundary turned into a 500 + support ref for a request whose+// only fault was a typo. It must answer the designed 400 without ever querying.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++const PIN_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';+const OWNER_DEVICE = 'device-owner-1';++let db;+function resetDb(pinOverrides = {}) {+ db = {+ pin: {+ id: PIN_ID, lat: 40.7484, lng: -73.9857, caption: 'Front desk',+ avatar_name: 'Lobby Guide', published: true, hidden_at: null,+ user_id: null, device_token: OWNER_DEVICE, ...pinOverrides,+ },+ shares: [],+ events: [],+ };+}++const fakeSql = vi.fn(async (strings, ...values) => {+ const q = strings.join('§').replace(/\s+/g, ' ');+ const has = (s) => q.includes(s);+ if (has('CREATE TABLE') || has('CREATE INDEX')) return [];+ if (has('FROM irl_pins WHERE id =')) {+ return values[0] === db.pin.id ? [db.pin] : [];+ }+ if (has('INSERT INTO irl_pin_shares')) {+ const [pin_id, token, image_key, image_url, device_hash] = values;+ db.shares.push({ pin_id, token, image_key, image_url, device_hash });+ return [];+ }+ if (has('INSERT INTO irl_events')) {+ db.events.push({ type: values[0], pin_id: values[1], geocell7: values[2] });+ return [];+ }+ return [];+});++const putObject = vi.fn(async () => {});++vi.mock('../../api/_lib/db.js', () => ({+ sql: fakeSql, isDbUnavailableError: () => false, isDbCapacityError: () => false,+}));+vi.mock('../../api/_lib/env.js', () => ({ env: {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: new Proxy({}, { get: () => async () => ({ success: true }) }),+ clientIp: () => '1.2.3.4',+}));+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => null) }));+// The object store is the one genuinely external dependency; everything else the+// handler touches (hashing, validation, event logging) runs for real.+vi.mock('../../api/_lib/r2.js', () => ({+ putObject: (...args) => putObject(...args),+ publicUrl: (key) => `https://cdn.three.ws/${key}`,+}));++const handler = (await import('../../api/irl/share.js')).default;++function call({ pinId, device = OWNER_DEVICE, bytes = 4096, method = 'POST' }) {+ const body = Buffer.alloc(bytes, 7);+ const req = Readable.from(bytes ? [body] : []);+ req.method = method;+ req.url = `/api/irl/share${pinId == null ? '' : `?pinId=${encodeURIComponent(pinId)}`}`;+ req.headers = {+ host: 'three.ws',+ 'content-type': 'application/octet-stream',+ 'content-length': String(bytes),+ ...(device ? { 'x-irl-device': device } : {}),+ };+ req.socket = { remoteAddress: '1.2.3.4' };+ const res = {+ statusCode: 0, _body: null, _h: {},+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(b) { this._body = b ?? null; },+ get headersSent() { return this._body !== null; },+ get writableEnded() { return this._body !== null; },+ };+ return handler(req, res).then(() => ({+ status: res.statusCode,+ body: res._body ? JSON.parse(res._body) : null,+ }));+}++beforeEach(() => {+ resetDb();+ fakeSql.mockClear();+ putObject.mockClear();+});++describe('POST /api/irl/share', () => {+ it('mints a token, uploads the capture, and returns the share url', async () => {+ const r = await call({ pinId: PIN_ID });+ expect(r.status).toBe(201);+ expect(r.body.token).toMatch(/^[A-Za-z0-9_-]{20,}$/);+ expect(r.body.url).toBe(`https://three.ws/irl/s/${r.body.token}`);+ expect(r.body.imageUrl).toBe(`https://cdn.three.ws/irl-share/${r.body.token}.png`);+ expect(putObject).toHaveBeenCalledTimes(1);+ expect(putObject.mock.calls[0][0].contentType).toBe('image/png');+ expect(db.shares).toHaveLength(1);+ expect(db.shares[0].pin_id).toBe(PIN_ID);+ // The stored device hash is the irreversible digest, never the raw token.+ expect(db.shares[0].device_hash).not.toBe(OWNER_DEVICE);+ expect(db.events.map((e) => e.type)).toContain('share_created');+ });++ it('rejects a malformed pinId with a 400 before it ever reaches the database', async () => {+ const r = await call({ pinId: "' OR 1=1--" });+ expect(r.status).toBe(400);+ expect(r.body.error).toBe('bad_request');+ expect(fakeSql).not.toHaveBeenCalled();+ });++ it('requires a pinId', async () => {+ const r = await call({ pinId: null });+ expect(r.status).toBe(400);+ expect(fakeSql).not.toHaveBeenCalled();+ });++ it('refuses an anonymous caller with no session and no device token', async () => {+ const r = await call({ pinId: PIN_ID, device: null });+ expect(r.status).toBe(401);+ });++ it('refuses a caller who does not own the pin', async () => {+ const r = await call({ pinId: PIN_ID, device: 'device-stranger' });+ expect(r.status).toBe(403);+ expect(db.shares).toHaveLength(0);+ });++ it('refuses to turn a private placement into a public link', async () => {+ resetDb({ published: false });+ const r = await call({ pinId: PIN_ID });+ expect(r.status).toBe(409);+ expect(r.body.error).toBe('not_shareable');+ // The copy has to tell the owner what to DO: publish the pin.+ expect(r.body.error_description).toMatch(/public/);+ expect(db.shares).toHaveLength(0);+ });++ it('refuses a pin that is hidden pending review', async () => {+ resetDb({ hidden_at: new Date().toISOString() });+ const r = await call({ pinId: PIN_ID });+ expect(r.status).toBe(409);+ expect(db.shares).toHaveLength(0);+ });++ it('refuses a body too small to be a capture', async () => {+ const r = await call({ pinId: PIN_ID, bytes: 12 });+ expect(r.status).toBe(400);+ expect(putObject).not.toHaveBeenCalled();+ });++ it('surfaces an upload failure as a 502, never a stored half-share', async () => {+ putObject.mockImplementationOnce(async () => { throw new Error('bucket unreachable'); });+ const r = await call({ pinId: PIN_ID });+ expect(r.status).toBe(502);+ expect(r.body.error).toBe('upload_failed');+ expect(db.shares).toHaveLength(0);+ });++ it('is POST only', async () => {+ const r = await call({ pinId: PIN_ID, method: 'GET', bytes: 0 });+ expect(r.status).toBe(405);+ });+});diff --git a/tests/api/world-lines-pins-schema.test.js b/tests/api/world-lines-pins-schema.test.jsnew file mode 100644index 000000000..81d081011--- /dev/null+++ b/tests/api/world-lines-pins-schema.test.js@@ -0,0 +1,97 @@+// api/irl/world-lines.js provisions irl_pins before it reads it.+//+// Regression: both coordinate feeds (`nearby` and the single-quest detail read)+// JOIN irl_pins for the anchor's precise position, but the handler's own+// ensureTables() only created irl_world_lines and irl_presence_proofs. On a+// database where no pin had ever been placed, the JOIN came back as a raw+// Postgres 42P01 (`relation "irl_pins" does not exist`) and the boundary turned+// it into a 500 + support ref. Same failure shape that hit /irl/s/:token on a+// fresh database (tests/irl-share-view.test.js) and the same fix: provision the+// table through the definition that owns it (api/irl/pins.js) before querying.+//+// The fake `sql` below models that database exactly: any SELECT touching+// irl_pins throws 42P01 until a `CREATE TABLE IF NOT EXISTS irl_pins` has been+// issued. So this test fails with a 500 if the provisioning call is ever removed.++import { describe, it, expect, vi } from 'vitest';+import { Readable } from 'node:stream';++const created = new Set();+const statements = [];++class UndefinedTable extends Error {+ constructor(relation) {+ super(`relation "${relation}" does not exist`);+ this.code = '42P01';+ }+}++const fakeSql = vi.fn(async (strings) => {+ const q = strings.join('§').replace(/\s+/g, ' ');+ statements.push(q);+ const ddl = q.match(/CREATE TABLE IF NOT EXISTS (\w+)/);+ if (ddl) { created.add(ddl[1]); return []; }+ if (/^\s*(CREATE INDEX|CREATE UNIQUE INDEX|ALTER TABLE|UPDATE|INSERT)/.test(q.trim())) return [];+ for (const relation of ['irl_pins', 'irl_world_lines', 'irl_presence_proofs']) {+ if (q.includes(relation) && !created.has(relation)) throw new UndefinedTable(relation);+ }+ return [];+});++vi.mock('../../api/_lib/db.js', () => ({+ sql: fakeSql, isDbUnavailableError: () => false, isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));+vi.mock('../../api/_lib/env.js', () => ({ env: {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => null) }));+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: new Proxy({}, { get: () => async () => ({ success: true }) }),+ limitFailClosedRead: async (_name, fn, ...args) => fn(...args),+ clientIp: () => '1.2.3.4',+}));++const handler = (await import('../../api/irl/world-lines.js')).default;++function call(url) {+ const req = Readable.from([]);+ req.method = 'GET';+ req.url = url;+ req.query = Object.fromEntries(new URL(url, 'http://x').searchParams);+ req.headers = { host: 'three.ws' };+ req.socket = { remoteAddress: '1.2.3.4' };+ const res = {+ statusCode: 0, _body: null, _h: {},+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(b) { this._body = b ?? null; },+ get headersSent() { return this._body !== null; },+ get writableEnded() { return this._body !== null; },+ };+ return handler(req, res).then(() => ({+ status: res.statusCode,+ body: res._body ? JSON.parse(res._body) : null,+ }));+}++describe('world-lines on a database with no irl_pins table', () => {+ it('provisions irl_pins and answers the nearby feed instead of 500ing', async () => {+ const r = await call('/api/irl/world-lines/nearby?lat=40.7484&lng=-73.9857');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ world_lines: [] });+ expect(created.has('irl_pins')).toBe(true);+ // Provisioning has to land BEFORE the first read of the table.+ const ddlAt = statements.findIndex((q) => q.includes('CREATE TABLE IF NOT EXISTS irl_pins'));+ const readAt = statements.findIndex((q) => q.includes('JOIN irl_pins'));+ expect(ddlAt).toBeGreaterThanOrEqual(0);+ expect(readAt).toBeGreaterThan(ddlAt);+ });++ it('answers the single-quest read the same way', async () => {+ const r = await call('/api/irl/world-lines/ffffffff-ffff-4fff-8fff-ffffffffffff');+ expect(r.status).toBe(404);+ expect(r.body.error).toBe('world line not found');+ });+});