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: remove scripts from .vercelignore except publish-lib.mjs

nirholasa9cca8cb0a14
diff --git a/api/_lib/audit.js b/api/_lib/audit.js
new file mode 100644
index 000000000..8b7119e8a
--- /dev/null
+++ b/api/_lib/audit.js
@@ -0,0 +1,31 @@
+// Audit log helper — fire-and-forget INSERT into audit_log.
+//
+// Policy: log sensitive state changes that need an after-the-fact "who did
+// what, when" trail (deletions, revocations, ownership transfers). Reads,
+// idempotent updates, and analytics belong in usage_events, not here.
+//
+// Schema: api/_lib/migrations/2026-05-01-audit-log.sql
+// Audit data starts 2026-05-01 — earlier deletions/revocations have no row.
+
+import { sql } from './db.js';
+
+/**
+ * Fire-and-forget audit log write. Never throws, never blocks the response.
+ * @param {object} entry
+ * @param {string|null} entry.userId — actor (null only when actor is unknown / system)
+ * @param {string} entry.action — short kebab-case verb, e.g. 'delete_avatar'
+ * @param {string|null} [entry.resourceId]
+ * @param {object|null} [entry.meta] — small JSON blob; avoid PII
+ */
+export function logAudit({ userId, action, resourceId = null, meta = null }) {
+ queueMicrotask(async () => {
+ try {
+ await sql`
+ insert into audit_log (user_id, action, resource_id, meta)
+ values (${userId}, ${action}, ${resourceId}, ${meta})
+ `;
+ } catch (err) {
+ console.error('[audit] insert failed', { action, resourceId, error: err?.message });
+ }
+ });
+}
diff --git a/api/_mcp/tools/avatars.js b/api/_mcp/tools/avatars.js
index 8a1af5011..fd7414bdd 100644
--- a/api/_mcp/tools/avatars.js
+++ b/api/_mcp/tools/avatars.js
@@ -14,7 +14,7 @@ import {
safeHttpsUrl,
} from '../render.js';
import { readMcpPolicyByAvatar } from '../embed-policy.js';
-import { sql } from '../../_lib/db.js';
+import { logAudit } from '../../_lib/audit.js';
function rpcError(code, message, data) {
const e = new Error(message);
@@ -237,13 +237,11 @@ export const toolDefs = [
}
const result = await deleteAvatar({ id: args.id, userId: auth.userId });
if (!result) throw new Error('avatar not found or not yours');
- queueMicrotask(async () => {
- try {
- await sql`
- INSERT INTO audit_log (user_id, action, resource_id)
- VALUES (${auth.userId}, 'delete_avatar', ${args.id})
- `;
- } catch { /* non-fatal */ }
+ logAudit({
+ userId: auth.userId,
+ action: 'delete_avatar',
+ resourceId: args.id,
+ meta: { via: 'mcp' },
});
return { content: [{ type: 'text', text: `Deleted avatar ${args.id}.` }] };
},
diff --git a/api/api-keys/[id].js b/api/api-keys/[id].js
index 98ddf3c6a..571c144fb 100644
--- a/api/api-keys/[id].js
+++ b/api/api-keys/[id].js
@@ -1,5 +1,6 @@
import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { logAudit } from '../_lib/audit.js';
import { cors, json, error, wrap, method } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -28,5 +29,11 @@ export default wrap(async (req, res) => {
if (!row) return error(res, 404, 'not_found', 'API key not found or already revoked');
+ logAudit({
+ userId,
+ action: 'revoke_api_key',
+ resourceId: row.id,
+ meta: { via: session ? 'session' : 'bearer' },
+ });
return json(res, 200, { data: { id: row.id, revoked: true } });
});
diff --git a/api/auth/wallet/[action].js b/api/auth/wallet/[action].js
index a3db1ef86..a1973e21c 100644
--- a/api/auth/wallet/[action].js
+++ b/api/auth/wallet/[action].js
@@ -4,6 +4,7 @@ import { verifyMessage, getAddress } from 'ethers';
import { z } from 'zod';
import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
+import { logAudit } from '../../_lib/audit.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
@@ -100,6 +101,7 @@ async function handleUnlink(req, res) {
}
await sql`delete from user_wallets where user_id = ${user.id} and address = ${addrLower}`;
+ logAudit({ userId: user.id, action: 'unlink_wallet', resourceId: addrLower });
return json(res, 200, { ok: true });
}
diff --git a/api/auth/wallets/[action].js b/api/auth/wallets/[action].js
index ee7fc0d7f..593c58f94 100644
--- a/api/auth/wallets/[action].js
+++ b/api/auth/wallets/[action].js
@@ -13,6 +13,7 @@ import { verifyMessage, getAddress } from 'ethers';
import { z } from 'zod';
import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
+import { logAudit } from '../../_lib/audit.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { parse } from '../../_lib/validate.js';
import { parseSiweMessage } from '../../_lib/siwe.js';
@@ -262,6 +263,7 @@ async function handleUnlinkWallet(req, res, address) {
// 4. Delete the wallet.
await sql`delete from user_wallets where user_id = ${session.id} and address = ${addrLower}`;
+ logAudit({ userId: session.id, action: 'unlink_wallet', resourceId: addrLower });
return json(res, 200, { removed: true });
}
diff --git a/api/avatars/[id].js b/api/avatars/[id].js
index 5814a0324..9882f63a7 100644
--- a/api/avatars/[id].js
+++ b/api/avatars/[id].js
@@ -12,6 +12,7 @@ import {
stripOwnerFor,
} from '../_lib/avatars.js';
import { sql } from '../_lib/db.js';
+import { logAudit } from '../_lib/audit.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { headObject } from '../_lib/r2.js';
import { limits } from '../_lib/rate-limit.js';
@@ -82,6 +83,12 @@ export default wrap(async (req, res) => {
}
const ok = await deleteAvatar({ id, userId: auth.userId });
if (!ok) return error(res, 404, 'not_found', 'avatar not found or not yours');
+ logAudit({
+ userId: auth.userId,
+ action: 'delete_avatar',
+ resourceId: id,
+ meta: { via: auth.source },
+ });
return json(res, 200, { ok: true });
});
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 224c7bb90..c5a0baabc 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -324,9 +324,10 @@ function erc8004Truncate(s, max) {
// index-delegations
// ═══════════════════════════════════════════════════════════════════════════
-const _dmIface = new Interface(DELEGATION_MANAGER_ABI);
-const DISABLED_TOPIC = _dmIface.getEvent('DisabledDelegation').topicHash;
-const REDEEMED_TOPIC = _dmIface.getEvent('RedeemedDelegation').topicHash;
+// Topic hashes are derived from the ABI so they stay in sync with contract changes.
+const dmIface = new Interface(DELEGATION_MANAGER_ABI);
+const DISABLED_TOPIC = dmIface.getEvent('DisabledDelegation').topicHash;
+const REDEEMED_TOPIC = dmIface.getEvent('RedeemedDelegation').topicHash;
// Max blocks per eth_getLogs call. Public RPCs 429 above ~2000.
const IDX_BLOCK_CAP = 2000;
@@ -338,7 +339,7 @@ const BLOCKS_PER_DAY = {
11155111: 7200, // Sepolia ~12 s/block
};
-// Public RPC fallbacks per chain — tried in order. Override primary via env RPC_<chainId>.
+// Public RPC fallbacks per chain — tried in order. Override primary via env RPC_URL_<chainId>.
const PUBLIC_RPCS = {
1: [
'https://cloudflare-eth.com',
@@ -458,6 +459,7 @@ async function idxIndexChain(chainId, contract) {
let toBlock = latestBlock; // updated each iteration; reflects final processed range
let revokedCount = 0;
let redeemedCount = 0;
+ let logErrorCount = 0;
while (fromBlock <= latestBlock) {
toBlock = Math.min(fromBlock + IDX_BLOCK_CAP - 1, latestBlock);
@@ -481,33 +483,81 @@ async function idxIndexChain(chainId, contract) {
}
for (const log of logs) {
- // DisabledDelegation: topics[1]=delegationHash, topics[2]=delegator, topics[3]=delegate
- // RedeemedDelegation: topics[1]=rootDelegator, topics[2]=redeemer (no delegationHash indexed)
- const delegationHash =
- log.topics[0] === DISABLED_TOPIC
- ? log.topics[1]
- : log.topics[2];
- const ts = blockTs[log.blockNumber];
-
- if (log.topics[0] === DISABLED_TOPIC) {
- const rows = await sql`
- UPDATE agent_delegations
- SET status = 'revoked',
- revoked_at = ${ts}::timestamptz,
- tx_hash_revoke = ${log.transactionHash}
- WHERE delegation_hash = ${delegationHash} AND status = 'active'
- RETURNING id
- `;
- revokedCount += rows.length;
- } else {
- const rows = await sql`
- UPDATE agent_delegations
- SET redemption_count = redemption_count + 1,
- last_redeemed_at = ${ts}::timestamptz
- WHERE delegation_hash = ${delegationHash}
- RETURNING id
- `;
- redeemedCount += rows.length;
+ try {
+ const ts = blockTs[log.blockNumber];
+ const topic = log.topics[0];
+
+ if (topic === DISABLED_TOPIC) {
+ // DisabledDelegation indexes delegationHash as topics[1].
+ const delegationHash = log.topics[1];
+ const rows = await sql`
+ UPDATE agent_delegations
+ SET status = 'revoked',
+ revoked_at = ${ts}::timestamptz,
+ tx_hash_revoke = ${log.transactionHash}
+ WHERE delegation_hash = ${delegationHash} AND status = 'active'
+ RETURNING id
+ `;
+ revokedCount += rows.length;
+ } else if (topic === REDEEMED_TOPIC) {
+ // RedeemedDelegation does not index delegationHash. Decode the
+ // non-indexed `delegation` tuple from log.data and defer to the
+ // contract's getDelegationHash() rather than reimplementing the
+ // EIP-712 struct hash locally — provably matches the on-chain
+ // value and survives any future ABI change to the struct.
+ const parsed = dmIface.parseLog({
+ topics: log.topics,
+ data: log.data,
+ });
+ const callData = dmIface.encodeFunctionData('getDelegationHash', [
+ parsed.args.delegation,
+ ]);
+ const raw = await idxRpc(urls, 'eth_call', [
+ { to: contract, data: callData },
+ 'latest',
+ ]);
+ const [delegationHash] = dmIface.decodeFunctionResult(
+ 'getDelegationHash',
+ raw,
+ );
+ const rows = await sql`
+ UPDATE agent_delegations
+ SET redemption_count = redemption_count + 1,
+ last_redeemed_at = ${ts}::timestamptz
+ WHERE delegation_hash = ${delegationHash}
+ RETURNING id
+ `;
+ redeemedCount += rows.length;
+ } else {
+ // eth_getLogs filter restricts to the two topics above, so this
+ // branch is unreachable under current configuration. Guard
+ // anyway so future filter widening fails loudly in logs
+ // rather than silently miscategorizing events.
+ logErrorCount++;
+ console.warn(
+ JSON.stringify({
+ stage: 'index-delegations',
+ chainId,
+ warning: 'unknown-topic',
+ topic,
+ tx: log.transactionHash,
+ }),
+ );
+ }
+ } catch (err) {
+ // Isolate per-log failures so one bad event doesn't abort the
+ // batch and force a full re-scan on the next tick.
+ logErrorCount++;
+ console.error(
+ JSON.stringify({
+ stage: 'index-delegations',
+ chainId,
+ error: 'log-process-failed',
+ message: err.message || String(err),
+ tx: log.transactionHash,
+ topic: log.topics?.[0],
+ }),
+ );
}
}
}
@@ -524,7 +574,7 @@ async function idxIndexChain(chainId, contract) {
fromBlock = toBlock + 1;
}
- return { fromBlock: initialFrom, toBlock, revokedCount, redeemedCount };
+ return { fromBlock: initialFrom, toBlock, revokedCount, redeemedCount, logErrorCount };
}
async function idxRpc(urls, method, params) {
diff --git a/api/keys/[id].js b/api/keys/[id].js
index 772f0e9e3..315b38451 100644
--- a/api/keys/[id].js
+++ b/api/keys/[id].js
@@ -2,6 +2,7 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
+import { logAudit } from '../_lib/audit.js';
import { cors, json, method, wrap, error } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
@@ -22,5 +23,11 @@ export default wrap(async (req, res) => {
returning id
`;
if (!rows[0]) return error(res, 404, 'not_found', 'key not found or already revoked');
+ logAudit({
+ userId: user.id,
+ action: 'revoke_api_key',
+ resourceId: rows[0].id,
+ meta: { via: 'session' },
+ });
return json(res, 200, { ok: true });
});