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.

harden(ops): one shared fail-closed gate for /admin/ops surfaces

fudjia6c4ea28bcc3d
diff --git a/api/_lib/ops-auth.js b/api/_lib/ops-auth.js
new file mode 100644
index 000000000..6d8b369cb
--- /dev/null
+++ b/api/_lib/ops-auth.js
@@ -0,0 +1,67 @@
+// @ts-check
+// The single authorization gate for the ops dashboard surfaces (/admin/ops and
+// its APIs: /api/ops/health, /api/admin/ops-alerts). One helper so both use
+// identical, auditable rules — no drift, no weaker second door.
+//
+// These surfaces expose internal state: endpoint/cron topology, wallet
+// addresses, tx signatures, key-rotation hints, and stack traces. So the gate
+// is strict and FAILS CLOSED in production. Two ways in:
+//
+// 1. A signed-in platform admin — session + admin wallet (the requireAdmin
+// model: wallet ∈ ADMIN_ADDRESSES, the built-in owner address, or
+// is_admin in the DB). The strongest path and the only one that yields a
+// real per-user identity for audit trails.
+//
+// 2. A dedicated OPS_SECRET presented as `x-ops-secret` (or `Authorization:
+// Bearer`). This is intentionally NOT CRON_SECRET: the ops dashboard must
+// never share a credential with the crons that move real funds, so a
+// leaked ops password can't be escalated into triggering a payment job.
+// Store OPS_SECRET in Secret Manager, high-entropy.
+//
+// With neither present the request is denied in production; it is allowed only
+// off-production (local dev, where no secret is configured) so the dashboard is
+// usable without secrets on a developer's machine.
+
+import { constantTimeEquals } from './crypto.js';
+import { getSessionUser } from './auth.js';
+import { isAdminUser } from './admin.js';
+
+// Read process.env directly, not the `env` façade: OPS_SECRET has no getter on
+// `env`, so `env.OPS_SECRET` is always undefined (the pre-existing bug that made
+// the old `env.OPS_SECRET || env.CRON_SECRET` silently fall through to
+// CRON_SECRET). Evaluated per-call so a test or a runtime env change is honoured.
+function isProd() {
+ return process.env.NODE_ENV === 'production' || process.env.VERCEL_ENV === 'production';
+}
+
+/**
+ * @param {import('http').IncomingMessage & { headers: Record<string,string|undefined> }} req
+ * @returns {Promise<{ ok: boolean, actor: string }>} actor identifies who was
+ * authorized (admin wallet, `ops-secret`, or `dev`) for attribution.
+ */
+export async function authorizeOps(req) {
+ // 1. Signed-in platform admin — preferred, carries a real identity.
+ try {
+ const user = await getSessionUser(req);
+ if (user && (await isAdminUser(user))) {
+ return { ok: true, actor: user.wallet_address || `user:${user.id}` };
+ }
+ } catch {
+ /* no / invalid session — fall through to the secret path */
+ }
+
+ // 2. Dedicated OPS_SECRET. Never CRON_SECRET.
+ const secret = process.env.OPS_SECRET;
+ if (secret) {
+ const header =
+ req.headers['x-ops-secret'] ||
+ (typeof req.headers['authorization'] === 'string'
+ ? req.headers['authorization'].replace(/^Bearer\s+/i, '')
+ : '');
+ if (header && constantTimeEquals(header, secret)) return { ok: true, actor: 'ops-secret' };
+ return { ok: false, actor: '' };
+ }
+
+ // 3. No secret configured: dev-only open, production denies.
+ return { ok: !isProd(), actor: 'dev' };
+}
diff --git a/api/admin/ops-alerts.js b/api/admin/ops-alerts.js
index 11aaf4d5a..26f65a143 100644
--- a/api/admin/ops-alerts.js
+++ b/api/admin/ops-alerts.js
@@ -12,47 +12,9 @@
// the same signature fires again (which re-activates it).
import { wrap, cors, json, error, readJson, rateLimited } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
-import { constantTimeEquals } from '../_lib/crypto.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { isAdminUser } from '../_lib/admin.js';
-
-const IS_PROD = env.NODE_ENV === 'production' || env.VERCEL_ENV === 'production';
-
-// Authorize a request and return the actor identity for attribution. Two ways
-// in, both fail CLOSED in production:
-// 1. A signed-in platform admin (session + admin wallet, the requireAdmin
-// model) — the strongest path, and the only one that yields a real per-user
-// identity for the acknowledge audit trail.
-// 2. A dedicated OPS_SECRET presented as `x-ops-secret` (bookmarkable page /
-// headless). This is deliberately NOT CRON_SECRET: the ops dashboard must
-// never share a credential with the crons that move real funds, so viewing
-// health can't be escalated into triggering a payment job. Set OPS_SECRET
-// and CRON_SECRET is no longer accepted here.
-// No secret configured + no admin session → allowed ONLY off-production (local
-// dev); in production this denies. The endpoint exposes wallet addresses, tx
-// signatures, key-rotation hints, and stack traces, so an open default is unsafe.
-async function authorize(req) {
- try {
- const user = await getSessionUser(req);
- if (user && (await isAdminUser(user))) {
- return { ok: true, actor: user.wallet_address || `user:${user.id}` };
- }
- } catch {
- /* no/invalid session — fall through to the secret path */
- }
- const secret = env.OPS_SECRET;
- if (secret) {
- const provided =
- req.headers['x-ops-secret'] || req.headers['authorization']?.replace(/^Bearer\s+/i, '');
- if (provided && constantTimeEquals(provided, secret)) return { ok: true, actor: 'ops-secret' };
- return { ok: false };
- }
- // No OPS_SECRET set: open in dev for local work, closed in production.
- return { ok: !IS_PROD, actor: 'dev' };
-}
+import { authorizeOps } from '../_lib/ops-auth.js';
const ACTIVE_LIMIT = 200;
const RESOLVED_LIMIT = 50;
@@ -93,7 +55,7 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const auth = await authorize(req);
+ const auth = await authorizeOps(req);
if (!auth.ok) return error(res, 401, 'unauthorized', 'admin session or x-ops-secret required');
const m = req.method?.toUpperCase();
diff --git a/api/ops/health.js b/api/ops/health.js
index 114ad6e95..f3cde844a 100644
--- a/api/ops/health.js
+++ b/api/ops/health.js
@@ -8,8 +8,8 @@ import { cors, error, json, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { cacheGet } from '../_lib/cache.js';
import { env } from '../_lib/env.js';
-import { constantTimeEquals } from '../_lib/crypto.js';
import { sql } from '../_lib/db.js';
+import { authorizeOps } from '../_lib/ops-auth.js';
const PROBE_TIMEOUT_MS = 8_000;
const ORIGIN = env.APP_ORIGIN || 'https://three.ws';
@@ -109,13 +109,10 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const secret = env.OPS_SECRET || env.CRON_SECRET;
- if (secret) {
- const provided = req.headers['x-ops-secret'] || req.headers['authorization']?.replace(/^Bearer\s+/i, '');
- if (!provided || !constantTimeEquals(provided, secret)) {
- return error(res, 401, 'unauthorized', 'x-ops-secret required');
- }
- }
+ // Same hardened gate as /api/admin/ops-alerts: admin session or a dedicated
+ // OPS_SECRET, fail-closed in production, never CRON_SECRET.
+ const auth = await authorizeOps(req);
+ if (!auth.ok) return error(res, 401, 'unauthorized', 'admin session or x-ops-secret required');
const t0 = Date.now();
diff --git a/tests/ops-auth.test.js b/tests/ops-auth.test.js
new file mode 100644
index 000000000..002ba1182
--- /dev/null
+++ b/tests/ops-auth.test.js
@@ -0,0 +1,83 @@
+// The shared ops-dashboard gate: admin session OR dedicated OPS_SECRET,
+// fail-closed in production, never CRON_SECRET.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const getSessionUser = vi.fn(async () => null);
+const isAdminUser = vi.fn(async () => false);
+
+vi.mock('../api/_lib/auth.js', () => ({ getSessionUser }));
+vi.mock('../api/_lib/admin.js', () => ({ isAdminUser }));
+
+let authorizeOps;
+
+async function loadFresh() {
+ vi.resetModules();
+ ({ authorizeOps } = await import('../api/_lib/ops-auth.js'));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getSessionUser.mockResolvedValue(null);
+ isAdminUser.mockResolvedValue(false);
+ delete process.env.OPS_SECRET;
+ delete process.env.CRON_SECRET;
+ delete process.env.NODE_ENV;
+ delete process.env.VERCEL_ENV;
+});
+
+const reqWith = (headers = {}) => ({ headers });
+
+describe('authorizeOps', () => {
+ it('authorizes a signed-in admin with their identity as actor', async () => {
+ getSessionUser.mockResolvedValue({ id: 7, wallet_address: 'Wa11etAdmin' });
+ isAdminUser.mockResolvedValue(true);
+ await loadFresh();
+ const r = await authorizeOps(reqWith());
+ expect(r.ok).toBe(true);
+ expect(r.actor).toBe('Wa11etAdmin');
+ });
+
+ it('rejects a signed-in NON-admin (falls through, no secret) in production', async () => {
+ process.env.VERCEL_ENV = 'production';
+ getSessionUser.mockResolvedValue({ id: 8, wallet_address: 'notadmin' });
+ isAdminUser.mockResolvedValue(false);
+ await loadFresh();
+ expect((await authorizeOps(reqWith())).ok).toBe(false);
+ });
+
+ it('accepts the correct OPS_SECRET via x-ops-secret', async () => {
+ process.env.OPS_SECRET = 'super-secret-value';
+ await loadFresh();
+ expect((await authorizeOps(reqWith({ 'x-ops-secret': 'super-secret-value' }))).ok).toBe(true);
+ expect((await authorizeOps(reqWith({ 'x-ops-secret': 'wrong' }))).ok).toBe(false);
+ expect((await authorizeOps(reqWith())).ok).toBe(false);
+ });
+
+ it('accepts OPS_SECRET via Authorization: Bearer', async () => {
+ process.env.OPS_SECRET = 'sek';
+ await loadFresh();
+ expect((await authorizeOps(reqWith({ authorization: 'Bearer sek' }))).ok).toBe(true);
+ });
+
+ it('does NOT accept CRON_SECRET (decoupled from the cron credential)', async () => {
+ process.env.VERCEL_ENV = 'production';
+ process.env.CRON_SECRET = 'cron-key';
+ // OPS_SECRET intentionally unset
+ await loadFresh();
+ expect((await authorizeOps(reqWith({ 'x-ops-secret': 'cron-key' }))).ok).toBe(false);
+ });
+
+ it('FAILS CLOSED in production when no OPS_SECRET is configured', async () => {
+ process.env.VERCEL_ENV = 'production';
+ await loadFresh();
+ expect((await authorizeOps(reqWith())).ok).toBe(false);
+ expect((await authorizeOps(reqWith({ 'x-ops-secret': 'anything' }))).ok).toBe(false);
+ });
+
+ it('is open in local dev (no secret, not production) for developer convenience', async () => {
+ // neither NODE_ENV nor VERCEL_ENV = production, no secret
+ await loadFresh();
+ expect((await authorizeOps(reqWith())).ok).toBe(true);
+ });
+});