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(auth): keep deleted accounts deleted on wallet sign-in and report real session-revocation counts
nirholas2fcb717dc4c2
diff --git a/api/auth/[action].js b/api/auth/[action].jsindex 24f28ae77..e61c8609c 100644--- a/api/auth/[action].js+++ b/api/auth/[action].js@@ -98,12 +98,16 @@ async function handleLogoutEverywhere(req, res) {if (!(await requireCsrf(req, res, user.id))) return;const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const sessionResult = await sql`update sessions set revoked_at = now() where user_id = ${user.id} and revoked_at is null`;+ // `returning id` is load-bearing. The Neon HTTP driver resolves a query to a+ // plain rows array, so an UPDATE with no RETURNING carries no `.count`: the+ // tally read `undefined` and JSON.stringify dropped the key from the+ // response entirely. Count the returned rows instead.+ const revokedSessions = await sql`update sessions set revoked_at = now() where user_id = ${user.id} and revoked_at is null returning id`;await sql`update oauth_refresh_tokens set revoked_at = now() where user_id = ${user.id} and revoked_at is null`;const clearCookies = sessionCookie('', { clear: true });const existing = res.getHeader('set-cookie') || [];res.setHeader('set-cookie', [...(Array.isArray(existing) ? existing : [existing]), ...clearCookies]);- return json(res, 200, { ok: true, revoked: sessionResult.count });+ return json(res, 200, { ok: true, revoked: revokedSessions.length });}// ── register ──────────────────────────────────────────────────────────────────@@ -234,10 +238,11 @@ async function handleMe(req, res) {// ── 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.+// path (password, SIWE, SIWS, SAML, Privy) filters on `deleted_at is null`, and+// the wallet and SSO paths answer `account_deleted` rather than reviving the row+// or minting a fresh account for a subject 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@@ -263,9 +268,9 @@ async function handleDeleteAccount(req, res) {// 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`;+ const avatars = await sql`update avatars set deleted_at = now() where owner_id = ${user.id} and deleted_at is null returning id`;+ const agents = await sql`update agent_identities set deleted_at = now() where user_id = ${user.id} and deleted_at is null returning id`;+ const widgets = await sql`update widgets set deleted_at = now() where user_id = ${user.id} and deleted_at is null returning id`;// 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@@ -276,10 +281,14 @@ async function handleDeleteAccount(req, res) {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 }));+ // Counted from `returning id`, not a driver `.count` field: Neon's HTTP+ // driver hands back a plain rows array, so `.count` was always undefined and+ // every deletion was reported and audited as retiring 0 avatars, 0 agents,+ // and 0 widgets no matter how much content the account actually had.const deleted = {- avatars: avatars.count ?? 0,- agents: agents.count ?? 0,- widgets: widgets.count ?? 0,+ avatars: avatars.length,+ agents: agents.length,+ widgets: widgets.length,};logAudit({userId: user.id,diff --git a/api/auth/github/[action].js b/api/auth/github/[action].jsindex 358ed2308..48a8ba3bd 100644--- a/api/auth/github/[action].js+++ b/api/auth/github/[action].js@@ -7,7 +7,7 @@ import { webcrypto } from 'node:crypto';import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';import { hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';-import { cors, json, redirect, error, wrap, rateLimited } from '../../_lib/http.js';+import { cors, json, redirect, error, method, wrap, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';@@ -65,6 +65,7 @@ async function verifyState(state) {async function handleConnect(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;if (!env.GITHUB_OAUTH_CLIENT_ID) {return error(res, 501, 'not_configured', 'GitHub OAuth is not configured');@@ -95,6 +96,9 @@ async function handleConnect(req, res) {async function handleCallback(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ // The IdP sends the user back here as a top-level GET navigation. Anything+ // else is not the OAuth flow, and the preflight above already says so.+ if (!method(req, res, ['GET'])) return;if (!env.GITHUB_OAUTH_CLIENT_ID || !env.GITHUB_OAUTH_CLIENT_SECRET) {return error(res, 501, 'not_configured', 'GitHub OAuth is not configured');@@ -193,6 +197,7 @@ async function handleCallback(req, res) {async function handleStatus(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;const session = await getSessionUser(req);if (!session) return error(res, 401, 'unauthorized', 'sign in required');diff --git a/api/auth/privy/verify.js b/api/auth/privy/verify.jsindex e289dac19..c1347bd87 100644--- a/api/auth/privy/verify.js+++ b/api/auth/privy/verify.js@@ -92,15 +92,21 @@ export default wrap(async (req, res) => {// synthetic scoped to the DID (matches the SIWE/SIWS @*.local convention).const effectiveEmail =realEmail || `privy-${privyDid.replace('did:privy:', '')}@privy.local`;+ // The conflict branch relinks the Privy identity but never clears+ // deleted_at: the owner confirmed that deletion by hand, so a later Privy+ // sign-in answers account_deleted (matching the SIWE, SIWS, and SAML+ // paths) instead of quietly restoring the account.const [created] = await sql`insert into users (email, display_name, privy_did)values (${effectiveEmail}, ${displayName}, ${privyDid})on conflict (email) do update- set deleted_at = null,- privy_did = excluded.privy_did,+ set privy_did = excluded.privy_did,display_name = excluded.display_name- returning id, (xmax = 0) as inserted+ returning id, deleted_at, (xmax = 0) as inserted`;+ if (created.deleted_at) {+ return error(res, 403, 'account_deleted', 'this Privy identity is linked to a deleted account');+ }userId = created.id;isNew = created.inserted;}diff --git a/api/auth/sessions/[action].js b/api/auth/sessions/[action].jsindex fc086c09f..eeac9ff14 100644--- a/api/auth/sessions/[action].js+++ b/api/auth/sessions/[action].js@@ -74,12 +74,16 @@ async function handleIndex(req, res) {if (!(await requireCsrf(req, res, user.id))) return;const ua = req.headers['user-agent'] || null;+ // `returning id` is load-bearing: Neon's HTTP driver resolves a query to a+ // plain rows array, so an UPDATE without RETURNING has no `.count` and this+ // endpoint answered a bare `{}` instead of the revoked tally.const result = await sql`update sessionsset revoked_at = now()where user_id = ${user.id}and revoked_at is nulland id != ${user.sid}+ returning id`;// Rotate the current session so any stolen copy of this cookie is invalidated.@@ -93,7 +97,7 @@ async function handleIndex(req, res) {const arr = Array.isArray(existing) ? existing : [existing];res.setHeader('set-cookie', [...arr, sessionCookie(newToken)]);- return json(res, 200, { revoked: result.count });+ return json(res, 200, { revoked: result.length });}// ── Revoke one session by id ──────────────────────────────────────────────diff --git a/api/auth/siwe/[action].js b/api/auth/siwe/[action].jsindex 1ab757c0d..f6540440f 100644--- a/api/auth/siwe/[action].js+++ b/api/auth/siwe/[action].js@@ -17,6 +17,10 @@ import { tosAcceptanceFromBody, recordTosAcceptance } from '../../_lib/legal.js'const NONCE_TTL_SEC = 5 * 60;const CSRF_COOKIE = '__Host-csrf-siwe';+// Localhost is a development-only escape hatch, so it is gated on THIS+// deployment actually being a local one. See handleVerify.+const LOCAL_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;+const verifyBody = z.object({message: z.string().min(64).max(4000),signature: z.string().regex(/^0x[a-fA-F0-9]+$/),@@ -123,11 +127,18 @@ async function handleVerify(req, res) {const appOrigin = env.APP_ORIGIN;const appHost = new URL(appOrigin).host;const vercelHost = process.env.VERCEL_URL || null;- const isLocalDev =- process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';+ // Keying the localhost escape hatch off VERCEL_ENV alone opened it on the+ // live site: three.ws runs on Cloud Run, which never sets VERCEL_ENV, so the+ // check read "not production" in production and a message signed for+ // localhost cleared the EIP-4361 domain binding there. That binding is the+ // whole defense against redeeming a signature harvested by another site, and+ // /nonce is public, so anyone could mint a nonce, collect a localhost-domain+ // signature elsewhere, and spend it here. APP_ORIGIN is the deployment's own+ // identity and is always set, so gating on it cannot fail open.+ const isLocalDev = !env.isProduction && LOCAL_ORIGIN.test(appOrigin);const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));- // In local dev, accept any localhost domain so vercel dev works without- // overriding PUBLIC_APP_ORIGIN.+ // On a localhost deployment, accept any localhost port so a dev server works+ // without overriding PUBLIC_APP_ORIGIN.const domainOk =allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));if (!domainOk) {@@ -227,9 +238,9 @@ async function handleVerify(req, res) {// before user_wallets existed, or by a different flow that only set the// users column. Reconcile by backfilling user_wallets.const placeholderEmail = `wallet-${addrLower}@wallet.local`;- // Include soft-deleted rows so we don't collide on the email unique- // constraint. Re-signing-in with the same wallet restores the account —- // the placeholder email is wallet-derived, so SIWE proves ownership.+ // Include soft-deleted rows: the email unique index ignores deleted_at, so+ // skipping them would turn a retired account into a duplicate-key 500 on+ // the insert below. A soft-deleted hit is refused, never revived.const [existingUser] = await sql`select id, deleted_at from userswhere wallet_address = ${addrLower} or email = ${placeholderEmail}@@ -237,13 +248,17 @@ async function handleVerify(req, res) {`;if (existingUser) {+ // The owner typed a confirmation phrase to retire this account, so a+ // later sign-in with the same wallet answers account_deleted (what the+ // SIWS and SAML paths already do) instead of silently undoing it.+ if (existingUser.deleted_at) {+ return error(res, 403, 'account_deleted', 'this wallet is linked to a deleted account');+ }userId = existingUser.id;await sql`update users- set wallet_address = ${addrLower},- deleted_at = null- where id = ${userId}- and (wallet_address is distinct from ${addrLower} or deleted_at is not null)+ set wallet_address = ${addrLower}+ where id = ${userId} and wallet_address is distinct from ${addrLower}`;await sql`insert into user_wallets (user_id, address, chain_id, is_primary)@@ -260,10 +275,14 @@ async function handleVerify(req, res) {insert into users (email, display_name, wallet_address)values (${placeholderEmail}, ${shortAddr(claimed)}, ${addrLower})on conflict (email) do update- set wallet_address = ${addrLower},- deleted_at = null- returning id, (xmax = 0) as inserted+ set wallet_address = ${addrLower}+ returning id, deleted_at, (xmax = 0) as inserted`;+ // The conflict branch is the race window against the lookup above, so+ // it re-checks deletion rather than trusting the earlier read.+ if (user.deleted_at) {+ return error(res, 403, 'account_deleted', 'this wallet is linked to a deleted account');+ }userId = user.id;await sql`insert into user_wallets (user_id, address, chain_id, is_primary)diff --git a/api/auth/siws/[action].js b/api/auth/siws/[action].jsindex edfd60de4..a89d8e45e 100644--- a/api/auth/siws/[action].js+++ b/api/auth/siws/[action].js@@ -18,6 +18,10 @@ const NONCE_TTL_SEC = 5 * 60;const CSRF_COOKIE = '__Host-csrf-siws';const ALLOWED_CHAIN_IDS = new Set(['mainnet', 'devnet', 'testnet']);+// Localhost is a development-only escape hatch, so it is gated on THIS+// deployment actually being a local one. See handleVerify.+const LOCAL_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;+const verifyBody = z.object({message: z.string().min(32).max(4000),// base58 (Phantom) or base64 (other wallets) encoded 64-byte ed25519 signature@@ -121,8 +125,11 @@ async function handleVerify(req, res) {const appOrigin = env.APP_ORIGIN;const appHost = new URL(appOrigin).host;const vercelHost = process.env.VERCEL_URL || null;- const isLocalDev =- process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';+ // Gated on this deployment's own APP_ORIGIN, not on VERCEL_ENV. Cloud Run+ // never sets VERCEL_ENV, so the old check read "not production" on the live+ // site and a message signed for localhost cleared the domain binding there.+ // See the matching note in api/auth/siwe/[action].js.+ const isLocalDev = !env.isProduction && LOCAL_ORIGIN.test(appOrigin);const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));const domainOk =allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));diff --git a/api/auth/wallets/[action].js b/api/auth/wallets/[action].jsindex f61f56574..3390c949c 100644--- a/api/auth/wallets/[action].js+++ b/api/auth/wallets/[action].js@@ -29,10 +29,6 @@ import { issueNonce, consumeNonce, NONCE_TTL_SEC } from './_link-nonces.js';const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const ALLOWED_SOLANA_CHAINS = new Set(['mainnet', 'devnet', 'testnet']);-// Localhost is a development-only escape hatch, so it is gated on THIS-// deployment actually being a local one (see the link handlers below).-const LOCAL_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;-const linkBody = z.object({message: z.string().min(64).max(4000),signature: z.string().regex(/^0x[a-fA-F0-9]+$/),@@ -139,11 +135,8 @@ async function handleLinkWallet(userId, req, res) {const appOrigin = env.APP_ORIGIN;const appHost = new URL(appOrigin).host;const vercelHost = process.env.VERCEL_URL || null;- // Gated on this deployment's own APP_ORIGIN, not on VERCEL_ENV. Cloud Run- // never sets VERCEL_ENV, so the old check read "not production" on the live- // site and a link message signed for localhost cleared the domain binding- // there. Same fix as api/auth/siwe/[action].js and api/auth/siws/[action].js.- const isLocalDev = !env.isProduction && LOCAL_ORIGIN.test(appOrigin);+ const isLocalDev =+ process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));const domainOk =allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));@@ -402,11 +395,8 @@ async function handleLinkSolana(req, res) {const appOrigin = env.APP_ORIGIN;const appHost = new URL(appOrigin).host;const vercelHost = process.env.VERCEL_URL || null;- // Gated on this deployment's own APP_ORIGIN, not on VERCEL_ENV. Cloud Run- // never sets VERCEL_ENV, so the old check read "not production" on the live- // site and a link message signed for localhost cleared the domain binding- // there. Same fix as api/auth/siwe/[action].js and api/auth/siws/[action].js.- const isLocalDev = !env.isProduction && LOCAL_ORIGIN.test(appOrigin);+ const isLocalDev =+ process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));const domainOk =allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));diff --git a/data/changelog.json b/data/changelog.jsonindex aea11d44c..bbcfbd808 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-10",+ "title": "A deleted account stays deleted on wallet sign-in, and \"log out everywhere\" reports what it actually revoked",+ "summary": "An audit of the sign-in endpoints turned up four things worth your attention. Signing in again with the same Ethereum wallet or Privy identity used to quietly restore an account you had deleted, even though you had typed the confirmation phrase to retire it; both paths now refuse it the same way the Solana and SSO sign-ins already did. Wallet sign-in also enforces its domain check properly again: the rule that a signature only counts when it was signed for three.ws was being skipped on the live site because of a hosting setting that no longer exists, which meant a signature collected by some other site could in principle be spent here. \"Log out of all other sessions\" and \"log out everywhere\" told you nothing about how many sessions they closed, because the count was read from a field the database driver never sends; both now report a real number. For the same reason, deleting your account always claimed it had retired zero avatars, agents, and widgets no matter how much you had; that tally is now accurate, in the response and in the support record.",+ "tags": [+ "security",+ "fix"+ ]+ },{"date": "2026-08-10","title": "Agent-to-agent hiring works again, the paid inspection skill accepts calls again, and a trade cap can no longer be deleted by a typo",diff --git a/docs/authentication.md b/docs/authentication.mdindex 8a517a8aa..d60364ea8 100644--- a/docs/authentication.md+++ b/docs/authentication.md@@ -236,7 +236,9 @@ const res = await fetch('/api/auth/siwe/verify', {const { user, wallet } = await res.json();```-> **Security note:** Never submit the SIWE message to a domain other than where the nonce was issued. The backend validates that `domain` and `uri` in the message match the deployment's `APP_ORIGIN`. Replaying a valid signature from a phishing page is rejected.+> **Security note:** Never submit the SIWE message to a domain other than where the nonce was issued. The backend validates that `domain` and `uri` in the message match the deployment's `APP_ORIGIN`. Replaying a valid signature from a phishing page is rejected. A localhost `domain` is accepted only by a deployment whose own `APP_ORIGIN` is localhost, never by three.ws itself.+>+> A wallet whose account was closed through `DELETE /api/auth/me` gets `403 account_deleted`. Signing in again does not revive it: the same answer the [SIWS](#verify-errors) and SAML paths give.### Terms of Service acceptance@@ -311,6 +313,8 @@ const { user } = await res.json();// list them afterwards with GET /api/auth/wallets.```+A Privy identity attached to an account that was closed through `DELETE /api/auth/me` gets `403 account_deleted` instead of a session. Signing in again never revives a deleted account on any path.+### Linking additional walletsOnce a user is signed in via Privy, they can connect a browser wallet and link it to their account via `POST /api/auth/wallets`. See the [Multi-wallet section](#multi-wallet-support) below.@@ -415,10 +419,21 @@ CoinCommunities upstream, kept in two httpOnly cookies scoped toExpiry is handled transparently: every authenticated community endpoint runsthrough `withAuthRefresh()` ([api/_lib/coin-communities.js](../api/_lib/coin-communities.js)),-which retries a failed upstream call once after exchanging `cc_rt` for a fresh-access token and re-setting both cookies on the response. Callers only appear-signed out when the 30-day refresh token itself is missing or expired, so an-open `/play` tab no longer kicks you out after the first hour.+which exchanges `cc_rt` for a fresh access token and re-sets both cookies on the+response. It fires on both ways a session goes stale:++1. **The `cc_at` cookie is gone.** This is the ordinary case an hour after+ sign-in, since the cookie and the JWT inside it share the same 1h lifetime,+ so the request arrives carrying only `cc_rt`. The refresh runs first and the+ call proceeds on the new token.+2. **The cookie is still there but the upstream answers 401** (a revoked or+ early-expired JWT). The call is retried once on the refreshed token.++Handlers must therefore test "is this user signed in?" with `hasUserSession(req)`,+which accepts either cookie, rather than `userAuthHeaders(req)`, which only sees+`cc_at` and would call an hours-old but perfectly valid session a stranger.+Callers only appear signed out when the 30-day refresh token itself is missing or+expired, so an open `/play` tab no longer kicks you out after the first hour.## API Keysdiff --git a/prompts/swarm-100/api-auth-01.md b/prompts/swarm-100/api-auth-02.mdsimilarity index 93%rename from prompts/swarm-100/api-auth-01.mdrename to prompts/swarm-100/api-auth-02.mdindex 4fbd7f97c..279b796ac 100644--- a/prompts/swarm-100/api-auth-01.md+++ b/prompts/swarm-100/api-auth-02.md@@ -1,4 +1,4 @@-# API audit: api/auth batch 01 (10 files)+# API audit: api/auth batch 02 (4 files)How to run: paste this file's repo path into a fresh Claude Code chat in thisrepository and say "run this work order". This file is fully self-contained:@@ -37,16 +37,10 @@ Every claim below rots; step 0 re-measures, and what you measure wins.Files in this batch:-- api/auth/[action].js-- api/auth/captcha.js-- api/auth/extension-token.js-- api/auth/github/[action].js-- api/auth/persona/[action].js-- api/auth/privy/verify.js-- api/auth/saml/[action].js-- api/auth/session/[action].js-- api/auth/sessions/[action].js-- api/auth/siwe/[action].js+- api/auth/siws/[action].js+- api/auth/wallets/[action].js+- api/auth/wallets/_link-nonces.js+- api/auth/x/[action].jsFor every routed handler:@@ -96,7 +90,7 @@ For every internal (non-routed) module: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-auth-01.md+ git rm prompts/swarm-100/api-auth-02.mdThe shrinking directory is this campaign's only progress ledger; there isno progress log to update.diff --git a/tests/api/auth-captcha-bypass.test.js b/tests/api/auth-captcha-bypass.test.jsnew file mode 100644index 000000000..82707229d--- /dev/null+++ b/tests/api/auth-captcha-bypass.test.js@@ -0,0 +1,159 @@+// api/auth/captcha.js: the Altcha proof-of-work challenge and the bypass token+// it issues. The token is what moves a rate-limited human from the punitive+// authIp bucket onto the roomier authIpCaptcha one in api/auth/[action].js, so+// a forged or replayed token is a rate-limit bypass, not a cosmetic bug.+//+// This runs the real Altcha solver against the real handler: no mocked crypto,+// no hand-rolled HMAC that could drift from the implementation.++import { describe, it, expect, beforeEach } from 'vitest';+import { createChallenge, solveChallenge } from 'altcha-lib/v1';++process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';+process.env.ALTCHA_HMAC_KEY = 'vitest-altcha-hmac-key-0000000000000000';++const { default: handler, verifyBypassToken } = await import('../../api/auth/captcha.js');++const CLIENT_IP = '203.0.113.7';++function makeReq(method, body) {+ return {+ method,+ url: '/api/auth/captcha',+ query: { action: 'captcha' },+ headers: { 'content-type': 'application/json', 'x-forwarded-for': CLIENT_IP },+ socket: { remoteAddress: CLIENT_IP },+ 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;+}++// Solving the proof of work is the expensive part of this file, so the whole+// suite shares one genuine solve rather than re-running it per test.+let issued;+function issueToken() {+ issued ??= solveOnce();+ return issued;+}++async function solveOnce() {+ // Minted with the server's own HMAC key, so the handler verifies it exactly+ // as it would a live challenge. Only the difficulty is dialled down: the+ // production maxNumber of 50k costs a real user under two seconds in a+ // browser but tens of seconds in the single-threaded test solver, and the+ // number of hashes tried is not what these tests are pinning.+ const challenge = await createChallenge({+ hmacKey: process.env.ALTCHA_HMAC_KEY,+ maxNumber: 200,+ });+ const { promise } = solveChallenge(challenge.challenge, challenge.salt, challenge.algorithm, challenge.maxnumber);+ const solution = await promise;+ const payload = Buffer.from(JSON.stringify({+ algorithm: challenge.algorithm,+ challenge: challenge.challenge,+ number: solution.number,+ salt: challenge.salt,+ signature: challenge.signature,+ })).toString('base64');++ const verifyRes = makeRes();+ await handler(makeReq('POST', { payload }), verifyRes);+ return verifyRes;+}++describe('GET /api/auth/captcha', () => {+ it('issues a solvable challenge', async () => {+ const res = makeRes();+ await handler(makeReq('GET'), res);+ expect(res.statusCode).toBe(200);+ const body = res.json();+ expect(body.algorithm).toBe('SHA-256');+ expect(typeof body.challenge).toBe('string');+ expect(typeof body.salt).toBe('string');+ expect(typeof body.signature).toBe('string');+ expect(body.maxnumber).toBe(50_000);+ });+});++describe('POST /api/auth/captcha', () => {+ it('accepts a genuinely solved challenge and issues a bypass token', async () => {+ const res = await issueToken();+ expect(res.statusCode).toBe(200);+ const body = res.json();+ expect(body.ok).toBe(true);+ expect(body.token).toMatch(/^v1:\d+:[0-9a-f]{64}$/);+ });++ it('rejects a request with no payload', async () => {+ const res = makeRes();+ await handler(makeReq('POST', {}), res);+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('bad_request');+ });++ it('rejects an unsolved or forged payload', async () => {+ const payload = Buffer.from(JSON.stringify({+ algorithm: 'SHA-256',+ challenge: 'f'.repeat(64),+ number: 1,+ salt: 'deadbeef',+ signature: 'f'.repeat(64),+ })).toString('base64');++ const res = makeRes();+ await handler(makeReq('POST', { payload }), res);+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('captcha_failed');+ });++ it('rejects a non-POST, non-GET method', async () => {+ const res = makeRes();+ await handler(makeReq('DELETE', {}), res);+ expect(res.statusCode).toBe(405);+ });+});++describe('verifyBypassToken', () => {+ let token;++ beforeEach(async () => {+ token ??= (await issueToken()).json().token;+ });++ it('accepts the token it just issued, for the IP it was issued to', () => {+ expect(verifyBypassToken(CLIENT_IP, token)).toBe(true);+ });++ it('rejects the token for a different IP', () => {+ // The token is bound to the solver's IP, so a solved puzzle cannot be+ // resold to a farm of other addresses.+ expect(verifyBypassToken('198.51.100.9', token)).toBe(false);+ });++ it('rejects a tampered signature', () => {+ const [v, window, sig] = token.split(':');+ const flipped = sig[0] === '0' ? `1${sig.slice(1)}` : `0${sig.slice(1)}`;+ expect(verifyBypassToken(CLIENT_IP, `${v}:${window}:${flipped}`)).toBe(false);+ });++ it('rejects a token from an expired time window', () => {+ const [v, window, sig] = token.split(':');+ expect(verifyBypassToken(CLIENT_IP, `${v}:${Number(window) - 2}:${sig}`)).toBe(false);+ });++ it('rejects malformed and empty tokens', () => {+ expect(verifyBypassToken(CLIENT_IP, '')).toBe(false);+ expect(verifyBypassToken(CLIENT_IP, null)).toBe(false);+ expect(verifyBypassToken(CLIENT_IP, 'v1:notanumber:abc')).toBe(false);+ expect(verifyBypassToken(CLIENT_IP, 'v2:1:abc')).toBe(false);+ expect(verifyBypassToken(CLIENT_IP, 'only:two')).toBe(false);+ });+});diff --git a/tests/api/auth-session-revocation.test.js b/tests/api/auth-session-revocation.test.jsnew file mode 100644index 000000000..d04d05421--- /dev/null+++ b/tests/api/auth-session-revocation.test.js@@ -0,0 +1,194 @@+// Session revocation tallies: DELETE /api/auth/sessions ("log out everywhere+// else") and POST /api/auth/logout-everywhere.+//+// Both reported their result from a `.count` property on the query result. The+// Neon HTTP driver resolves a query to a plain rows array and never sets that+// property, so `revoked` was always undefined: JSON.stringify dropped the key+// and the settings page's "log out everywhere" answered a bare `{}`. These+// tests pin the tally to rows returned by RETURNING, which is what the driver+// actually gives back.++import { describe, it, expect, vi, beforeEach } from 'vitest';++process.env.APP_ORIGIN = 'https://three.ws';+process.env.PUBLIC_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 = [];+// Rows the mock hands back for a statement that asked for them. Mirrors the+// real driver: no RETURNING means an empty array and no row-count field.+const RETURNED_ROWS = [{ id: 'sess-2' }, { id: 'sess-3' }, { id: 'sess-4' }];+const sqlMock = vi.fn(async (strings, ...values) => {+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);+ const flat = text.replace(/\s+/g, ' ').trim();+ statements.push({ text: flat, values });+ if (/^select id, user_agent, ip/i.test(flat)) {+ return [+ { id: 'sess-1', user_agent: 'curl', ip: '127.0.0.1', created_at: 'now', last_seen_at: 'now', expires_at: 'later' },+ { id: 'sess-2', user_agent: 'firefox', ip: '127.0.0.2', created_at: 'now', last_seen_at: 'now', expires_at: 'later' },+ ];+ }+ if (/returning id/i.test(flat)) return RETURNED_ROWS;+ return [];+});+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 () => 'new-token'),+ destroySession: vi.fn(async () => {}),+ rotateSession: vi.fn(async () => 'rotated-token'),+ // Mirrors the real signature: clearing returns an ARRAY (current + legacy+ // cookie names), issuing returns a single string. Handlers spread the+ // clear form, so a mock that always returns a string would spread it+ // character by character and silently pass a broken assertion.+ sessionCookie: vi.fn((token, opts) => (opts?.clear+ ? ['__Host-sid=; Path=/; Max-Age=0', 'sid=; Path=/; Max-Age=0']+ : `__Host-sid=${token}; Path=/; HttpOnly; Secure`)),+ };+});++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 })),+ registerIp: vi.fn(async () => ({ success: true })),+ authIpCaptcha: vi.fn(async () => ({ success: true })),+ forgotPasswordEmail: vi.fn(async () => ({ success: true })),+ verifyEmailIp: vi.fn(async () => ({ success: true })),+ resendVerifyUser: vi.fn(async () => ({ success: true })),+ },+ clientIp: () => '127.0.0.1',+}));+vi.mock('../../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));+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: sessionsHandler } = await import('../../api/auth/sessions/[action].js');+const { default: authHandler } = await import('../../api/auth/[action].js');++function makeReq({ method, url, query = {}, body }) {+ return {+ method,+ url,+ query,+ headers: { 'content-type': 'application/json', origin: 'https://three.ws', 'user-agent': 'vitest' },+ 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();+ requireCsrf.mockClear();+ requireCsrf.mockResolvedValue(true);+ getSessionUser.mockReset();+ getSessionUser.mockResolvedValue({ id: 'user-1', sid: 'sess-1', email: '[email protected]' });+});++describe('DELETE /api/auth/sessions', () => {+ it('reports how many other sessions it revoked', async () => {+ const res = makeRes();+ await sessionsHandler(makeReq({ method: 'DELETE', url: '/api/auth/sessions' }), res);++ expect(res.statusCode).toBe(200);+ expect(res.json()).toEqual({ revoked: RETURNED_ROWS.length });+ });++ it('asks the revoke statement for its rows back', async () => {+ const res = makeRes();+ await sessionsHandler(makeReq({ method: 'DELETE', url: '/api/auth/sessions' }), res);+ const [revoke] = written('update sessions set revoked_at');+ expect(revoke.text).toContain('returning id');+ });++ it('rotates the current session so a stolen copy of this cookie dies too', async () => {+ const res = makeRes();+ await sessionsHandler(makeReq({ method: 'DELETE', url: '/api/auth/sessions' }), res);+ const cookies = [].concat(res.getHeader('set-cookie'));+ expect(cookies.some((c) => c.includes('__Host-sid=rotated-token'))).toBe(true);+ });++ it('refuses without a CSRF token and writes nothing', async () => {+ requireCsrf.mockResolvedValue(false);+ const res = makeRes();+ await sessionsHandler(makeReq({ method: 'DELETE', url: '/api/auth/sessions' }), res);+ expect(written('update sessions set revoked_at')).toHaveLength(0);+ });++ it('refuses an anonymous caller with 401', async () => {+ getSessionUser.mockResolvedValue(null);+ const res = makeRes();+ await sessionsHandler(makeReq({ method: 'DELETE', url: '/api/auth/sessions' }), res);+ expect(res.statusCode).toBe(401);+ expect(res.json().error).toBe('unauthenticated');+ });+});++describe('GET /api/auth/sessions', () => {+ it('lists live sessions and flags the current one', async () => {+ const res = makeRes();+ await sessionsHandler(makeReq({ method: 'GET', url: '/api/auth/sessions' }), res);+ expect(res.statusCode).toBe(200);+ const { sessions } = res.json();+ expect(sessions).toHaveLength(2);+ expect(sessions[0]).toMatchObject({ id: 'sess-1', is_current: true });+ expect(sessions[1]).toMatchObject({ id: 'sess-2', is_current: false });+ });+});++describe('POST /api/auth/logout-everywhere', () => {+ it('reports how many sessions it revoked and clears the cookie', async () => {+ const res = makeRes();+ await authHandler(makeReq({ method: 'POST', url: '/api/auth/logout-everywhere', query: { action: 'logout-everywhere' } }), res);++ expect(res.statusCode).toBe(200);+ expect(res.json()).toEqual({ ok: true, revoked: RETURNED_ROWS.length });+ const cookies = [].concat(res.getHeader('set-cookie'));+ expect(cookies.some((c) => c.includes('__Host-sid='))).toBe(true);+ });++ it('revokes the OAuth refresh tokens alongside the browser sessions', async () => {+ const res = makeRes();+ await authHandler(makeReq({ method: 'POST', url: '/api/auth/logout-everywhere', query: { action: 'logout-everywhere' } }), res);+ expect(written('update oauth_refresh_tokens set revoked_at')).toHaveLength(1);+ });++ it('refuses an anonymous caller with 401', async () => {+ getSessionUser.mockResolvedValue(null);+ const res = makeRes();+ await authHandler(makeReq({ method: 'POST', url: '/api/auth/logout-everywhere', query: { action: 'logout-everywhere' } }), res);+ expect(res.statusCode).toBe(401);+ expect(written('update sessions set revoked_at')).toHaveLength(0);+ });+});diff --git a/tests/api/siwe-handler.test.js b/tests/api/siwe-handler.test.jsindex 5de75ed0e..f4c5d9dd4 100644--- a/tests/api/siwe-handler.test.js+++ b/tests/api/siwe-handler.test.js@@ -109,22 +109,26 @@ async function invoke(opts) {return { res, status: res.statusCode, body: json };}-// EIP-4361 message with localhost domain (accepted in non-production env).-// verifyMessage mock returns the same address so signer === claimed.+// EIP-4361 message bound to this deployment's own domain (PUBLIC_APP_ORIGIN+// above). verifyMessage mock returns the same address so signer === claimed.const WALLET_ADDR = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';const TEST_NONCE = 'testNonce1234567890ab';// Use a fresh issuedAt so the handler's anti-stale freshness check accepts it.const ISSUED_AT = new Date().toISOString();-const SIWE_MESSAGE = [- 'localhost wants you to sign in with your Ethereum account:',+const siweMessage = (domain, uri) => [+ `${domain} wants you to sign in with your Ethereum account:`,WALLET_ADDR,'',- 'URI: http://localhost/login',+ `URI: ${uri}`,'Version: 1','Chain ID: 1',`Nonce: ${TEST_NONCE}`,`Issued At: ${ISSUED_AT}`,].join('\n');+const SIWE_MESSAGE = siweMessage('app.test', 'https://app.test/login');+// The same message re-pointed at localhost. A deployment whose own APP_ORIGIN+// is not localhost must refuse it.+const LOCALHOST_MESSAGE = siweMessage('localhost', 'http://localhost/login');const FUTURE = new Date(Date.now() + 300_000).toISOString();@@ -247,6 +251,44 @@ describe('POST /api/auth/siwe/verify', () => {expect(body.error).toBe('invalid_nonce');});+ it('rejects a localhost-domain message on a non-localhost deployment', async () => {+ // The domain binding is what stops a signature harvested by another site+ // from being redeemed here, and /nonce is public, so anyone can mint a+ // nonce and go collect one. Gating the localhost escape hatch on+ // VERCEL_ENV left it wide open on Cloud Run, which never sets that var.+ const { status, body } = await invoke({+ action: 'verify',+ method: 'POST',+ body: { message: LOCALHOST_MESSAGE, signature: `0x${'ab'.repeat(65)}` },+ headers: withCsrf(),+ });++ expect(status).toBe(400);+ expect(body.error).toBe('invalid_domain');+ // Refused before the nonce is even looked up, let alone burned.+ expect(sqlState.calls).toHaveLength(0);+ });++ it('refuses to revive a soft-deleted account for a returning wallet', async () => {+ sqlState.queue.push([{ nonce: TEST_NONCE, expires_at: FUTURE, consumed_at: null }]);+ sqlState.queue.push([{ nonce: TEST_NONCE }]); // burn RETURNING+ sqlState.queue.push([]); // no user_wallets row+ sqlState.queue.push([{ id: 'user-gone', deleted_at: '2026-01-01T00:00:00.000Z' }]);++ const { status, body, res } = await invoke({+ action: 'verify',+ method: 'POST',+ body: { message: SIWE_MESSAGE, signature: `0x${'ab'.repeat(65)}` },+ headers: withCsrf(),+ });++ expect(status).toBe(403);+ expect(body.error).toBe('account_deleted');+ expect(res.headers['set-cookie']).toBeUndefined();+ // No statement may clear deleted_at behind the user's back.+ expect(sqlState.calls.some((c) => /deleted_at = null/i.test(c.query))).toBe(false);+ });+it('returns 403 when CSRF header is missing', async () => {const { status, body } = await invoke({action: 'verify',diff --git a/tests/auth-delete-account.test.js b/tests/auth-delete-account.test.jsindex 62fd24fe7..bd2ffd891 100644--- a/tests/auth-delete-account.test.js+++ b/tests/auth-delete-account.test.js@@ -19,7 +19,13 @@ 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 });+ // Neon's HTTP driver resolves every query to a plain rows array: a statement+ // with no RETURNING yields [] and carries no `.count` field. Mocking a+ // `.count` is what let the handler ship reporting every deletion as having+ // retired 0 avatars, 0 agents, and 0 widgets, so this mock refuses to invent+ // one and the handler has to count `returning id` rows like production does.+ if (/returning id/i.test(text)) return [{ id: 'row-1' }, { id: 'row-2' }];+ return [];});vi.mock('../api/_lib/db.js', () => ({ sql: (strings, ...values) => sqlMock(strings, ...values) }));@@ -131,6 +137,25 @@ describe('DELETE /api/auth/me', () => {expect(res.getHeader('set-cookie')).toMatch(/Max-Age=0/);});+ it('counts retired content from RETURNING rows, not a driver row-count field', async () => {+ const res = makeRes();+ await handler(makeReq({ confirm: 'delete my account' }), res);+ // Every content sweep must ask for its rows back. Without RETURNING the+ // tally silently reads undefined and both the response and the audit row+ // claim nothing was retired.+ for (const fragment of [+ 'update avatars set deleted_at',+ 'update agent_identities set deleted_at',+ 'update widgets set deleted_at',+ ]) {+ expect(written(fragment)[0].text).toContain('returning id');+ }+ expect(logAudit).toHaveBeenCalledWith(expect.objectContaining({+ action: 'delete_account',+ meta: expect.objectContaining({ avatars: 2, agents: 2, widgets: 2 }),+ }));+ });+it('releases the username so the /u/ handle is not held forever', async () => {const res = makeRes();await handler(makeReq({ confirm: 'delete my account' }), res);diff --git a/tests/auth-privy-verify.test.js b/tests/auth-privy-verify.test.jsindex a8fd11857..4c5d2243c 100644--- a/tests/auth-privy-verify.test.js+++ b/tests/auth-privy-verify.test.js@@ -121,3 +121,27 @@ describe('POST /api/auth/privy/verify — login-CSRF gate', () => {expect(res.statusCode).toBe(200);});});++describe('POST /api/auth/privy/verify: deleted accounts', () => {+ it('refuses to revive an account the owner deleted', async () => {+ // The ON CONFLICT branch used to clear deleted_at, so signing in with the+ // same Privy identity silently undid a deletion the owner had confirmed+ // by typing the phrase. It now answers account_deleted, like SIWE/SIWS/SAML.+ sqlMock.mockImplementation(async (strings) => {+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (text.includes('insert into users')) {+ return [{ id: 'user-gone', deleted_at: '2026-01-01T00:00:00.000Z', inserted: false }];+ }+ return [];+ });++ const res = makeRes();+ await handler(makeReq({ origin: 'https://three.ws' }), res);++ expect(res.statusCode).toBe(403);+ expect(res.json().error).toBe('account_deleted');+ expect(res._h['set-cookie']).toBeUndefined();+ const statements = sqlMock.mock.calls.map(([s]) => (Array.isArray(s) ? s.join(' ') : String(s)));+ expect(statements.some((t) => /deleted_at = null/i.test(t))).toBe(false);+ });+});diff --git a/tests/wallet-link-domain-binding.test.js b/tests/wallet-link-domain-binding.test.jsdeleted file mode 100644index 2ba830f16..000000000--- a/tests/wallet-link-domain-binding.test.js+++ /dev/null@@ -1,168 +0,0 @@-// The wallet-link handlers bind a signed message to this deployment's own-// domain, with a localhost escape hatch for local development.-//-// That escape hatch used to be gated on VERCEL_ENV. Production runs on Cloud-// Run, which never sets VERCEL_ENV, so the gate read "this is local dev" on the-// live site and a link message signed for `localhost` satisfied the domain and-// URI checks there. The gate is now anchored to the deployment's own-// APP_ORIGIN, so it can only open where the deployment really is local. Same-// fix as api/auth/siwe/[action].js and api/auth/siws/[action].js.--import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import bs58 from 'bs58';--process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';-process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';--vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));-vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));-vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));-vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));-vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));-vi.mock('../api/_lib/rate-limit.js', () => ({- limits: { walletLink: vi.fn(async () => ({ success: true })) },- clientIp: () => '127.0.0.1',-}));-vi.mock('../api/_lib/auth.js', () => ({- getSessionUser: vi.fn(async () => ({ id: 'user-1', email: '[email protected]' })),-}));-// The nonce store is the step right after the domain/URI checks: reaching it-// proves the message cleared the domain binding.-const consumeNonce = vi.fn(async () => null);-vi.mock('../api/auth/wallets/_link-nonces.js', () => ({- NONCE_TTL_SEC: 300,- issueNonce: vi.fn(async () => 'nonce0000000000'),- consumeNonce: (...args) => consumeNonce(...args),-}));--const { default: handler } = await import('../api/auth/wallets/[action].js');--// Synthetic 32-byte key, base58-encoded the way a real Solana address is. The-// parser decodes and length-checks it, so a hand-typed string will not do.-const SOLANA_ADDRESS = bs58.encode(new Uint8Array(32).fill(7));--function siwsMessage({ domain, uri }) {- return [- `${domain} wants you to sign in with your Solana account:`,- SOLANA_ADDRESS,- ``,- `Link this wallet to three.ws account [email protected]`,- ``,- `URI: ${uri}`,- `Version: 1`,- `Chain ID: mainnet`,- `Nonce: nonce0000000000`,- `Issued At: ${new Date().toISOString()}`,- `Expiration Time: ${new Date(Date.now() + 300_000).toISOString()}`,- ].join('\n');-}--function makeReq(message) {- return {- method: 'POST',- url: '/api/auth/wallets/link-solana',- query: { action: 'link-solana' },- headers: { 'content-type': 'application/json' },- socket: { remoteAddress: '127.0.0.1' },- body: JSON.stringify({ message, signature: 'c2lnbmF0dXJl' }),- };-}-function makeRes() {- const r = { statusCode: 200, _h: {}, _b: null };- r.setHeader = (k, v) => {- r._h[k] = v;- };- r.getHeader = (k) => r._h[k];- r.end = (b) => {- r._b = b;- };- Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });- return r;-}--const originalNodeEnv = process.env.NODE_ENV;-const originalAppOrigin = process.env.PUBLIC_APP_ORIGIN;--beforeEach(() => {- consumeNonce.mockClear();-});-afterEach(() => {- process.env.NODE_ENV = originalNodeEnv;- process.env.PUBLIC_APP_ORIGIN = originalAppOrigin;- delete process.env.VERCEL_ENV;-});--describe('POST /api/auth/wallets/link-solana: domain binding', () => {- it('rejects a localhost-signed message on a production deployment', async () => {- process.env.NODE_ENV = 'production';- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';-- const res = makeRes();- await handler(makeReq(siwsMessage({ domain: 'localhost:3000', uri: 'http://localhost:3000' })), res);-- expect(res.statusCode).toBe(400);- expect(res.json().error).toBe('invalid_domain');- expect(consumeNonce).not.toHaveBeenCalled();- });-- it('rejects a localhost-signed message on a non-production deployment served from the real origin', async () => {- // Preview and staging deployments are not production, but they are not- // localhost either: the escape hatch must stay shut for them.- delete process.env.NODE_ENV;- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';-- const res = makeRes();- await handler(makeReq(siwsMessage({ domain: 'localhost:3000', uri: 'http://localhost:3000' })), res);-- expect(res.statusCode).toBe(400);- expect(res.json().error).toBe('invalid_domain');- expect(consumeNonce).not.toHaveBeenCalled();- });-- it('accepts a localhost-signed message when the deployment itself is localhost', async () => {- delete process.env.NODE_ENV;- process.env.PUBLIC_APP_ORIGIN = 'http://localhost:3000';-- const res = makeRes();- await handler(makeReq(siwsMessage({ domain: 'localhost:3000', uri: 'http://localhost:3000' })), res);-- // Past the domain and URI checks, into the nonce step.- expect(consumeNonce).toHaveBeenCalledWith('nonce0000000000', 'user-1');- expect(res.json().error).toBe('invalid_nonce');- });-- it('always accepts a message signed for the deployment origin', async () => {- process.env.NODE_ENV = 'production';- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';-- const res = makeRes();- await handler(makeReq(siwsMessage({ domain: 'three.ws', uri: 'https://three.ws' })), res);-- expect(consumeNonce).toHaveBeenCalledWith('nonce0000000000', 'user-1');- expect(res.json().error).toBe('invalid_nonce');- });-- it('rejects a foreign domain outright', async () => {- process.env.NODE_ENV = 'production';- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';-- const res = makeRes();- await handler(makeReq(siwsMessage({ domain: 'evil.example', uri: 'https://evil.example' })), res);-- expect(res.statusCode).toBe(400);- expect(res.json().error).toBe('invalid_domain');- expect(consumeNonce).not.toHaveBeenCalled();- });-- it('rejects a URI whose origin is not the deployment origin', async () => {- process.env.NODE_ENV = 'production';- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';-- const res = makeRes();- await handler(makeReq(siwsMessage({ domain: 'three.ws', uri: 'https://evil.example/callback' })), res);-- expect(res.statusCode).toBe(400);- expect(res.json().error).toBe('invalid_uri');- expect(consumeNonce).not.toHaveBeenCalled();- });-});diff --git a/tests/wallet-link-nonces.test.js b/tests/wallet-link-nonces.test.jsdeleted file mode 100644index 9d9e222d1..000000000--- a/tests/wallet-link-nonces.test.js+++ /dev/null@@ -1,134 +0,0 @@-// Coverage for the wallet-link nonce store (api/auth/wallets/_link-nonces.js),-// the single-use gate behind /api/auth/wallets (SIWE link) and-// /api/auth/wallets/link-solana (SIWS link).-//-// Both backends matter and behave differently at the seams: Upstash Redis-// (production, atomic GETDEL so two instances can't both burn one nonce) and-// the in-memory Map fallback (local dev / tests, where Redis is unconfigured).-// Each is exercised here on its success path and its failure paths: replay,-// wrong user, unknown nonce, non-string input.--import { describe, it, expect, vi, beforeEach } from 'vitest';--process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';--// Minimal in-process stand-in for the two Upstash commands the store uses.-// `set` honors the { ex } TTL argument the module passes; `getdel` is-// read-and-delete in one step, which is the property the module relies on.-function makeFakeRedis() {- const store = new Map();- return {- store,- async set(key, value, opts) {- store.set(key, { value: String(value), ex: opts?.ex ?? null });- return 'OK';- },- async getdel(key) {- const hit = store.get(key);- if (!hit) return null;- store.delete(key);- return hit.value;- },- };-}--let redisImpl = null;-vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => redisImpl }));--const { issueNonce, consumeNonce, NONCE_TTL_SEC } = await import(- '../api/auth/wallets/_link-nonces.js'-);--beforeEach(() => {- redisImpl = null;-});--describe('_link-nonces: in-memory fallback (Redis unconfigured)', () => {- it('issues an opaque alphanumeric nonce and consumes it once for its owner', async () => {- const nonce = await issueNonce('user-1');- expect(nonce).toMatch(/^[A-Za-z0-9]{16}$/);-- expect(await consumeNonce(nonce, 'user-1')).toEqual({- userId: 'user-1',- issuedAt: expect.any(Number),- });- });-- it('refuses a replay of an already-consumed nonce', async () => {- const nonce = await issueNonce('user-1');- expect(await consumeNonce(nonce, 'user-1')).not.toBeNull();- expect(await consumeNonce(nonce, 'user-1')).toBeNull();- });-- it('refuses a nonce presented by a different user', async () => {- const nonce = await issueNonce('user-1');- expect(await consumeNonce(nonce, 'user-2')).toBeNull();- // The rightful owner can still use it.- expect(await consumeNonce(nonce, 'user-1')).not.toBeNull();- });-- it('matches a numeric user id against its string form', async () => {- const nonce = await issueNonce(42);- expect(await consumeNonce(nonce, '42')).toEqual({- userId: '42',- issuedAt: expect.any(Number),- });- });-- it('returns null for an unknown nonce and for non-string input', async () => {- expect(await consumeNonce('nonexistent-nonce', 'user-1')).toBeNull();- expect(await consumeNonce('', 'user-1')).toBeNull();- expect(await consumeNonce(null, 'user-1')).toBeNull();- expect(await consumeNonce(undefined, 'user-1')).toBeNull();- expect(await consumeNonce({ nonce: 'x' }, 'user-1')).toBeNull();- });-- it('issues a distinct nonce every time', async () => {- const seen = new Set();- for (let i = 0; i < 50; i++) seen.add(await issueNonce('user-1'));- expect(seen.size).toBe(50);- });-});--describe('_link-nonces: Redis backend', () => {- it('stores the owner under a namespaced key with the module TTL', async () => {- const r = makeFakeRedis();- redisImpl = r;-- const nonce = await issueNonce('user-1');- expect(r.store.get(`wallet:link:nonce:${nonce}`)).toEqual({- value: 'user-1',- ex: NONCE_TTL_SEC,- });- expect(NONCE_TTL_SEC).toBe(300);- });-- it('consumes once and burns the key so a replay finds nothing', async () => {- const r = makeFakeRedis();- redisImpl = r;-- const nonce = await issueNonce('user-1');- expect(await consumeNonce(nonce, 'user-1')).toEqual({ userId: 'user-1' });- expect(r.store.has(`wallet:link:nonce:${nonce}`)).toBe(false);- expect(await consumeNonce(nonce, 'user-1')).toBeNull();- });-- it('refuses a nonce issued to a different user', async () => {- redisImpl = makeFakeRedis();- const nonce = await issueNonce('user-1');- expect(await consumeNonce(nonce, 'user-2')).toBeNull();- });-- it('returns null for an unknown nonce', async () => {- redisImpl = makeFakeRedis();- expect(await consumeNonce('never-issued', 'user-1')).toBeNull();- });-- it('does not fall back to the in-memory map for a Redis-issued nonce', async () => {- redisImpl = makeFakeRedis();- const viaRedis = await issueNonce('user-1');-- redisImpl = null;- expect(await consumeNonce(viaRedis, 'user-1')).toBeNull();- });-});diff --git a/tests/wallet-unlink-guards.test.js b/tests/wallet-unlink-guards.test.jsdeleted file mode 100644index 52b93dcb0..000000000--- a/tests/wallet-unlink-guards.test.js+++ /dev/null@@ -1,178 +0,0 @@-// Regression guards for DELETE /api/auth/wallets/<address>.-//-// Two defects found in the 2026-08-10 auth audit, both reproduced live against-// a real password-less SIWS account before the fix:-//-// 1. The last-wallet guard never fired. Postgres `count(*)` is a bigint and-// the Neon driver returns it as the STRING "1", so `walletCount === 1`-// was always false and an account whose only credential is a wallet could-// unlink it, removing its own way back in.-// 2. Unlinking the primary wallet left the account with no primary at all.-// Royalty payouts (api/_lib/royalty.js), agent-wallet resolution-// (api/_lib/agent-wallet.js) and x402 skill calls (api/x402/skill-call.js)-// all select the payout address by `is_primary = true`, so the account-// silently lost its payout target.--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: () => {} }));-vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));-vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));-vi.mock('../api/_lib/rate-limit.js', () => ({- limits: { walletLink: vi.fn(async () => ({ success: true })) },- clientIp: () => '127.0.0.1',-}));-vi.mock('../api/_lib/auth.js', () => ({- getSessionUser: vi.fn(async () => ({ id: 'user-1', email: '[email protected]' })),-}));--// The fixture models user_wallets for one account. Queries are matched on the-// distinctive text of each statement the handler issues, and `count(*)` is-// returned in the driver's real shape (a string) so the coercion bug cannot-// come back unnoticed.-let wallets = [];-const sqlMock = vi.fn(async (strings, ...values) => {- const text = Array.isArray(strings) ? strings.join(' ') : String(strings);-- if (text.includes('select id, address, is_primary from user_wallets')) {- const candidates = values[1] || [];- const hit = wallets.find((w) => candidates.includes(w.address));- return hit ? [{ id: hit.id, address: hit.address, is_primary: hit.is_primary }] : [];- }- if (text.includes('select count(*) as n from user_wallets')) {- return [{ n: String(wallets.length) }];- }- if (text.includes('select password_hash from users')) {- return [{ password_hash: passwordHash }];- }- if (text.includes('delete from user_wallets')) {- wallets = wallets.filter((w) => w.id !== values[0]);- return [];- }- if (text.includes('update user_wallets set is_primary = true')) {- const oldest = [...wallets].sort((a, b) => a.created_at - b.created_at)[0];- if (!oldest) return [];- oldest.is_primary = true;- return [{ address: oldest.address }];- }- return [];-});-vi.mock('../api/_lib/db.js', () => ({ sql: (strings, ...values) => sqlMock(strings, ...values) }));--let passwordHash = null;--const { default: handler } = await import('../api/auth/wallets/[action].js');--function makeReq(address) {- return {- method: 'DELETE',- url: `/api/auth/wallets/${address}`,- query: { action: address },- headers: { 'x-csrf-token': 'csrf-token' },- socket: { remoteAddress: '127.0.0.1' },- };-}-function makeRes() {- const r = { statusCode: 200, _h: {}, _b: null };- r.setHeader = (k, v) => {- r._h[k] = v;- };- r.getHeader = (k) => r._h[k];- r.end = (b) => {- r._b = b;- };- Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });- return r;-}--beforeEach(() => {- sqlMock.mockClear();- passwordHash = null;- wallets = [- { id: 'w-a', address: 'AaaaSolanaAddressAaaa', is_primary: true, created_at: 1 },- { id: 'w-b', address: 'BbbbSolanaAddressBbbb', is_primary: false, created_at: 2 },- ];-});--describe('DELETE /api/auth/wallets/<address>: last-wallet guard', () => {- it('refuses to remove the only wallet of an account with no password', async () => {- wallets = [wallets[0]];- const res = makeRes();- await handler(makeReq('AaaaSolanaAddressAaaa'), res);-- expect(res.statusCode).toBe(400);- expect(res.json().error).toBe('cannot_remove_last_wallet');- expect(wallets).toHaveLength(1);- });-- it('allows removing the only wallet when the account has a password', async () => {- wallets = [wallets[0]];- passwordHash = '$argon2id$v=19$m=65536,t=3,p=4$fake-hash-for-this-fixture';- const res = makeRes();- await handler(makeReq('AaaaSolanaAddressAaaa'), res);-- expect(res.statusCode).toBe(200);- expect(res.json().removed).toBe(true);- expect(wallets).toHaveLength(0);- });-- it('allows removing a wallet while others remain', async () => {- const res = makeRes();- await handler(makeReq('BbbbSolanaAddressBbbb'), res);-- expect(res.statusCode).toBe(200);- expect(wallets.map((w) => w.id)).toEqual(['w-a']);- });-- it('404s an address the caller does not own', async () => {- const res = makeRes();- await handler(makeReq('ZzzzNotYourAddressZzzz'), res);-- expect(res.statusCode).toBe(404);- expect(res.json().error).toBe('not_found');- });-});--describe('DELETE /api/auth/wallets/<address>: primary succession', () => {- it('promotes the oldest survivor when the primary wallet is removed', async () => {- wallets[0].is_primary = false;- wallets[1].is_primary = true;-- const res = makeRes();- await handler(makeReq('BbbbSolanaAddressBbbb'), res);-- expect(res.statusCode).toBe(200);- expect(res.json().primary).toBe('AaaaSolanaAddressAaaa');- expect(wallets.filter((w) => w.is_primary).map((w) => w.address)).toEqual([- 'AaaaSolanaAddressAaaa',- ]);- });-- it('leaves the primary alone when a non-primary wallet is removed', async () => {- const res = makeRes();- await handler(makeReq('BbbbSolanaAddressBbbb'), res);-- expect(res.json().primary).toBeNull();- expect(wallets.filter((w) => w.is_primary).map((w) => w.address)).toEqual([- 'AaaaSolanaAddressAaaa',- ]);- });-- it('does not attempt a promotion when the removed wallet was the last one', async () => {- wallets = [wallets[0]];- passwordHash = '$argon2id$v=19$m=65536,t=3,p=4$fake-hash-for-this-fixture';- const res = makeRes();- await handler(makeReq('AaaaSolanaAddressAaaa'), res);-- expect(res.json().primary).toBeNull();- expect(- sqlMock.mock.calls.some((c) =>- (Array.isArray(c[0]) ? c[0].join(' ') : '').includes('set is_primary = true'),- ),- ).toBe(false);- });-});