Skip to content

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

fix(irl): one claim per payout wallet, and CSRF on agent-funded bounties

nirholasa07b2b1cf94d
diff --git a/api/_lib/irl-drops.js b/api/_lib/irl-drops.js
index c9564165e..2946ef789 100644
--- a/api/_lib/irl-drops.js
+++ b/api/_lib/irl-drops.js
@@ -346,8 +346,11 @@ export async function confirmFunding({ drop, signature, refundAddress = null })
// ── claim (atomic reservation under advisory lock) ────────────────────────────
/**
* Atomically reserve a claim slot for a claimant. Serialized per drop by an
- * advisory lock; bounded by max_claims; idempotent per claimant (a live claim
- * blocks a second). Returns { ok, claimId, amount_atomics, asset } on success, or
+ * advisory lock; bounded by max_claims; idempotent per claimant AND per payout
+ * wallet (a live claim blocks a second). The wallet half matters because an
+ * anonymous claimant's identity is a self-chosen device token: without it one
+ * person rotating the x-irl-device header drains every slot of a multi-claim
+ * drop into a single wallet. Returns { ok, claimId, amount_atomics, asset } on success, or
* { ok:false, reason } where reason ∈ inactive | expired | exhausted | already_claimed.
*/
export async function reserveClaim({ dropId, claimantUserId = null, claimantDevice = null, claimantKey, claimWallet }) {
@@ -372,7 +375,8 @@ export async function reserveClaim({ dropId, claimantUserId = null, claimantDevi
AND d.claims_count < d.max_claims
AND NOT EXISTS (
SELECT 1 FROM irl_drop_claims c
- WHERE c.drop_id = d.id AND c.claimant_key = ${claimantKey}
+ WHERE c.drop_id = d.id
+ AND (c.claimant_key = ${claimantKey} OR c.claim_wallet = ${claimWallet})
AND c.status IN ('pending','confirmed')
)
RETURNING id, amount_atomics, asset
@@ -394,7 +398,9 @@ export async function reserveClaim({ dropId, claimantUserId = null, claimantDevi
(SELECT (claims_count >= max_claims) FROM d) AS is_full,
(SELECT EXISTS (
SELECT 1 FROM irl_drop_claims c
- WHERE c.drop_id = ${dropId} AND c.claimant_key = ${claimantKey} AND c.status IN ('pending','confirmed')
+ WHERE c.drop_id = ${dropId}
+ AND (c.claimant_key = ${claimantKey} OR c.claim_wallet = ${claimWallet})
+ AND c.status IN ('pending','confirmed')
)) AS already
`;
const r = rows[0] || {};
diff --git a/api/irl/drops.js b/api/irl/drops.js
index 57509ef21..f3e1ca484 100644
--- a/api/irl/drops.js
+++ b/api/irl/drops.js
@@ -28,6 +28,7 @@ import { cors, json, wrap, error, rateLimited, readJson } from '../_lib/http.js'
import { ataExists } from '../_lib/solana/read-guards.js';
import { limits, clientIp, limitFailClosedRead } from '../_lib/rate-limit.js';
import { getSessionUser } from '../_lib/auth.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { readDeviceToken } from '../_lib/irl-auth.js';
import { verifyFixToken, fixEnforced } from '../_lib/irl-presence.js';
@@ -226,6 +227,9 @@ async function handleCreate(req, res, { body, userId, deviceToken, session }) {
// ── agent bounty (server-funded from the agent's custodial wallet) ─────────────
async function handleAgentBounty(req, res, { body, userId, agentId }) {
+ // Cookie-authed spend from a custodial agent wallet: same CSRF bar as every
+ // other route that signs with an agent key (world-lines, wallet send).
+ if (!(await requireCsrf(req, res, userId))) return;
if (!(await requireRealFundsAgreement(req, res, { userId, context: 'irl-agent-bounty' }))) return;
const loaded = await loadAgentForSigning(agentId, userId, { reason: 'irl_bounty_fund' });
if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
diff --git a/tests/api/irl-drops-handler.test.js b/tests/api/irl-drops-handler.test.js
index ab736f3df..5a4955dd9 100644
--- a/tests/api/irl-drops-handler.test.js
+++ b/tests/api/irl-drops-handler.test.js
@@ -63,6 +63,18 @@ vi.mock('../../api/_lib/db.js', () => ({
let sessionUser = null;
vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => sessionUser) }));
+// CSRF: refuse unless the header is present, the contract the real helper enforces
+// for a cookie-borne request.
+const requireCsrfMock = vi.fn(async (req, res) => {
+ if (req.headers['x-csrf-token']) return true;
+ res.statusCode = 403;
+ res.end(JSON.stringify({ error: 'csrf_missing' }));
+ return false;
+});
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: (...a) => requireCsrfMock(...a) }));
+const realFundsMock = vi.fn(async () => true);
+vi.mock('../../api/_lib/real-funds-agreement.js', () => ({ requireRealFundsAgreement: (...a) => realFundsMock(...a) }));
+
vi.mock('../../api/_lib/rate-limit.js', () => ({
limits: {
publicIp: vi.fn(async () => ({ success: true })),
@@ -176,3 +188,17 @@ describe('write paths refuse before any custody work', () => {
expect(res.statusCode).toBe(405);
});
});
+
+describe('agent bounty spends a custodial wallet, so it requires CSRF', () => {
+ it('403s a signed-in agent-bounty create without an X-CSRF-Token, before any signing', async () => {
+ sessionUser = { id: 'user-1' };
+ realFundsMock.mockClear();
+ const { res, body } = await call('POST', '/api/irl/drops', {
+ body: { agentId: 'agent-1', amount: 1, maxClaims: 1, lat: 1, lng: 1 },
+ });
+ expect(res.statusCode).toBe(403);
+ expect(body.error).toBe('csrf_missing');
+ expect(realFundsMock).not.toHaveBeenCalled();
+ expect(createDropMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/irl-drops-claim-wallet.test.js b/tests/irl-drops-claim-wallet.test.js
new file mode 100644
index 000000000..0ead09465
--- /dev/null
+++ b/tests/irl-drops-claim-wallet.test.js
@@ -0,0 +1,47 @@
+// IRL drop claims are idempotent per payout wallet, not only per claimant key.
+//
+// An anonymous claimant's identity is the x-irl-device header, a string the
+// client picks. Keying the "one claim per person" rule on that alone let one
+// person rotate the header and drain every slot of a multi-claim drop into a
+// single wallet. reserveClaim must refuse a second live claim to the same
+// claim_wallet on the same drop, both in the INSERT guard and in the
+// "already claimed" diagnosis that picks the error the caller sees.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const calls = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ calls.push({ text: strings.join('?'), values });
+ return [{ claim_id: null, drop_status: 'active', is_expired: false, is_full: false, already: true }];
+ }),
+}));
+
+const { reserveClaim } = await import('../api/_lib/irl-drops.js');
+
+const WALLET = 'So11111111111111111111111111111111111111112';
+
+describe('reserveClaim binds the payout wallet into the one-claim rule', () => {
+ beforeEach(() => { calls.length = 0; });
+
+ it('checks claim_wallet alongside claimant_key in the insert guard and the diagnosis', async () => {
+ const r = await reserveClaim({
+ dropId: '00000000-0000-4000-8000-000000000001',
+ claimantDevice: 'device-rotated-123',
+ claimantKey: 'd:device-rotated-123',
+ claimWallet: WALLET,
+ });
+ expect(r).toEqual({ ok: false, reason: 'already_claimed' });
+ expect(calls).toHaveLength(1);
+ const { text, values } = calls[0];
+ const walletChecks = text.match(/c\.claim_wallet = \?/g) || [];
+ expect(walletChecks).toHaveLength(2);
+ expect(values.filter((v) => v === WALLET).length).toBeGreaterThanOrEqual(3);
+ });
+
+ it('still refuses a malformed wallet before touching the database', async () => {
+ await expect(reserveClaim({ dropId: 'x', claimantKey: 'd:a', claimWallet: 'not a wallet' }))
+ .rejects.toMatchObject({ status: 400 });
+ expect(calls).toHaveLength(0);
+ });
+});