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(premium): show wallet-bought passes on the billing page and meter key rotation
nirholascf45c6461eaa
diff --git a/api/_lib/premium.js b/api/_lib/premium.jsindex b5c33730a..a10406295 100644--- a/api/_lib/premium.js+++ b/api/_lib/premium.js@@ -75,7 +75,7 @@ const TIERS = [defaultUsd: 99,defaultRate: 600,commercial: true,- blurb: 'Commercial use for products, dashboards, and research desks — 5× the throughput.',+ blurb: 'Commercial use for products, dashboards, and research desks, at 5x the throughput.',},{id: 'enterprise',@@ -136,7 +136,14 @@ export const PREMIUM_RESOURCES = ['https://three.ws/api/news/archive'];const QUOTE_TTL_MS = 10 * 60_000;const SOL_DECIMALS = 9;-function assetConfig(asset) {+/**+ * Mint + decimals for one accepted asset (mint is null for native SOL).+ * Exported so the pricing surface reports the same decimals the atomic amounts+ * were computed with. A hardcoded 6 there would silently misrender every+ * $THREE price the day THREE_TOKEN_DECIMALS is anything else.+ * Throws a 400 bad_asset for anything unaccepted.+ */+export function assetConfig(asset) {if (asset === 'USDC') {return { mint: env.X402_ASSET_MINT_SOLANA, decimals: USDC_DECIMALS };}diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 50cb75b6a..776745ca8 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -533,6 +533,14 @@ export const limits = {// minutes per IP is an active conversation, not a drain.agentRunIp: (ip) =>getLimiter('agent:run:ip', { limit: 30, window: '5 m', local: true }).limit(ip),+ // Public headless-chromium renderers (/api/render/glb, /api/render/avatar-clip).+ // One call boots or borrows a chromium page, pulls up to 10 MB of GLB, and+ // holds a CPU for seconds, so this is a real cost ceiling and NOT local: a+ // per-instance counter multiplies by however many Cloud Run instances are up,+ // which is exactly the bypass that made a 60/10m cap meaningless under+ // autoscale. Both renderers share one bucket because they share the browser.+ renderIp: (ip) =>+ getLimiter('render:ip', { limit: 60, window: '10 m' }).limit(ip),// Auth buckets gate credential guessing / account-creation spam. They are// sensitive (critical) but use degradeToMemory: on a Redis outage they fall// back to the per-instance memory limiter rather than failing closed. Failing@@ -1598,6 +1606,14 @@ export const limits = {getLimiter('premium:subscribe:ip', { limit: 30, window: '10 m' }).limit(ip),premiumStatusIp: (ip) =>getLimiter('premium:status:ip', { limit: 120, window: '1 m', local: true }).limit(ip),+ // Key management (api/premium/keys). Metered per account, not per IP: it is+ // session-gated, so the principal is the user. A rotate mints a real+ // x402_subscriptions row every call, which is the one premium action an+ // already-authenticated caller can repeat to grow a table without paying+ // anything; nobody legitimately rotates a key more than a handful of times+ // a day.+ premiumKeysUser: (userId) =>+ getLimiter('premium:keys:user', { limit: 20, window: '1 h' }).limit(userId),// Fact Checker (api/x402/fact-check) free daily lane. Same "free tier is the// funnel, x402 is the metered overage" shape as the AI speech routes above —// each free check runs the REAL search+LLM chain (never a degraded fake), sodiff --git a/api/premium/keys.js b/api/premium/keys.jsindex e5617b45b..34f855f96 100644--- a/api/premium/keys.js+++ b/api/premium/keys.js@@ -12,8 +12,9 @@// rotate returns the fresh plaintext exactly once and re-links the pass row// so status/mine keep reporting the live key.-import { cors, json, error, wrap, method, readJson } from '../_lib/http.js';+import { cors, json, error, wrap, method, readJson, rateLimited } from '../_lib/http.js';import { sql } from '../_lib/db.js';+import { limits } from '../_lib/rate-limit.js';import { getSessionUser } from '../_lib/auth.js';import { requireCsrf } from '../_lib/csrf.js';import { createSubscription, revokeSubscription } from '../_lib/x402/api-keys.js';@@ -31,6 +32,11 @@ export default wrap(async (req, res) => {if (!user) return json(res, 401, { error: 'unauthenticated' });if (!(await requireCsrf(req, res, user.id))) return;+ // Per-account, after auth: rotate mints a fresh x402_subscriptions row on+ // every call, so the bucket meters the principal doing the minting.+ const rl = await limits.premiumKeysUser(user.id);+ if (!rl.success) return rateLimited(res, rl, 'too many key operations; try again later');+const body = await readJson(req).catch(() => null);const action = String(body?.action || '');const id = String(body?.id || '').trim();diff --git a/api/premium/mine.js b/api/premium/mine.jsindex b186864c3..0716df6b1 100644--- a/api/premium/mine.js+++ b/api/premium/mine.js@@ -1,15 +1,23 @@// GET /api/premium/mine: the signed-in user's premium passes and keys.//// Session-cookie authed (the billing dashboard's data source). Returns passes-// purchased while signed in (user_id-linked) plus, when the account has a-// wallet_address that is a Solana key, passes bought by that wallet directly.+// purchased while signed in (user_id-linked) plus passes bought directly by any+// Solana wallet this account has proven it owns.+//+// "Proven it owns" is the whole point of resolving the wallets through+// linkedSolanaWallets(): a Solana address only reaches `user_wallets` by way of+// a verified SIWS signature, and `users.wallet_address` only by a verified SIWE+// one. Reading the legacy column alone (what this handler used to do) missed+// every Solana wallet on the platform, because the SIWS lane writes+// `user_wallets` and never touches `wallet_address`, and the SIWE lane writes a+// lowercased EVM address that can never be a Solana key. The effect was a+// billing page that showed nothing to exactly the buyers who paid wallet-only.import { cors, json, wrap, method } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { listPlans, premiumPlan, PREMIUM_RESOURCES } from '../_lib/premium.js';--const SOLANA_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+import { linkedSolanaWallets } from '../_lib/credit-deposit.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -23,12 +31,12 @@ export default wrap(async (req, res) => {}if (!user) return json(res, 401, { error: 'unauthenticated' });- const wallet = SOLANA_RE.test(user.wallet_address || '') ? user.wallet_address : null;+ const wallets = [...(await linkedSolanaWallets(user))];const passes = await sql`select id, wallet, plan, asset, amount_atomics, usd_price, tx_signature,api_subscription_id, started_at, expires_at, created_atfrom premium_passes- where user_id = ${user.id} ${wallet ? sql`or wallet = ${wallet}` : sql``}+ where user_id = ${user.id} ${wallets.length ? sql`or wallet = any(${wallets})` : sql``}order by created_at desclimit 50`;diff --git a/api/premium/plans.js b/api/premium/plans.jsindex c405822c7..9485acd9c 100644--- a/api/premium/plans.js+++ b/api/premium/plans.js@@ -8,8 +8,7 @@// parity and can never fail, so there is always at least one payable rail.import { cors, json, method, wrap } from '../_lib/http.js';-import { listPlans, priceAsset, PREMIUM_RESOURCES } from '../_lib/premium.js';-import { env } from '../_lib/env.js';+import { listPlans, priceAsset, assetConfig, PREMIUM_RESOURCES } from '../_lib/premium.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;@@ -21,17 +20,18 @@ export default wrap(async (req, res) => {['THREE', 'SOL', 'USDC'].map(async (asset) => {try {const p = await priceAsset(asset, plan);+ // Mint and decimals come from the same table the atomic+ // amount was computed against, so the two can never drift.+ // SOL is native and carries no mint.+ const { mint, decimals } = assetConfig(asset);return {asset,available: true,usd: p.usd,amount_atomics: p.atomics.toString(),- decimals: asset === 'SOL' ? 9 : 6,- ...(asset === 'THREE'- ? { mint: env.THREE_TOKEN_MINT, discount: plan.threeDiscount }- : asset === 'USDC'- ? { mint: env.X402_ASSET_MINT_SOLANA }- : {}),+ decimals,+ ...(mint ? { mint } : {}),+ ...(asset === 'THREE' ? { discount: plan.threeDiscount } : {}),};} catch (e) {return { asset, available: false, reason: e.message };diff --git a/docs/premium.md b/docs/premium.mdindex addc4a9b6..38a94df67 100644--- a/docs/premium.md+++ b/docs/premium.md@@ -96,9 +96,16 @@ at [/dashboard/billing](/dashboard/billing).The dashboards ride two raw endpoints you can also call directly:`POST /api/premium/keys` with `{ action: "rotate" | "revoke", id }`-(session + CSRF; rotate returns the fresh plaintext exactly once) and+(session + CSRF; rotate returns the fresh plaintext exactly once, and the+route is metered at 20 key operations per account per hour) and`GET /api/premium/mine` (session-authenticated; your passes and keys,-including passes bought directly by your linked Solana wallet).+including passes bought directly by any Solana wallet linked to your account).++"Linked" means a wallet you have signed in with: connecting a Solana wallet+once (SIWS) attaches it to the account, and every pass that wallet ever bought,+including ones bought before you had an account, shows up on the billing page+from then on. Nothing links by typing an address, so nobody else's purchases+can be claimed.## Rules and edge casesdiff --git a/prompts/swarm-100/api-premium-01.md b/prompts/swarm-100/api-premium-01.mddeleted file mode 100644index 6b0d90250..000000000--- a/prompts/swarm-100/api-premium-01.md+++ /dev/null@@ -1,106 +0,0 @@-# API audit: api/premium batch 01 (6 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/premium/keys.js-- api/premium/mine.js-- api/premium/plans.js-- api/premium/quote.js-- api/premium/status.js-- api/premium/subscribe.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-premium-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/premium-endpoints.test.js b/tests/premium-endpoints.test.jsindex 9b021ef14..110f68155 100644--- a/tests/premium-endpoints.test.js+++ b/tests/premium-endpoints.test.js@@ -24,7 +24,7 @@ const QUOTE_ID = '2af3ee5e-8b10-40d5-bbf2-f375197dc39f';const TX_SIG = '5Zx1uWnPZ8kkVYQ9mLXJx3nQ8Yb2c1D4eF5gH6jK7mN8pQ9rS1tU2vW3xY4zA5bC6dE7fG8hJ9kL1mN2pQ3r';const db = vi.hoisted(() => ({ handlers: [], calls: [] }));-const keyLane = vi.hoisted(() => ({ order: [], mintFails: false }));+const keyLane = vi.hoisted(() => ({ order: [], mintFails: false, underLimit: true }));vi.mock('../api/_lib/db.js', () => ({sql: async (strings, ...values) => {@@ -44,6 +44,7 @@ vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }))vi.mock('../api/_lib/rate-limit.js', () => ({limits: {premiumSubscribeIp: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })),+ premiumKeysUser: vi.fn(async () => ({ success: keyLane.underLimit, reset: Date.now() + 3_600_000 })),},clientIp: () => '127.0.0.1',}));@@ -95,6 +96,7 @@ beforeEach(() => {db.calls = [];keyLane.order = [];keyLane.mintFails = false;+ keyLane.underLimit = true;vi.clearAllMocks();});@@ -151,6 +153,14 @@ describe('POST /api/premium/keys: rotate ordering', () => {expect(db.calls.some((c) => /update premium_passes/.test(c.text))).toBe(false);});+ it('meters rotations per account, so a session cannot mint keys in a loop', async () => {+ keyLane.underLimit = false;+ const r = await call(keysHandler, '/api/premium/keys', { action: 'rotate', id: KEY_ID });+ expect(r._s).toBe(429);+ expect(r.json().error).toBe('rate_limited');+ expect(keyLane.order).toEqual([]);+ });+it('rejects a key that belongs to another account', async () => {db.handlers = [{ match: /from x402_subscriptions/, result: () => [{ ...premiumKeyRow, meta: { source: 'premium-pass', user_id: 'someone-else' } }] },diff --git a/tests/premium-mine.test.js b/tests/premium-mine.test.jsnew file mode 100644index 000000000..2b261f78e--- /dev/null+++ b/tests/premium-mine.test.js@@ -0,0 +1,197 @@+/**+ * GET /api/premium/mine: which passes the billing dashboard is allowed to show.+ *+ * The handler has to answer for two kinds of purchase: passes bought while+ * signed in (user_id-linked) and passes bought wallet-only, which carry no+ * user_id at all and can only be matched by wallet address.+ *+ * The wallet half is the part that broke. It used to read `users.wallet_address`+ * alone, but a Solana wallet reaches an account through the SIWS lane, which+ * writes `user_wallets` and never touches that column; the column is only+ * written by the SIWE lane, as a lowercased EVM address that can never look like+ * a Solana key. So the clause was dead for every Solana buyer on the platform.+ * These tests pin the resolution to the linked-wallet set, and pin the negative+ * case too: an EVM-only account must not splice a hex address into a Solana+ * address match.+ *+ * The DB and the session are mocked; linkedSolanaWallets() runs for real against+ * the mocked DB, so the user_wallets lookup itself is under test rather than+ * assumed. The HTTP envelope helpers run for real, so status codes and bodies+ * are genuine.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const USER_ID = '9c1f0a52-2c41-4a2c-9c65-9f6f8f5a4d10';+const SOL_A = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const SOL_B = 'THREEsynthetic1111111111111111111111111111';+const EVM = '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984';++const db = vi.hoisted(() => ({ handlers: [], calls: [] }));+const session = vi.hoisted(() => ({ user: null }));++vi.mock('../api/_lib/db.js', () => ({+ sql: async (strings, ...values) => {+ const text = strings.join(' $ ').replace(/\s+/g, ' ').trim();+ db.calls.push({ text, values });+ for (const h of db.handlers) {+ if (h.match.test(text)) return h.result(values, text);+ }+ return [];+ },+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));+vi.mock('../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => session.user) }));++const { default: handler } = await import('../api/premium/mine.js');++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, '_s', { get() { return this.statusCode; } });+ Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });+ return r;+}+async function call() {+ const req = {+ method: 'GET',+ url: '/api/premium/mine',+ headers: { origin: 'https://three.ws' },+ socket: { remoteAddress: '127.0.0.1' },+ };+ const res = makeRes();+ await handler(req, res);+ return res;+}++/** The `or wallet = any(...)` fragment, if the handler built one. */+function walletClause() {+ return db.calls.find((c) => /wallet = any/.test(c.text)) || null;+}++beforeEach(() => {+ db.handlers = [];+ db.calls = [];+ session.user = { id: USER_ID, email: '[email protected]', wallet_address: null };+ vi.clearAllMocks();+});++describe('GET /api/premium/mine: authentication', () => {+ it('answers 401 and touches no table when there is no session', async () => {+ session.user = null;+ const r = await call();+ expect(r._s).toBe(401);+ expect(r.json()).toEqual({ error: 'unauthenticated' });+ expect(db.calls).toEqual([]);+ });+});++describe('GET /api/premium/mine: which wallets a pass can be matched by', () => {+ it('matches every SIWS-linked Solana wallet, not just the legacy column', async () => {+ db.handlers = [{ match: /from user_wallets/, result: () => [{ address: SOL_A }, { address: SOL_B }] }];+ const r = await call();+ expect(r._s).toBe(200);++ const lookup = db.calls.find((c) => /from user_wallets/.test(c.text));+ expect(lookup.text).toMatch(/chain_type = 'solana'/);+ expect(lookup.values).toEqual([USER_ID]);+ expect(walletClause().values[0].sort()).toEqual([SOL_A, SOL_B].sort());+ });++ it('still honours a legacy wallet_address that is a Solana key', async () => {+ session.user = { ...session.user, wallet_address: SOL_A };+ const r = await call();+ expect(r._s).toBe(200);+ expect(walletClause().values[0]).toEqual([SOL_A]);+ });++ it('never matches on an EVM wallet_address, and omits the clause entirely', async () => {+ session.user = { ...session.user, wallet_address: EVM };+ const r = await call();+ expect(r._s).toBe(200);+ expect(walletClause()).toBe(null);+ expect(db.calls.every((c) => !c.values.includes(EVM))).toBe(true);+ });+});++describe('GET /api/premium/mine: payload', () => {+ const expired = {+ id: 'pass-old', wallet: SOL_A, plan: 'developer', asset: 'USDC', amount_atomics: '19990000',+ usd_price: '19.9900', tx_signature: 'sig-old', api_subscription_id: 'sub_old01',+ started_at: '2026-05-01T00:00:00.000Z', expires_at: '2026-05-31T00:00:00.000Z',+ created_at: '2026-05-01T00:00:00.000Z',+ };+ const live = {+ id: 'pass-live', wallet: SOL_A, plan: 'pro', asset: 'THREE', amount_atomics: '44025221398',+ usd_price: '79.2000', tx_signature: 'sig-live', api_subscription_id: 'sub_live01',+ started_at: '2026-08-01T00:00:00.000Z', expires_at: '2099-01-01T00:00:00.000Z',+ created_at: '2026-08-01T00:00:00.000Z',+ };++ beforeEach(() => {+ db.handlers = [+ { match: /from user_wallets/, result: () => [{ address: SOL_A }] },+ { match: /from premium_passes/, result: () => [live, expired] },+ {+ match: /from x402_subscriptions/,+ result: () => [{+ id: 'sub_live01', name: 'three.ws Pro pass', key_prefix: 'x402_live_ABCDEF',+ rate_limit_per_minute: 600, expires_at: '2099-01-01T00:00:00.000Z', revoked_at: null,+ meta: { source: 'premium-pass', plan: 'pro', wallet: SOL_A },+ granted: '128', denied: '2', last_seen: '2026-08-14T12:00:00.000Z',+ }, {+ id: 'sub_old01', name: 'three.ws Developer pass', key_prefix: 'x402_live_GHIJKL',+ rate_limit_per_minute: 120, expires_at: '2026-05-31T00:00:00.000Z',+ revoked_at: '2026-06-01T00:00:00.000Z', meta: { source: 'premium-pass', wallet: SOL_A },+ granted: null, denied: null, last_seen: null,+ }],+ },+ ];+ });++ it('reports the live pass as active and both keys with their usage', async () => {+ const r = await call();+ expect(r._s).toBe(200);+ const body = r.json();++ expect(body.active).toEqual({+ id: 'pass-live', wallet: SOL_A, expires_at: live.expires_at, asset: 'THREE', plan: 'pro',+ });+ expect(body.passes).toHaveLength(2);+ expect(body.plans.map((p) => p.id)).toEqual(['developer', 'pro', 'enterprise']);+ expect(body.plan.id).toBe('developer');+ expect(body.resources.length).toBeGreaterThan(0);++ expect(body.keys).toEqual([+ {+ id: 'sub_live01', name: 'three.ws Pro pass', key_prefix: 'x402_live_ABCDEF',+ rate_limit_per_minute: 600, expires_at: '2099-01-01T00:00:00.000Z', status: 'active',+ wallet: SOL_A, usage: { granted: 128, denied: 2, last_seen: '2026-08-14T12:00:00.000Z' },+ },+ {+ id: 'sub_old01', name: 'three.ws Developer pass', key_prefix: 'x402_live_GHIJKL',+ rate_limit_per_minute: 120, expires_at: '2026-05-31T00:00:00.000Z', status: 'revoked',+ wallet: SOL_A, usage: { granted: 0, denied: 0, last_seen: null },+ },+ ]);+ });++ it('never lets the response be cached', async () => {+ const r = await call();+ expect(String(r.getHeader('cache-control'))).toContain('no-store');+ });++ it('skips the key query when no pass carries a subscription', async () => {+ db.handlers = [+ { match: /from user_wallets/, result: () => [] },+ { match: /from premium_passes/, result: () => [{ ...live, api_subscription_id: null }] },+ ];+ const r = await call();+ expect(r._s).toBe(200);+ expect(r.json().keys).toEqual([]);+ expect(db.calls.some((c) => /from x402_subscriptions/.test(c.text))).toBe(false);+ });+});