Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(community): keep a coin-world sign-in alive for its full 30 days

nirholas40b78ff49f9a
diff --git a/api/community/auth/callback.js b/api/community/auth/callback.js
index 779d15160..c7b45a38b 100644
--- a/api/community/auth/callback.js
+++ b/api/community/auth/callback.js
@@ -3,9 +3,10 @@
// X redirects the popup here after the user authorizes. We exchange the
// one-time challenge code for the user's CoinCommunities session server-side,
// set httpOnly cookies, then hand control back to the opener via postMessage
-// and close the popup. Only the one-time challengeCode exchange is accepted —
+// and close the popup. Only the one-time challengeCode exchange is accepted;
// raw tokens in the redirect URL are never trusted (login CSRF / fixation).
-import { text, wrap } from '../../_lib/http.js';
+import { method, text, wrap } from '../../_lib/http.js';
+import { clientIp, limits } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
import { cc, setUserSession, UnconfiguredError } from '../../_lib/coin-communities.js';
import { publishMemberJoin } from '../../_lib/feed.js';
@@ -26,7 +27,7 @@ function page({ ok, user = null, message = '' }) {
const payload = JSON.stringify({ type: 'cc-auth', ok, user, message }).replace(/</g, '\\u003c');
return `<!doctype html><meta charset="utf-8"><title>Signing in…</title>
<body style="margin:0;display:grid;place-items:center;height:100vh;font:15px system-ui;background:#0a0e1c;color:#cdd9f5">
-<div>${ok ? 'Signed in — you can close this window.' : 'Sign-in failed. You can close this window.'}</div>
+<div>${ok ? 'Signed in. You can close this window.' : 'Sign-in failed. You can close this window.'}</div>
<script>
(function(){
var msg = ${payload};
@@ -36,7 +37,24 @@ function page({ ok, user = null, message = '' }) {
</script>`;
}
+function htmlPage(res, status, opts) {
+ return text(res, status, page(opts), { 'content-type': 'text/html; charset=utf-8' });
+}
+
export default wrap(async (req, res) => {
+ // The redirect target is a browser navigation, nothing else. Anything with a
+ // body is someone probing the exchange, not X handing back a user.
+ if (!method(req, res, ['GET'])) return;
+
+ // A challenge code is a one-shot credential: without a ceiling this endpoint
+ // is an unmetered oracle for guessing them. The rest of the session surface
+ // (wallet link, unlink, posting) already sits behind the same bucket, and one
+ // sign-in spends exactly one request of it.
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) {
+ return htmlPage(res, 429, { ok: false, message: 'too many sign-in attempts, try again shortly' });
+ }
+
const url = new URL(req.url, 'http://x');
const challengeCode = url.searchParams.get('challengeCode');
@@ -45,9 +63,7 @@ export default wrap(async (req, res) => {
api = cc();
} catch (err) {
if (err instanceof UnconfiguredError) {
- return text(res, 503, page({ ok: false, message: 'not configured' }), {
- 'content-type': 'text/html; charset=utf-8',
- });
+ return htmlPage(res, 503, { ok: false, message: 'not configured' });
}
throw err;
}
@@ -61,12 +77,8 @@ export default wrap(async (req, res) => {
const session = data;
setUserSession(res, session);
announceSignIn(session.user);
- return text(res, 200, page({ ok: true, user: session.user }), {
- 'content-type': 'text/html; charset=utf-8',
- });
+ return htmlPage(res, 200, { ok: true, user: session.user });
} catch (err) {
- return text(res, 200, page({ ok: false, message: err.message || 'sign-in failed' }), {
- 'content-type': 'text/html; charset=utf-8',
- });
+ return htmlPage(res, 200, { ok: false, message: err.message || 'sign-in failed' });
}
});
diff --git a/api/community/capabilities.js b/api/community/capabilities.js
index 767140351..69e5378a6 100644
--- a/api/community/capabilities.js
+++ b/api/community/capabilities.js
@@ -1,7 +1,7 @@
// GET /api/community/capabilities
// Tells the browser which Town affordances are live: reads/realtime (needs
// CC_API_KEY) and posting (needs the server key-pair). The browser uses this
-// to render the composer enabled vs. in its designed locked state — never a
+// to render the composer enabled vs. in its designed locked state, never a
// dead button.
import { cors, json, method, wrap } from '../_lib/http.js';
import { capabilities } from '../_lib/coin-communities.js';
diff --git a/api/community/holder-pass.js b/api/community/holder-pass.js
index f35c08653..4edf4fbb9 100644
--- a/api/community/holder-pass.js
+++ b/api/community/holder-pass.js
@@ -1,7 +1,7 @@
// POST /api/community/holder-pass?token=<mint>
//
-// Mints a holder pass — proof a signed-in user holds at least HOLDER_MIN_USD of
-// a coin — so the multiplayer server can admit them into that coin's gated
+// Mints a holder pass (proof a signed-in user holds at least HOLDER_MIN_USD of
+// a coin) so the multiplayer server can admit them into that coin's gated
// Holders world without running Solana RPC itself.
//
// The check is on the user's *authenticated* wallet: we read the linked Solana
@@ -11,12 +11,12 @@
// pass can't be minted against someone else's address.
//
// Responses (always 200 unless the request itself is bad):
-// { eligible: true, usd, amount, minUsd, wallet, holderPass } — admit
-// { eligible: false, usd, amount, minUsd, wallet } — short; UI
-// shows buy CTA
+// { eligible: true, usd, amount, minUsd, wallet, holderPass } admit them
+// { eligible: false, usd, amount, minUsd, wallet } short, so the
+// UI shows a buy CTA
// Auth/wallet problems are real errors the gate UI routes on:
-// 401 auth_required — not signed in to CoinCommunities
-// 403 wallet_required — signed in but no linked Solana wallet
+// 401 auth_required: not signed in to CoinCommunities
+// 403 wallet_required: signed in but no linked Solana wallet
import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { cc, withAuthRefresh, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';
@@ -54,7 +54,7 @@ export default wrap(async (req, res) => {
throw err;
}
- // The wallets are taken from the authenticated session — never the request
+ // The wallets are taken from the authenticated session, never the request
// body. Transparently refreshes an expired (1h) access token off the 30-day
// refresh token before giving up, so a player who's been signed in for a
// while isn't wrongly bounced out of the holders-world gate as "not signed in".
@@ -103,7 +103,7 @@ export default wrap(async (req, res) => {
primaryWallet = address;
}
}
- // Only surface an upstream error if we couldn't read *any* wallet — a partial
+ // Only surface an upstream error if we couldn't read *any* wallet: a partial
// failure still gates correctly on whatever we did read.
if (amount === 0 && balanceError) {
const status = balanceError?.status === 503 ? 503 : 502;
@@ -123,7 +123,7 @@ export default wrap(async (req, res) => {
const minUsd = HOLDER_MIN_USD;
// A coin's creator may pin a token-amount threshold (R24); absent that, the
- // world gates on the platform USD floor. Read it best-effort — a KV hiccup
+ // world gates on the platform USD floor. Read it best-effort: a KV hiccup
// falls back to the USD floor rather than wrongly locking the world.
const gate = await readWorldGate(token);
const minTokens = gate?.minTokens || 0;
diff --git a/api/community/logout.js b/api/community/logout.js
index c7326a096..21915320e 100644
--- a/api/community/logout.js
+++ b/api/community/logout.js
@@ -1,4 +1,4 @@
-// POST /api/community/logout — clears the CoinCommunities user session cookies.
+// POST /api/community/logout clears the CoinCommunities user session cookies.
import { cors, json, method, wrap } from '../_lib/http.js';
import { clearUserSession } from '../_lib/coin-communities.js';
diff --git a/api/community/me.js b/api/community/me.js
index cd41abf5d..5b51e80e6 100644
--- a/api/community/me.js
+++ b/api/community/me.js
@@ -31,7 +31,7 @@ export default wrap(async (req, res) => {
return { data: { user: me.data?.user, wallets } };
});
- // No usable session — never signed in, or the refresh token itself expired.
+ // No usable session: never signed in, or the refresh token itself expired.
if (!headers) return json(res, 200, { data: { user: null } });
if (apiErr) return error(res, 502, 'upstream_error', apiErr.message || 'failed to load user');
diff --git a/api/community/messages.js b/api/community/messages.js
index e3298fe86..2c6b27a78 100644
--- a/api/community/messages.js
+++ b/api/community/messages.js
@@ -1,6 +1,6 @@
// /api/community/messages?token=<mint>
-// GET — recent messages for a coin's community (public read).
-// POST — post a message. Two real paths, preferred in this order:
+// GET: recent messages for a coin's community (public read).
+// POST: post a message. Two real paths, preferred in this order:
// 1. User-scoped: a signed-in CoinCommunities user (session cookie)
// posts as themselves from their linked wallet (api.postMessage).
// 2. Server attribution: when the server key-pair is configured and a
diff --git a/api/community/wallet/unlink.js b/api/community/wallet/unlink.js
index f98b44ec5..7b177bd5d 100644
--- a/api/community/wallet/unlink.js
+++ b/api/community/wallet/unlink.js
@@ -1,6 +1,6 @@
// POST /api/community/wallet/unlink
// Unlinks the signed-in user's Solana (svm) wallet(s) so they can link a
-// different one — e.g. when the wallet they linked first doesn't hold the coin
+// different one, e.g. when the wallet they linked first doesn't hold the coin
// and they need to switch to the one that does. Idempotent: succeeds (unlinked:0)
// when nothing is linked, so the gate's "use a different wallet" path is safe to
// call from any state.
diff --git a/prompts/swarm-100/api-community-01.md b/prompts/swarm-100/api-community-01.md
deleted file mode 100644
index cdc632f33..000000000
--- a/prompts/swarm-100/api-community-01.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# API audit: api/community batch 01 (10 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/community/auth/callback.js
-- api/community/auth/url.js
-- api/community/capabilities.js
-- api/community/holder-pass.js
-- api/community/logout.js
-- api/community/me.js
-- api/community/messages.js
-- api/community/wallet/challenge.js
-- api/community/wallet/link.js
-- api/community/wallet/unlink.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-community-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/tests/community-session-refresh.test.js b/tests/community-session-refresh.test.js
new file mode 100644
index 000000000..8a26a63e5
--- /dev/null
+++ b/tests/community-session-refresh.test.js
@@ -0,0 +1,319 @@
+/**
+ * CoinCommunities session survival across the 1h access-token expiry.
+ *
+ * Regression target: `cc_at` (the access-token cookie) and the JWT inside it
+ * share a 1h lifetime, so an hour after sign-in the browser has dropped it and
+ * only the 30-day `cc_rt` refresh cookie is still sent. Every user-scoped
+ * surface read the session with `userAuthHeaders(req)`, which sees no `cc_at`
+ * and reports "not signed in", and `withAuthRefresh` bailed on the same check
+ * before it ever reached the refresh token. Net effect: the 30-day refresh
+ * token was never once used and every session silently died at 1h, locking the
+ * Town composer and the wallet-link flow behind a sign-in the user had already
+ * completed.
+ *
+ * These tests pin the fixed behavior: a request carrying only `cc_rt` mints a
+ * fresh access token, re-runs the call, and persists the new cookies; a request
+ * carrying nothing is still treated as signed out; and a dead refresh token
+ * clears the stale cookies instead of looping.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const rl = { ok: true };
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ publicIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })),
+ authIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })),
+ authedReadIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+// The upstream SDK, driven per-test. cc() is the only door to it, so stubbing
+// the module's client here exercises the real session logic in
+// api/_lib/coin-communities.js rather than a re-implementation of it.
+const sdk = {
+ refreshToken: vi.fn(),
+ postMessage: vi.fn(),
+ walletChallenge: vi.fn(),
+ linkWallet: vi.fn(),
+ getWallets: vi.fn(),
+ unlinkWallet: vi.fn(),
+};
+vi.mock('@coin-communities/sdk/node', () => ({
+ configureApi: vi.fn(),
+ api: sdk,
+}));
+
+process.env.CC_API_KEY = 'test-key';
+
+const { withAuthRefresh, hasUserSession, userAuthHeaders } = await import(
+ '../api/_lib/coin-communities.js'
+);
+const { default: messagesHandler } = await import('../api/community/messages.js');
+const { default: challengeHandler } = await import('../api/community/wallet/challenge.js');
+const { default: linkHandler } = await import('../api/community/wallet/link.js');
+const { default: unlinkHandler } = await import('../api/community/wallet/unlink.js');
+
+const TOKEN = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+function makeReq({ method = 'POST', url = '/api/community/messages', cookie = '', body } = {}) {
+ return {
+ method,
+ url,
+ headers: {
+ origin: 'https://three.ws',
+ 'content-type': 'application/json',
+ ...(cookie ? { cookie } : {}),
+ },
+ rawBody: body === undefined ? undefined : Buffer.from(JSON.stringify(body)),
+ socket: { remoteAddress: '127.0.0.1' },
+ };
+}
+
+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.removeHeader = (k) => {
+ delete r._h[k.toLowerCase()];
+ };
+ r.end = (b) => {
+ r._b = b;
+ };
+ r.json = () => JSON.parse(r._b);
+ return r;
+}
+
+const ok = (data) => ({ data, error: null });
+const fail = (statusCode, message) => ({ data: null, error: { statusCode, message } });
+
+beforeEach(() => {
+ rl.ok = true;
+ for (const fn of Object.values(sdk)) fn.mockReset();
+});
+
+describe('hasUserSession', () => {
+ it('sees an hours-old session that has only the refresh cookie left', () => {
+ const req = makeReq({ cookie: 'cc_rt=refresh-token' });
+ // The old gate: no access cookie, so this is null and the user reads as a
+ // stranger. The new gate must still recognize them.
+ expect(userAuthHeaders(req)).toBeNull();
+ expect(hasUserSession(req)).toBe(true);
+ });
+
+ it('is false when no session cookie is present at all', () => {
+ expect(hasUserSession(makeReq())).toBe(false);
+ });
+});
+
+describe('withAuthRefresh with an expired access-token cookie', () => {
+ it('refreshes from cc_rt, retries the call, and persists the new cookies', async () => {
+ sdk.refreshToken.mockResolvedValue(ok({ accessToken: 'fresh-at', refreshToken: 'fresh-rt' }));
+ const call = vi.fn(async (h) => ok({ seen: h.Authorization }));
+
+ const res = makeRes();
+ const result = await withAuthRefresh(makeReq({ cookie: 'cc_rt=old-rt' }), res, call);
+
+ expect(sdk.refreshToken).toHaveBeenCalledWith({ body: { refreshToken: 'old-rt' } });
+ expect(result.headers).toEqual({ Authorization: 'Bearer fresh-at' });
+ expect(result.data.seen).toBe('Bearer fresh-at');
+ const cookies = res.getHeader('set-cookie');
+ expect(cookies.some((c) => c.startsWith('cc_at=fresh-at;'))).toBe(true);
+ expect(cookies.some((c) => c.startsWith('cc_rt=fresh-rt;'))).toBe(true);
+ });
+
+ it('reports no session and clears cookies when the refresh token is dead', async () => {
+ sdk.refreshToken.mockResolvedValue(fail(401, 'refresh token expired'));
+ const call = vi.fn();
+
+ const res = makeRes();
+ const result = await withAuthRefresh(makeReq({ cookie: 'cc_rt=dead' }), res, call);
+
+ expect(result.headers).toBeNull();
+ expect(call).not.toHaveBeenCalled();
+ expect(res.getHeader('set-cookie').every((c) => c.includes('Max-Age=0'))).toBe(true);
+ });
+
+ it('never calls refresh when there is no session at all', async () => {
+ const res = makeRes();
+ const result = await withAuthRefresh(makeReq(), res, vi.fn());
+ expect(result.headers).toBeNull();
+ expect(sdk.refreshToken).not.toHaveBeenCalled();
+ expect(res.getHeader('set-cookie')).toBeUndefined();
+ });
+
+ it('still refreshes on an upstream 401 when the access cookie is present', async () => {
+ sdk.refreshToken.mockResolvedValue(ok({ accessToken: 'fresh-at', refreshToken: 'fresh-rt' }));
+ const call = vi
+ .fn()
+ .mockResolvedValueOnce(fail(401, 'jwt expired'))
+ .mockResolvedValueOnce(ok({ retried: true }));
+
+ const result = await withAuthRefresh(
+ makeReq({ cookie: 'cc_at=stale; cc_rt=good' }),
+ makeRes(),
+ call,
+ );
+
+ expect(call).toHaveBeenCalledTimes(2);
+ expect(result.data).toEqual({ retried: true });
+ expect(result.headers).toEqual({ Authorization: 'Bearer fresh-at' });
+ });
+});
+
+describe('POST /api/community/messages with a refresh-only session', () => {
+ const body = { content: 'gm from the holders world', walletAddress: TOKEN, chainId: 'solana' };
+
+ it('posts as the user after refreshing, instead of locking the composer', async () => {
+ sdk.refreshToken.mockResolvedValue(ok({ accessToken: 'fresh-at', refreshToken: 'fresh-rt' }));
+ sdk.postMessage.mockResolvedValue(
+ ok({ message: { id: 'm1', tokenAddress: TOKEN, content: body.content, createdAt: 'now' } }),
+ );
+
+ const res = makeRes();
+ await messagesHandler(
+ makeReq({ url: `/api/community/messages?token=${TOKEN}`, cookie: 'cc_rt=old-rt', body }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data.message.id).toBe('m1');
+ expect(sdk.postMessage).toHaveBeenCalledTimes(1);
+ expect(sdk.postMessage.mock.calls[0][0].headers).toEqual({ Authorization: 'Bearer fresh-at' });
+ });
+
+ it('answers 401 auth_required (not posting_locked) when the refresh fails', async () => {
+ sdk.refreshToken.mockResolvedValue(fail(401, 'refresh token expired'));
+
+ const res = makeRes();
+ await messagesHandler(
+ makeReq({ url: `/api/community/messages?token=${TOKEN}`, cookie: 'cc_rt=dead', body }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(401);
+ expect(res.json().error).toBe('auth_required');
+ expect(sdk.postMessage).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/community/wallet/challenge with a refresh-only session', () => {
+ it('issues the challenge on the refreshed token', async () => {
+ sdk.refreshToken.mockResolvedValue(ok({ accessToken: 'fresh-at', refreshToken: 'fresh-rt' }));
+ sdk.walletChallenge.mockResolvedValue(ok({ message: 'sign this', nonce: 'n1' }));
+
+ const res = makeRes();
+ await challengeHandler(
+ makeReq({
+ url: '/api/community/wallet/challenge',
+ cookie: 'cc_rt=old-rt',
+ body: { address: TOKEN },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data).toEqual({ message: 'sign this', nonce: 'n1' });
+ });
+
+ it('rejects a request with no session before touching the upstream', async () => {
+ const res = makeRes();
+ await challengeHandler(
+ makeReq({ url: '/api/community/wallet/challenge', body: { address: TOKEN } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(401);
+ expect(res.json().error).toBe('unauthorized');
+ expect(sdk.walletChallenge).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/community/wallet/unlink', () => {
+ it('removes every linked svm wallet and reports the count', async () => {
+ sdk.getWallets.mockResolvedValue(
+ ok({
+ wallets: [
+ { id: 'w1', chainType: 'svm', address: 'A' },
+ { id: 'w2', chainType: 'svm', address: 'B' },
+ { id: 'w3', chainType: 'evm', address: '0xabc' },
+ ],
+ }),
+ );
+ sdk.unlinkWallet.mockResolvedValue(ok({}));
+
+ const res = makeRes();
+ await unlinkHandler(makeReq({ url: '/api/community/wallet/unlink', cookie: 'cc_at=at' }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data).toEqual({ unlinked: 2 });
+ expect(sdk.unlinkWallet).toHaveBeenCalledTimes(2);
+ });
+
+ it('treats an already-gone wallet (404) as unlinked', async () => {
+ sdk.getWallets.mockResolvedValue(
+ ok({ wallets: [{ id: 'w1', chainType: 'svm', address: 'A' }] }),
+ );
+ sdk.unlinkWallet.mockResolvedValue(fail(404, 'not found'));
+
+ const res = makeRes();
+ await unlinkHandler(makeReq({ url: '/api/community/wallet/unlink', cookie: 'cc_at=at' }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data).toEqual({ unlinked: 1 });
+ });
+
+ it('surfaces a real upstream unlink failure as 502', async () => {
+ sdk.getWallets.mockResolvedValue(
+ ok({ wallets: [{ id: 'w1', chainType: 'svm', address: 'A' }] }),
+ );
+ sdk.unlinkWallet.mockResolvedValue(fail(500, 'upstream exploded'));
+
+ const res = makeRes();
+ await unlinkHandler(makeReq({ url: '/api/community/wallet/unlink', cookie: 'cc_at=at' }), res);
+
+ expect(res.statusCode).toBe(502);
+ expect(res.json().error).toBe('unlink_failed');
+ });
+});
+
+describe('POST /api/community/wallet/link', () => {
+ it('links the wallet on a refreshed session and echoes the stored address', async () => {
+ sdk.refreshToken.mockResolvedValue(ok({ accessToken: 'fresh-at', refreshToken: 'fresh-rt' }));
+ sdk.linkWallet.mockResolvedValue(ok({ wallet: { address: TOKEN } }));
+
+ const res = makeRes();
+ await linkHandler(
+ makeReq({
+ url: '/api/community/wallet/link',
+ cookie: 'cc_rt=old-rt',
+ body: { address: TOKEN, signature: 'sig' },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.json().data).toEqual({ address: TOKEN });
+ expect(sdk.linkWallet.mock.calls[0][0].headers).toEqual({ Authorization: 'Bearer fresh-at' });
+ });
+
+ it('passes an upstream 409 (already linked) through instead of flattening it to 502', async () => {
+ sdk.linkWallet.mockResolvedValue(fail(409, 'wallet already linked'));
+
+ const res = makeRes();
+ await linkHandler(
+ makeReq({
+ url: '/api/community/wallet/link',
+ cookie: 'cc_at=at',
+ body: { address: TOKEN, signature: 'sig' },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(409);
+ expect(res.json().error).toBe('link_failed');
+ });
+});