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
test(api): cover the x402 front door, Solana Pay webhook, widget shares, previews, and tutor sessions
nirholas57a3181dda7f
diff --git a/tests/api/v1-x-front-door.test.js b/tests/api/v1-x-front-door.test.jsnew file mode 100644index 000000000..4d9d3f3d0--- /dev/null+++ b/tests/api/v1-x-front-door.test.js@@ -0,0 +1,95 @@+// GET /api/v1/x - the aggregator front door, and the routing regression that+// api/v1/x/index.js exists to prevent.+//+// The dispatch logic all lives in api/v1/x/[...slug].js, but a single-bracket+// catch-all never matches ZERO segments, so without the sibling index.js the+// exact URL documented in docs/api-reference.md, advertised as `base_url` in+// the discovery payload, and fetched by the /crypto-api storefront 404s. These+// tests pin both halves of that: index.js really is the same handler, and that+// handler answers the bare URL with the machine-readable provider catalog.+//+// Only the zero- and wrong-segment paths are exercised here, so nothing+// upstream is contacted and no billing lane runs: the free lane, the x402+// hand-off, and the plan/BYOK lanes are covered by tests/api/v1-free-tier.test.js+// and the x402 suites.++import { describe, it, expect } from 'vitest';+import { Readable } from 'node:stream';++function makeReq({ url, method = 'GET', host = 'three.ws' } = {}) {+ const stream = Readable.from([]);+ stream.method = method;+ stream.url = url;+ stream.headers = { host };+ return stream;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; this.writableEnded = true; },+ };+}++async function dispatch(modulePath, url) {+ const mod = await import(modulePath);+ const res = makeRes();+ await mod.default(makeReq({ url }), res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++describe('GET /api/v1/x front door', () => {+ it('api/v1/x/index.js re-exports the catch-all handler itself, not a copy', async () => {+ const index = await import('../../api/v1/x/index.js');+ const catchAll = await import('../../api/v1/x/[...slug].js');+ expect(typeof index.default).toBe('function');+ expect(index.default).toBe(catchAll.default);+ });++ it('answers the bare /api/v1/x with the provider catalog', async () => {+ const { res, body } = await dispatch('../../api/v1/x/index.js', '/api/v1/x');+ expect(res.statusCode).toBe(200);+ expect(body.data.base_url).toBe('/api/v1/x');+ expect(Array.isArray(body.data.providers)).toBe(true);+ expect(body.data.providers.length).toBeGreaterThan(0);+ for (const lane of ['byok', 'plan', 'free', 'x402']) {+ expect(typeof body.data.billing[lane]).toBe('string');+ }+ });++ it('lists real provider/endpoint pairs a caller can then request', async () => {+ const { body } = await dispatch('../../api/v1/x/index.js', '/api/v1/x');+ const { ENDPOINT_INDEX } = await import('../../api/v1/_providers.js');+ for (const provider of body.data.providers) {+ expect(provider.endpoints.length).toBeGreaterThan(0);+ for (const endpoint of provider.endpoints) {+ expect(ENDPOINT_INDEX.has(`${provider.id}/${endpoint.id}`)).toBe(true);+ }+ }+ });++ it('404s a provider with no endpoint, pointing at the catalog', async () => {+ const { res, body } = await dispatch('../../api/v1/x/[...slug].js', '/api/v1/x/coingecko');+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ expect(body.error_description).toContain('/api/v1/x');+ });++ it('404s an unregistered provider/endpoint pair by name', async () => {+ const { res, body } = await dispatch('../../api/v1/x/[...slug].js', '/api/v1/x/nosuch/endpoint');+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('unknown_endpoint');+ expect(body.error_description).toContain('nosuch/endpoint');+ });++ it('treats a parameterless request as a discovery probe, a parameterized one as a call', async () => {+ const { isParameterlessProbe } = await import('../../api/v1/x/[...slug].js');+ expect(isParameterlessProbe(makeReq({ url: '/api/v1/x/coingecko/price' }))).toBe(true);+ expect(isParameterlessProbe(makeReq({ url: '/api/v1/x/coingecko/price?ids=solana' }))).toBe(false);+ });+});diff --git a/tests/api/webhooks-solana-pay.test.js b/tests/api/webhooks-solana-pay.test.jsnew file mode 100644index 000000000..cdc5f9c06--- /dev/null+++ b/tests/api/webhooks-solana-pay.test.js@@ -0,0 +1,248 @@+// Tests for /api/webhooks/solana-pay - the off-web Solana Pay confirmation leg.+//+// Two contracts matter here and neither was covered before:+//+// 1. The GET discovery probe. Wallets render `label` + `icon` in the sheet the+// buyer approves, so the icon has to be a URL the site actually serves. It+// pointed at /assets/logo.png, which 404s to the HTML shell, and carried the+// retired 3D-Agent brand.+// 2. The POST leg moves money-adjacent state (ledger writes, receipts, referral+// splits via confirmSkillPurchase), so its auth gate, its input validation,+// and the mapping from each confirm outcome to a status code are the whole+// security and correctness surface.+//+// confirmSkillPurchase itself is mocked: this file tests the webhook boundary,+// and the confirm pipeline has its own on-chain coverage.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+const captureException = vi.fn();+vi.mock('../../api/_lib/sentry.js', () => ({ captureException }));+const sendOpsAlert = vi.fn(async () => {});+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert }));+vi.mock('../../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));++// One purchase row, keyed by reference, so the handler's lookup is real SQL+// shape against an in-memory table.+const purchasesByReference = new Map();+const sqlMock = vi.fn(async (strings, ...values) => {+ const text = strings.join('?').toLowerCase();+ if (text.includes('from skill_purchases')) {+ const row = purchasesByReference.get(values[0]);+ return row ? [row] : [];+ }+ return [];+});+vi.mock('../../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));++const confirmSkillPurchase = vi.fn(async () => ({ status: 'pending' }));+vi.mock('../../api/_lib/purchase-confirm.js', () => ({ confirmSkillPurchase }));++const { default: handler } = await import('../../api/webhooks/solana-pay.js');++const SECRET = 'test-webhook-secret';+const REFERENCE = 'THREEsyntheticReference1111111111111111111';++function mkReq({ method = 'POST', body = null, headers = {} } = {}) {+ const listeners = {};+ const req = {+ method,+ url: '/api/webhooks/solana-pay',+ headers: { 'content-type': 'application/json', ...headers },+ on(event, cb) { listeners[event] = cb; return req; },+ destroy() {},+ };+ queueMicrotask(() => {+ if (body && listeners.data) listeners.data(Buffer.from(body, 'utf8'));+ if (listeners.end) listeners.end();+ });+ return req;+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(b) { this.body = b; this.writableEnded = true; },+ };+}++async function invoke(opts = {}) {+ const res = mkRes();+ await handler(mkReq(opts), res);+ return { status: res.statusCode, headers: res.headers, body: res.body ? JSON.parse(res.body) : undefined };+}++function authed(body) {+ return { body: JSON.stringify(body), headers: { authorization: `Bearer ${SECRET}` } };+}++describe('/api/webhooks/solana-pay discovery probe', () => {+ it('advertises the current brand and an icon URL the site actually serves', async () => {+ const { status, body } = await invoke({ method: 'GET' });+ expect(status).toBe(200);+ expect(body.label).toContain('three.ws');+ // The regression this file exists for: /assets/logo.png is not a real path,+ // so a wallet rendered a broken merchant icon at the approval step.+ expect(body.icon).toBe('https://three.ws/logo.png');+ expect(body.icon).not.toContain('/assets/');+ });++ it('answers cross-origin so a wallet can fetch the probe', async () => {+ const { headers } = await invoke({ method: 'GET', headers: { origin: 'https://phantom.app' } });+ expect(headers['access-control-allow-origin']).toBe('*');+ });++ it('short-circuits the CORS preflight', async () => {+ const { status } = await invoke({ method: 'OPTIONS', headers: { origin: 'https://phantom.app' } });+ expect(status).toBe(204);+ });++ it('rejects a method the endpoint does not implement', async () => {+ const { status, body } = await invoke({ method: 'PUT' });+ expect(status).toBe(405);+ expect(body.error).toBe('method_not_allowed');+ });+});++describe('/api/webhooks/solana-pay confirm leg', () => {+ beforeEach(() => {+ confirmSkillPurchase.mockClear();+ captureException.mockClear();+ sendOpsAlert.mockClear();+ purchasesByReference.clear();+ purchasesByReference.set(REFERENCE, {+ id: 'pur-1',+ user_id: 'user-1',+ agent_id: 'agent-1',+ skill: 'render',+ status: 'pending',+ amount: '1500000',+ chain: 'solana',+ reference: REFERENCE,+ mint_decimals: 6,+ });+ process.env.WEBHOOK_SECRET = SECRET;+ });++ it('rejects a request with no bearer secret', async () => {+ const { status, body } = await invoke({ body: JSON.stringify({ reference: REFERENCE }) });+ expect(status).toBe(401);+ expect(body.error).toBe('unauthorized');+ expect(confirmSkillPurchase).not.toHaveBeenCalled();+ });++ it('rejects a wrong bearer secret', async () => {+ const { status } = await invoke({+ body: JSON.stringify({ reference: REFERENCE }),+ headers: { authorization: 'Bearer not-the-secret' },+ });+ expect(status).toBe(401);+ expect(confirmSkillPurchase).not.toHaveBeenCalled();+ });++ it('refuses every caller when no secret is configured on the deployment', async () => {+ delete process.env.WEBHOOK_SECRET;+ const { status } = await invoke(authed({ reference: REFERENCE }));+ expect(status).toBe(401);+ expect(confirmSkillPurchase).not.toHaveBeenCalled();+ });++ it('validates that a reference was supplied', async () => {+ const { status, body } = await invoke(authed({}));+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('rejects a non-string reference rather than coercing it into the lookup', async () => {+ const { status } = await invoke(authed({ reference: { $ne: null } }));+ expect(status).toBe(400);+ expect(confirmSkillPurchase).not.toHaveBeenCalled();+ });++ it('404s a reference with no purchase row', async () => {+ const { status, body } = await invoke(authed({ reference: 'THREEsyntheticUnknown22222222222222222222' }));+ expect(status).toBe(404);+ expect(body.error).toBe('not_found');+ expect(confirmSkillPurchase).not.toHaveBeenCalled();+ });++ it('returns the settled signature once the on-chain transfer validates', async () => {+ confirmSkillPurchase.mockResolvedValueOnce({ status: 'confirmed', tx_signature: 'sig-abc' });+ const { status, body } = await invoke(authed({ reference: REFERENCE }));+ expect(status).toBe(200);+ expect(body.data).toEqual({ status: 'confirmed', tx_signature: 'sig-abc' });+ expect(confirmSkillPurchase.mock.calls[0][0].reference).toBe(REFERENCE);+ });++ it('reports pending while the buyer has not broadcast yet', async () => {+ confirmSkillPurchase.mockResolvedValueOnce({ status: 'pending' });+ const { status, body } = await invoke(authed({ reference: REFERENCE }));+ expect(status).toBe(200);+ expect(body.data.status).toBe('pending');+ });++ it('maps an expired purchase to 410', async () => {+ confirmSkillPurchase.mockResolvedValueOnce({ status: 'expired' });+ const { status, body } = await invoke(authed({ reference: REFERENCE }));+ expect(status).toBe(410);+ expect(body.error).toBe('expired');+ });++ it('maps a mismatched transfer to 409', async () => {+ confirmSkillPurchase.mockResolvedValueOnce({ status: 'mismatch', message: 'no matching transfer found' });+ const { status, body } = await invoke(authed({ reference: REFERENCE }));+ expect(status).toBe(409);+ expect(body.error).toBe('transfer_mismatch');+ });++ it('surfaces the tipped amount so an underpaying buyer is not told their funds vanished', async () => {+ confirmSkillPurchase.mockResolvedValueOnce({+ status: 'tipped',+ message: 'transfer was smaller than the price',+ tipped_amount: '250000',+ tx_signature: 'sig-tip',+ });+ const { status, body } = await invoke(authed({ reference: REFERENCE }));+ expect(status).toBe(409);+ expect(body.status).toBe('tipped');+ expect(body.tipped_amount).toBe('250000');+ expect(body.tx_signature).toBe('sig-tip');+ });++ it('forwards a settlement hash so an EVM purchase is confirmable, not stuck pending', async () => {+ confirmSkillPurchase.mockResolvedValueOnce({ status: 'confirmed', tx_signature: '0xdead' });+ const { status } = await invoke(authed({ reference: REFERENCE, tx_hash: '0xdead' }));+ expect(status).toBe(200);+ expect(confirmSkillPurchase.mock.calls[0][1]).toEqual({ txHash: '0xdead' });+ });++ it('passes no hash for the Solana path, which scans by reference instead', async () => {+ confirmSkillPurchase.mockResolvedValueOnce({ status: 'pending' });+ await invoke(authed({ reference: REFERENCE }));+ expect(confirmSkillPurchase.mock.calls[0][1]).toEqual({ txHash: null });+ });++ it('escalates a confirm fault to the error tracker instead of swallowing it into a bare 500', async () => {+ confirmSkillPurchase.mockRejectedValueOnce(+ new Error('rpc failed: https://mainnet.helius-rpc.com/?api-key=leaky'),+ );+ const { status, body } = await invoke(authed({ reference: REFERENCE }));+ expect(status).toBe(500);+ // wrap() owns the 5xx envelope: the upstream message (which embeds a keyed+ // RPC URL) must never reach the caller, and ops must see the exception.+ expect(JSON.stringify(body)).not.toContain('api-key');+ expect(captureException).toHaveBeenCalledTimes(1);+ });+});diff --git a/tests/api/widgets-share-surfaces.test.js b/tests/api/widgets-share-surfaces.test.jsnew file mode 100644index 000000000..7fc05bb2a--- /dev/null+++ b/tests/api/widgets-share-surfaces.test.js@@ -0,0 +1,482 @@+/**+ * Widget share surfaces: oEmbed, the /w/:id metadata page, the baked-in demo+ * fixtures, and the edge geo header the view logger records.+ *+ * These are the endpoints social consumers hit (Slack, Discord, X, WordPress,+ * Ghost, Notion), so their contract is the preview every shared widget link+ * renders. Postgres and the embed-policy reader are mocked at the module+ * boundary; nothing here touches the network.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++const sqlQueue = [];+const sqlMock = vi.fn(() => {+ if (sqlQueue.length === 0) return Promise.resolve([]);+ const next = sqlQueue.shift();+ if (next instanceof Error) return Promise.reject(next);+ return Promise.resolve(next);+});++vi.mock('../../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const policyState = { policy: null };+vi.mock('../../api/_lib/embed-policy.js', () => ({+ readEmbedPolicy: vi.fn(async () => policyState.policy),+ originAllowed: (referer, policy) => {+ if (!policy?.origins?.length) return true;+ if (!referer) return false;+ return policy.origins.includes(new URL(referer).hostname);+ },+}));++const oembedHandler = (await import('../../api/widgets/oembed.js')).default;+const pageHandler = (await import('../../api/widgets/page.js')).default;+const viewHandler = (await import('../../api/widgets/view.js')).default;+const { DEMO_WIDGETS, isDemoWidgetId, getDemoWidget } = await import(+ '../../api/widgets/_demo-fixtures.js'+);+const { clientCountry, normalizeCountry } = await import('../../api/_lib/client-geo.js');+const { env } = await import('../../api/_lib/env.js');++function mockRes() {+ return {+ statusCode: 200,+ headers: {},+ _body: '',+ writableEnded: false,+ setHeader(name, value) {+ this.headers[name.toLowerCase()] = value;+ },+ getHeader(name) {+ return this.headers[name.toLowerCase()];+ },+ end(body) {+ if (body !== undefined) this._body = body;+ this.writableEnded = true;+ },+ };+}++function mockReq({ method = 'GET', url = '/', headers = {} } = {}) {+ return { method, url, headers: { ...headers }, socket: { remoteAddress: '127.0.0.1' } };+}++const ORIGIN = env.APP_ORIGIN;++function oembedReq(target, extra = '') {+ return mockReq({+ url: `/api/widgets/oembed?url=${encodeURIComponent(target)}${extra}`,+ });+}++beforeEach(() => {+ sqlQueue.length = 0;+ sqlMock.mockClear();+ policyState.policy = null;+});++// ── GET /api/widgets/oembed ─────────────────────────────────────────────────++describe('GET /api/widgets/oembed', () => {+ it('400s when the url parameter is missing', async () => {+ const res = mockRes();+ await oembedHandler(mockReq({ url: '/api/widgets/oembed' }), res);+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res._body).error).toBe('invalid_request');+ });++ it('returns a rich oEmbed payload for a demo widget without touching the DB', async () => {+ const res = mockRes();+ await oembedHandler(oembedReq(`${ORIGIN}/w/wdgt_demo_turntab`), res);+ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toMatch(/application\/json\+oembed/);+ const body = JSON.parse(res._body);+ expect(body.type).toBe('rich');+ expect(body.version).toBe('1.0');+ expect(body.title).toBe('Turntable Showcase');+ expect(body.html).toContain('<iframe');+ expect(body.html).toContain('wdgt_demo_turntab');+ expect(body.thumbnail_url).toBe(`${ORIGIN}/api/widgets/wdgt_demo_turntab/og`);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('sandboxes the embed iframe so a consumer cannot be navigated by it', async () => {+ const res = mockRes();+ await oembedHandler(oembedReq(`${ORIGIN}/w/wdgt_demo_turntab`), res);+ const { html } = JSON.parse(res._body);+ expect(html).toMatch(/sandbox="[^"]*allow-scripts/);+ expect(html).not.toContain('allow-top-navigation');+ });++ it('404s a url whose origin is not ours, so we cannot be used as an open resolver', async () => {+ const res = mockRes();+ await oembedHandler(oembedReq('https://evil.example.com/w/wdgt_demo_turntab'), res);+ expect(res.statusCode).toBe(404);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('404s a url that does not parse', async () => {+ const res = mockRes();+ await oembedHandler(oembedReq('not-a-url'), res);+ expect(res.statusCode).toBe(404);+ });++ it('501s an unsupported format instead of silently serving json', async () => {+ const res = mockRes();+ await oembedHandler(oembedReq(`${ORIGIN}/w/wdgt_demo_turntab`, '&format=yaml'), res);+ expect(res.statusCode).toBe(501);+ expect(JSON.parse(res._body).error).toBe('unsupported_format');+ });++ it('serves well-formed xml when format=xml', async () => {+ const res = mockRes();+ await oembedHandler(oembedReq(`${ORIGIN}/w/wdgt_demo_turntab`, '&format=xml'), res);+ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toMatch(/text\/xml/);+ expect(res._body).toMatch(/^<\?xml version="1\.0"/);+ expect(res._body).toContain('<title>Turntable Showcase</title>');+ // The iframe markup must be entity-escaped inside the xml element.+ expect(res._body).toContain('<iframe');+ expect(res._body).not.toMatch(/<html><iframe/);+ });++ it('resolves the /widget# and legacy /app# hash forms to the same widget', async () => {+ for (const target of [+ `${ORIGIN}/widget#widget=wdgt_demo_animgal`,+ `${ORIGIN}/app#widget=wdgt_demo_animgal`,+ `${ORIGIN}/#widget=wdgt_demo_animgal`,+ ]) {+ const res = mockRes();+ await oembedHandler(oembedReq(target), res);+ expect(res.statusCode).toBe(200);+ expect(JSON.parse(res._body).title).toBe('Animation Gallery');+ }+ });++ it('clamps maxwidth/maxheight into the supported range', async () => {+ const res = mockRes();+ await oembedHandler(+ oembedReq(`${ORIGIN}/w/wdgt_demo_turntab`, '&maxwidth=99999&maxheight=10'),+ res,+ );+ const body = JSON.parse(res._body);+ expect(body.width).toBe(1600);+ expect(body.height).toBe(240);+ });++ it('404s a private widget: the DB filters on is_public', async () => {+ sqlQueue.push([]);+ const res = mockRes();+ await oembedHandler(oembedReq(`${ORIGIN}/w/wdgt_private1`), res);+ expect(res.statusCode).toBe(404);+ expect(sqlMock).toHaveBeenCalled();+ });++ it('404s rather than 500s when the widgets table is absent', async () => {+ sqlQueue.push(new Error('relation "widgets" does not exist'));+ const res = mockRes();+ await oembedHandler(oembedReq(`${ORIGIN}/w/wdgt_real1234`), res);+ expect(res.statusCode).toBe(404);+ });+});++// ── GET /api/widgets/page (/w/:id) ──────────────────────────────────────────++describe('GET /api/widgets/page', () => {+ it('404s an HTML card when id is missing', async () => {+ const res = mockRes();+ await pageHandler(mockReq({ url: '/api/widgets/page' }), res);+ expect(res.statusCode).toBe(404);+ expect(res.headers['content-type']).toMatch(/text\/html/);+ expect(res._body).toContain('Widget not found');+ });++ it('renders the full crawler card for a demo widget', async () => {+ const res = mockRes();+ await pageHandler(mockReq({ url: '/api/widgets/page?id=wdgt_demo_hotspot' }), res);+ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toMatch(/text\/html/);+ const html = res._body;+ expect(html).toContain('<meta property="og:title" content="Hotspot Tour">');+ expect(html).toContain(`<meta property="og:url" content="${ORIGIN}/w/wdgt_demo_hotspot">`);+ expect(html).toContain(`<meta property="og:image" content="${ORIGIN}/api/widgets/wdgt_demo_hotspot/og">`);+ expect(html).toContain('<meta name="twitter:card" content="summary_large_image">');+ expect(html).toContain('application/json+oembed');+ expect(html).toContain(`<link rel="canonical" href="${ORIGIN}/w/wdgt_demo_hotspot">`);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('emits valid ld+json with the widget identity', async () => {+ const res = mockRes();+ await pageHandler(mockReq({ url: '/api/widgets/page?id=wdgt_demo_turntab' }), res);+ const ld = res._body.match(+ /<script type="application\/ld\+json">\n([\s\S]*?)\n\t<\/script>/,+ );+ expect(ld).not.toBeNull();+ const parsed = JSON.parse(ld[1]);+ expect(parsed['@type']).toBe('CreativeWork');+ expect(parsed.identifier).toBe('wdgt_demo_turntab');+ expect(parsed.url).toBe(`${ORIGIN}/w/wdgt_demo_turntab`);+ });++ it('escapes a hostile widget name instead of injecting markup', async () => {+ sqlQueue.push([+ {+ id: 'wdgt_xss12345',+ name: '</title><script>alert(1)</script>',+ type: 'turntable',+ avatar_id: null,+ agent_id: null,+ is_public: true,+ },+ ]);+ const res = mockRes();+ await pageHandler(mockReq({ url: '/api/widgets/page?id=wdgt_xss12345' }), res);+ expect(res.statusCode).toBe(200);+ expect(res._body).not.toContain('<script>alert(1)</script>');+ expect(res._body).toContain('<script>');+ });++ it('serves a noindex placeholder for a private widget, never its name', async () => {+ sqlQueue.push([+ {+ id: 'wdgt_private1',+ name: 'Unreleased Client Pitch',+ type: 'turntable',+ avatar_id: null,+ agent_id: null,+ is_public: false,+ },+ ]);+ const res = mockRes();+ await pageHandler(mockReq({ url: '/api/widgets/page?id=wdgt_private1' }), res);+ expect(res.statusCode).toBe(200);+ expect(res._body).toContain('noindex, nofollow');+ expect(res._body).toContain('Private widget');+ expect(res._body).not.toContain('Unreleased Client Pitch');+ expect(res.headers['cache-control']).toContain('private');+ });++ it('403s when the agent owner disabled the widget surface', async () => {+ sqlQueue.push([+ {+ id: 'wdgt_agent123',+ name: 'Agent widget',+ type: 'turntable',+ avatar_id: null,+ agent_id: 'agent-1',+ is_public: true,+ },+ ]);+ policyState.policy = { surfaces: { widget: false }, origins: [] };+ const res = mockRes();+ await pageHandler(mockReq({ url: '/api/widgets/page?id=wdgt_agent123' }), res);+ expect(res.statusCode).toBe(403);+ expect(res._body).toContain('Access denied');+ });++ it('403s when the referring origin is outside the agent policy allowlist', async () => {+ sqlQueue.push([+ {+ id: 'wdgt_agent123',+ name: 'Agent widget',+ type: 'turntable',+ avatar_id: null,+ agent_id: 'agent-1',+ is_public: true,+ },+ ]);+ policyState.policy = { surfaces: { widget: true }, origins: ['partner.example'] };+ const res = mockRes();+ await pageHandler(+ mockReq({+ url: '/api/widgets/page?id=wdgt_agent123',+ headers: { referer: 'https://scraper.example/post' },+ }),+ res,+ );+ expect(res.statusCode).toBe(403);+ });++ it('falls back to the pre-agent_id query when that column is absent', async () => {+ sqlQueue.push(new Error('column "agent_id" does not exist'));+ sqlQueue.push([+ {+ id: 'wdgt_legacy12',+ name: 'Legacy',+ type: 'turntable',+ avatar_id: null,+ is_public: true,+ },+ ]);+ const res = mockRes();+ await pageHandler(mockReq({ url: '/api/widgets/page?id=wdgt_legacy12' }), res);+ expect(res.statusCode).toBe(200);+ expect(res._body).toContain('Legacy');+ });++ it('404s rather than 500s when the widgets table is absent', async () => {+ sqlQueue.push(new Error('relation "widgets" does not exist'));+ const res = mockRes();+ await pageHandler(mockReq({ url: '/api/widgets/page?id=wdgt_real1234' }), res);+ expect(res.statusCode).toBe(404);+ });+});++// ── Demo fixtures ───────────────────────────────────────────────────────────++describe('widget demo fixtures', () => {+ const showcase = JSON.parse(+ readFileSync(+ fileURLToPath(new URL('../../public/widgets-gallery/showcase.json', import.meta.url)),+ 'utf8',+ ),+ );++ // The fixture module is the server-side half of the public gallery. If the+ // two lists drift, a gallery tile links to /w/<id> and gets the not-found+ // card, which is invisible until someone clicks it.+ it('stays in sync with the public gallery showcase', () => {+ const showcaseIds = (Array.isArray(showcase) ? showcase : showcase.widgets || showcase.items)+ .map((w) => w.id)+ .sort();+ expect(Object.keys(DEMO_WIDGETS).sort()).toEqual(showcaseIds);+ });++ it('gives every fixture the shape the share surfaces read', () => {+ for (const [key, w] of Object.entries(DEMO_WIDGETS)) {+ expect(w.id, key).toBe(key);+ expect(typeof w.name, key).toBe('string');+ expect(w.name.length, key).toBeGreaterThan(0);+ expect(typeof w.type, key).toBe('string');+ expect(w.is_public, key).toBe(true);+ expect(w.config, key).toBeTypeOf('object');+ // Every fixture serves its mesh from /public, so a share page never+ // needs an R2 round-trip or a signed URL.+ expect(w.avatar.model_url, key).toMatch(/^\//);+ }+ });++ it('declares only widget types the platform actually supports', async () => {+ const { WIDGET_TYPES } = await import('../../api/_lib/widget-types.js');+ for (const [key, w] of Object.entries(DEMO_WIDGETS)) {+ expect(WIDGET_TYPES, key).toContain(w.type);+ }+ });++ it('recognises demo ids and rejects everything else', () => {+ expect(isDemoWidgetId('wdgt_demo_turntab')).toBe(true);+ expect(isDemoWidgetId('wdgt_realone123')).toBe(false);+ expect(isDemoWidgetId(null)).toBe(false);+ expect(isDemoWidgetId(undefined)).toBe(false);+ expect(getDemoWidget('wdgt_demo_turntab').name).toBe('Turntable Showcase');+ // A demo-shaped id with no fixture must miss, not resolve to a partial.+ expect(getDemoWidget('wdgt_demo_nothere')).toBeNull();+ });+});++// ── Edge geo header ─────────────────────────────────────────────────────────++describe('clientCountry', () => {+ it('reads the Google Cloud load balancer geo header', () => {+ expect(clientCountry({ headers: { 'x-client-geo-location': 'US,Mountain View' } })).toBe('US');+ expect(clientCountry({ headers: { 'x-client-region': 'de' } })).toBe('DE');+ });++ it('still reads the Cloudflare and Vercel headers', () => {+ expect(clientCountry({ headers: { 'cf-ipcountry': 'FR' } })).toBe('FR');+ expect(clientCountry({ headers: { 'x-vercel-ip-country': 'JP' } })).toBe('JP');+ });++ it('prefers the load balancer header over a client-supplied one', () => {+ const headers = { 'x-client-geo-location': 'US,Reno', 'x-vercel-ip-country': 'ZZ' };+ expect(clientCountry({ headers })).toBe('US');+ });++ it('rejects anything that is not a two-letter code', () => {+ expect(normalizeCountry('NOT-A-COUNTRY-CODE')).toBeNull();+ expect(normalizeCountry('U')).toBeNull();+ expect(normalizeCountry('USA')).toBeNull();+ expect(normalizeCountry('<script>')).toBeNull();+ expect(normalizeCountry('')).toBeNull();+ expect(normalizeCountry(null)).toBeNull();+ expect(normalizeCountry(42)).toBeNull();+ });++ it('treats the Cloudflare unknown and Tor placeholders as no country', () => {+ expect(normalizeCountry('XX')).toBeNull();+ expect(normalizeCountry('T1')).toBeNull();+ });++ it('returns null when no geo header is present', () => {+ expect(clientCountry({ headers: {} })).toBeNull();+ expect(clientCountry({})).toBeNull();+ });+});++// ── POST /api/widgets/:id/view: country capture ──────────────────────────────++describe('POST /api/widgets/:id/view records the edge country', () => {+ function viewReq(headers) {+ return mockReq({ method: 'POST', url: '/api/widgets/view?id=wdgt_real1234', headers });+ }++ it('passes the normalised country through to the insert', async () => {+ sqlQueue.push([]);+ sqlQueue.push([]);+ const res = mockRes();+ await viewHandler(+ viewReq({ 'x-client-geo-location': 'NZ,Auckland', referer: 'https://example.com/a/b?q=1' }),+ res,+ );+ expect(res.statusCode).toBe(204);+ const values = sqlMock.mock.calls[0].slice(1);+ expect(values).toContain('NZ');+ // Referer is reduced to a bare hostname: no path, no query.+ expect(values).toContain('example.com');+ expect(values.some((v) => String(v).includes('?q=1'))).toBe(false);+ });++ it('drops a forged country header rather than storing arbitrary text', async () => {+ sqlQueue.push([]);+ sqlQueue.push([]);+ const res = mockRes();+ await viewHandler(viewReq({ 'x-vercel-ip-country': 'X'.repeat(500) }), res);+ expect(res.statusCode).toBe(204);+ // Bound values are (widget_id, country, referer_host): country must be null+ // and the forged string must appear nowhere in the statement.+ const values = sqlMock.mock.calls[0].slice(1);+ expect(values[1]).toBeNull();+ expect(values.some((v) => String(v).includes('XXX'))).toBe(false);+ });++ it('still 204s when the widget id matches no row (foreign-key miss)', async () => {+ const fk = Object.assign(new Error('insert violates foreign key constraint'), {+ code: '23503',+ });+ sqlQueue.push(fk);+ sqlQueue.push(fk);+ const res = mockRes();+ await viewHandler(viewReq({}), res);+ expect(res.statusCode).toBe(204);+ });++ // The best-effort swallow is deliberately narrow. A fault outside it must+ // reach the wrap() boundary and surface as a 5xx, never a phantom 204 that+ // hides the analytics lane going dark.+ it('surfaces a real database fault instead of reporting success', async () => {+ sqlQueue.push(+ Object.assign(new Error('column "country" does not exist'), { code: '42703' }),+ );+ const res = mockRes();+ await viewHandler(viewReq({}), res);+ expect(res.statusCode).toBeGreaterThanOrEqual(500);+ });+});diff --git a/tests/traders-preview.test.js b/tests/traders-preview.test.jsnew file mode 100644index 000000000..f76d0a4ca--- /dev/null+++ b/tests/traders-preview.test.js@@ -0,0 +1,305 @@+// Contract tests for GET /api/traders/preview — the public wallet track-record+// read behind /claim-wallet.+//+// Four defects this endpoint shipped with, each pinned below:+//+// 1. A database fault was swallowed by walletProfile()'s blanket catch, so an+// unreachable brain answered 200 `{known:false, claimable:false, coins:[]}`+// with `Cache-Control: public, max-age=120, stale-while-revalidate=300`.+// A 30-second Neon blip pinned "this wallet has no track record" over a+// real trader's record for the life of the CDN entry. Same class of bug as+// the Oracle read APIs in tests/oracle/api-db-outage.test.js; this endpoint+// was missed by that sweep.+// 2. `network=devnet` answered with the wallet's MAINNET trades: only the+// reputation read filtered on network, the coin read never did.+// 3. `claimable` required a wallet_reputation row, so a wallet with thousands+// of indexed pump.fun trades rendered as "no record found" whenever the+// rollup scorer hadn't graded it yet — which is the normal state for a+// wallet the indexer just picked up.+// 4. Win/loss counted every non-positive pnl, so an untouched open bag was a+// realized loss: a sniper holding 60 fresh positions read "0 wins / 60+// losses" next to `win_rate_window: null`, and the server disagreed with+// the client's own closed-only aggregate() on the same numbers.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../api/_lib/http.js', async () => {+ const actual = await vi.importActual('../api/_lib/http.js');+ return {+ ...actual,+ // wrap() is this contract's counterpart: it converts a propagated fault+ // into the shared 503 + Retry-After. Reduce it to identity so a test can+ // assert "the handler rejected" without the ops-alert and Sentry side+ // effects the real wrap() fires.+ wrap: (fn) => fn,+ cors: () => false,+ method: () => true,+ rateLimited: (res) => { res._rateLimited = true; },+ json: (res, status, body, headers = {}) => { res._json = { status, body, headers }; return res; },+ error: (res, status, code, message) => {+ res._json = { status, body: { error: code, error_description: message } };+ return res;+ },+ };+});++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '1.2.3.4',+}));++// The real classifier on a stubbed transport: the handler has to route on+// isDbUnavailableError() correctly, so mocking that function would test nothing.+// `dbQueue` answers the tagged-template reads in order (walletProfile issues the+// reputation read first, then the coin read); an Error entry rejects instead.+let dbQueue = [];+const dbCalls = [];+vi.mock('../api/_lib/db.js', async () => {+ const actual = await vi.importActual('../api/_lib/db.js');+ return {+ ...actual,+ sql: (strings, ...values) => {+ dbCalls.push({ text: Array.isArray(strings) ? strings.join('?') : String(strings), values });+ const next = dbQueue.shift();+ if (next instanceof Error) return Promise.reject(next);+ return Promise.resolve(next || []);+ },+ };+});++import { isDbUnavailableError } from '../api/_lib/db.js';+import preview from '../api/traders/preview.js';++// Shaped the way the Neon driver actually throws a transport failure: the `name`+// is load-bearing, because db.js only reads a connection-level message as an+// outage on a NeonDbError. A plain Error with the same text would test nothing.+const CONN_ERROR = Object.assign(new Error('Error connecting to database: fetch failed'), {+ name: 'NeonDbError',+});+const NO_URL_ERROR = new Error('Missing required env var: DATABASE_URL');+const STATEMENT_ERROR = new Error('column "nope" does not exist');++const WALLET = 'H454CBvtoGr5H4Eycmw5WusfWLCRCF8bbv7tRWPt787p';+const LAMPORTS = 1e9;++function fakeRes() {+ return {+ statusCode: 200,+ _headers: {},+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end() { this.writableEnded = true; },+ };+}++function fakeReq(url) {+ return { method: 'GET', url, headers: { host: 'three.ws' } };+}++// One pump_coin_wallets row, shaped the way the indexer writes it.+function coinRow(mint, { buySol = 1, sellSol = 0, bought = 1000, sold = 0, category = 'meme', creator = false } = {}) {+ return {+ mint,+ buy_count: 1,+ sell_count: sellSol > 0 ? 1 : 0,+ buy_lamports: String(buySol * LAMPORTS),+ sell_lamports: String(sellSol * LAMPORTS),+ base_bought: String(bought),+ base_sold: String(sold),+ is_creator: creator,+ first_seen_at: '2026-08-01T00:00:00.000Z',+ last_seen_at: '2026-08-01T00:10:00.000Z',+ symbol: mint.slice(0, 4),+ name: mint,+ image_uri: null,+ category,+ quality_score: 50,+ narrative: null,+ graduated: null,+ rugged: null,+ ath_multiple: null,+ last_market_cap_usd: null,+ };+}++const REP_ROW = {+ wallet: WALLET,+ coins_traded: 72, early_entries: 72, wins: 72, early_wins: 72, duds: 0, dumps: 0,+ creator_count: 0, creator_wins: 0,+ win_rate: 100, early_win_rate: 100, dump_rate: 0, smart_money_score: 100,+ label: 'smart_money',+ first_seen_at: '2026-07-29T11:25:01.117Z',+ last_active_at: '2026-08-06T09:05:01.633Z',+};++async function run(url) {+ const res = fakeRes();+ await preview(fakeReq(url), res);+ return res;+}++beforeEach(() => {+ dbQueue = [];+ dbCalls.length = 0;+});++describe('the classifier the outage contract branches on', () => {+ it('separates a connectivity failure from a statement fault', () => {+ expect(isDbUnavailableError(CONN_ERROR)).toBe(true);+ expect(isDbUnavailableError(NO_URL_ERROR)).toBe(true);+ expect(isDbUnavailableError(STATEMENT_ERROR)).toBe(false);+ });+});++describe('GET /api/traders/preview — input validation', () => {+ it('rejects a missing wallet with a 400 JSON error, never a stack trace', async () => {+ const res = await run('/api/traders/preview');+ expect(res._json.status).toBe(400);+ expect(res._json.body.error).toBe('invalid_wallet');+ expect(dbCalls).toHaveLength(0);+ });++ it('rejects base-58 lookalikes and injection-shaped input before any query', async () => {+ for (const bad of ['abc', '0OIl0OIl0OIl0OIl0OIl0OIl0OIl0OIl', "' or 1=1--", 'A'.repeat(5000)]) {+ const res = await run(`/api/traders/preview?wallet=${encodeURIComponent(bad)}`);+ expect(res._json.status).toBe(400);+ }+ expect(dbCalls).toHaveLength(0);+ });+});++describe('GET /api/traders/preview — outage honesty', () => {+ it('propagates a connectivity failure instead of publishing an empty record', async () => {+ dbQueue = [CONN_ERROR];+ await expect(run(`/api/traders/preview?wallet=${WALLET}`)).rejects.toThrow(/connecting to database/);+ });++ it('propagates an unset DATABASE_URL rather than answering "wallet not indexed"', async () => {+ dbQueue = [NO_URL_ERROR];+ await expect(run(`/api/traders/preview?wallet=${WALLET}`)).rejects.toThrow(/DATABASE_URL/);+ });++ it('propagates a fault on the coin read too, after the reputation read succeeded', async () => {+ // A half-answered profile is the worst outcome of all: it would publish a+ // graded reputation next to an empty ledger and cache that for two minutes.+ dbQueue = [[REP_ROW], CONN_ERROR];+ await expect(run(`/api/traders/preview?wallet=${WALLET}`)).rejects.toThrow(/connecting to database/);+ });++ it('propagates a statement fault as well, because there is no partial answer worth caching', async () => {+ dbQueue = [STATEMENT_ERROR];+ await expect(run(`/api/traders/preview?wallet=${WALLET}`)).rejects.toThrow(/does not exist/);+ });+});++describe('GET /api/traders/preview — network scoping', () => {+ it('scopes the coin read to the requested network, not just the reputation read', async () => {+ dbQueue = [[], []];+ await run(`/api/traders/preview?wallet=${WALLET}&network=devnet`);+ expect(dbCalls).toHaveLength(2);+ const [rep, coins] = dbCalls;+ expect(rep.values).toContain('devnet');+ expect(coins.text).toMatch(/i\.network/);+ expect(coins.values).toContain('devnet');+ });++ it('falls back to mainnet for an unknown network rather than trusting the caller', async () => {+ dbQueue = [[], []];+ const res = await run(`/api/traders/preview?wallet=${WALLET}&network=pwned`);+ expect(res._json.body.network).toBe('mainnet');+ expect(dbCalls[1].values).toContain('mainnet');+ });+});++describe('GET /api/traders/preview — claimability', () => {+ it('is claimable on indexed trades alone, before the rollup has graded the wallet', async () => {+ dbQueue = [[], [coinRow('MintAAAA')]];+ const res = await run(`/api/traders/preview?wallet=${WALLET}`);+ expect(res._json.status).toBe(200);+ expect(res._json.body.known).toBe(false);+ expect(res._json.body.profile).toBeNull();+ expect(res._json.body.claimable).toBe(true);+ });++ it('is claimable on a graded reputation alone, before the coin ledger loads any rows', async () => {+ dbQueue = [[REP_ROW], []];+ const res = await run(`/api/traders/preview?wallet=${WALLET}`);+ expect(res._json.body.known).toBe(true);+ expect(res._json.body.claimable).toBe(true);+ });++ it('reports a genuinely unseen wallet as neither known nor claimable', async () => {+ dbQueue = [[], []];+ const res = await run(`/api/traders/preview?wallet=${WALLET}`);+ expect(res._json.body.known).toBe(false);+ expect(res._json.body.claimable).toBe(false);+ expect(res._json.body.summary.total_coins).toBe(0);+ });+});++describe('GET /api/traders/preview — realized vs open accounting', () => {+ // Three positions, hand-computed:+ // WIN bought 1 SOL, sold 3 SOL, fully exited → closed, +2 SOL, roi +2+ // LOSS bought 2 SOL, sold 1 SOL, fully exited → closed, −1 SOL, roi −0.5+ // OPEN bought 4 SOL, sold nothing, bag intact → open, realized −4 SOL+ const LEDGER = [+ coinRow('MintWIN', { buySol: 1, sellSol: 3, bought: 1000, sold: 1000 }),+ coinRow('MintLOSS', { buySol: 2, sellSol: 1, bought: 1000, sold: 1000, category: 'ai' }),+ coinRow('MintOPEN', { buySol: 4, sellSol: 0, bought: 1000, sold: 0 }),+ ];++ it('counts only closed positions as wins and losses', async () => {+ dbQueue = [[REP_ROW], LEDGER];+ const { summary } = (await run(`/api/traders/preview?wallet=${WALLET}`))._json.body;+ expect(summary.total_coins).toBe(3);+ expect(summary.closed_coins).toBe(2);+ expect(summary.open_positions).toBe(1);+ expect(summary.wins_in_window).toBe(1);+ expect(summary.losses_in_window).toBe(1);+ expect(summary.win_rate_window).toBe(0.5);+ });++ it('reports realized PnL separately from the buy-inclusive net', async () => {+ dbQueue = [[REP_ROW], LEDGER];+ const { summary } = (await run(`/api/traders/preview?wallet=${WALLET}`))._json.body;+ // Realized: +2 from the winner, −1 from the loser. The open bag's 4 SOL+ // buy is not a realized loss and must not touch this number.+ expect(summary.realized_pnl_sol).toBe(1);+ // Net still books every lamport in and out: (3+1+0) − (1+2+4) = −3.+ expect(summary.net_pnl_sol).toBe(-3);+ expect(summary.total_buy_sol).toBe(7);+ expect(summary.total_sell_sol).toBe(4);+ expect(summary.total_volume_sol).toBe(11);+ });++ it('buckets closed positions by realized return and leaves open bags out', async () => {+ dbQueue = [[REP_ROW], LEDGER];+ const { summary } = (await run(`/api/traders/preview?wallet=${WALLET}`))._json.body;+ // +2× lands in x2, −50% lands in down, the open bag is in neither.+ expect(summary.distribution).toEqual({ x5: 0, x2: 1, up: 0, down: 1, rug: 0 });+ });++ it('marks a fully-held position open and a fully-exited one closed', async () => {+ dbQueue = [[REP_ROW], LEDGER];+ const { coins } = (await run(`/api/traders/preview?wallet=${WALLET}`))._json.body;+ const byMint = Object.fromEntries(coins.map((c) => [c.mint, c]));+ expect(byMint.MintOPEN.open).toBe(true);+ expect(byMint.MintOPEN.base_held).toBe(1000);+ expect(byMint.MintWIN.open).toBe(false);+ expect(byMint.MintWIN.base_held).toBe(0);+ expect(byMint.MintWIN.pnl_sol).toBe(2);+ expect(byMint.MintWIN.roi).toBe(2);+ });++ it('serves a successful read from the CDN and normalizes every timestamp', async () => {+ dbQueue = [[REP_ROW], LEDGER];+ const res = await run(`/api/traders/preview?wallet=${WALLET}`);+ expect(res._json.headers['Cache-Control']).toMatch(/max-age=120/);+ expect(res._json.body.profile.label).toBe('smart_money');+ expect(res._json.body.profile.first_seen_at).toBe('2026-07-29T11:25:01.117Z');+ for (const c of res._json.body.coins) {+ expect(c.first_seen_at).toBe('2026-08-01T00:00:00.000Z');+ expect(c.hold_ms).toBe(600000);+ }+ });+});diff --git a/tests/tutor-session-handler.test.js b/tests/tutor-session-handler.test.jsnew file mode 100644index 000000000..91c9cc5df--- /dev/null+++ b/tests/tutor-session-handler.test.js@@ -0,0 +1,217 @@+// GET/POST /api/tutor/session, the free tutor ledger endpoint, plus the ledger+// it reads.+//+// The endpoint shipped with no coverage and its only storage backend was an+// Upstash KV rail that is not configured on this deployment, so in production+// every read returned an empty tab and every "end session" returned a $0 invoice+// no matter how many $0.01 answers the learner had paid for. These tests pin the+// behaviour that fix depends on: the tab round-trips through the Postgres tier,+// a close is idempotent, closing an id that has no tab never poisons it, and a+// store fault surfaces as a failure instead of a false "you owe nothing".++import { beforeEach, describe, expect, it, vi } from 'vitest';++// Fake Postgres: enough of the tutor_sessions table to round-trip a session.+const rows = new Map();+const dbState = { failNextRead: false, failNextWrite: false };++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ const q = (typeof strings === 'string' ? strings : strings.join('?')).toLowerCase();+ if (q.includes('create table') || q.includes('create index') || q.includes('delete from')) return [];+ if (q.includes('insert into tutor_sessions')) {+ if (dbState.failNextWrite) {+ dbState.failNextWrite = false;+ throw new Error('write failed: storage at cap');+ }+ rows.set(values[0], values[3]);+ return [];+ }+ if (q.includes('select session from tutor_sessions')) {+ if (dbState.failNextRead) {+ dbState.failNextRead = false;+ throw new Error('connection terminated unexpectedly');+ }+ const stored = rows.get(values[0]);+ return stored ? [{ session: stored }] : [];+ }+ return [];+ }),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false, sizeMb: 1, highWaterMb: 100 }),+}));++const { default: handler } = await import('../api/tutor/session.js');+const ledger = await import('../agents/tutor/src/session.js');++function makeRes() {+ return {+ statusCode: 0,+ payload: null,+ headers: {},+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },+ writeHead(code) { this.statusCode = code; return this; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ end(chunk) {+ if (chunk) { try { this.payload = JSON.parse(String(chunk)); } catch { this.payload = String(chunk); } }+ return this;+ },+ };+}++async function call(req) {+ const res = makeRes();+ await handler(req, res);+ return res;+}++const get = (query) => call({ method: 'GET', url: `/api/tutor/session${query}`, headers: {} });++const post = (body) =>+ call({ method: 'POST', url: '/api/tutor/session', headers: { 'content-type': 'application/json' }, body });++const charge = (sessionId, question) =>+ ledger.appendCharge(sessionId, { question, level: 'beginner', costAtomics: 10_000, outputTokens: 42 });++beforeEach(() => {+ rows.clear();+ dbState.failNextRead = false;+ dbState.failNextWrite = false;+ // The tier production runs on: DATABASE_URL set, no KV.+ vi.stubEnv('DATABASE_URL', 'postgresql://tutor:tutor@localhost:5432/tutor');+ vi.stubEnv('UPSTASH_REDIS_REST_URL', '');+ vi.stubEnv('UPSTASH_REDIS_REST_TOKEN', '');+});++describe('tutor session ledger backend', () => {+ it('prefers Postgres, falls back to KV, then to process memory', () => {+ expect(ledger.sessionBackend()).toBe('db');+ vi.stubEnv('DATABASE_URL', '');+ vi.stubEnv('UPSTASH_REDIS_REST_URL', 'https://kv.example.upstash.io');+ vi.stubEnv('UPSTASH_REDIS_REST_TOKEN', 'token');+ expect(ledger.sessionBackend()).toBe('kv');+ vi.stubEnv('UPSTASH_REDIS_REST_URL', '');+ vi.stubEnv('UPSTASH_REDIS_REST_TOKEN', '');+ expect(ledger.sessionBackend()).toBe('memory');+ });++ it('renders atomics as a USDC 6dp string', () => {+ expect(ledger.atomicsToUsd(10_000)).toBe('0.010000');+ expect(ledger.atomicsToUsd(0)).toBe('0.000000');+ });++ it('rejects a charge on a closed session', async () => {+ await charge('s-closed', 'Why does my recursion overflow?');+ await ledger.closeSession('s-closed');+ await expect(charge('s-closed', 'one more')).rejects.toMatchObject({+ status: 409,+ code: 'session_closed',+ });+ });++ it('surfaces a store fault instead of reporting an empty tab', async () => {+ await charge('s-fault', 'Why does my recursion overflow?');+ dbState.failNextRead = true;+ await expect(ledger.loadSession('s-fault')).rejects.toThrow(/connection terminated/);+ });++ it('keeps the answer when the ledger read fails on the paid path', async () => {+ dbState.failNextRead = true;+ const session = await charge('s-degraded-read', 'Why does my recursion overflow?');+ expect(session.entries).toHaveLength(1);+ expect(session.totalAtomics).toBe(10_000);+ });++ it('keeps the answer when the ledger write fails on the paid path', async () => {+ dbState.failNextWrite = true;+ const session = await charge('s-degraded-write', 'Why does my recursion overflow?');+ expect(session.entries).toHaveLength(1);+ expect(rows.has('s-degraded-write')).toBe(false);+ });+});++describe('GET /api/tutor/session', () => {+ it('400s without a sessionId', async () => {+ const res = await get('');+ expect(res.statusCode).toBe(400);+ expect(res.payload.error).toBe('missing_session');+ });++ it('returns an empty open tab for an id that has no session yet', async () => {+ const res = await get('?sessionId=s-fresh');+ expect(res.statusCode).toBe(200);+ expect(res.payload).toMatchObject({ sessionId: 's-fresh', status: 'open', questionCount: 0, totalUsd: '0.000000' });+ expect(res.payload.lineItems).toEqual([]);+ });++ it('itemizes a tab persisted by an earlier paid answer', async () => {+ await charge('s-tab', 'Why does my recursion overflow?');+ await charge('s-tab', 'How do I make it iterative?');+ const res = await get('?sessionId=s-tab');+ expect(res.statusCode).toBe(200);+ expect(res.payload.questionCount).toBe(2);+ expect(res.payload.totalAtomics).toBe(20_000);+ expect(res.payload.totalUsd).toBe('0.020000');+ expect(res.payload.lineItems.map((l) => l.n)).toEqual([1, 2]);+ expect(res.payload.lineItems[0]).toMatchObject({ question: 'Why does my recursion overflow?', costUsd: '0.010000' });+ });++ it('caps an oversized sessionId rather than passing it to the store', async () => {+ const res = await get(`?sessionId=${'x'.repeat(400)}`);+ expect(res.statusCode).toBe(200);+ expect(res.payload.sessionId).toHaveLength(100);+ });+});++describe('POST /api/tutor/session', () => {+ it('400s without a sessionId', async () => {+ const res = await post({ action: 'end' });+ expect(res.statusCode).toBe(400);+ expect(res.payload.error).toBe('missing_session');+ });++ it('400s on an action other than end', async () => {+ const res = await post({ sessionId: 's-x', action: 'delete' });+ expect(res.statusCode).toBe(400);+ expect(res.payload.error).toBe('bad_action');+ });++ it('405s on a method the endpoint does not serve', async () => {+ const res = await call({ method: 'PUT', url: '/api/tutor/session', headers: {} });+ expect(res.statusCode).toBe(405);+ });++ it('closes the session with an itemized, attested invoice', async () => {+ await charge('s-close', 'Why does my recursion overflow?');+ const res = await post({ sessionId: 's-close', action: 'end' });+ expect(res.statusCode).toBe(200);+ expect(res.payload.questionCount).toBe(1);+ expect(res.payload.totalUsd).toBe('0.010000');+ expect(res.payload.attestation).toMatch(/^sha256:[0-9a-f]{64}$/);+ const after = await get('?sessionId=s-close');+ expect(after.payload.status).toBe('closed');+ expect(after.payload.invoice.attestation).toBe(res.payload.attestation);+ });++ it('returns the identical invoice when the same session is closed twice', async () => {+ await charge('s-twice', 'Why does my recursion overflow?');+ const first = await post({ sessionId: 's-twice', action: 'end' });+ const second = await post({ sessionId: 's-twice', action: 'end' });+ expect(second.payload).toEqual(first.payload);+ expect(second.payload.closedAt).toBe(first.payload.closedAt);+ });++ it('does not poison an id that has no tab, so its first charge still lands', async () => {+ const res = await post({ sessionId: 's-unused', action: 'end' });+ expect(res.statusCode).toBe(200);+ expect(res.payload.questionCount).toBe(0);+ expect(rows.has('s-unused')).toBe(false);+ const session = await charge('s-unused', 'first question');+ expect(session.status).toBe('open');+ expect(session.entries).toHaveLength(1);+ });+});