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.

feat(mocap): resolve a clip by slug and send the CSRF token the save and delete endpoints require

nirholasc2c588cf36be
diff --git a/api/_lib/migrations/20260813120000_mocap_clips_slug_lookup.sql b/api/_lib/migrations/20260813120000_mocap_clips_slug_lookup.sql
new file mode 100644
index 000000000..5856d4fe4
--- /dev/null
+++ b/api/_lib/migrations/20260813120000_mocap_clips_slug_lookup.sql
@@ -0,0 +1,12 @@
+-- Index mocap clip slugs so /api/mocap/clips/:idOrSlug can resolve the slug form.
+--
+-- The table's only slug index is the UNIQUE (owner_id, slug) constraint, whose
+-- leading column is the owner. A slug lookup that does not know the owner (the
+-- share-link path: GET /api/mocap/clips/<slug> from a signed-out visitor) cannot
+-- use it and degrades to a sequential scan over every clip ever recorded. This
+-- index makes the lookup a direct probe, and mirrors the partial-on-deleted_at
+-- pattern the table's other indexes already use so soft-deleted rows stay out.
+
+CREATE INDEX IF NOT EXISTS mocap_clips_slug_idx
+ ON mocap_clips (slug)
+ WHERE deleted_at IS NULL;
diff --git a/api/mocap/[id].js b/api/mocap/[id].js
index 4621f7126..6d5315cc2 100644
--- a/api/mocap/[id].js
+++ b/api/mocap/[id].js
@@ -15,6 +15,8 @@ import { z } from 'zod';
// Sentry event plus an ops alert. Matches what gen_random_uuid() emits, in any
// hex case, without demanding a specific version/variant nibble.
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+// Mirrors the slug grammar api/mocap/clips.js accepts on create.
+const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;
const patchSchema = z.object({
name: z.string().trim().min(1).max(120).optional(),
@@ -35,34 +37,43 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'PATCH', 'DELETE'])) return;
- const id =
+ const ident = parseIdent(
req.query?.id ||
- new URL(req.url, 'http://x').pathname.split('/').filter(Boolean).pop();
- if (!id || !UUID_RE.test(id)) {
- return error(res, 400, 'invalid_request', 'id must be a clip UUID');
+ new URL(req.url, 'http://x').pathname.split('/').filter(Boolean).pop(),
+ );
+ if (!ident) {
+ return error(res, 400, 'invalid_request', 'id must be a clip UUID or slug');
}
const auth = await resolveAuth(req);
- if (req.method === 'GET') return handleGet(req, res, auth, id);
+ if (req.method === 'GET') return handleGet(req, res, auth, ident);
if (!auth) return error(res, 401, 'unauthorized', 'authentication required');
// Cookie-session mutations need a CSRF token; bearer callers self-exempt
// inside requireCsrf. Mirrors api/avatars/[id].js, this endpoint is
// credentialed CORS, and the allowlist includes partner origins, so a
// same-site cookie alone is not proof of intent.
if (!(await requireCsrf(req, res, auth.userId))) return;
- if (req.method === 'PATCH') return handlePatch(req, res, auth, id);
- return handleDelete(req, res, auth, id);
+ if (req.method === 'PATCH') return handlePatch(req, res, auth, ident);
+ return handleDelete(req, res, auth, ident);
});
-async function handleGet(req, res, auth, id) {
+async function handleGet(req, res, auth, ident) {
+ // A slug is unique per owner, not globally, so one can match rows belonging to
+ // several owners. Scope the match to what this caller may see, prefer their
+ // own clip, and break any remaining tie by age, so a slug lookup is stable
+ // instead of whichever row the planner happened to return first. An id lookup
+ // matches at most one row either way, so the extra clauses are inert for it.
+ const viewerId = auth?.userId || null;
const [row] = await sql`
select id, owner_id, avatar_id, slug, name, description, kind, format,
duration_ms, frame_count, frames, tags, visibility,
price_amount, price_currency, play_count,
created_at, updated_at
from mocap_clips
- where id = ${id} and deleted_at is null
+ where ${selectorFor(ident)} and deleted_at is null
+ and (owner_id = ${viewerId} or visibility <> 'private')
+ order by (owner_id = ${viewerId}) desc nulls last, created_at asc
limit 1
`;
if (!row) return error(res, 404, 'not_found', 'clip not found');
@@ -83,7 +94,7 @@ async function handleGet(req, res, auth, id) {
// Fire-and-forget; failure must not block the response.
queueMicrotask(async () => {
try {
- await sql`update mocap_clips set play_count = play_count + 1 where id = ${id}`;
+ await sql`update mocap_clips set play_count = play_count + 1 where id = ${row.id}`;
} catch (err) {
console.warn('[mocap] play_count update failed', err?.message);
}
@@ -120,7 +131,7 @@ async function handleGet(req, res, auth, id) {
});
}
-async function handlePatch(req, res, auth, id) {
+async function handlePatch(req, res, auth, ident) {
if (auth.source === 'oauth' || auth.source === 'apikey') {
if (!hasScope(auth.scope, 'avatars:write'))
return error(res, 403, 'insufficient_scope', 'avatars:write required');
@@ -163,7 +174,7 @@ async function handlePatch(req, res, auth, id) {
const [row] = await sql`
update mocap_clips
${setClause}
- where id = ${id} and owner_id = ${auth.userId} and deleted_at is null
+ where ${selectorFor(ident)} and owner_id = ${auth.userId} and deleted_at is null
returning id, slug, name, description, kind, format, duration_ms, frame_count,
tags, visibility, avatar_id, price_amount, price_currency,
created_at, updated_at
@@ -179,7 +190,7 @@ async function handlePatch(req, res, auth, id) {
});
}
-async function handleDelete(req, res, auth, id) {
+async function handleDelete(req, res, auth, ident) {
if (auth.source === 'oauth' || auth.source === 'apikey') {
if (!hasScope(auth.scope, 'avatars:delete'))
return error(res, 403, 'insufficient_scope', 'avatars:delete required');
@@ -187,13 +198,29 @@ async function handleDelete(req, res, auth, id) {
const [row] = await sql`
update mocap_clips
set deleted_at = now()
- where id = ${id} and owner_id = ${auth.userId} and deleted_at is null
+ where ${selectorFor(ident)} and owner_id = ${auth.userId} and deleted_at is null
returning id
`;
if (!row) return error(res, 404, 'not_found', 'clip not found or not yours');
return json(res, 200, { ok: true });
}
+// The published @three-ws/mocap client takes `idOrSlug` on getClip/updateClip/
+// deleteClip and its README shares a saved clip as /mocap/<slug>, so both forms
+// have to resolve here. Rejecting the slug form answered 400 for a call the SDK
+// documents as supported. A uuid always wins the tie (it is also valid slug
+// text) because it selects one row globally.
+function parseIdent(raw) {
+ const value = typeof raw === 'string' ? raw.trim() : '';
+ if (UUID_RE.test(value)) return { column: 'id', value };
+ if (SLUG_RE.test(value)) return { column: 'slug', value };
+ return null;
+}
+
+function selectorFor(ident) {
+ return ident.column === 'id' ? sql`id = ${ident.value}` : sql`slug = ${ident.value}`;
+}
+
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session)
diff --git a/src/mocap-studio.js b/src/mocap-studio.js
index 90e8da1c8..70a13dd45 100644
--- a/src/mocap-studio.js
+++ b/src/mocap-studio.js
@@ -13,6 +13,11 @@ import { Viewer } from './viewer.js';
import { FaceMocap } from './face-mocap.js';
import { IdleAnimation } from './idle-animation.js';
import { log } from './shared/log.js';
+// Saving and deleting a clip are cookie-session mutations, and the endpoints
+// gate those on a single-use X-CSRF-Token (api/_lib/csrf.js). A bare fetch()
+// never carries one, so every save and delete from this page answered 403
+// csrf_missing in production. apiFetch mints and attaches the token per call.
+import { apiFetch, noteSession } from './api.js';
const $ = (sel) => document.querySelector(sel);
@@ -115,8 +120,12 @@ downloadBtn.addEventListener('click', () => downloadClip());
async function fetchMe() {
try {
const r = await fetch('/api/auth/me', { credentials: 'include' });
- if (!r.ok) return null;
+ if (!r.ok) {
+ noteSession(false);
+ return null;
+ }
const data = await r.json().catch(() => null);
+ noteSession(!!data?.user);
return data?.user || null;
} catch {
return null;
@@ -350,15 +359,16 @@ async function saveClip() {
saveBtn.disabled = true;
saveBtn.textContent = 'Saving…';
try {
- const r = await fetch('/api/mocap/clips', {
+ const r = await apiFetch('/api/mocap/clips', {
method: 'POST',
- credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
});
if (!r.ok) {
const body = await r.json().catch(() => null);
- throw new Error(body?.message || `save failed (${r.status})`);
+ throw new Error(
+ body?.error_description || body?.message || `save failed (${r.status})`,
+ );
}
saveBtn.textContent = 'Saved';
nameInput.value = '';
@@ -449,11 +459,13 @@ async function playSavedClip(id) {
async function deleteSavedClip(id) {
if (!confirm('Delete this clip?')) return;
try {
- const r = await fetch(`/api/mocap/clips/${encodeURIComponent(id)}`, {
+ const r = await apiFetch(`/api/mocap/clips/${encodeURIComponent(id)}`, {
method: 'DELETE',
- credentials: 'include',
});
- if (!r.ok) throw new Error(`delete failed (${r.status})`);
+ if (!r.ok) {
+ const body = await r.json().catch(() => null);
+ throw new Error(body?.error_description || `delete failed (${r.status})`);
+ }
refreshClipList();
} catch (err) {
alert(err?.message || 'Could not delete.');
diff --git a/tests/mocap-clips-endpoint.test.js b/tests/mocap-clips-endpoint.test.js
new file mode 100644
index 000000000..0d42f4706
--- /dev/null
+++ b/tests/mocap-clips-endpoint.test.js
@@ -0,0 +1,438 @@
+// api/mocap/clips.js + api/mocap/[id].js — the mocap clip store's HTTP surface.
+//
+// Covers the success path and the failure path of every method, plus the two
+// boundaries that used to be wrong: the `:idOrSlug` segment (the published
+// @three-ws/mocap client sends slugs, which the endpoint rejected and the route
+// table never even delivered) and the per-owner ambiguity a slug carries.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import fs from 'node:fs';
+import path from 'node:path';
+
+// A tagged-template recorder that also honours the composable-fragment pattern
+// api/_lib/db.js provides: a `sql` call whose text is not a whole statement is a
+// fragment spliced into a parent query, so it must return a plain value rather
+// than consume a queued result set.
+const calls = [];
+let queue = [];
+function render(strings, values) {
+ let text = '';
+ strings.forEach((s, i) => {
+ text += s;
+ if (i < values.length) text += `$${i + 1}`;
+ });
+ return text.replace(/\s+/g, ' ').trim();
+}
+const sqlMock = vi.fn((...args) => {
+ if (Array.isArray(args[0]) && Array.isArray(args[0].raw)) {
+ const [strings, ...values] = args;
+ const text = render(strings, values);
+ const fragment = !/^(select|insert|update|delete|with)\b/i.test(text);
+ const rec = { text, values, fragment };
+ calls.push(rec);
+ if (fragment) return rec;
+ return Promise.resolve(queue.length ? queue.shift() : []);
+ }
+ const [text, params] = args;
+ calls.push({ text: String(text).replace(/\s+/g, ' ').trim(), values: params, fragment: false });
+ return Promise.resolve(queue.length ? queue.shift() : []);
+});
+const statements = () => calls.filter((c) => !c.fragment);
+const fragments = () => calls.filter((c) => c.fragment);
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: sqlMock,
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const getSessionUserMock = vi.fn();
+const authenticateBearerMock = vi.fn();
+const extractBearerMock = vi.fn();
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: (...a) => extractBearerMock(...a),
+ hasScope: (granted, required) => {
+ const g = new Set((granted || '').split(/\s+/).filter(Boolean));
+ return required.split(/\s+/).every((s) => g.has(s));
+ },
+}));
+
+const requireCsrfMock = vi.fn(async () => true);
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: (...a) => requireCsrfMock(...a) }));
+
+const avatarPatchMock = vi.fn(async () => ({ success: true, limit: 20, remaining: 19, reset: 0 }));
+vi.mock('../api/_lib/rate-limit.js', () => ({ limits: { avatarPatch: (...a) => avatarPatchMock(...a) } }));
+
+vi.mock('../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://t', MCP_RESOURCE: 'http://t' },
+}));
+
+const { default: clipsHandler } = await import('../api/mocap/clips.js');
+const { default: clipHandler } = await import('../api/mocap/[id].js');
+
+const OWNER = '11111111-1111-1111-1111-111111111111';
+const OTHER = '22222222-2222-2222-2222-222222222222';
+const CLIP = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
+
+function mkReq({ method = 'GET', url = '/api/mocap/clips', headers = {}, body = null, query } = {}) {
+ const hdrs = { ...headers };
+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';
+ return {
+ method,
+ url,
+ headers: hdrs,
+ query,
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ queueMicrotask(() => {
+ cb(buf);
+ this._endCb?.();
+ });
+ } else if (event === 'end') {
+ this._endCb = cb;
+ if (body == null) queueMicrotask(() => cb());
+ }
+ },
+ destroy() {},
+ };
+}
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ // A real ServerResponse has getHeader, and http.js's secure-by-default
+ // cache policy reads it to decide whether the handler already chose a
+ // Cache-Control. A mock without it makes every response look uncached.
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(b) {
+ this.body = b;
+ this.writableEnded = true;
+ },
+ };
+}
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+function clipRow(over = {}) {
+ return {
+ id: CLIP,
+ owner_id: OWNER,
+ avatar_id: null,
+ slug: 'wink',
+ name: 'Wink',
+ description: null,
+ kind: 'face',
+ format: 'three.ws.face-mocap.v1',
+ duration_ms: 1000,
+ frame_count: 2,
+ frames: [{ t: 0, shapes: { eyeBlinkLeft: 0 } }],
+ tags: ['emote'],
+ visibility: 'public',
+ price_amount: null,
+ price_currency: null,
+ play_count: 7,
+ created_at: new Date('2026-06-01T00:00:00Z'),
+ updated_at: new Date('2026-06-01T00:00:00Z'),
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ calls.length = 0;
+ queue = [];
+ sqlMock.mockClear();
+ getSessionUserMock.mockReset().mockResolvedValue(null);
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+ extractBearerMock.mockReset().mockReturnValue(null);
+ requireCsrfMock.mockClear().mockResolvedValue(true);
+ avatarPatchMock.mockClear().mockResolvedValue({ success: true, limit: 20, remaining: 19, reset: 0 });
+});
+
+describe('GET /api/mocap/clips', () => {
+ it('serves an anonymous caller public clips only, with a shareable cache header', async () => {
+ queue = [[clipRow()]];
+ const res = mkRes();
+ await clipsHandler(mkReq({ url: '/api/mocap/clips' }), res);
+
+ expect(res.statusCode).toBe(200);
+ const out = parse(res);
+ expect(out.items).toHaveLength(1);
+ expect(out.items[0]).toMatchObject({ id: CLIP, slug: 'wink', owner: 'other', play_count: 7 });
+ expect(out.next_cursor).toBeNull();
+ expect(statements()[0].text).toContain(`visibility = 'public'`);
+ expect(res.headers['cache-control']).toContain('s-maxage=60');
+ });
+
+ it('scopes a signed-in caller to their own clips and marks them as theirs', async () => {
+ getSessionUserMock.mockResolvedValue({ id: OWNER });
+ queue = [[clipRow({ visibility: 'private' })]];
+ const res = mkRes();
+ await clipsHandler(mkReq({ url: '/api/mocap/clips' }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).items[0].owner).toBe('self');
+ expect(statements()[0].text).toContain('owner_id = $1');
+ expect(statements()[0].values[0]).toBe(OWNER);
+ expect(res.headers['cache-control']).toBe('private, max-age=0');
+ });
+
+ it('rejects a kind no row can ever carry instead of answering an unfiltered page', async () => {
+ const res = mkRes();
+ await clipsHandler(mkReq({ url: '/api/mocap/clips?kind=bogus' }), res);
+
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_request');
+ expect(statements()).toHaveLength(0);
+ });
+
+ it('rejects a malformed cursor rather than restarting at page one', async () => {
+ const res = mkRes();
+ await clipsHandler(mkReq({ url: '/api/mocap/clips?cursor=not-a-cursor' }), res);
+
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_cursor');
+ expect(statements()).toHaveLength(0);
+ });
+
+ it('round-trips its own next_cursor into a bounded second page', async () => {
+ queue = [[clipRow({ id: CLIP }), clipRow({ id: OTHER })]];
+ const first = mkRes();
+ await clipsHandler(mkReq({ url: '/api/mocap/clips?limit=1' }), first);
+ const { next_cursor: cursor } = parse(first);
+ expect(cursor).toBeTruthy();
+
+ calls.length = 0;
+ queue = [[]];
+ const second = mkRes();
+ await clipsHandler(mkReq({ url: `/api/mocap/clips?limit=1&cursor=${encodeURIComponent(cursor)}` }), second);
+
+ expect(second.statusCode).toBe(200);
+ const stmt = statements()[0];
+ expect(stmt.text).toContain('created_at < $');
+ expect(stmt.values.some((v) => v instanceof Date)).toBe(true);
+ });
+
+ it('refuses an unauthenticated create', async () => {
+ const res = mkRes();
+ await clipsHandler(mkReq({ method: 'POST', body: {} }), res);
+
+ expect(res.statusCode).toBe(401);
+ expect(parse(res).error).toBe('unauthorized');
+ });
+});
+
+describe('POST /api/mocap/clips', () => {
+ const recording = {
+ format: 'three.ws.face-mocap.v1',
+ duration: 1,
+ frames: [{ t: 0, shapes: { eyeBlinkLeft: 0.2 } }],
+ };
+
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: OWNER });
+ });
+
+ it('stores a recording and answers 201 with the persisted row', async () => {
+ queue = [[], [clipRow()]]; // dup-slug probe, then the insert
+ const res = mkRes();
+ await clipsHandler(mkReq({ method: 'POST', body: { name: 'Wink', slug: 'wink', clip: recording } }), res);
+
+ expect(res.statusCode).toBe(201);
+ expect(parse(res).clip.slug).toBe('wink');
+ const insert = statements().find((c) => c.text.startsWith('insert'));
+ expect(insert.values).toContain(OWNER);
+ expect(insert.values).toContain('face');
+ });
+
+ it('rejects a format the replay runtime cannot drive', async () => {
+ const res = mkRes();
+ await clipsHandler(
+ mkReq({ method: 'POST', body: { name: 'Wink', clip: { ...recording, format: 'three.ws.face-mocap.v9' } } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('unsupported_format');
+ expect(statements()).toHaveLength(0);
+ });
+
+ it('answers the loser of a slug race 409 rather than 500ing on the unique index', async () => {
+ queue = [[]]; // dup-slug probe comes back free for both tabs
+ sqlMock.mockImplementationOnce((...args) => {
+ calls.push({ text: 'select-dup', values: args, fragment: false });
+ return Promise.resolve([]);
+ });
+ const res = mkRes();
+ const err = Object.assign(new Error('duplicate key'), { code: '23505' });
+ let seenInsert = false;
+ sqlMock.mockImplementationOnce(() => {
+ seenInsert = true;
+ return Promise.reject(err);
+ });
+ await clipsHandler(mkReq({ method: 'POST', body: { name: 'Wink', slug: 'wink', clip: recording } }), res);
+
+ expect(seenInsert).toBe(true);
+ expect(res.statusCode).toBe(409);
+ expect(parse(res).error).toBe('duplicate_slug');
+ });
+
+ it('rejects a body that is not a clip at all', async () => {
+ const res = mkRes();
+ await clipsHandler(mkReq({ method: 'POST', body: { name: '' } }), res);
+
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('validation_error');
+ });
+});
+
+describe('GET /api/mocap/clips/:idOrSlug', () => {
+ it('resolves a uuid in any hex case', async () => {
+ queue = [[clipRow()]];
+ const res = mkRes();
+ await clipHandler(mkReq({ url: `/api/mocap/clips/${CLIP.toUpperCase()}`, query: { id: CLIP.toUpperCase() } }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).clip.id).toBe(CLIP);
+ const selector = fragments().find((f) => f.text.startsWith('id ='));
+ expect(selector.values[0]).toBe(CLIP.toUpperCase());
+ });
+
+ it('resolves the slug form the published SDK sends', async () => {
+ queue = [[clipRow()]];
+ const res = mkRes();
+ await clipHandler(mkReq({ url: '/api/mocap/clips/wink', query: { id: 'wink' } }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).clip.slug).toBe('wink');
+ const selector = fragments().find((f) => f.text.startsWith('slug ='));
+ expect(selector.values[0]).toBe('wink');
+ });
+
+ it('disambiguates a per-owner slug toward the caller and away from private rows', async () => {
+ getSessionUserMock.mockResolvedValue({ id: OWNER });
+ queue = [[clipRow()]];
+ const res = mkRes();
+ await clipHandler(mkReq({ url: '/api/mocap/clips/wink', query: { id: 'wink' } }), res);
+
+ expect(res.statusCode).toBe(200);
+ const stmt = statements()[0];
+ expect(stmt.text).toContain(`visibility <> 'private'`);
+ expect(stmt.text).toContain('order by (owner_id =');
+ expect(stmt.values).toContain(OWNER);
+ });
+
+ it('rejects an identifier that is neither a uuid nor a slug, without touching Postgres', async () => {
+ const res = mkRes();
+ await clipHandler(mkReq({ url: '/api/mocap/clips/Not_A_Slug', query: { id: 'Not_A_Slug' } }), res);
+
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_request');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('hides a private clip from a bearer that lacks avatars:read, even its owner’s', async () => {
+ extractBearerMock.mockReturnValue('tok');
+ authenticateBearerMock.mockResolvedValue({ userId: OWNER, scope: 'wallet:read', source: 'apikey' });
+ queue = [[clipRow({ visibility: 'private' })]];
+ const res = mkRes();
+ await clipHandler(mkReq({ url: `/api/mocap/clips/${CLIP}`, query: { id: CLIP } }), res);
+
+ expect(res.statusCode).toBe(404);
+ expect(parse(res).error).toBe('not_found');
+ });
+
+ it('counts a play for a visitor and not for the owner', async () => {
+ getSessionUserMock.mockResolvedValue({ id: OTHER });
+ queue = [[clipRow()], []];
+ const res = mkRes();
+ await clipHandler(mkReq({ url: `/api/mocap/clips/${CLIP}`, query: { id: CLIP } }), res);
+ await new Promise((r) => queueMicrotask(r));
+
+ expect(res.statusCode).toBe(200);
+ const bump = statements().find((c) => c.text.includes('play_count = play_count + 1'));
+ expect(bump).toBeTruthy();
+ expect(bump.values[0]).toBe(CLIP);
+ });
+});
+
+describe('PATCH / DELETE /api/mocap/clips/:idOrSlug', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: OWNER });
+ });
+
+ it('patches by slug scoped to the owner, so another account’s identical slug is untouched', async () => {
+ queue = [[clipRow({ name: 'Slow wink' })]];
+ const res = mkRes();
+ await clipHandler(
+ mkReq({ method: 'PATCH', url: '/api/mocap/clips/wink', query: { id: 'wink' }, body: { name: 'Slow wink' } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).clip.name).toBe('Slow wink');
+ const update = statements().find((c) => c.text.startsWith('update'));
+ expect(update.text).toContain('owner_id = $');
+ expect(update.values).toContain(OWNER);
+ expect(fragments().some((f) => f.text.startsWith('slug ='))).toBe(true);
+ });
+
+ it('rejects an empty patch instead of issuing a no-op update', async () => {
+ const res = mkRes();
+ await clipHandler(mkReq({ method: 'PATCH', url: `/api/mocap/clips/${CLIP}`, query: { id: CLIP }, body: {} }), res);
+
+ expect(res.statusCode).toBe(400);
+ expect(statements()).toHaveLength(0);
+ });
+
+ it('soft-deletes by slug and reports a miss as not found', async () => {
+ queue = [[]];
+ const res = mkRes();
+ await clipHandler(mkReq({ method: 'DELETE', url: '/api/mocap/clips/wink', query: { id: 'wink' } }), res);
+
+ expect(res.statusCode).toBe(404);
+ const del = statements().find((c) => c.text.startsWith('update'));
+ expect(del.text).toContain('deleted_at = now()');
+ expect(fragments().some((f) => f.text.startsWith('slug ='))).toBe(true);
+ });
+
+ it('requires avatars:delete before a bearer may soft-delete', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ extractBearerMock.mockReturnValue('tok');
+ authenticateBearerMock.mockResolvedValue({ userId: OWNER, scope: 'avatars:read', source: 'apikey' });
+ const res = mkRes();
+ await clipHandler(mkReq({ method: 'DELETE', url: `/api/mocap/clips/${CLIP}`, query: { id: CLIP } }), res);
+
+ expect(res.statusCode).toBe(403);
+ expect(parse(res).error).toBe('insufficient_scope');
+ expect(statements()).toHaveLength(0);
+ });
+});
+
+describe('route table', () => {
+ const routes = JSON.parse(
+ fs.readFileSync(path.resolve(process.cwd(), 'vercel.json'), 'utf8'),
+ ).routes;
+ const clipRoute = routes.find((r) => r.src?.startsWith('/api/mocap/clips/'));
+ const re = new RegExp(`^${clipRoute.src}$`);
+
+ it('delivers every identifier the handler knows how to answer', () => {
+ expect(re.test(`/api/mocap/clips/${CLIP}`)).toBe(true);
+ expect(re.test(`/api/mocap/clips/${CLIP.toUpperCase()}`)).toBe(true);
+ expect(re.test('/api/mocap/clips/wink')).toBe(true);
+ expect(re.test('/api/mocap/clips/my-slow-wink-2')).toBe(true);
+ });
+
+ it('does not swallow a nested path or an empty segment', () => {
+ expect(re.test('/api/mocap/clips/')).toBe(false);
+ expect(re.test('/api/mocap/clips/wink/frames')).toBe(false);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 4d69b6a23..140817b85 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1807,7 +1807,7 @@
"dest": "/api/mocap/clips"
},
{
- "src": "/api/mocap/clips/([0-9a-f-]+)",
+ "src": "/api/mocap/clips/([A-Za-z0-9][A-Za-z0-9-]{0,79})",
"dest": "/api/mocap/[id]?id=$1"
},
{