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.

feat: add runtime feature flags and audit for x402 endpoint documentation

qbdz421457a72b8e
diff --git a/.gitignore b/.gitignore
index c0bae76e5..e9924628d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -307,4 +307,3 @@ three-ws-*-log-export-*.json
.pump-launch-wallets/
pump-launch-wallets*.zip
.preview/
-three-ws-club-music.wav
diff --git a/api/_lib/flags.js b/api/_lib/flags.js
new file mode 100644
index 000000000..b15265422
--- /dev/null
+++ b/api/_lib/flags.js
@@ -0,0 +1,132 @@
+// @ts-check
+// Runtime feature flags — DB-backed switches that flip without a redeploy.
+//
+// A flag lives in the `app_flags` table (key, enabled, value). Code reads it
+// with isFlagEnabled()/getFlag(); an admin flips it via POST /api/admin/flags.
+// When no row exists the flag reports its caller-supplied `fallback` (normally
+// the matching env var), so adopting a flag is back-compatible: behavior only
+// changes once someone sets a row.
+//
+// Reads are cached in-process for a short TTL so a per-minute cron and hot paths
+// don't hit the DB every call. Each serverless instance refreshes independently,
+// so a toggle propagates fleet-wide within CACHE_TTL_MS. setFlag() clears the
+// local entry immediately so the writer sees its own change at once.
+//
+// Every read is fail-soft: if the DB is unconfigured or the query throws, the
+// flag resolves to `fallback` rather than propagating the error — a flags table
+// outage must never take down a cron or a request path.
+
+import { sql } from './db.js';
+
+const CACHE_TTL_MS = 30_000;
+
+/** @type {Map<string, { enabled: boolean, value: unknown, exists: boolean, expires: number }>} */
+const _cache = new Map();
+
+// Known flags: lets the admin console list switches (with their effective state)
+// even before a row exists, and documents which env var each one falls back to.
+export const KNOWN_FLAGS = {
+ avaturn_seed: {
+ env: 'AVATURN_SEED_ENABLED',
+ description:
+ 'Per-minute headless Avaturn seed cron — forges a fully-rigged Avaturn avatar and publishes it public to the gallery.',
+ },
+};
+
+/**
+ * Read a flag's full state. Returns the cached row when fresh, otherwise queries
+ * `app_flags` and caches the result. On any DB error returns the fallback with
+ * exists=false so callers degrade to the code default.
+ *
+ * @param {string} key
+ * @param {{ fallback?: boolean }} [opts]
+ * @returns {Promise<{ enabled: boolean, value: unknown, exists: boolean }>}
+ */
+export async function getFlag(key, { fallback = false } = {}) {
+ const now = Date.now();
+ const hit = _cache.get(key);
+ if (hit && hit.expires > now) {
+ return { enabled: hit.exists ? hit.enabled : fallback, value: hit.value, exists: hit.exists };
+ }
+
+ try {
+ const [row] = await sql`
+ select enabled, value from app_flags where key = ${key} limit 1
+ `;
+ const exists = !!row;
+ const enabled = exists ? row.enabled === true : false;
+ const value = exists ? (row.value ?? null) : null;
+ _cache.set(key, { enabled, value, exists, expires: now + CACHE_TTL_MS });
+ return { enabled: exists ? enabled : fallback, value, exists };
+ } catch {
+ // Fail-soft: never let a flags-table hiccup break the caller.
+ return { enabled: fallback, value: null, exists: false };
+ }
+}
+
+/**
+ * Convenience boolean read.
+ * @param {string} key
+ * @param {{ fallback?: boolean }} [opts]
+ * @returns {Promise<boolean>}
+ */
+export async function isFlagEnabled(key, opts) {
+ return (await getFlag(key, opts)).enabled;
+}
+
+/**
+ * Upsert a flag and clear its cache entry so the writing instance sees the new
+ * value immediately. `value` is optional structured JSON for non-boolean flags.
+ *
+ * @param {string} key
+ * @param {{ enabled: boolean, value?: unknown, updatedBy?: string | null }} patch
+ * @returns {Promise<{ key: string, enabled: boolean, value: unknown, updated_at: string }>}
+ */
+export async function setFlag(key, { enabled, value = null, updatedBy = null }) {
+ const [row] = await sql`
+ insert into app_flags (key, enabled, value, updated_by, updated_at)
+ values (${key}, ${enabled === true}, ${value === null ? null : JSON.stringify(value)}::jsonb, ${updatedBy}, now())
+ on conflict (key) do update
+ set enabled = excluded.enabled,
+ value = excluded.value,
+ updated_by = excluded.updated_by,
+ updated_at = now()
+ returning key, enabled, value, updated_at
+ `;
+ _cache.delete(key);
+ return row;
+}
+
+/**
+ * List every flag row, merged with the KNOWN_FLAGS registry so the console shows
+ * documented switches that have no row yet (enabled=false, exists=false).
+ * @returns {Promise<Array<{ key: string, enabled: boolean, value: unknown, exists: boolean, env: string | null, description: string | null, updated_at: string | null }>>}
+ */
+export async function listFlags() {
+ let rows = [];
+ try {
+ rows = await sql`select key, enabled, value, updated_at from app_flags order by key`;
+ } catch {
+ rows = [];
+ }
+ const byKey = new Map(rows.map((r) => [r.key, r]));
+ const keys = new Set([...Object.keys(KNOWN_FLAGS), ...byKey.keys()]);
+ return [...keys].sort().map((key) => {
+ const row = byKey.get(key);
+ const meta = KNOWN_FLAGS[key] || {};
+ return {
+ key,
+ enabled: row ? row.enabled === true : false,
+ value: row ? (row.value ?? null) : null,
+ exists: !!row,
+ env: meta.env ?? null,
+ description: meta.description ?? null,
+ updated_at: row ? row.updated_at : null,
+ };
+ });
+}
+
+// Test seam — drop cached entries so a unit test sees fresh DB reads.
+export function __clearFlagCache() {
+ _cache.clear();
+}
diff --git a/api/_lib/migrations/20260630120000_app_flags.sql b/api/_lib/migrations/20260630120000_app_flags.sql
new file mode 100644
index 000000000..34cd18300
--- /dev/null
+++ b/api/_lib/migrations/20260630120000_app_flags.sql
@@ -0,0 +1,17 @@
+-- app_flags — generic runtime feature flags, flippable without a redeploy.
+--
+-- Each row is one named switch the platform reads at request/cron time. The
+-- canonical use is gating headless seed crons (e.g. 'avaturn_seed') so an
+-- operator can arm or disarm them instantly from the admin console instead of
+-- editing a Vercel env var and waiting for a build. A missing row means "fall
+-- back to the code default" (usually the matching env var), so adopting a flag
+-- never changes behavior until someone actually sets it.
+create table if not exists app_flags (
+ key text primary key,
+ enabled boolean not null default false,
+ -- Optional structured payload for flags that carry more than on/off
+ -- (cadence overrides, percentages, allowlists). Null for plain switches.
+ value jsonb,
+ updated_by uuid references users(id) on delete set null,
+ updated_at timestamptz not null default now()
+);
diff --git a/api/cron/avaturn-seed-cron.js b/api/cron/avaturn-seed-cron.js
index 84ae26e37..7a7fe25e7 100644
--- a/api/cron/avaturn-seed-cron.js
+++ b/api/cron/avaturn-seed-cron.js
@@ -34,6 +34,7 @@ import {
import { exportRandomAvaturnAvatar } from '../_lib/avaturn-headless.js';
import { putObject } from '../_lib/r2.js';
import { inspectGlb } from '../_lib/glb-inspect.js';
+import { isFlagEnabled } from '../_lib/flags.js';
import { pickBodyType } from '../_lib/avaturn-seed.js';
import { randomUUID } from 'node:crypto';
@@ -173,8 +174,16 @@ export default wrapCron(async (req, res) => {
if (!method(req, res, ['GET'])) return;
if (!requireCron(req, res)) return;
- if (!env.AVATURN_SEED_ENABLED) {
- return json(res, 200, { ok: true, skipped: 'disabled', hint: 'set AVATURN_SEED_ENABLED=1 to enable' });
+ // DB flag is the live control (flip it from the admin console with no
+ // redeploy); the AVATURN_SEED_ENABLED env var is the fallback default used
+ // only when no app_flags row exists yet, preserving the prior behavior.
+ const enabled = await isFlagEnabled('avaturn_seed', { fallback: env.AVATURN_SEED_ENABLED });
+ if (!enabled) {
+ return json(res, 200, {
+ ok: true,
+ skipped: 'disabled',
+ hint: 'enable instantly via POST /api/admin/flags { "key":"avaturn_seed","enabled":true } (or set AVATURN_SEED_ENABLED=1)',
+ });
}
// Single headless export in flight at a time, fleet-wide.
diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.md
index e9f478f26..82dc4bf13 100644
--- a/docs/x402-endpoints.md
+++ b/docs/x402-endpoints.md
@@ -77,7 +77,7 @@ for to feed the oracle and sniper.
| Endpoint | Default | Returns |
|---|---|---|
| `/api/x402/forge` | tiered | Text/image → 3D model (price by tier; GPU-bound). See [Avatar pipeline](avatar-pipeline.md). |
-| `/api/x402/mint-to-mesh` | per call | Token/mint → 3D mesh; `-batch` variant $0.05. |
+| `/api/x402/mint-to-mesh`, `/api/x402/mint-to-mesh-batch` | per call | Token/mint → 3D mesh; `mint-to-mesh-batch` runs a set at $0.05. |
| `/api/x402/model-check`, `/api/x402/model-validation-sweep` | $0.001 | Validate a GLB / sweep a batch. |
| `/api/x402/glb-optimization-report` | per call | GLB size/optimization analysis. |
| `/api/x402/avatar-optimize-batch` | $0.001 | Batch optimization pass over the top N avatars. |
@@ -102,7 +102,8 @@ for to feed the oracle and sniper.
| `/api/x402/wallet-connect` | $0.001 | Wallet-bridge connect probe. |
| `/api/x402/permit2-paid-demo` | $0.001 | Reference endpoint for the Permit2 / EIP-2612 gasless-approval scheme. |
| `/api/x402/cross-chain`, `/api/x402/network-cost` | per call | Cross-chain cost comparison. |
-| `/api/x402/*-health`, `/api/x402/rate-limit-probe`, `/api/x402/schema-check` | $0.001 | Paid health/diagnostic probes used by the autonomous loop. |
+| `/api/x402/rate-limit-probe`, `/api/x402/schema-check` | $0.001 | Paid diagnostic probes used by the autonomous loop. |
+| `/api/x402/auth-health`, `/api/x402/api-key-health`, `/api/x402/feed-health`, `/api/x402/granite-health`, `/api/x402/telegram-health`, `/api/x402/solana-register-health` | $0.001 | Paid SLA/health probes for each backend dependency (auth, API keys, the live feed, IBM Granite, Telegram, Solana register). |
> Prices above marked "per call / per tier / per source" are computed by the
> handler rather than a flat default; check the handler and any
diff --git a/package.json b/package.json
index 7ee3423d1..f85190c5b 100644
--- a/package.json
+++ b/package.json
@@ -127,7 +127,8 @@
"audit:pages": "node scripts/audit-page-index.mjs",
"audit:routes": "node scripts/verify-routes.mjs",
"audit:handlers": "node scripts/audit-empty-handlers.mjs",
- "gate": "npm run test:gate && npm run audit:mcp && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard",
+ "audit:x402-catalog": "node scripts/audit-x402-catalog.mjs",
+ "gate": "npm run test:gate && npm run audit:mcp && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog",
"audit:hidden-guard": "node scripts/audit-hidden-guard.mjs",
"guard:hidden": "node scripts/inject-hidden-guard.mjs --write",
"check:images": "node scripts/audit-image-loading.mjs --strict",
diff --git a/scripts/audit-x402-catalog.mjs b/scripts/audit-x402-catalog.mjs
new file mode 100644
index 000000000..51ffd686a
--- /dev/null
+++ b/scripts/audit-x402-catalog.mjs
@@ -0,0 +1,51 @@
+#!/usr/bin/env node
+/**
+ * x402 endpoint-catalog drift guard.
+ *
+ * Every paid HTTP endpoint under api/x402/ is a sellable product an agent can
+ * discover and pay for — so every one MUST appear in the public catalog at
+ * docs/x402-endpoints.md. This is exactly the drift that let 18 endpoints ship
+ * undocumented: a new handler lands, nobody updates the catalog, and buyers
+ * can't find it. This guard fails the build when an endpoint file has no
+ * corresponding mention in the catalog, by its slug.
+ *
+ * Invariant: for each `api/x402/<slug>.js`, the string `<slug>` appears
+ * somewhere in docs/x402-endpoints.md (typically as a `/api/x402/<slug>` row).
+ * That keeps the check wiring-agnostic — it doesn't care HOW an endpoint
+ * declares its price, only that it is catalogued.
+ *
+ * Excluded (not buyer-facing endpoints):
+ * - *.test.js / *.spec.js
+ * - shared helpers in nested dirs (only top-level api/x402/*.js are routes)
+ *
+ * Usage:
+ * node scripts/audit-x402-catalog.mjs # exit 1 if any endpoint is undocumented
+ */
+import { readFileSync, readdirSync } from 'node:fs';
+import { resolve, dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const X402_DIR = resolve(root, 'api', 'x402');
+const CATALOG = resolve(root, 'docs', 'x402-endpoints.md');
+
+// Top-level route files only — nested dirs hold shared helpers, not routes.
+const slugs = readdirSync(X402_DIR, { withFileTypes: true })
+ .filter((e) => e.isFile() && e.name.endsWith('.js') && !/\.(test|spec)\.js$/.test(e.name))
+ .map((e) => e.name.replace(/\.js$/, ''));
+
+const catalog = readFileSync(CATALOG, 'utf8');
+
+const undocumented = slugs.filter((slug) => !catalog.includes(slug));
+
+if (undocumented.length) {
+ console.error(`\n✗ ${undocumented.length} x402 endpoint(s) missing from docs/x402-endpoints.md:\n`);
+ for (const slug of undocumented) console.error(` /api/x402/${slug}`);
+ console.error(
+ '\nEvery api/x402/*.js endpoint must be listed in the catalog (docs/x402-endpoints.md).\n' +
+ 'Add a row with its slug, default price, and what it returns — see the existing tables.\n',
+ );
+ process.exit(1);
+}
+
+console.log(`✓ audit-x402-catalog: all ${slugs.length} x402 endpoints are documented`);
diff --git a/three-ws-club-music.wav b/three-ws-club-music.wav
new file mode 100644
index 000000000..a1de6bad9
Binary files /dev/null and b/three-ws-club-music.wav differ