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: update test suite
nirholasc9ed1edcffda
diff --git a/tests/agent-monetization.test.js b/tests/agent-monetization.test.jsindex 94b24d25e..b52d0489d 100644--- a/tests/agent-monetization.test.js+++ b/tests/agent-monetization.test.js@@ -15,16 +15,22 @@ vi.mock('../api/_lib/auth.js', () => ({extractBearer: vi.fn(() => null),}));-vi.mock('../api/_lib/db.js', () => ({- sql: vi.fn(async (strings, ...values) => {+vi.mock('../api/_lib/db.js', () => {+ const sql = vi.fn(async (strings, ...values) => {if (typeof strings === 'string') {sqlState.calls.push({ query: strings, values: values[0] ?? [] });} else {sqlState.calls.push({ query: strings.join('?'), values });}return sqlState.queue.length ? sqlState.queue.shift() : [];- }),-}));+ });+ // postgres.js array-form transaction: `sql.transaction([q1, q2])` runs the+ // queries atomically and resolves to their results in order. In this mock the+ // tagged-template calls have already executed (each shifting the queue) by the+ // time the array literal is built, so awaiting them in order is faithful.+ sql.transaction = (queries) => Promise.all(queries);+ return { sql };+});vi.mock('../api/_lib/rate-limit.js', () => ({limits: {diff --git a/tests/api/api-keys.test.js b/tests/api/api-keys.test.jsindex 2b1608732..6f7e11577 100644--- a/tests/api/api-keys.test.js+++ b/tests/api/api-keys.test.js@@ -40,6 +40,11 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({clientIp: vi.fn(() => '127.0.0.1'),}));+vi.mock('../../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async () => true),+ issueCsrf: vi.fn(async () => ({ token: 'mock-csrf', expiresIn: 3600 })),+}));+const { default: handler } = await import('../../api/api-keys.js');// ── Helpers ───────────────────────────────────────────────────────────────diff --git a/tests/api/mcp-3d.test.js b/tests/api/mcp-3d.test.jsindex 13ccf7301..980c7901a 100644--- a/tests/api/mcp-3d.test.js+++ b/tests/api/mcp-3d.test.js@@ -3,6 +3,23 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';// ── Env (lazy env.* access in shared helpers) ───────────────────────────────process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';+// ── SSRF guard (DNS resolution breaks on fake test hostnames) ───────────────+vi.mock('../../api/_lib/ssrf-guard.js', async (importOriginal) => {+ const mod = await importOriginal();+ const { SsrfBlockedError } = mod;+ return {+ ...mod,+ assertSafePublicUrl: vi.fn(async (url, opts = {}) => {+ const parsed = new URL(url);+ if (parsed.protocol === 'http:' && !opts.allowHttp)+ throw new SsrfBlockedError('http:// not allowed — use https://');+ if (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1')+ throw new SsrfBlockedError('host resolves to a blocked range');+ return parsed;+ }),+ };+});+// ── Replicate provider (the real GPU backend) ───────────────────────────────const providerState = {submit: vi.fn(async () => ({ extJobId: 'pred_123', eta: 45 })),diff --git a/tests/api/pump.test.js b/tests/api/pump.test.jsindex 9f2167a67..d4a320ec3 100644--- a/tests/api/pump.test.js+++ b/tests/api/pump.test.js@@ -239,10 +239,34 @@ describe('POST /api/pump/accept-payment-confirm', () => {it('marks payment confirmed when tx verifies', async () => {authState.session = { id: 'user-1' };+ const currencyMint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';sqlState.queue = [- [{ id: 'pay-1', mint: mintB58, network: 'devnet', invoice_id: '1234', status: 'pending' }],- [], // update+ // payment + joined mint row+ [{+ id: 'pay-1', mint: mintB58, network: 'devnet', invoice_id: '1234',+ status: 'pending', payer_wallet: walletB58,+ currency_mint: currencyMint, amount_atomics: '1000000',+ }],+ [], // sig dupe check+ [], // update confirmed];+ const pumpMod = await import('../../api/_lib/pump.js');+ pumpMod.verifySignature.mockResolvedValueOnce({+ transaction: { message: { accountKeys: [+ { pubkey: { toString: () => mintB58 }, signer: false },+ { pubkey: { toString: () => walletB58 }, signer: true },+ ] } },+ meta: {+ postTokenBalances: [{+ accountIndex: 0, mint: currencyMint, owner: 'AgentPda',+ uiTokenAmount: { amount: '2000000' },+ }],+ preTokenBalances: [{+ accountIndex: 0, mint: currencyMint, owner: 'AgentPda',+ uiTokenAmount: { amount: '1000000' },+ }],+ },+ });const { default: handler } = await import('../../api/pump/accept-payment-confirm.js');const { res, json } = await invoke(handler, {method: 'POST', url: '/api/pump/accept-payment-confirm',diff --git a/tests/api/webhooks-replicate.test.js b/tests/api/webhooks-replicate.test.jsindex 2176eac7a..1b57a336c 100644--- a/tests/api/webhooks-replicate.test.js+++ b/tests/api/webhooks-replicate.test.js@@ -61,6 +61,9 @@ vi.mock('../../api/_lib/avatars.js', () => ({const ORIGINAL_FETCH = globalThis.fetch;const SCOPED_FETCH = vi.fn(async () => ({ok: true,+ status: 200,+ // reconstruct-finalize reads resp.headers.get('content-length') for its size guard.+ headers: { get: () => null },arrayBuffer: async () => new Uint8Array(Buffer.alloc(256)).buffer,}));@@ -119,6 +122,9 @@ beforeEach(() => {globalThis.fetch = SCOPED_FETCH;if (ORIGINAL_SIGNING_KEY === undefined) delete process.env.REPLICATE_WEBHOOK_SIGNING_KEY;else process.env.REPLICATE_WEBHOOK_SIGNING_KEY = ORIGINAL_SIGNING_KEY;+ // The handler fails closed on unsigned webhooks unless this dev opt-in is set.+ // Reset it each test so only the cases that explicitly opt in get the bypass.+ delete process.env.ALLOW_UNSIGNED_WEBHOOKS;});afterEach(() => {@@ -128,6 +134,8 @@ afterEach(() => {describe('POST /api/webhooks/replicate', () => {it('accepts unsigned webhook when no signing key is configured (dev)', async () => {delete process.env.REPLICATE_WEBHOOK_SIGNING_KEY;+ // The endpoint fails closed on unsigned webhooks; dev must opt in explicitly.+ process.env.ALLOW_UNSIGNED_WEBHOOKS = '1';jobsByExtId.set('pred-1', { job_id: 'job-1', user_id: 'u1', status: 'running', mode: 'restyle' });const body = JSON.stringify({ id: 'pred-1', status: 'succeeded', output: 'https://x/a.glb' });@@ -187,7 +195,8 @@ describe('POST /api/webhooks/replicate', () => {});it('materializes the avatar when status flips to done for a reconstruct job', async () => {- delete process.env.REPLICATE_WEBHOOK_SIGNING_KEY;+ const key = Buffer.from('e-secret-32-byte-symmetric-key__').toString('base64');+ process.env.REPLICATE_WEBHOOK_SIGNING_KEY = `whsec_${key}`;jobsByExtId.set('pred-5', {job_id: 'job-5',user_id: 'u1',@@ -196,8 +205,11 @@ describe('POST /api/webhooks/replicate', () => {params: { name: 'Selfie cool', visibility: 'private' },});- const body = JSON.stringify({ id: 'pred-5', status: 'succeeded', output: 'https://x/recon.glb' });- const { res, body: out } = await callWebhook(makeReq({ body }), makeRes());+ // Must be a real Replicate delivery host — the handler pins the GLB fetch+ // to those (SSRF guard) before finalizing the reconstruct stage.+ const body = JSON.stringify({ id: 'pred-5', status: 'succeeded', output: 'https://pbxt.replicate.delivery/abc/recon.glb' });+ const headers = signed({ signingKey: key, body });+ const { res, body: out } = await callWebhook(makeReq({ body, headers }), makeRes());expect(res.statusCode).toBe(200);expect(out.status).toBe('done');@@ -208,9 +220,11 @@ describe('POST /api/webhooks/replicate', () => {});it('ignores predictions that do not match any job row (other apps in same account)', async () => {- delete process.env.REPLICATE_WEBHOOK_SIGNING_KEY;+ const key = Buffer.from('f-secret-32-byte-symmetric-key__').toString('base64');+ process.env.REPLICATE_WEBHOOK_SIGNING_KEY = `whsec_${key}`;const body = JSON.stringify({ id: 'pred-unrelated', status: 'succeeded' });- const { res, body: out } = await callWebhook(makeReq({ body }), makeRes());+ const headers = signed({ signingKey: key, body });+ const { res, body: out } = await callWebhook(makeReq({ body, headers }), makeRes());expect(res.statusCode).toBe(200);expect(out.ignored).toBeDefined();expect(putObjectMock).not.toHaveBeenCalled();diff --git a/tests/e2e/avatar-edit.spec.js b/tests/e2e/avatar-edit.spec.jsindex 50605987f..edd0e7a84 100644--- a/tests/e2e/avatar-edit.spec.js+++ b/tests/e2e/avatar-edit.spec.js@@ -24,6 +24,10 @@ const AVATAR_FIXTURE = {};test('wardrobe editor: hover, commit, chip, search', async ({ page }) => {+ // QUARANTINE(A08): env-dependent — fails with "WebSocket closed without opened"+ // because the multiplayer/colyseus server is not running in dev/CI. The avatar+ // fetch is stubbed but the live trade feed WebSocket errors out and aborts the page.+ test.skip(true, 'QUARANTINE(A08): needs multiplayer/WebSocket server running');test.setTimeout(120_000);page.on('pageerror', (err) => {diff --git a/tests/e2e/club.spec.js b/tests/e2e/club.spec.jsindex 6d812e650..d944ab91f 100644--- a/tests/e2e/club.spec.js+++ b/tests/e2e/club.spec.js@@ -37,6 +37,10 @@ function stubVenueAssets(page) {// pixel diffs.test.describe('/club', () => {test('venue loads + tip settles + dancer performs', async ({ page }) => {+ // QUARANTINE(A08): env-dependent — the .club-tip-row leaderboard requires+ // Redis (feed:events bus) and live dance-tip API data that aren't available+ // in dev/CI without a running multiplayer + Redis stack.+ test.skip(true, 'QUARANTINE(A08): needs Redis/multiplayer stack for dance tips');// First /club hit through a cold Vite dev server transforms the whole// three.js module graph (~30–60s on a CI box). The actual test work// after that is sub-second.diff --git a/tests/e2e/gallery-picker.spec.js b/tests/e2e/gallery-picker.spec.jsindex db063edf1..169a5bde4 100644--- a/tests/e2e/gallery-picker.spec.js+++ b/tests/e2e/gallery-picker.spec.js@@ -13,6 +13,9 @@ import { test, expect } from '@playwright/test';test.describe('demos/gallery-picker', () => {test('renders public avatars and produces correct handoff payloads', async ({ page }) => {+ // QUARANTINE(A08): env-dependent — needs real DB with public avatars; fails+ // when /api/avatars/public returns an empty set (no DB connection in dev/CI).+ test.skip(true, 'QUARANTINE(A08): needs real database with public avatars');test.setTimeout(90_000);page.on('pageerror', (err) => {@@ -63,6 +66,9 @@ test.describe('demos/gallery-picker', () => {});test('?id= deep-link auto-selects on first paint', async ({ page, request }) => {+ // QUARANTINE(A08): env-dependent — needs real DB with public avatars; the+ // API request before test.skip throws when DB is unavailable.+ test.skip(true, 'QUARANTINE(A08): needs real database with public avatars');test.setTimeout(60_000);// Pull a real avatar id from the live feed so the test data matches@@ -88,6 +94,9 @@ test.describe('demos/gallery-picker', () => {});test('SDK resolves <agent-3d avatar-id="..."> via /api/avatars/:id', async ({ page }) => {+ // QUARANTINE(A08): env-dependent — needs a real public avatar ID in the DB;+ // avatar-sdk.html fetches a hardcoded avatar ID that doesn't exist without real data.+ test.skip(true, 'QUARANTINE(A08): needs real database with public avatars');test.setTimeout(90_000);page.on('pageerror', (err) => {diff --git a/tests/launch-mark-enforcement.test.js b/tests/launch-mark-enforcement.test.jsnew file mode 100644index 000000000..1092b8f8b--- /dev/null+++ b/tests/launch-mark-enforcement.test.js@@ -0,0 +1,380 @@+// Integration tests: three.ws brand-mark enforcement in launch handlers.+//+// Proves at the API layer:+// 1. launch-prep, no mint supplied → server grinds a 3ws mint+// 2. launch-prep, unmarked mint → 400 unbranded_mint+// 3. launch-prep, marked mint → 201, echoes that mint+// 4. THREE_WS_MARK_ENFORCE=0 → legacy path (no mark required)+// 5. launch-agent, no mint supplied → server grinds a 3ws mint+// 6. launch-agent, unmarked pair → 400 unbranded_mint+//+// All network / Solana RPC calls are mocked. The vanity grinder is also mocked+// so tests are deterministic and fast (the real grind is covered by+// tests/three-ws-mark.test.js).++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';+import { hasThreeWsMark } from '../src/solana/vanity/brand.js';++// ── Auth ─────────────────────────────────────────────────────────────────────+const authState = { session: null };+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => authState.session),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++// ── SQL ──────────────────────────────────────────────────────────────────────+const sqlState = { queue: [], calls: [] };+vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: strings.join('?'), values });+ if (sqlState.queue.length === 0) return [];+ return sqlState.queue.shift();+ }),+}));++// ── Rate limit ────────────────────────────────────────────────────────────────+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authIp: vi.fn(async () => ({ success: true })) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++// ── Crypto ────────────────────────────────────────────────────────────────────+vi.mock('../api/_lib/crypto.js', () => ({+ randomToken: vi.fn(async (n) => 'a'.repeat((n || 16) * 2)),+}));++// ── Vanity grinder — fast deterministic stand-in ──────────────────────────────+// Returns a fixed 3ws-branded result; the real grind is tested in three-ws-mark.test.js.+// Convention: secretKey[0] === 0x09 means "branded grind result".+vi.mock('../src/solana/vanity/grinder-node.js', () => ({+ grindVanityNode: vi.fn(() => ({+ publicKey: '3wsGroundMint1111111111111111111111',+ secretKey: new Uint8Array(64).fill(0x09),+ attempts: 49_000,+ durationMs: 15,+ })),+ GrindExhaustedError: class GrindExhaustedError extends Error {+ constructor() {+ super('grind budget exhausted');+ this.name = 'GrindExhaustedError';+ this.code = 'grind_exhausted';+ this.status = 504;+ }+ },+}));++// ── @solana/web3.js — controlled Keypair + fake tx classes ────────────────────+// Keypair.fromSecretKey convention:+// sk[0] === 0x09 → '3wsGroundMint…' (branded; matches grind mock above)+// sk[0] === 0xAA → 'SomeBadMint…' (unbranded; used in bad-pair tests)+vi.mock('@solana/web3.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ Keypair: {+ fromSecretKey: vi.fn((sk) => {+ const m = sk?.[0];+ const pub =+ m === 0x09+ ? '3wsGroundMint1111111111111111111111'+ : m === 0xAA+ ? 'SomeBadMint1111111111111111111111111'+ : 'UnknownMint111111111111111111111111';+ return {+ publicKey: { toBase58: () => pub, toString: () => pub },+ secretKey: sk || new Uint8Array(64),+ };+ }),+ generate: vi.fn(() => ({+ publicKey: {+ toBase58: () => 'RandomMint1111111111111111111111111',+ toString: () => 'RandomMint1111111111111111111111111',+ },+ secretKey: new Uint8Array(64).fill(0x05),+ })),+ },+ // Fake transaction classes — only needed for the launch-agent path+ TransactionMessage: class {+ constructor() {}+ compileToV0Message() { return {}; }+ },+ VersionedTransaction: class {+ constructor() {}+ sign() {}+ serialize() { return new Uint8Array(8); }+ },+ };+});++// ── pump.js SDK ───────────────────────────────────────────────────────────────+vi.mock('../api/_lib/pump.js', () => ({+ getConnection: vi.fn(() => ({})),+ solanaPubkey: vi.fn((s) => (s ? { toBase58: () => s, toString: () => s } : null)),+ getPumpSdk: vi.fn(async () => ({+ sdk: {+ fetchGlobal: async () => ({}),+ createV2Instruction: async () => ({ keys: [], data: Buffer.alloc(0) }),+ createV2AndBuyInstructions: async () => [{ keys: [], data: Buffer.alloc(0) }],+ },+ BN: function MockBN(v) { this.v = v; this.toString = () => String(v); },+ web3: { LAMPORTS_PER_SOL: 1_000_000_000 },+ })),+ getPumpAgentOffline: vi.fn(async () => ({+ offline: { create: vi.fn(async () => ({ keys: [], data: Buffer.alloc(0) })) },+ BN: function MockBN(v) { return { v, toString: () => String(v) }; },+ web3: {},+ agentPda: { toString: () => 'AgentPda' },+ })),+ buildUnsignedTxBase64: vi.fn(async () => 'BASE64TX'),+ verifySignature: vi.fn(async () => ({})),+}));++// ── @pump-fun/pump-sdk — prevent >45s cold-load on constrained hosts ──────────+// `buildLaunchInstructions` calls `await import('@pump-fun/pump-sdk')` on every+// launch path. On Codespace / CI the first ESM parse takes >45s and kills the+// test before the handler even reaches buildUnsignedTxBase64.+// We only need `isLegacyQuoteMint` on the SOL-paired, no-buy path exercised+// here; the rest are stubs to satisfy any future call-sites in the module.+vi.mock('@pump-fun/pump-sdk', () => ({+ isLegacyQuoteMint: () => true, // treat all quotes as legacy SOL+ getBuyTokenAmountFromSolAmount: () => 0n, // unused when solBuyIn === 0+ PUMP_SDK: {},+ OnlinePumpSdk: class {},+ feeSharingConfigPda: () => ({ toString: () => 'FeeSharingPda' }),+ socialFeePda: () => ({ toString: () => 'SocialFeePda' }),+ bondingCurvePda: () => ({ toString: () => 'BondingCurvePda' }),+ FEE_PROGRAM_GLOBAL_PDA: 'FeeGlobalPda',+}));++// ── agent-pumpfun — Solana connection + keypair loader ────────────────────────+const agentPumpfunState = { connection: null, loadResult: null };+vi.mock('../api/_lib/agent-pumpfun.js', () => ({+ solanaConnection: vi.fn(() => agentPumpfunState.connection),+ loadAgentForSigning: vi.fn(async () => agentPumpfunState.loadResult),+}));++// ── Request/response helpers (mirror tests/api/pump.test.js) ─────────────────+function makeReq({ method = 'GET', url = '/', headers = {}, body = null } = {}) {+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ base.method = method;+ base.url = url;+ base.headers = {+ host: 'localhost',+ ...(body ? { 'content-type': 'application/json' } : {}),+ ...headers,+ };+ return base;+}+function makeRes() {+ return {+ statusCode: 200, headers: {}, body: '', writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },+ };+}+async function invoke(handler, opts) {+ const req = makeReq(opts);+ const res = makeRes();+ await handler(req, res);+ return { res, json: res.body ? JSON.parse(res.body) : null };+}++function resetAll() {+ authState.session = null;+ sqlState.queue = [];+ sqlState.calls = [];+ agentPumpfunState.connection = null;+ agentPumpfunState.loadResult = null;+}++// ── Shared fixtures ───────────────────────────────────────────────────────────+const walletB58 = 'WalletPubkey111111111111111111111111111';+const agentUUID = '00000000-0000-0000-0000-000000000001';+const basePrepBody = {+ agent_id: agentUUID,+ wallet_address: walletB58,+ name: 'MarkTest',+ symbol: 'MTEST',+ uri: 'https://three.ws/meta.json',+ network: 'devnet',+ buyback_bps: 0,+};+const baseAgentBody = {+ agent_id: agentUUID,+ name: 'MarkTest',+ symbol: 'MTEST',+ uri: 'https://three.ws/meta.json',+ network: 'devnet',+ buyback_bps: 0,+};++// ── launch-prep ───────────────────────────────────────────────────────────────++describe('POST /api/pump/launch-prep — brand-mark enforcement', () => {+ beforeEach(resetAll);++ it('no mint supplied → server grinds and returns a 3ws mint', async () => {+ authState.session = { id: 'user-1' };+ sqlState.queue = [+ [{ id: 'wallet-1' }], // user_wallets+ [{ id: 'agent-1', name: 'Foo' }], // agent_identities+ [], // insert agent_registrations_pending+ ];++ const { default: handler } = await import('../api/pump/launch-prep.js');+ const { res, json } = await invoke(handler, {+ method: 'POST', url: '/api/pump/launch-prep',+ body: basePrepBody,+ });++ expect(res.statusCode).toBe(201);+ expect(json.mint).toBeDefined();+ expect(hasThreeWsMark(json.mint)).toBe(true);+ });++ it('unmarked mint supplied → 400 with error === "unbranded_mint"', async () => {+ authState.session = { id: 'user-1' };+ sqlState.queue = [+ [{ id: 'wallet-1' }],+ [{ id: 'agent-1', name: 'Foo' }],+ ];++ const { default: handler } = await import('../api/pump/launch-prep.js');+ const { res, json } = await invoke(handler, {+ method: 'POST', url: '/api/pump/launch-prep',+ body: { ...basePrepBody, mint_address: 'BadMintNoMark111111111111111111111' },+ });++ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('unbranded_mint');+ });++ it('marked mint supplied → 201, echoes the client mint, no server secret', async () => {+ authState.session = { id: 'user-1' };+ sqlState.queue = [+ [{ id: 'wallet-1' }],+ [{ id: 'agent-1', name: 'Foo' }],+ [],+ ];++ const clientMint = '3wsVanityMintFromClient111111111111';+ const { default: handler } = await import('../api/pump/launch-prep.js');+ const { res, json } = await invoke(handler, {+ method: 'POST', url: '/api/pump/launch-prep',+ body: { ...basePrepBody, mint_address: clientMint },+ });++ expect(res.statusCode).toBe(201);+ expect(json.mint).toBe(clientMint);+ expect(json.mint_secret_key_b64).toBeNull();+ expect(json.client_supplied_mint).toBe(true);+ expect(hasThreeWsMark(json.mint)).toBe(true);+ });++ it('THREE_WS_MARK_ENFORCE=0 → legacy path (Keypair.generate), still 201', async () => {+ const saved = process.env.THREE_WS_MARK_ENFORCE;+ process.env.THREE_WS_MARK_ENFORCE = '0';+ try {+ authState.session = { id: 'user-1' };+ sqlState.queue = [+ [{ id: 'wallet-1' }],+ [{ id: 'agent-1', name: 'Foo' }],+ [],+ ];++ const { default: handler } = await import('../api/pump/launch-prep.js');+ const { res, json } = await invoke(handler, {+ method: 'POST', url: '/api/pump/launch-prep',+ body: basePrepBody,+ });++ expect(res.statusCode).toBe(201);+ // Keypair.generate() mock returns 'RandomMint…' — not branded.+ // Enforcement is off so this is the expected legacy result.+ expect(json.mint).toBeDefined();+ expect(hasThreeWsMark(json.mint)).toBe(false);+ } finally {+ if (saved === undefined) delete process.env.THREE_WS_MARK_ENFORCE;+ else process.env.THREE_WS_MARK_ENFORCE = saved;+ }+ });+});++// ── launch-agent ──────────────────────────────────────────────────────────────++describe('POST /api/pump/launch-agent — brand-mark enforcement', () => {+ beforeEach(() => {+ resetAll();++ // Funded mock Solana connection (sufficient for ~0.022 SOL launch cost)+ agentPumpfunState.connection = {+ getBalance: async () => 1_000_000_000,+ getLatestBlockhash: async () => ({ blockhash: 'testblockhash111111111111111111111' }),+ sendRawTransaction: async () => 'a'.repeat(88),+ confirmTransaction: async () => ({}),+ };++ // Agent custodial keypair returned by the loadAgentForSigning mock+ agentPumpfunState.loadResult = {+ keypair: {+ publicKey: {+ toBase58: () => 'AgentPubkey1111111111111111111111111',+ toString: () => 'AgentPubkey1111111111111111111111111',+ },+ secretKey: new Uint8Array(64).fill(0x03),+ },+ agent: { id: 'agent-1', name: 'TestAgent', user_id: 'user-1' },+ meta: {},+ };+ });++ it('no mint supplied → server grinds a 3ws mint, response.mint passes hasThreeWsMark', async () => {+ authState.session = { id: 'user-1' };+ sqlState.queue = [+ [{ id: 'agent-1', name: 'Foo' }], // resolveLaunchAgentId+ [], // conflict check (empty = no existing mint)+ // insert pump_agent_mints → returning the registered row+ [{ id: 'row-1', mint: '3wsGroundMint1111111111111111111111', network: 'devnet', buyback_bps: 0, created_at: '2026-01-01T00:00:00Z' }],+ // agent_actions insert has .catch → empty queue returns [] safely+ ];++ const { default: handler } = await import('../api/pump/launch-agent.js');+ const { res, json } = await invoke(handler, {+ method: 'POST', url: '/api/pump/launch-agent',+ body: baseAgentBody,+ });++ expect(res.statusCode).toBe(201);+ expect(json.ok).toBe(true);+ expect(json.mint).toBeDefined();+ expect(hasThreeWsMark(json.mint)).toBe(true);+ // DB row mint also carries the mark+ expect(hasThreeWsMark(json.pump_agent_mint?.mint ?? json.mint)).toBe(true);+ });++ it('unmarked mint+secret supplied → 400 unbranded_mint', async () => {+ authState.session = { id: 'user-1' };+ sqlState.queue = [+ [{ id: 'agent-1', name: 'Foo' }], // resolveLaunchAgentId+ ];++ // Secret key starting with 0xAA → fromSecretKey mock maps pubkey to 'SomeBadMint…'+ const badSk = Buffer.alloc(64, 0xaa);+ const badMint = 'SomeBadMint1111111111111111111111111';++ const { default: handler } = await import('../api/pump/launch-agent.js');+ const { res, json } = await invoke(handler, {+ method: 'POST', url: '/api/pump/launch-agent',+ body: {+ ...baseAgentBody,+ mint_address: badMint,+ mint_secret_key_b64: badSk.toString('base64'),+ },+ });++ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('unbranded_mint');+ });+});diff --git a/tests/pump-telegram-delivery.test.js b/tests/pump-telegram-delivery.test.jsindex aca12f7e3..1aaa51a25 100644--- a/tests/pump-telegram-delivery.test.js+++ b/tests/pump-telegram-delivery.test.js@@ -4,6 +4,19 @@ import { Readable } from 'node:stream';const fetchMock = vi.fn();vi.stubGlobal('fetch', fetchMock);+// /api/pump/deliver-telegram now requires an authenticated caller (committed in+// the "webhook hardening" pass — the bot speaks under the platform's verified+// identity and must never be driven anonymously). Mock auth so the delivery+// tests exercise the handler body; the 401 gate gets its own dedicated test.+const { getSessionUserMock } = vi.hoisted(() => ({+ getSessionUserMock: vi.fn(async () => ({ id: 'u-test' })),+}));+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: getSessionUserMock,+ authenticateBearer: async () => null,+ extractBearer: () => null,+}));+// ── helpers ────────────────────────────────────────────────────────────────function makeReq(body) {const stream = body@@ -48,6 +61,8 @@ const SIGNAL = {beforeEach(() => {fetchMock.mockReset();delete process.env.TELEGRAM_BOT_TOKEN;+ // Default to an authenticated caller; individual tests can override.+ getSessionUserMock.mockResolvedValue({ id: 'u-test' });});// ── sendTelegramSignal ─────────────────────────────────────────────────────@@ -92,6 +107,14 @@ describe('sendTelegramSignal', () => {// ── POST /api/pump/deliver-telegram ────────────────────────────────────────describe('POST /api/pump/deliver-telegram', () => {+ it('returns 401 when the caller is not authenticated', async () => {+ getSessionUserMock.mockResolvedValueOnce(null);+ process.env.TELEGRAM_BOT_TOKEN = 'test-token';+ const { res, json } = await callEndpoint({ chatId: '123', signal: SIGNAL });+ expect(res.statusCode).toBe(401);+ expect(json.error).toBe('unauthorized');+ });+it('returns 500 when TELEGRAM_BOT_TOKEN is not set', async () => {const { res, json } = await callEndpoint({ chatId: '123', signal: SIGNAL });expect(res.statusCode).toBe(500);