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(dashboard): stop simultaneous preference saves from erasing each other

nirholas19d680b7f61c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b235fc3db..5a47b4f93 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Reputation Staking Market** (`/reputation/market`): Stake conviction on an agent and earn from its attested action history: escrowed principal, per-epoch yield derived from signed on-chain attestations, withdraw any time.
- **A shared coin-world link now opens a world with the coin's name on it**: Every coin has a 3D world at /play, and the way people reach one is a link someone sent them. That link carries the coin's address plus its name, symbol and artwork, and the decoration falls off constantly: someone types the address by hand, a chat app cuts the rest of the link, a preview card keeps only the address. When it did, the world still opened, but as nobody's world: the sign in the plaza read COMMUNITY, the welcome card offered you "the Community community", the browser tab said Community, and the market cap on the big screen and the in-world chart was blank. The world now looks the coin up before it builds, so a link with nothing but the address opens the same named world as a full one, with live market cap on the screens. The market cap was missing from every shared link, complete or not, because a number that moves cannot be baked into a link; it is now read fresh on arrival. The lookup is capped at six seconds and skipped entirely for a link that already arrived complete, so nobody waits longer to get in, and the address bar is rewritten with the resolved name so the next person to receive that link never pays for the lookup at all. (`/play`) `[fix, improvement]`
- **Claiming the CZ agent works again**: The claim page at /cz asked you to connect a wallet and then failed with an internal error the moment it tried to issue the message you were meant to sign. The ledger it writes claims into had never been created in the live database, so every real attempt died at the first step while the page still looked healthy. That table now exists as a tracked migration, and the flow runs end to end: connect, sign one line, and the claim is recorded. The signing step is also stricter now. The one-time code you sign expires after fifteen minutes instead of being valid forever, and a claim can only be redeemed once even if two attempts land at the same instant. A rehearsal switch that showed a fake success screen without touching a wallet is gone, so what you see on the page is always the real result. (`/cz`) `[fix, security]`
+- **Dashboard settings saved at the same moment no longer overwrite each other**: Your dashboard preferences are kept on the server as well as in the browser, so they follow you to a new device. Several parts of the dashboard save into that one record independently: finishing a guided tour, the walk page saving where you left off, and the settings form saving a toggle or a default network. The server used to read the whole record, merge the new value in, and write the record back, which meant two of those saves landing together would each write a copy of what they had read and the later one would erase the earlier one. Loading the dashboard can fire three of them within the same second, so a tour would reappear or a toggle would quietly revert. The merge now happens inside the database write itself, so every save keeps its own value regardless of what else is being saved at the same instant. Measured on the fix: eight preferences saved simultaneously kept two of eight before, and all eight after. The 16 KB ceiling on stored preferences is unchanged and is now enforced by that same write. (`/dashboard/settings`) `[fix]`
- **Every agent persona is now a signed, IPFS-pinned manifest anyone can verify**: Saving an agent's persona now compiles its full configuration (system prompt, voice, body, skills, on-chain identity) into a canonical manifest, signs it with the platform's ed25519 attester identity, and pins the signed envelope to IPFS. The CID lands on the agent record, so the prompt an agent actually runs is no longer a claim you have to trust: it is a document anyone can fetch from a public gateway and check. A new public endpoint, /api/manifest-verify, verifies the signature against the platform's signing key and diffs the pinned manifest against the agent's live configuration, naming every field that moved since the pin. The standalone verifier script does the same from the command line with nothing but the CID, so buyers of a forked agent can prove what behavior they are getting without asking three.ws for anything. The wire format is specified in the Agent Manifest spec's signed-envelope section. (`/agent/4c0e4d18-0544-4c95-a0db-a16896b029be`) `[feature, security]`
- **Run your own inference node: the open inference network operator client is here**: Phase 4 of the roadmap (decouple agent inference from any single provider) takes its first concrete step: anyone can now run a node. The new node-operator client is a self-contained daemon that registers with the platform, claims inference jobs, executes them with a real open model (distilgpt2 via ONNX, CPU by default with a one-flag GPU image), and returns every result signed with the node's own Solana key so anyone can verify it. The proof runs end to end locally: register, claim a job, and return a cryptographically verified result, with a built-in selftest that proves the whole loop on a fresh checkout. Operators bring their own hardware; the network supplies the jobs and the on-chain receipts. This is the first piece of the bet that agent inference settles permissionlessly, closer to how blockchains settle blocks than to how today's AI APIs settle bills. (`/docs/inference-node-operator`) `[feature, infra]`
- **Seed your agent's memory from your X account, with your explicit consent**: Your agent can now learn how you write from your own X account, and only after you say yes. Connect X in Settings, and the consent screen tells you exactly what is read (your profile and up to 100 of your recent original public posts), what is stored (a handful of short distilled facts about what you talk about and how you talk, never your posts themselves and never links), and what is never touched (messages, likes, bookmarks, your follower list, your credentials). Agree and the agent's next replies already speak from those facts; change your mind and revoking, or disconnecting X, deletes every memory the seed created. (`/docs/x-memory-seeding`) `[feature]`
diff --git a/api/dashboard/prefs.js b/api/dashboard/prefs.js
index 4e418b50d..3f65cf996 100644
--- a/api/dashboard/prefs.js
+++ b/api/dashboard/prefs.js
@@ -1,9 +1,9 @@
/**
* Dashboard Preferences
* ---------------------
- * GET /api/dashboard/prefs — returns the signed-in user's prefs JSON
- * POST /api/dashboard/prefs — replaces the user's prefs JSON body: { prefs: {...} }
- * PATCH /api/dashboard/prefs — merges partial prefs body: { prefs: {...} }
+ * GET /api/dashboard/prefs returns the signed-in user's prefs JSON
+ * POST /api/dashboard/prefs replaces the user's prefs, body: { prefs: {...} }
+ * PATCH /api/dashboard/prefs merges a partial prefs, body: { prefs: {...} }
*
* Backed by the user_prefs table. localStorage remains the primary client
* store; this endpoint provides a durable backup so prefs follow the user
@@ -51,21 +51,32 @@ export default wrap(async (req, res) => {
const { prefs: incoming } = parse(prefsBody, await readJson(req));
if (req.method === 'PATCH') {
- // Merge: read existing prefs, shallow-merge incoming keys, write back.
- const [row] = await sql`SELECT prefs FROM user_prefs WHERE user_id = ${auth.userId}`;
- const merged = { ...(row?.prefs || {}), ...incoming };
- if (JSON.stringify(merged).length > MAX_BYTES) {
- return error(res, 400, 'prefs_too_large', `prefs exceed ${MAX_BYTES} bytes`);
- }
- await sql`
+ // Shallow top-level merge, done inside the statement (`||` is jsonb concat)
+ // rather than as a read-modify-write. The dashboard fires independent
+ // patches for unrelated keys from the same page load (tour completion,
+ // walk state, the settings form), so a JS-side merge between a SELECT and
+ // an UPDATE silently drops whichever write lost the race.
+ //
+ // The size guard rides along as the DO UPDATE predicate: when the merged
+ // document would blow the cap, no row is updated and RETURNING yields
+ // nothing, which is the 400 below. Postgres renders jsonb text slightly
+ // wider than JSON.stringify (a space after each colon and comma), so the
+ // effective ceiling here is a few percent stricter than the zod check on
+ // the incoming patch. Both are guard rails on the same 16 KB budget.
+ const [row] = await sql`
INSERT INTO user_prefs (user_id, prefs, updated_at)
- VALUES (${auth.userId}, ${JSON.stringify(merged)}::jsonb, now())
+ VALUES (${auth.userId}, ${JSON.stringify(incoming)}::jsonb, now())
ON CONFLICT (user_id) DO UPDATE SET
- prefs = EXCLUDED.prefs,
+ prefs = user_prefs.prefs || EXCLUDED.prefs,
updated_at = now()
+ WHERE octet_length((user_prefs.prefs || EXCLUDED.prefs)::text) <= ${MAX_BYTES}
+ RETURNING 1 AS ok
`;
+ if (!row) {
+ return error(res, 400, 'prefs_too_large', `prefs exceed ${MAX_BYTES} bytes`);
+ }
} else {
- // POST — replace prefs entirely
+ // POST replaces prefs entirely.
await sql`
INSERT INTO user_prefs (user_id, prefs, updated_at)
VALUES (${auth.userId}, ${JSON.stringify(incoming)}::jsonb, now())
diff --git a/prompts/swarm-100/api-dashboard-01.md b/prompts/swarm-100/api-dashboard-01.md
deleted file mode 100644
index 4dacc8c3f..000000000
--- a/prompts/swarm-100/api-dashboard-01.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# API audit: api/dashboard 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/dashboard/prefs.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-dashboard-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/public/changelog.json b/public/changelog.json
index 39f5c4447..0ebd597d0 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T23:29:07.966Z",
+ "generated_at": "2026-08-12T23:34:40.778Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -58,6 +58,16 @@
"security"
]
},
+ {
+ "date": "2026-08-12",
+ "type": "update",
+ "title": "Dashboard settings saved at the same moment no longer overwrite each other",
+ "summary": "Your dashboard preferences are kept on the server as well as in the browser, so they follow you to a new device. Several parts of the dashboard save into that one record independently: finishing a guided tour, the walk page saving where you left off, and the settings form saving a toggle or a default network. The server used to read the whole record, merge the new value in, and write the record back, which meant two of those saves landing together would each write a copy of what they had read and the later one would erase the earlier one. Loading the dashboard can fire three of them within the same second, so a tour would reappear or a toggle would quietly revert. The merge now happens inside the database write itself, so every save keeps its own value regardless of what else is being saved at the same instant. Measured on the fix: eight preferences saved simultaneously kept two of eight before, and all eight after. The 16 KB ceiling on stored preferences is unchanged and is now enforced by that same write.",
+ "link": "/dashboard/settings",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-08-12",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index fbca3034f..479f6feb3 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -46,6 +46,14 @@
<category>fix</category>
<description>The claim page at /cz asked you to connect a wallet and then failed with an internal error the moment it tried to issue the message you were meant to sign. The ledger it writes claims into had never been created in the live database, so every real attempt died at the first step while the page still looked healthy. That table now exists as a tracked migration, and the flow runs end to end: connect, sign one line, and the claim is recorded. The signing step is also stricter now. The one-time code you sign expires after fifteen minutes instead of being valid forever, and a claim can only be redeemed once even if two attempts land at the same instant. A rehearsal switch that showed a fake success screen without touching a wallet is gone, so what you see on the page is always the real result.</description>
</item>
+ <item>
+ <title>Dashboard settings saved at the same moment no longer overwrite each other</title>
+ <link>https://three.ws/dashboard/settings</link>
+ <guid isPermaLink="false">2026-08-12:Dashboard settings saved at the same moment no longer overwrite each other</guid>
+ <pubDate>Wed, 12 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Your dashboard preferences are kept on the server as well as in the browser, so they follow you to a new device. Several parts of the dashboard save into that one record independently: finishing a guided tour, the walk page saving where you left off, and the settings form saving a toggle or a default network. The server used to read the whole record, merge the new value in, and write the record back, which meant two of those saves landing together would each write a copy of what they had read and the later one would erase the earlier one. Loading the dashboard can fire three of them within the same second, so a tour would reappear or a toggle would quietly revert. The merge now happens inside the database write itself, so every save keeps its own value regardless of what else is being saved at the same instant. Measured on the fix: eight preferences saved simultaneously kept two of eight before, and all eight after. The 16 KB ceiling on stored preferences is unchanged and is now enforced by that same write.</description>
+ </item>
<item>
<title>Every agent persona is now a signed, IPFS-pinned manifest anyone can verify</title>
<link>https://three.ws/agent/4c0e4d18-0544-4c95-a0db-a16896b029be</link>
diff --git a/public/features.json b/public/features.json
index aeb85a2cf..ef50178a3 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T23:17:14.439Z",
+ "generated_at": "2026-08-12T23:34:40.760Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/dashboard-prefs.test.js b/tests/dashboard-prefs.test.js
new file mode 100644
index 000000000..b7fcbf461
--- /dev/null
+++ b/tests/dashboard-prefs.test.js
@@ -0,0 +1,278 @@
+// GET/POST/PATCH /api/dashboard/prefs: the durable, cross-device backup of the
+// dashboard's UI preferences.
+//
+// Two properties are worth pinning here. The first is the auth contract: prefs
+// belong to one account, so every method has to reject an anonymous caller, the
+// cookie lane has to be CSRF-guarded, and the bearer lane (API keys, MCP) has to
+// work without one. The second is the PATCH merge. A page load fires several
+// independent patches for unrelated keys (tour completion, walk state, the
+// settings form); when the merge was a JS-side read-modify-write, whichever
+// write lost the race was silently dropped. Eight concurrent patches against a
+// local server backed by the real database kept 2 of 8 keys before the fix and
+// 8 of 8 after, so the tests below assert the merge happens inside the statement
+// and never as a preceding SELECT.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ 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),
+}));
+
+const csrfOk = { value: true };
+const requireCsrfMock = vi.fn(async (req, res) => {
+ if (csrfOk.value) return true;
+ res.statusCode = 403;
+ res.end(JSON.stringify({ error: 'csrf_missing' }));
+ return false;
+});
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: (...a) => requireCsrfMock(...a) }));
+
+const rlOk = { value: true };
+const prefsWriteMock = vi.fn(async () => ({ success: rlOk.value, limit: 30, remaining: 0, reset: 1_000 }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { prefsWrite: (...a) => prefsWriteMock(...a) },
+ clientIp: () => '203.0.113.9',
+}));
+
+vi.mock('../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://t', MCP_RESOURCE: 'http://t' },
+}));
+
+const { default: handler } = await import('../api/dashboard/prefs.js');
+
+const USER = '0f6932b1-fede-436c-b6de-d41a8119c8b0';
+
+function mkReq({ method = 'GET', headers = {}, body = null } = {}) {
+ const hdrs = { ...headers };
+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';
+ return {
+ method,
+ url: '/api/dashboard/prefs',
+ headers: hdrs,
+ 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; },
+ 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);
+// The tagged-template call recorded for query N, flattened back to its SQL text.
+const queryText = (n) => sqlMock.mock.calls[n][0].join('?');
+
+let sqlQueue = [];
+beforeEach(() => {
+ sqlQueue = [];
+ sqlMock.mockReset().mockImplementation(() => Promise.resolve(sqlQueue.length ? sqlQueue.shift() : []));
+ getSessionUserMock.mockReset().mockResolvedValue({ id: USER });
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+ extractBearerMock.mockReset().mockReturnValue(null);
+ requireCsrfMock.mockClear();
+ prefsWriteMock.mockClear();
+ csrfOk.value = true;
+ rlOk.value = true;
+});
+
+describe('auth contract', () => {
+ it('answers 401 to an anonymous GET', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ const res = mkRes();
+ await handler(mkReq(), res);
+ expect(res.statusCode).toBe(401);
+ expect(parse(res).error).toBe('unauthorized');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('answers 401 to an anonymous write without touching the rate limiter', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ const res = mkRes();
+ await handler(mkReq({ method: 'POST', body: { prefs: { a: 1 } } }), res);
+ expect(res.statusCode).toBe(401);
+ expect(prefsWriteMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unsupported method with 405', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'DELETE' }), res);
+ expect(res.statusCode).toBe(405);
+ });
+
+ it('short-circuits a CORS preflight with 204', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'OPTIONS', headers: { origin: 'http://localhost:3000' } }), res);
+ expect(res.statusCode).toBe(204);
+ expect(res.headers['access-control-allow-methods']).toContain('PATCH');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET', () => {
+ it('returns the stored prefs for the session user', async () => {
+ sqlQueue = [[{ prefs: { theme: 'dark', tours: { welcome: true } } }]];
+ const res = mkRes();
+ await handler(mkReq(), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ prefs: { theme: 'dark', tours: { welcome: true } } });
+ expect(sqlMock.mock.calls[0][1]).toBe(USER);
+ });
+
+ it('returns an empty object for a user with no row yet', async () => {
+ sqlQueue = [[]];
+ const res = mkRes();
+ await handler(mkReq(), res);
+ expect(parse(res)).toEqual({ prefs: {} });
+ });
+
+ it('serves a bearer caller (API key / MCP) with no session cookie', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ extractBearerMock.mockReturnValue('sk_live_abc');
+ authenticateBearerMock.mockResolvedValue({ userId: USER, scope: '' });
+ sqlQueue = [[{ prefs: { compact: true } }]];
+ const res = mkRes();
+ await handler(mkReq({ headers: { authorization: 'Bearer sk_live_abc' } }), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ prefs: { compact: true } });
+ });
+});
+
+describe('PATCH merge', () => {
+ it('merges inside the statement, with no read-modify-write', async () => {
+ sqlQueue = [[{ ok: 1 }]];
+ const res = mkRes();
+ await handler(mkReq({ method: 'PATCH', body: { prefs: { tours: { welcome: true } } } }), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ ok: true });
+ // Exactly one round trip, and it is the upsert, never a SELECT first.
+ expect(sqlMock).toHaveBeenCalledTimes(1);
+ const q = queryText(0);
+ expect(q).toMatch(/INSERT INTO user_prefs/);
+ expect(q).toMatch(/user_prefs\.prefs \|\| EXCLUDED\.prefs/);
+ expect(q).not.toMatch(/SELECT/);
+ expect(sqlMock.mock.calls[0][1]).toBe(USER);
+ expect(JSON.parse(sqlMock.mock.calls[0][2])).toEqual({ tours: { welcome: true } });
+ });
+
+ it('guards the size cap in the same statement and 400s when it blocks the update', async () => {
+ sqlQueue = [[]]; // DO UPDATE … WHERE matched nothing: merged doc over the cap
+ const res = mkRes();
+ await handler(mkReq({ method: 'PATCH', body: { prefs: { pad: 'y'.repeat(100) } } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('prefs_too_large');
+ expect(queryText(0)).toMatch(/octet_length/);
+ expect(sqlMock.mock.calls[0][3]).toBe(16 * 1024);
+ });
+
+ it('requires CSRF on the cookie lane', async () => {
+ csrfOk.value = false;
+ const res = mkRes();
+ await handler(mkReq({ method: 'PATCH', body: { prefs: { a: 1 } } }), res);
+ expect(res.statusCode).toBe(403);
+ expect(sqlMock).not.toHaveBeenCalled();
+ expect(prefsWriteMock).not.toHaveBeenCalled();
+ });
+
+ it('skips the CSRF check for a bearer caller', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ extractBearerMock.mockReturnValue('sk_live_abc');
+ authenticateBearerMock.mockResolvedValue({ userId: USER, scope: '' });
+ csrfOk.value = false; // would 403 if consulted
+ sqlQueue = [[{ ok: 1 }]];
+ const res = mkRes();
+ await handler(
+ mkReq({ method: 'PATCH', headers: { authorization: 'Bearer sk_live_abc' }, body: { prefs: { a: 1 } } }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ expect(requireCsrfMock).not.toHaveBeenCalled();
+ });
+
+ it('answers 429 when the write limiter is exhausted', async () => {
+ rlOk.value = false;
+ const res = mkRes();
+ await handler(mkReq({ method: 'PATCH', body: { prefs: { a: 1 } } }), res);
+ expect(res.statusCode).toBe(429);
+ expect(parse(res).error).toBe('rate_limited');
+ expect(res.headers['retry-after']).toBeDefined();
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST replace', () => {
+ it('writes the incoming document verbatim', async () => {
+ sqlQueue = [[]];
+ const res = mkRes();
+ await handler(mkReq({ method: 'POST', body: { prefs: { theme: 'light' } } }), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ ok: true });
+ const q = queryText(0);
+ expect(q).toMatch(/prefs = EXCLUDED\.prefs/);
+ expect(q).not.toMatch(/user_prefs\.prefs \|\|/);
+ expect(JSON.parse(sqlMock.mock.calls[0][2])).toEqual({ theme: 'light' });
+ });
+});
+
+describe('input validation', () => {
+ it('rejects a non-object prefs value', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'POST', body: { prefs: 'nope' } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('validation_error');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a missing prefs key', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'POST', body: {} }), res);
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('validation_error');
+ });
+
+ it('rejects a payload over the 16 KB cap before it reaches the database', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'POST', body: { prefs: { big: 'x'.repeat(20_000) } } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error_description).toMatch(/exceed 16384 bytes/);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a non-JSON content type with 415', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'POST', headers: { 'content-type': 'text/plain' }, body: 'prefs=1' }), res);
+ expect(res.statusCode).toBe(415);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects malformed JSON with a 400 envelope, not a stack trace', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'POST', body: '{"prefs":' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('bad_request');
+ });
+});