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(cron-auth): keep a machine session off the owner's activity streak and revoke it once the sweep ends
nirholas88f43deb8b27
diff --git a/api/_lib/auth.js b/api/_lib/auth.jsindex b3ae0381a..ae84d82c8 100644--- a/api/_lib/auth.js+++ b/api/_lib/auth.js@@ -147,7 +147,7 @@ export async function rotateSession({ currentSid, userId, userAgent, ip }) {return newSecret;}-export async function createSession({ userId, userAgent, ip }) {+export async function createSession({ userId, userAgent, ip, recordActivity = true }) {const secret = randomToken(32);const hash = await sha256(secret);await sql`@@ -157,10 +157,27 @@ export async function createSession({ userId, userAgent, ip }) {// A login (or the once-a-day silent session rotation in getSessionUser)// is a qualifying activity for the cross-surface streak. Fire-and-forget —// a streak-tracking hiccup must never block sign-in.- recordDailyActivity(userId).catch(() => {});+ //+ // Machine callers that mint a session purely to reach an owner-scoped+ // endpoint on the user's behalf (the launcher claimer's fee sweep, and any+ // future background sweep) pass recordActivity:false. A cron running on a+ // timer is not the owner showing up, and counting it would keep those+ // owners' streaks alive forever without them ever opening the site.+ if (recordActivity) recordDailyActivity(userId).catch(() => {});return secret;}+/**+ * Revoke a session by its plaintext token. Machine callers that mint a+ * short-lived session use this to leave no usable credential behind once their+ * sweep is done, instead of letting it sit valid for the full session TTL.+ */+export async function revokeSessionToken(token) {+ if (!token) return;+ const hash = await sha256(token);+ await sql`update sessions set revoked_at = now() where token_hash = ${hash}`;+}+export function sessionCookie(token, { clear = false } = {}) {if (clear) {// Clear both the current and legacy cookie names so logout fully drops session.@@ -232,10 +249,7 @@ export async function getSessionUser(req, res) {}export async function destroySession(req) {- const token = readSessionCookie(req);- if (!token) return;- const hash = await sha256(token);- await sql`update sessions set revoked_at = now() where token_hash = ${hash}`;+ await revokeSessionToken(readSessionCookie(req));}// CSRF token bound to the session cookie value. Because the cookie is HttpOnly,diff --git a/api/cron/launcher-claimer.js b/api/cron/launcher-claimer.jsindex 001bac62b..5846c9290 100644--- a/api/cron/launcher-claimer.js+++ b/api/cron/launcher-claimer.js@@ -17,10 +17,10 @@//// Auth: CRON_SECRET Bearer (same pattern as all cron endpoints).-import { json, error, method, wrapCron } from '../_lib/http.js';+import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';-import { createSession } from '../_lib/auth.js';+import { createSession, revokeSessionToken } from '../_lib/auth.js';import { requireCron } from '../_lib/cron-auth.js';const CLAIM_THRESHOLD_SOL = 0.01;@@ -53,11 +53,29 @@ async function ensureSchema() {_schemaDone = true;}-// Create a session as an agent's owner, then make a fetch call to an internal API-// path. The agent's owner session is required because collect-creator-fee-agent-// verifies the caller owns the agent.-async function agentFetch(ownerUserId, urlOrPath, opts = {}) {- const token = await createSession({ userId: ownerUserId, userAgent: 'launcher-claimer', ip: null });+// One machine session per owner per tick, minted lazily and revoked when the+// tick ends (see runClaimerTick's finally). Minting one per REQUEST, the+// previous shape, left two live sessions behind for every coin checked, up to+// 40 per tick every five minutes, and because createSession records a daily+// activity it also made a background sweep look like the owner signing in,+// keeping every launcher owner's streak alive without them opening the site.+async function sessionFor(ownerUserId, cache) {+ let token = cache.get(ownerUserId);+ if (!token) {+ token = await createSession({+ userId: ownerUserId,+ userAgent: 'launcher-claimer',+ ip: null,+ recordActivity: false,+ });+ cache.set(ownerUserId, token);+ }+ return token;+}++// Call an internal API path as the agent's owner. The owner session is required+// because collect-creator-fee-agent verifies the caller owns the agent.+async function agentFetch(token, urlOrPath, opts = {}) {const url = urlOrPath.startsWith('http') ? urlOrPath : `${ORIGIN}${urlOrPath}`;const res = await fetch(url, {...opts,@@ -71,12 +89,12 @@ async function agentFetch(ownerUserId, urlOrPath, opts = {}) {return res;}-async function processMint(run) {- const { id: runId, mint, agent_id: agentId, network, buyback_bps, owner_user_id: userId } = run;+async function processMint(run, token) {+ const { id: runId, mint, agent_id: agentId, network, buyback_bps } = run;// 1. Fetch live claimable balance.const feeRes = await agentFetch(- userId,+ token,`/api/pump/fee-info?mint=${encodeURIComponent(mint)}&network=${encodeURIComponent(network)}`,);if (!feeRes || !feeRes.ok) return { runId, status: 'fee-info-failed' };@@ -89,7 +107,7 @@ async function processMint(run) {}// 2. Claim — the agent signs its own fee claim (same identity that created the coin).- const claimRes = await agentFetch(userId, '/api/pump/collect-creator-fee-agent', {+ const claimRes = await agentFetch(token, '/api/pump/collect-creator-fee-agent', {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ agentId, mint, network }),@@ -148,22 +166,34 @@ async function runClaimerTick() {limit ${MAX_PER_TICK}`;- if (!runs.length) return { checked: 0, claimed: 0, skipped: 0, errors: 0 };+ if (!runs.length) return { checked: 0, claimed: 0, skipped: 0, errors: 0, details: [] };let claimed = 0, skipped = 0, errors = 0;const details = [];-- for (const run of runs) {- const result = await processMint(run).catch((err) => ({- runId: run.id, status: 'error', error: err?.message,- }));- details.push(result);- if (result.status === 'claimed') claimed++;- else if (result.status === 'below-threshold') skipped++;- else errors++;+ const sessions = new Map();++ try {+ for (const run of runs) {+ const result = await sessionFor(run.owner_user_id, sessions)+ .then((token) => processMint(run, token))+ .catch((err) => ({ runId: run.id, status: 'error', error: err?.message }));+ details.push(result);+ if (result.status === 'claimed') claimed++;+ else if (result.status === 'below-threshold') skipped++;+ else errors++;+ }+ } finally {+ // Never leave a usable owner credential sitting valid for the full session+ // TTL because a claim threw halfway through the sweep.+ await Promise.all(+ [...sessions.values()].map((t) => revokeSessionToken(t).catch(() => {})),+ );}- return { checked: runs.length, claimed, skipped, errors };+ // details is bounded by MAX_PER_TICK, and it is the only place a per-run+ // failure reason (fee-info-failed, claim-rejected) is visible to whoever+ // reads the cron response.+ return { checked: runs.length, claimed, skipped, errors, details };}export default wrapCron(async (req, res) => {diff --git a/tests/api/launcher-claimer-cron.test.js b/tests/api/launcher-claimer-cron.test.jsnew file mode 100644index 000000000..595a79728--- /dev/null+++ b/tests/api/launcher-claimer-cron.test.js@@ -0,0 +1,162 @@+// api/cron/launcher-claimer.js: the pump.fun creator-fee sweep.+//+// The claimer reaches owner-scoped endpoints (/api/pump/fee-info and+// /api/pump/collect-creator-fee-agent) by minting a real session for the coin+// owner, because those endpoints authenticate by session cookie. It used to+// mint one per REQUEST, which meant:+// · two live sessions per coin checked, up to 40 every five minutes, none of+// them ever revoked; and+// · two recordDailyActivity() calls per coin, so a cron on a timer kept every+// launcher owner's cross-surface streak alive without them opening the site.+// One session per owner per tick now, minted with recordActivity:false and+// revoked when the tick ends, even if a claim throws mid-sweep.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++const sqlMock = vi.fn(async () => []);+const createSession = vi.fn(async () => `tok-${createSession.mock.calls.length}`);+const revokeSessionToken = vi.fn(async () => {});++vi.mock('../../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));+vi.mock('../../api/_lib/auth.js', () => ({ createSession, revokeSessionToken }));+vi.mock('../../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));++const { default: handler } = await import('../../api/cron/launcher-claimer.js');++const OWNER_A = '11111111-1111-1111-1111-111111111111';+const OWNER_B = '22222222-2222-2222-2222-222222222222';+const runRow = (id, ownerUserId, mint) => ({+ id, mint, agent_id: `agent-${id}`, network: 'mainnet', buyback_bps: 5000,+ owner_user_id: ownerUserId, agent_name: `Agent ${id}`,+});++function call(method = 'GET', auth = 'Bearer test-cron-secret') {+ const res = {+ statusCode: 0,+ body: null,+ headers: {},+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(b) { this.body = b ? JSON.parse(b) : null; },+ get headersSent() { return this.body !== null; },+ get writableEnded() { return this.body !== null; },+ };+ const req = { method, url: '/api/cron/launcher-claimer', headers: { authorization: auth } };+ return handler(req, res).then(() => res);+}++// The claimer's SELECT is the only query that returns rows; every other call+// (create table, create index, insert claim) resolves empty.+function withRuns(rows) {+ sqlMock.mockImplementation(async (strings) => {+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (text.includes('from launcher_runs')) return rows;+ return [];+ });+}++const originalFetch = global.fetch;+let requests;++beforeEach(() => {+ process.env.CRON_SECRET = 'test-cron-secret';+ requests = [];+ sqlMock.mockReset();+ createSession.mockClear();+ revokeSessionToken.mockClear();+ withRuns([]);+ global.fetch = vi.fn(async (url, opts = {}) => {+ requests.push({ url: String(url), cookie: opts.headers?.cookie });+ if (String(url).includes('fee-info')) {+ return { ok: true, status: 200, json: async () => ({ claimable_lamports: '50000000' }) };+ }+ return {+ ok: true, status: 201,+ json: async () => ({ ok: true, signature: 'sig-1', lamports: 50_000_000 }),+ };+ });+});+afterEach(() => {+ delete process.env.CRON_SECRET;+ global.fetch = originalFetch;+ vi.restoreAllMocks();+});++describe('GET/POST /api/cron/launcher-claimer', () => {+ it('rejects a method it does not serve', async () => {+ const res = await call('DELETE');+ expect(res.statusCode).toBe(405);+ expect(createSession).not.toHaveBeenCalled();+ });++ it('rejects a bad cron secret before minting anything', async () => {+ const res = await call('GET', 'Bearer wrong');+ expect(res.statusCode).toBe(401);+ expect(createSession).not.toHaveBeenCalled();+ });++ it('mints nothing when no run is eligible', async () => {+ const res = await call();+ expect(res.statusCode).toBe(200);+ expect(res.body).toMatchObject({ ok: true, checked: 0, claimed: 0 });+ expect(createSession).not.toHaveBeenCalled();+ });++ it('mints one session per owner, not one per request, and never records activity', async () => {+ withRuns([+ runRow('run-1', OWNER_A, 'MintOne'),+ runRow('run-2', OWNER_A, 'MintTwo'),+ runRow('run-3', OWNER_B, 'MintThree'),+ ]);+ const res = await call();+ expect(res.statusCode).toBe(200);+ expect(res.body.checked).toBe(3);+ expect(res.body.claimed).toBe(3);++ // Two owners, three coins, six HTTP calls, but only two sessions.+ expect(requests).toHaveLength(6);+ expect(createSession).toHaveBeenCalledTimes(2);+ expect(createSession.mock.calls.map((c) => c[0].userId)).toEqual([OWNER_A, OWNER_B]);+ for (const [args] of createSession.mock.calls) {+ expect(args.recordActivity).toBe(false);+ }+ // Both of owner A's coins reused the same cookie.+ const aCookies = new Set(requests.slice(0, 4).map((r) => r.cookie));+ expect(aCookies.size).toBe(1);+ });++ it('revokes every minted session when the tick ends', async () => {+ withRuns([runRow('run-1', OWNER_A, 'MintOne'), runRow('run-3', OWNER_B, 'MintThree')]);+ await call();+ expect(revokeSessionToken).toHaveBeenCalledTimes(2);+ expect(new Set(revokeSessionToken.mock.calls.map((c) => c[0])).size).toBe(2);+ });++ it('still revokes when a claim throws mid-sweep', async () => {+ withRuns([runRow('run-1', OWNER_A, 'MintOne')]);+ global.fetch = vi.fn(async () => { throw new Error('network down'); });+ const res = await call();+ expect(res.statusCode).toBe(200);+ expect(res.body.errors).toBe(1);+ expect(revokeSessionToken).toHaveBeenCalledTimes(1);+ });++ it('reports why a coin was skipped instead of swallowing the reason', async () => {+ withRuns([runRow('run-1', OWNER_A, 'MintOne')]);+ global.fetch = vi.fn(async (url) => {+ requests.push({ url: String(url) });+ return { ok: true, status: 200, json: async () => ({ claimable_lamports: '1000' }) };+ });+ const res = await call();+ expect(res.body.skipped).toBe(1);+ expect(res.body.details[0]).toMatchObject({ runId: 'run-1', status: 'below-threshold' });+ });+});