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.

fix(crews): require CSRF on crew mutations and make a crew's URL the only thing that picks the crew

nirholasad79bc26849d
diff --git a/api/_lib/crews-store.js b/api/_lib/crews-store.js
index 37b9e08f5..8bad0b669 100644
--- a/api/_lib/crews-store.js
+++ b/api/_lib/crews-store.js
@@ -227,7 +227,10 @@ export async function listCrewDirectory(limit = 24) {
// what a crew owner actually needs to know before clicking: whether the person
// is already in a crew (and which), and whether this crew already invited them.
// Both make the invite button render its true state instead of failing on click.
-export async function searchInvitees(meId, q, limit = 12) {
+// `crew` lets a caller that already resolved the searcher's crew (api/crews/
+// search.js does, to reject a crewless searcher) pass it in instead of paying for
+// the same lookup twice on a per-keystroke endpoint.
+export async function searchInvitees(meId, q, { crew = null, limit = 12 } = {}) {
const term = String(q || '').trim();
if (term.length < 2) return [];
const like = `%${term.replace(/[%_]/g, (m) => `\\${m}`)}%`;
@@ -246,7 +249,7 @@ export async function searchInvitees(meId, q, limit = 12) {
const ids = rows.map((r) => r.id);
const tags = await crewTagsFor(ids);
- const myCrew = await getMyCrew(meId);
+ const myCrew = crew || (await getMyCrew(meId));
const invited = myCrew
? new Set(
(
diff --git a/api/crews/[tag].js b/api/crews/[tag].js
index ba147d680..0345c5ddf 100644
--- a/api/crews/[tag].js
+++ b/api/crews/[tag].js
@@ -9,6 +9,29 @@ import { clientIp, limits } from '../_lib/rate-limit.js';
import { readPresence } from '../_lib/presence-store.js';
import { getCrewByTag, normalizeTag, isMissingRelation } from '../_lib/crews-store.js';
+// The crew a request is asking for. Its identity is the path segment, never the
+// query string: the router merges route params into req.query after the search
+// params (route params win), so reading req.query.tag first is what stops
+// `/api/crews/AAA?tag=BBB` from answering with BBB's roster at AAA's URL. The
+// path fallback covers callers that invoke this handler directly, and drops
+// empty segments so `/api/crews/AAA/` resolves like `/api/crews/AAA` instead of
+// reading the trailing slash as an empty tag and rejecting a valid link.
+export function crewTagFromRequest(req) {
+ const fromRoute = req?.query?.tag;
+ if (typeof fromRoute === 'string' && fromRoute) return normalizeTag(fromRoute);
+ const { pathname } = new URL(req?.url || '/', 'http://x');
+ const segments = pathname.split('/').filter(Boolean);
+ const last = segments[segments.length - 1] || '';
+ try {
+ return normalizeTag(decodeURIComponent(last));
+ } catch {
+ // A malformed %-escape has no tag in it. Failing closed matters: stripping
+ // the escape characters instead would turn `%E0%A4%A` into the plausible
+ // tag E0A4A and answer for whichever crew happens to fly it.
+ return '';
+ }
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
@@ -16,9 +39,7 @@ export default wrap(async (req, res) => {
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const url = new URL(req.url, 'http://x');
- const raw = url.searchParams.get('tag') || url.pathname.split('/').pop() || '';
- const tag = normalizeTag(decodeURIComponent(raw));
+ const tag = crewTagFromRequest(req);
if (!tag) return error(res, 400, 'bad_tag', 'invalid crew tag');
let crew;
diff --git a/api/crews/index.js b/api/crews/index.js
index caa2f4ee9..8a02ca9e8 100644
--- a/api/crews/index.js
+++ b/api/crews/index.js
@@ -9,13 +9,15 @@
// leave {} leave my crew (owner hands off / disbands)
// kick { userId } owner-only: remove a member
//
-// Validates the caller owns the account (session or bearer); the store layer
-// guards self-invite, duplicates, one-crew-per-account, and ownership. Rate-
-// limited per account. Mirrors api/friends/index.js.
+// Validates the caller owns the account (session or bearer) and, for cookie
+// callers, that the mutation carries a CSRF token; the store layer guards
+// self-invite, duplicates, one-crew-per-account, and ownership. Rate-limited
+// per account. Mirrors api/friends/index.js.
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { resolveAccount } from '../_lib/account-auth.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { readPresence, notifyMultiplayer } from '../_lib/presence-store.js';
import {
getMyCrew,
@@ -50,11 +52,28 @@ export default wrap(async (req, res) => {
return json(res, 200, { data: await crewWithPresence(me) });
}
- // POST — a crew mutation. 40 actions/min per account (shared chat limiter).
+ // POST is a crew mutation. CSRF-guard cookie-session callers (bearer exempt),
+ // exactly as api/friends/index.js guards the friend graph: founding, inviting,
+ // kicking and disbanding are state changes reachable with nothing but the
+ // session cookie the browser attaches on its own.
+ if (!(await requireCsrf(req, res, me))) return;
+
+ // 40 actions/min per account (shared chat limiter).
const rl = await limits.chatUser(me);
if (!rl.success) return rateLimited(res, rl, 'slow down');
- const body = await readJson(req).catch(() => ({}));
+ // A wrong content-type (415), an oversized body (413) and invalid JSON each
+ // carry their true status. Collapsing them into "unknown action" told an agent
+ // its action was wrong when it was the envelope, so surface what happened.
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status || 400, 'bad_body', e?.message || 'invalid JSON body');
+ }
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ return error(res, 400, 'bad_body', 'body must be a JSON object');
+ }
const action = String(body.action || '');
try {
switch (action) {
diff --git a/api/crews/search.js b/api/crews/search.js
index cd7578e76..4c040fba2 100644
--- a/api/crews/search.js
+++ b/api/crews/search.js
@@ -25,12 +25,16 @@ export default wrap(async (req, res) => {
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
const url = new URL(req.url, 'http://x');
- const q = url.searchParams.get('q') || '';
+ // A search term is a UI input, not a payload: bound it at the boundary so a
+ // pathological query string can never reach the store as a giant ILIKE pattern.
+ const q = (url.searchParams.get('q') || '').slice(0, 64);
try {
const crew = await getMyCrew(auth.userId);
if (!crew) return error(res, 400, 'no_crew', 'found or join a crew before inviting');
- return json(res, 200, { data: { results: await searchInvitees(auth.userId, q) } });
+ // Hand the crew we just resolved to the store rather than letting it look the
+ // same row up again: this endpoint runs on every keystroke of the invite box.
+ return json(res, 200, { data: { results: await searchInvitees(auth.userId, q, { crew }) } });
} catch (err) {
if (isMissingRelation(err)) return json(res, 200, { data: { results: [] } });
throw err;
diff --git a/docs/crews.md b/docs/crews.md
index 1afc3540a..1c3d7b13c 100644
--- a/docs/crews.md
+++ b/docs/crews.md
@@ -98,6 +98,16 @@ curl -s https://three.ws/api/crews \
-d '{"action":"create","tag":"NOVA","name":"Nova Collective"}'
```
+Mutations are CSRF-guarded. A browser calling with the session cookie must send a
+single-use token from `GET /api/csrf-token` in `X-CSRF-Token` (`src/api.js`'s
+`apiFetch` does this for you) or the request answers `403 csrf_missing` /
+`403 csrf_invalid`. Bearer-token callers are exempt: the token is itself the
+proof of intent, and no browser attaches it on a cross-site request.
+
+A malformed envelope answers with its own status rather than a guess at your
+intent: `415` for a non-JSON content-type, `413` for an oversized body, `400
+bad_body` for anything that is not a JSON object.
+
Error codes you should handle: `bad_tag`, `tag_taken`, `tag_reserved`,
`already_in_crew`, `target_in_crew`, `no_invite`, `not_owner`, `not_member`.
@@ -113,6 +123,11 @@ breaking an existing crew's link.
The public view of one crew: identity plus roster with presence and standees. No
auth required. `404 not_found` when no crew flies that tag.
+The tag is case-insensitive and a trailing slash is fine, so `/api/crews/NOVA`,
+`/api/crews/nova` and `/api/crews/NOVA/` are one resource. The path is the only
+thing that selects the crew: a `?tag=` on the query string is ignored, so a link
+can never answer with a different crew's roster than the one its URL names.
+
### `GET /api/crews/search?q=<term>`
Accounts to invite, for a caller who is already in a crew. Each hit carries what
diff --git a/tests/crews-endpoints.test.js b/tests/crews-endpoints.test.js
new file mode 100644
index 000000000..6c96371e0
--- /dev/null
+++ b/tests/crews-endpoints.test.js
@@ -0,0 +1,66 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { crewTagFromRequest } from '../api/crews/[tag].js';
+
+// Contract tests for the crews HTTP surface. `/api/crews/:tag` is the public,
+// shareable URL of a crew, so which crew it answers for has to be decided by the
+// path and nothing else, and a link with a trailing slash is still that link.
+
+const root = resolve(import.meta.dirname, '..');
+const read = (p) => readFileSync(resolve(root, p), 'utf8');
+
+describe('GET /api/crews/:tag tag resolution', () => {
+ it('reads the tag out of the path', () => {
+ expect(crewTagFromRequest({ url: '/api/crews/NOVA' })).toBe('NOVA');
+ });
+
+ it('resolves a link that carries a trailing slash', () => {
+ expect(crewTagFromRequest({ url: '/api/crews/NOVA/' })).toBe('NOVA');
+ });
+
+ it('upper-cases so /api/crews/nova is the same crew', () => {
+ expect(crewTagFromRequest({ url: '/api/crews/nova' })).toBe('NOVA');
+ });
+
+ it('prefers the route param, so ?tag= cannot answer for another crew', () => {
+ const req = { url: '/api/crews/NOVA?tag=AXIOM', query: { tag: 'NOVA' } };
+ expect(crewTagFromRequest(req)).toBe('NOVA');
+ });
+
+ it('rejects a tag outside the 2-6 char grammar', () => {
+ expect(crewTagFromRequest({ url: '/api/crews/N' })).toBe('');
+ expect(crewTagFromRequest({ url: '/api/crews/TOOMANYCHARS' })).toBe('');
+ });
+
+ it('rejects a malformed percent-escape instead of throwing', () => {
+ expect(crewTagFromRequest({ url: '/api/crews/%E0%A4%A' })).toBe('');
+ });
+});
+
+describe('POST /api/crews', () => {
+ it('CSRF-guards mutations for cookie callers, like the friends graph', () => {
+ const src = read('api/crews/index.js');
+ expect(src).toContain("import { requireCsrf } from '../_lib/csrf.js'");
+ expect(src).toContain('if (!(await requireCsrf(req, res, me))) return;');
+ // The guard has to sit ahead of the mutation switch, not beside it.
+ expect(src.indexOf('requireCsrf(req, res, me)')).toBeLessThan(src.indexOf("case 'create'"));
+ });
+
+ it('answers a bad envelope with its own status instead of "unknown action"', () => {
+ const src = read('api/crews/index.js');
+ expect(src).toContain("return error(res, e?.status || 400, 'bad_body'");
+ expect(src).toContain("return error(res, 400, 'bad_body', 'body must be a JSON object')");
+ });
+});
+
+describe('GET /api/crews/search', () => {
+ it('bounds the search term at the boundary', () => {
+ expect(read('api/crews/search.js')).toContain("slice(0, 64)");
+ });
+
+ it('reuses the crew it already resolved instead of looking it up twice', () => {
+ expect(read('api/crews/search.js')).toContain('searchInvitees(auth.userId, q, { crew })');
+ expect(read('api/_lib/crews-store.js')).toContain('const myCrew = crew || (await getMyCrew(meId));');
+ });
+});