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(settings): make profile saves, session revokes, and account deletion real
nirholas684713e08bfb
diff --git a/api/auth/[action].js b/api/auth/[action].jsindex 76428fe0c..24f28ae77 100644--- a/api/auth/[action].js+++ b/api/auth/[action].js@@ -219,8 +219,9 @@ async function handleRegister(req, res) {// cookie was presented but didn't resolve to a live session — the client// should clear local state and treat it as a forced logout.async function handleMe(req, res) {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET'])) return;+ if (cors(req, res, { methods: 'GET,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'DELETE'])) return;+ if (req.method === 'DELETE') return handleDeleteAccount(req, res);if (!hasSessionCookie(req)) return json(res, 200, { user: null });const user = await getSessionUser(req);if (!user) {@@ -230,6 +231,65 @@ async function handleMe(req, res) {return json(res, 200, { user });}+// ── delete account (DELETE /api/auth/me) ──────────────────────────────────────++// Soft delete, matching the model the rest of auth already assumes: every login+// path (password, SIWE, SIWS, SAML, Privy) filters on `deleted_at is null` and+// the wallet paths answer `account_deleted` rather than minting a fresh account+// for a wallet whose owner left. Rows stay for support/forensics; what changes+// is that nothing can sign in as this user and none of their content is public.+//+// Three explicit gates before anything is written: a live session, a single-use+// CSRF token, and a typed confirmation phrase in the body. CSRF alone would let+// a stray DELETE from an authenticated tab wipe an account.+const DELETE_ACCOUNT_CONFIRM = 'delete my account';++async function handleDeleteAccount(req, res) {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthenticated', 'not signed in');+ if (!(await requireCsrf(req, res, user.id))) return;+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req).catch(() => null);+ const confirm = String(body?.confirm ?? '').trim().toLowerCase();+ if (confirm !== DELETE_ACCOUNT_CONFIRM) {+ return error(res, 400, 'confirmation_required', `send {"confirm":"${DELETE_ACCOUNT_CONFIRM}"} to delete this account`);+ }++ const [current] = await sql`select username from users where id = ${user.id} and deleted_at is null limit 1`;+ if (!current) return error(res, 401, 'unauthenticated', 'not signed in');++ // Content first, identity second: if the request dies midway the account is+ // still signable-in and can be retried, rather than orphaned with its avatars+ // and embeds left serving publicly under a dead owner.+ const avatars = await sql`update avatars set deleted_at = now() where owner_id = ${user.id} and deleted_at is null`;+ const agents = await sql`update agent_identities set deleted_at = now() where user_id = ${user.id} and deleted_at is null`;+ const widgets = await sql`update widgets set deleted_at = now() where user_id = ${user.id} and deleted_at is null`;++ // The handle is released (its unique index ignores deleted_at, so keeping it+ // would hold /u/<name> hostage forever); the previous value goes to the audit+ // row so support can restore it on an appeal. Email is deliberately kept: the+ // wallet/SAML paths key their `account_deleted` answer off finding this row.+ await sql`update users set deleted_at = now(), username = null, updated_at = now() where id = ${user.id} and deleted_at is null`;+ await sql`update sessions set revoked_at = now() where user_id = ${user.id} and revoked_at is null`;+ await sql`update oauth_refresh_tokens set revoked_at = now() where user_id = ${user.id} and revoked_at is null`;++ res.setHeader('set-cookie', sessionCookie('', { clear: true }));+ const deleted = {+ avatars: avatars.count ?? 0,+ agents: agents.count ?? 0,+ widgets: widgets.count ?? 0,+ };+ logAudit({+ userId: user.id,+ action: 'delete_account',+ meta: { released_username: current.username || null, ...deleted },+ req,+ });+ return json(res, 200, { ok: true, deleted });+}+// ── profile ───────────────────────────────────────────────────────────────────const profileSchema = z.object({diff --git a/docs/authentication.md b/docs/authentication.mdindex e8cae8c9c..8a517a8aa 100644--- a/docs/authentication.md+++ b/docs/authentication.md@@ -372,6 +372,35 @@ await fetch('/api/auth/logout-everywhere', {});```+### Deleting the account++`DELETE /api/auth/me` closes an account for good. It is the endpoint behind the+Danger Zone on [/settings](https://three.ws/settings), and it has three gates:+a live session, a single-use CSRF token, and the literal confirmation phrase in+the body (case-insensitive). Miss the phrase and it answers+`400 confirmation_required` without writing anything.++```js+import { apiFetch } from '/src/api.js'; // attaches the x-csrf-token for you++const res = await apiFetch('/api/auth/me', {+ method: 'DELETE',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ confirm: 'delete my account' }),+});+const { deleted } = await res.json(); // { avatars, agents, widgets } counts+```++What it does, in order: retires the account's avatars, agent identities, and+embed widgets (so nothing of theirs keeps serving publicly), marks the user+row deleted, releases the `/u/<username>` handle back to the pool, revokes+every session and OAuth refresh token, and clears the session cookie. The row+itself is kept, which is what lets every sign-in path answer honestly+afterwards: password login fails as if the account never existed, and the+wallet/SAML paths return `account_deleted` rather than minting a fresh account+for the same wallet. The deletion is recorded in the audit log with the+released username, so support can restore a handle on an appeal.+### Coin-community sessions (Town, `/play` worlds)The coin-community surfaces (Town posting, holder passes, world gates) ride adiff --git a/docs/ux-flows/11-account-dashboard.md b/docs/ux-flows/11-account-dashboard.mdindex 82734910c..1d19eb629 100644--- a/docs/ux-flows/11-account-dashboard.md+++ b/docs/ux-flows/11-account-dashboard.md@@ -199,12 +199,12 @@ Shared auth concepts:5. **(optional) Privacy tab:** default avatar visibility select (private/unlisted/public) → **Save** → `localStorage['3dagent:default-vis']` → "Saved preference."6. **(optional) Sessions tab:** list from `GET /api/auth/sessions` (device/IP/date); "Revoke" → `DELETE /api/auth/sessions/{id}` (row removed); **Revoke all other sessions** → `DELETE /api/auth/sessions` → "All other sessions revoked." + reload.7. **(optional) Connected Accounts tab:** GitHub status `GET /api/auth/github/status`; connect → `/api/auth/github/connect?agent_id=…`; seed agent memory → `POST /api/agents/{agentId}/memory-seed`. X status `GET /api/agents/{agentId}/memory/seed/x`; connect → `/api/auth/x/connect?agent_id=…`; seed → `POST /api/agents/{agentId}/memory/seed/x`. Supports `?agent_id=` prefill.- 8. **(optional) Danger Zone tab:** click "Delete my account…" → type "delete my account" to enable → **Permanently delete** → `DELETE /api/auth/me` → clear localStorage → redirect to `/?deleted=1`.+ 8. **(optional) Danger Zone tab:** click "Delete my account…" → type "delete my account" to enable → **Permanently delete** → `DELETE /api/auth/me` with `{ confirm: 'delete my account' }` (the server refuses without the phrase, `400 confirmation_required`) → the account's avatars, agents, and widgets are retired, the `/u/<username>` handle is released, every session is revoked and the cookie cleared → clear localStorage → redirect to `/?deleted=1`. Sign-in is refused afterwards (wallet/SAML paths answer `account_deleted`).- **Decision points / branches:** Six hash-routed tabs; profile is the primary editable surface; privacy is local-only; account/sessions/connections/danger hit live APIs. Distinct from `/dashboard/settings` (which is app preferences, no identity/security fields).- **External calls / dependencies:** `GET /api/auth/me`, `PATCH /api/auth/profile`, `GET /api/auth/wallets`, `POST /api/auth/logout-everywhere`, `GET /api/auth/sessions`, `DELETE /api/auth/sessions/{id}`, `DELETE /api/auth/sessions`, `GET /api/auth/github/status`, `/api/auth/github/connect`, `POST /api/agents/{id}/memory-seed`, `GET`/`POST /api/agents/{id}/memory/seed/x`, `/api/auth/x/connect`, `DELETE /api/auth/me`.- **Success state:** "Saved!" / "Saved preference." / "All other sessions revoked." inline messages (auto-hide 4s); GitHub/X "Connected" tags; account deletion redirect to `/?deleted=1`.- **Empty / error states:** "No sessions found."; "Not connected" + connect buttons for GitHub/X; inline `.ok`/`.err` messages; delete-flow confirmation gate + error alert with button revert; "Checking…"/"Loading…" placeholders during async loads.-- **Known issues (verified against source, 2026-08-05):** the Danger Zone calls `DELETE /api/auth/me`, but the server's `me` handler only accepts GET (no delete-account endpoint exists), so deletion fails with the "contact support" alert. Separately, this page's local fetch helper attaches no `x-csrf-token`, so in production the profile **Save changes** and both session-revoke calls are rejected by the CSRF gate (`403 csrf_missing`); only `logout-everywhere` was moved to the CSRF-carrying client. The `/dashboard/*` equivalents are unaffected (they go through `src/api.js`, which auto-attaches the token).+- **Fixed 2026-08-06 (was: two broken writes):** the page ran on a local `fetch` helper that attached no `x-csrf-token`, so profile **Save changes** and both session revokes were rejected in production with `403 csrf_missing` while the UI still reported success; and the Danger Zone called a `DELETE /api/auth/me` the server did not implement (`me` was GET-only), so deletion always ended in the "contact support" alert. Every call on the page now goes through the shared CSRF-carrying client (`src/api.js`), a non-ok response surfaces as an error instead of a false success, and `DELETE /api/auth/me` is implemented (see [authentication.md](../authentication.md#deleting-the-account)).- **Step count:** 3 required (boot + profile load + save profile) (+5 optional tab flows)---diff --git a/public/settings/index.html b/public/settings/index.htmlindex 5787b2dcf..e729e9270 100644--- a/public/settings/index.html+++ b/public/settings/index.html@@ -553,23 +553,28 @@<script type="module">import { renderHeaderUser } from '/src/header-user.js';- const API = '';+ import { apiFetch as sharedFetch } from '/src/api.js';+ // Every call routes through the shared client so mutations carry a+ // single-use x-csrf-token. A local raw fetch() used to send none, and+ // the server's CSRF gate answered 403 csrf_missing to profile saves and+ // session revokes while this page still reported them as successful.async function apiFetch(path, opts = {}) {- const res = await fetch(path, { credentials: 'include', ...opts });- if (res.status === 401) {- location.href = '/login?next=' + encodeURIComponent(location.pathname + location.hash);- throw new Error('unauthenticated');- }+ const res = await sharedFetch(path, opts);+ if (!res.ok) throw await apiError(res);return res;}+ async function apiError(res) {+ const ct = res.headers.get('content-type') || '';+ const data = ct.includes('application/json') ? await res.json().catch(() => null) : null;+ return Object.assign(new Error(data?.error_description || res.statusText), { status: res.status, data });+ }+async function apiJson(path, opts = {}) {const res = await apiFetch(path, opts);const ct = res.headers.get('content-type') || '';- const data = ct.includes('application/json') ? await res.json() : null;- if (!res.ok) throw Object.assign(new Error(data?.error_description || res.statusText), { status: res.status, data });- return data;+ return ct.includes('application/json') ? await res.json() : null;}function showMsg(el, type, text) {@@ -691,8 +696,9 @@try {await apiFetch(`/api/auth/sessions/${btn.dataset.revoke}`, { method: 'DELETE' });btn.closest('.session-row').remove();- } catch {+ } catch (e) {btn.disabled = false;+ showMsg(document.getElementById('sessions-msg'), 'err', e.data?.error_description || 'Failed to revoke that session.');}});});@@ -719,16 +725,12 @@document.getElementById('sign-out-everywhere-btn').addEventListener('click', async () => {const btn = document.getElementById('sign-out-everywhere-btn');btn.disabled = true;- // Cookie-session mutation: attach the single-use double-submit CSRF- // token (this page's local apiFetch helper does not carry one).- const csrf = await fetch('/api/csrf-token', { credentials: 'include' })- .then((r) => (r.ok ? r.json() : null))- .then((j) => j?.data?.token || '')- .catch(() => '');- await fetch('/api/auth/logout-everywhere', { method: 'POST', credentials: 'include', headers: { 'x-csrf-token': csrf } }).finally(() => {- try { localStorage.removeItem('3dagent:auth-hint'); } catch {}- location.href = '/login';- });+ await apiFetch('/api/auth/logout-everywhere', { method: 'POST' })+ .catch(() => {})+ .finally(() => {+ try { localStorage.removeItem('3dagent:auth-hint'); } catch {}+ location.href = '/login';+ });});// ── Delete account ────────────────────────────────────────────@@ -750,11 +752,19 @@btn.disabled = true;btn.textContent = 'Deleting…';try {- await apiFetch('/api/auth/me', { method: 'DELETE' });+ // The typed phrase is echoed to the server, which refuses the+ // delete without it. CSRF alone shouldn't be able to wipe an+ // account from a stray request in an authenticated tab.+ await apiFetch('/api/auth/me', {+ method: 'DELETE',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ confirm: 'delete my account' }),+ });try { localStorage.removeItem('3dagent:auth-hint'); } catch {}location.href = '/?deleted=1';} catch (e) {btn.textContent = 'Permanently delete';+ btn.disabled = false;alert(e.data?.error_description || 'Failed to delete account. Please contact support.');}});diff --git a/tests/auth-delete-account.test.js b/tests/auth-delete-account.test.jsnew file mode 100644index 000000000..62fd24fe7--- /dev/null+++ b/tests/auth-delete-account.test.js@@ -0,0 +1,161 @@+// DELETE /api/auth/me: account deletion.+//+// The /settings Danger Zone shipped calling this endpoint while the `me` action+// only accepted GET, so "Permanently delete" always failed with the generic+// "contact support" alert. These tests pin the behavior it needs: three gates+// (session, CSRF, typed confirmation) before any write, a soft delete that also+// retires the account's public content, and a cleared session cookie.++import { describe, it, expect, vi, beforeEach } from 'vitest';++process.env.APP_ORIGIN = 'https://three.ws';+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';++vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));++const statements = [];+const sqlMock = vi.fn(async (strings, ...values) => {+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);+ statements.push({ text: text.replace(/\s+/g, ' ').trim(), values });+ if (text.includes('select username from users')) return [{ username: 'ada' }];+ return Object.assign([], { count: 2 });+});+vi.mock('../api/_lib/db.js', () => ({ sql: (strings, ...values) => sqlMock(strings, ...values) }));++const getSessionUser = vi.fn();+vi.mock('../api/_lib/auth.js', async () => {+ const actual = await vi.importActual('../api/_lib/auth.js');+ return {+ ...actual,+ getSessionUser: (...args) => getSessionUser(...args),+ hasSessionCookie: () => true,+ createSession: vi.fn(async () => 'sess-token'),+ destroySession: vi.fn(async () => {}),+ sessionCookie: vi.fn(() => '__Host-sid=; Path=/; Max-Age=0'),+ };+});++const requireCsrf = vi.fn(async () => true);+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: (...args) => requireCsrf(...args) }));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '127.0.0.1',+}));+const logAudit = vi.fn();+vi.mock('../api/_lib/audit.js', () => ({ logAudit: (...args) => logAudit(...args) }));+vi.mock('../api/_lib/email.js', () => ({+ sendPasswordResetEmail: vi.fn(async () => {}),+ sendVerificationEmail: vi.fn(async () => {}),+}));+vi.mock('../api/_lib/seed-default-agent.js', () => ({ seedDefaultAgent: vi.fn() }));+vi.mock('../api/_lib/usage.js', () => ({ recordEvent: vi.fn() }));+vi.mock('../api/_lib/legal.js', () => ({+ tosAcceptanceFromBody: vi.fn(() => null),+ recordTosAcceptance: vi.fn(),+ TOS_VERSION: 2,+}));++const { default: handler } = await import('../api/auth/[action].js');++function makeReq(body, headers = {}) {+ return {+ method: 'DELETE',+ url: '/api/auth/me',+ query: { action: 'me' },+ headers: { 'content-type': 'application/json', origin: 'https://three.ws', ...headers },+ socket: { remoteAddress: '127.0.0.1' },+ body: body === undefined ? undefined : JSON.stringify(body),+ };+}+function makeRes() {+ const r = { statusCode: 200, _h: {}, _b: null };+ r.setHeader = (k, v) => { r._h[k.toLowerCase()] = v; };+ r.getHeader = (k) => r._h[k.toLowerCase()];+ r.end = (b) => { r._b = b; };+ Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });+ return r;+}+const written = (fragment) => statements.filter((s) => s.text.includes(fragment));++beforeEach(() => {+ statements.length = 0;+ sqlMock.mockClear();+ logAudit.mockClear();+ requireCsrf.mockClear();+ requireCsrf.mockResolvedValue(true);+ getSessionUser.mockReset();+ getSessionUser.mockResolvedValue({ id: 'user-1', email: '[email protected]' });+});++describe('DELETE /api/auth/me', () => {+ it('rejects an anonymous caller before touching the database', async () => {+ getSessionUser.mockResolvedValue(null);+ const res = makeRes();+ await handler(makeReq({ confirm: 'delete my account' }), res);+ expect(res.statusCode).toBe(401);+ expect(written('update users set deleted_at')).toHaveLength(0);+ });++ it('rejects a request without a CSRF token', async () => {+ requireCsrf.mockImplementation(async (_req, res) => {+ res.statusCode = 403;+ res.end(JSON.stringify({ error: 'csrf_missing' }));+ return false;+ });+ const res = makeRes();+ await handler(makeReq({ confirm: 'delete my account' }), res);+ expect(res.statusCode).toBe(403);+ expect(written('update users set deleted_at')).toHaveLength(0);+ });++ it('rejects a request without the typed confirmation phrase', async () => {+ const res = makeRes();+ await handler(makeReq({}), res);+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('confirmation_required');+ expect(written('update users set deleted_at')).toHaveLength(0);+ });++ it('soft-deletes the account, retires its content, and clears the cookie', async () => {+ const res = makeRes();+ await handler(makeReq({ confirm: 'Delete My Account' }), res);++ expect(res.statusCode).toBe(200);+ expect(res.json()).toMatchObject({ ok: true, deleted: { avatars: 2, agents: 2, widgets: 2 } });+ expect(written('update avatars set deleted_at')).toHaveLength(1);+ expect(written('update agent_identities set deleted_at')).toHaveLength(1);+ expect(written('update widgets set deleted_at')).toHaveLength(1);+ expect(written('update sessions set revoked_at')).toHaveLength(1);+ expect(written('update oauth_refresh_tokens set revoked_at')).toHaveLength(1);+ expect(res.getHeader('set-cookie')).toMatch(/Max-Age=0/);+ });++ it('releases the username so the /u/ handle is not held forever', async () => {+ const res = makeRes();+ await handler(makeReq({ confirm: 'delete my account' }), res);+ const [userUpdate] = written('update users set deleted_at');+ expect(userUpdate.text).toContain('username = null');+ expect(logAudit).toHaveBeenCalledWith(expect.objectContaining({+ action: 'delete_account',+ meta: expect.objectContaining({ released_username: 'ada' }),+ }));+ });++ it('retires content before the identity so a mid-flight failure is retryable', async () => {+ const res = makeRes();+ await handler(makeReq({ confirm: 'delete my account' }), res);+ const order = statements.map((s) => s.text);+ expect(order.findIndex((t) => t.includes('update avatars set deleted_at')))+ .toBeLessThan(order.findIndex((t) => t.includes('update users set deleted_at')));+ });++ it('still answers GET /api/auth/me with the session user', async () => {+ const res = makeRes();+ const req = makeReq(undefined);+ req.method = 'GET';+ await handler(req, res);+ expect(res.statusCode).toBe(200);+ expect(res.json().user).toMatchObject({ id: 'user-1' });+ });+});