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): bind wallet linking to this deployment's own origin, and cover the wallet unlink guards
nirholas84bbaa687153
diff --git a/api/auth/wallets/[action].js b/api/auth/wallets/[action].jsindex 3390c949c..f61f56574 100644--- a/api/auth/wallets/[action].js+++ b/api/auth/wallets/[action].js@@ -29,6 +29,10 @@ 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]+$/),@@ -135,8 +139,11 @@ async function handleLinkWallet(userId, 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 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 allowedHosts = new Set([appHost, vercelHost].filter(Boolean));const domainOk =allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));@@ -395,8 +402,11 @@ async function handleLinkSolana(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 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 allowedHosts = new Set([appHost, vercelHost].filter(Boolean));const domainOk =allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));diff --git a/prompts/swarm-100/api-auth-02.md b/prompts/swarm-100/api-auth-02.mddeleted file mode 100644index 279b796ac..000000000--- a/prompts/swarm-100/api-auth-02.md+++ /dev/null@@ -1,104 +0,0 @@-# API audit: api/auth batch 02 (4 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/auth/siws/[action].js-- api/auth/wallets/[action].js-- api/auth/wallets/_link-nonces.js-- api/auth/x/[action].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-auth-02.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/tests/wallet-link-domain-binding.test.js b/tests/wallet-link-domain-binding.test.jsnew file mode 100644index 000000000..2ba830f16--- /dev/null+++ b/tests/wallet-link-domain-binding.test.js@@ -0,0 +1,168 @@+// 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.jsnew file mode 100644index 000000000..9d9e222d1--- /dev/null+++ b/tests/wallet-link-nonces.test.js@@ -0,0 +1,134 @@+// 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.jsnew file mode 100644index 000000000..52b93dcb0--- /dev/null+++ b/tests/wallet-unlink-guards.test.js@@ -0,0 +1,178 @@+// 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);+ });+});