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
feat(audit): implement audit log for token revocation and cleanup cron job
nirholasf28034121672
diff --git a/api/_lib/auth.js b/api/_lib/auth.jsindex 7c498874f..429882f78 100644--- a/api/_lib/auth.js+++ b/api/_lib/auth.js@@ -4,6 +4,7 @@ import bcrypt from 'bcryptjs';import { SignJWT, jwtVerify } from 'jose';import { env } from './env.js';import { sql } from './db.js';+import { logAudit } from './audit.js';import { randomToken, sha256, hmacSha256, constantTimeEquals } from './crypto.js';const ACCESS_TTL_SEC = 60 * 60; // 1h access tokens@@ -104,8 +105,17 @@ export async function rotateRefreshToken({ oldSecret, clientId, narrowScope }) {export async function revokeRefreshToken(secret, clientId) {const hash = await sha256(secret);- await sql`update oauth_refresh_tokens set revoked_at = now()- where token_hash = ${hash} and client_id = ${clientId} and revoked_at is null`;+ const [row] = await sql`update oauth_refresh_tokens set revoked_at = now()+ where token_hash = ${hash} and client_id = ${clientId} and revoked_at is null+ returning id, user_id`;+ if (row) {+ logAudit({+ userId: row.user_id,+ action: 'revoke_oauth_token',+ resourceId: row.id,+ meta: { client_id: clientId },+ });+ }}// ── browser sessions (cookie auth for the site itself) ──────────────────────diff --git a/api/_lib/migrations/2026-05-01-audit-log.sql b/api/_lib/migrations/2026-05-01-audit-log.sqlindex 5b0a1076d..b0b8552ae 100644--- a/api/_lib/migrations/2026-05-01-audit-log.sql+++ b/api/_lib/migrations/2026-05-01-audit-log.sql@@ -1,6 +1,13 @@-- Migration: audit log for sensitive operations.-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-01-audit-log.sql-- Idempotent.+--+-- Coverage: avatar deletion (MCP + REST), API key revocation,+-- OAuth refresh-token revocation, wallet unlink. Helper: api/_lib/audit.js.+--+-- Backfill: not possible — events before 2026-05-01 have no row. Log starts+-- the day this migration is applied. Retention: 365 days, enforced by the+-- audit-log-cleanup cron (see vercel.json).create table if not exists audit_log (id uuid primary key default gen_random_uuid(),diff --git a/api/avatars/index.js b/api/avatars/index.jsindex 9cb79dc60..7486c8278 100644--- a/api/avatars/index.js+++ b/api/avatars/index.js@@ -123,8 +123,12 @@ async function handleCreate(req, res) {order by created_at asclimit 1`;- } catch {- // Log and ignore — don't block the response.+ } catch (err) {+ console.error('[avatars] auto-link to agent_identities failed', {+ avatarId: avatar.id,+ userId: auth.userId,+ error: err?.message,+ });}});}diff --git a/api/cron/[name].js b/api/cron/[name].jsindex c5a0baabc..7c5f08dff 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -7,6 +7,7 @@* especially around auth / CRON_SECRET checks.** Cron paths handled (kebab-case → handler):+ * audit-log-cleanup → handleAuditLogCleanup* erc8004-crawl → handleErc8004Crawl* index-delegations → handleIndexDelegations* process-subscriptions → handleProcessSubscriptions@@ -59,6 +60,7 @@ const HANDLERS = {'run-dca': handleRunDca,'run-distribute-payments': handleRunDistributePayments,'run-subscriptions': handleRunSubscriptions,+ 'audit-log-cleanup': handleAuditLogCleanup,'settle-royalties': handleSettleRoyalties,'solana-attest-event-cleanup': handleSolanaAttestEventCleanup,'solana-attestations-crawl': handleSolanaAttestationsCrawl,@@ -2333,3 +2335,27 @@ async function handleSettleRoyalties(req, res) {const report = await settleAllPendingRoyalties();return json(res, 200, { ok: true, ...report });}++// ═══════════════════════════════════════════════════════════════════════════+// audit-log-cleanup — retention policy: keep 365 days of audit_log rows.+// ═══════════════════════════════════════════════════════════════════════════++const AUDIT_LOG_RETENTION_DAYS = 365;++async function handleAuditLogCleanup(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;++ const auth = req.headers['authorization'] || '';+ const cronSecret = env.CRON_SECRET;+ const fromCron = req.headers['x-vercel-cron'] === '1';+ if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {+ return error(res, 401, 'unauthorized', 'cron secret required');+ }++ const result = await sql`+ delete from audit_log+ where created_at < now() - (${AUDIT_LOG_RETENTION_DAYS} || ' days')::interval+ returning id+ `;+ return json(res, 200, { deleted: result.length, retention_days: AUDIT_LOG_RETENTION_DAYS });+}diff --git a/vercel-fix-prompts/RUNBOOK.md b/vercel-fix-prompts/RUNBOOK.mdnew file mode 100644index 000000000..7ffb04e10--- /dev/null+++ b/vercel-fix-prompts/RUNBOOK.md@@ -0,0 +1,108 @@+# Production Fix Runbook — 2026-05-01++Consolidated runbook for the 10 fix prompts in this directory. Everything code-side has shipped; operational steps remain.++---++## ✅ Already done++### Code fixes (in repo, deployed on next push)+- **#01** `parent_avatar_id` column added to `schema.sql`+- **#02** `index-delegations` topic hashes derived from ABI; `delegationHash` decoded from correct topic index+- **#03** `getRpcUrl` in `api/permissions/[action].js` has fallbacks for all 6 deployed chains+- **#04** `erc8004-crawl` default lookback reduced to 2000 blocks; 240s budget enforced+- **#06** Indexer reads `RPC_URL_<chainId>` (matches `.env.example`)+- **#08** `indexer_state` table added to `schema.sql`+- **#10** Audit log INSERT in MCP `delete_avatar` handler++### DB migrations applied to Neon production (2026-05-01)+- All 18 migrations from `api/_lib/migrations/2026-04-29-*` and `2026-04-30-*` (9 were already applied; 8 newly applied this run)+- `2026-05-01-audit-log.sql`+- Full `api/_lib/schema.sql` re-applied (idempotent) — picked up `parent_avatar_id` column and `indexer_state` table++`schema_migrations` tracking table now lists 19 applied migrations.++---++## ⚠️ Remaining operational steps++### 1. Rotate the Neon DB password (URGENT)++The production `DATABASE_URL` was pasted in chat on 2026-05-01 and must be rotated.++```+Neon Console → project → Branch → Roles → neondb_owner → Reset password+```++Then update `DATABASE_URL` in **Vercel → Settings → Environment Variables (Production)**.++### 2. Set the 10 required `req()` env vars in Vercel++Source of truth: `api/_lib/env.js` (anything wrapped in `req()` throws 500 on first access if unset).++| Variable | How to generate / where to find |+|---|---|+| `JWT_SECRET` | `openssl rand -base64 64` |+| `DATABASE_URL` | Neon connection string (rotate first — see step 1) |+| `S3_ENDPOINT` | Cloudflare R2: `https://<account_id>.r2.cloudflarestorage.com` |+| `S3_ACCESS_KEY_ID` | R2 dashboard → API tokens |+| `S3_SECRET_ACCESS_KEY` | R2 dashboard → API tokens |+| `S3_BUCKET` | Bucket name, e.g. `3d-agent-avatars` |+| `S3_PUBLIC_DOMAIN` | Public CDN URL for the bucket, no trailing slash |+| `ANTHROPIC_API_KEY` | console.anthropic.com → API keys |+| `AGENT_RELAYER_KEY` | `node -e "const {Wallet}=require('ethers'); const w=Wallet.createRandom(); console.log(w.privateKey, w.address)"` — fund the address with testnet ETH |+| `VOYAGE_API_KEY` | dash.voyageai.com → API keys |++Plus these "high but optional" vars to avoid silent feature degradation:++| Variable | Notes |+|---|---|+| `JWT_KID` | Defaults to `"k1"` if unset |+| `CRON_SECRET` | Random; crons run unauthenticated if unset |+| `UPSTASH_REDIS_REST_URL` + `UPSTASH_REDIS_REST_TOKEN` | Rate limiting fails open without these |++### 3. Set paid RPC providers (fixes #07 — 429 errors)++```+RPC_URL_1=https://eth-mainnet.g.alchemy.com/v2/<KEY> # Most important — public 1rpc.io currently 429-ing+RPC_URL_8453=https://base-mainnet.g.alchemy.com/v2/<KEY>+RPC_URL_84532=https://base-sepolia.g.alchemy.com/v2/<KEY>+RPC_URL_421614=https://arb-sepolia.g.alchemy.com/v2/<KEY>+RPC_URL_11155420=https://opt-sepolia.g.alchemy.com/v2/<KEY>+SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?api-key=<KEY>+```++The codebase keeps the public RPCs as automatic fallbacks, so paid endpoints only get hit during normal traffic.++### 4. Redeploy and verify++```+Vercel → Deployments → ⋯ → Redeploy+```++Then tail logs:++```bash+vercel logs --prod | grep -E '(Missing required env var|RPC HTTP 429|NeonDbError|Task timed out)'+```++Expected: empty. If anything appears, paste the error and trace it back to a fix prompt.++---++## How to apply future migrations++This repo has two separate scripts. Use them in this order:++```bash+export DATABASE_URL='postgres://...neon.tech/...?sslmode=require'++# 1. Apply tracked migrations (idempotent, recorded in schema_migrations).+node scripts/apply-migrations.mjs # dry-run: shows pending+node scripts/apply-migrations.mjs --apply # executes++# 2. Re-apply schema.sql for additive ALTER TABLE / CREATE TABLE (idempotent).+node scripts/apply-schema.mjs+```++Going forward, prefer adding new tables/columns as a dated migration in `api/_lib/migrations/` rather than editing `schema.sql` directly — the migrations runner is the single source of truth for production state.diff --git a/vercel.json b/vercel.jsonindex 1c78952d6..fe4e7be73 100644--- a/vercel.json+++ b/vercel.json@@ -963,6 +963,10 @@}],"crons": [+ {+ "path": "/api/cron/audit-log-cleanup",+ "schedule": "0 4 * * *"+ },{"path": "/api/cron/erc8004-crawl","schedule": "*/15 * * * *"