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
refactor(cron): one shared fail-closed cron gate instead of 78 pasted copies
nirholas194a55c4a426
diff --git a/api/_lib/cron-auth.js b/api/_lib/cron-auth.jsnew file mode 100644index 000000000..0360587a4--- /dev/null+++ b/api/_lib/cron-auth.js@@ -0,0 +1,63 @@+// The one cron gate. Every scheduled handler (api/cron/*, plus the few tick+// endpoints Cloud Scheduler drives directly) authenticates through this module+// and nowhere else.+//+// Why it is shared: the gate used to be copy-pasted per file. All the copies+// were fail-closed, but there were eleven distinct spellings of the same eight+// lines, two of them with INVERTED return semantics ("true" meant "handled",+// i.e. rejected) — so a future paste had a real chance of landing an accidental+// fail-open, and no single place existed to review or harden. One export, one+// review surface, one set of semantics.+//+// The contract, deliberately fail-closed at every step:+// • CRON_SECRET unset → 503, never a pass. A misconfigured deploy+// must not expose money-moving sweeps (custody attestation, buybacks,+// wallet intents, budget refunds) to the open internet.+// • credential compared in constant time → no timing oracle on the secret.+// • Authorization: Bearer <secret> (case-insensitive scheme, per Cloud+// Scheduler / Vercel cron) OR X-Cron-Secret: <secret>, which several+// handlers were already invoked with. Both are the same secret; accepting+// either is a superset of what each call site accepted before, never a+// weakening.+// • The presence of an `x-vercel-cron` (or any other) header is NOT+// authorization on its own — an inbound header is spoofable if it ever+// reaches the function unstripped.+//+// Returns true when the caller is the scheduler (handler may proceed). On+// failure it has already written the response and returns false, so every call+// site is `if (!requireCron(req, res)) return;`.++import { error } from './http.js';+import { env } from './env.js';+import { constantTimeEquals } from './crypto.js';++function presentedSecret(req) {+ const auth = req.headers?.['authorization'] || '';+ if (typeof auth === 'string' && auth.toLowerCase().startsWith('bearer ')) {+ return auth.slice(7).trim();+ }+ const header = req.headers?.['x-cron-secret'];+ return typeof header === 'string' ? header.trim() : '';+}++// Is this request the scheduler? No response is written; use requireCron in a+// handler. Exported for the internal fan-out callers that need the verdict+// without the 401/503 side effect.+export function isCronAuthorized(req) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) return false;+ return constantTimeEquals(presentedSecret(req), secret);+}++export function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ error(res, 503, 'not_configured', 'CRON_SECRET unset');+ return false;+ }+ if (!constantTimeEquals(presentedSecret(req), secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}diff --git a/api/cron/[name].js b/api/cron/[name].jsindex d29224dff..50c0a7259 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -65,33 +65,9 @@ import { chargeSubscription, failPayment } from '../_lib/subscription-billing.jsimport { sendEmail } from '../_lib/email.js';import { fetchSafePublicUrl } from '../_lib/ssrf-guard.js';import { runPumpAlertRules } from '../_lib/pump-alert-runner.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { publishUserEvent } from '../_lib/feed.js';import { confirmSkillPurchase } from '../_lib/purchase-confirm.js';--// ─── Cron auth ───────────────────────────────────────────────────────────────-//-// Every cron handler is privileged (some move funds). Vercel's scheduler always-// sends `Authorization: Bearer $CRON_SECRET` on its invocations, so we require a-// valid secret UNCONDITIONALLY and compare it constant-time. The presence of the-// `x-vercel-cron` header is NOT trusted as authorization on its own — an inbound-// request header is spoofable if it ever reaches the function unstripped, and-// must never be allowed to skip the secret. Returns true on success; on failure-// it writes the response and returns false (caller must `return`).-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const token = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';- if (!constantTimeEquals(token, secret)) {- error(res, 401, 'unauthorized', 'cron secret required');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';// ─── Dispatcher ──────────────────────────────────────────────────────────────diff --git a/api/cron/agent-avatar-backfill.js b/api/cron/agent-avatar-backfill.jsindex 2f7023df4..b4310f903 100644--- a/api/cron/agent-avatar-backfill.js+++ b/api/cron/agent-avatar-backfill.js@@ -19,9 +19,9 @@import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { logger } from '../_lib/usage.js';import { backfillAgentAvatars, agentAvatarCoverage } from '../_lib/agent-avatars.js';+import { requireCron } from '../_lib/cron-auth.js';export const maxDuration = 120;@@ -29,21 +29,6 @@ const log = logger('agent-avatar-backfill');const BATCH = Math.max(0, Number(process.env.AGENT_AVATAR_BACKFILL_BATCH || 100));-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- json(res, 503, { error: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(token, secret)) {- json(res, 401, { error: 'unauthorized' });- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (req.method !== 'GET') return json(res, 405, { error: 'method_not_allowed' });if (!requireCron(req, res)) return;diff --git a/api/cron/auto-rig-sweep.js b/api/cron/auto-rig-sweep.jsindex 0eaec5c50..04c3fe2c2 100644--- a/api/cron/auto-rig-sweep.js+++ b/api/cron/auto-rig-sweep.js@@ -19,12 +19,11 @@// submit path chose. No per-job BYOK key juggling.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { getRegenProviderForMode } from '../_lib/regen-provider.js';import { finalizeAutoRigStage } from '../_lib/auto-rig.js';import { isAllowedProviderResultUrl } from '../_lib/provider-result-url.js';+import { requireCron } from '../_lib/cron-auth.js';// Leave the webhook a clear runway before we touch a job: most rigs finish in// 60–90s, so a 3-minute quiet window means we only ever sweep genuinely stalled@@ -42,21 +41,6 @@ const MAX_AGE = "6 hours";// drains FIFO and the oldest job can never be perpetually overtaken.const BATCH = 100;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-// Best-effort hostname for a log line — never throws on a malformed URL.function hostOf(raw) {try { return new URL(raw).hostname; } catch { return 'unparseable'; }diff --git a/api/cron/avatar-thumbnail-backfill.js b/api/cron/avatar-thumbnail-backfill.jsindex 5acb7f6dc..9b14c6a30 100644--- a/api/cron/avatar-thumbnail-backfill.js+++ b/api/cron/avatar-thumbnail-backfill.js@@ -38,7 +38,6 @@import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { logger } from '../_lib/usage.js';import {ensureBackfillSchema,@@ -46,6 +45,7 @@ import {renderBatch,coverage,} from '../_lib/avatar-thumbs.js';+import { requireCron } from '../_lib/cron-auth.js';export const maxDuration = 120;@@ -55,21 +55,6 @@ const RENDER_BATCH = Math.max(0, Number(process.env.THUMBNAIL_BACKFILL_RENDER_BAconst ADOPT_BATCH = Math.max(0, Number(process.env.THUMBNAIL_BACKFILL_ADOPT_BATCH || 200));const CONCURRENCY = Math.max(1, Number(process.env.THUMBNAIL_BACKFILL_CONCURRENCY || 2));-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- json(res, 503, { error: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(token, secret)) {- json(res, 401, { error: 'unauthorized' });- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (req.method !== 'GET') return json(res, 405, { error: 'method_not_allowed' });if (!requireCron(req, res)) return;diff --git a/api/cron/avatar-thumbnail-render.js b/api/cron/avatar-thumbnail-render.jsindex 70319020d..3a337c0cd 100644--- a/api/cron/avatar-thumbnail-render.js+++ b/api/cron/avatar-thumbnail-render.js@@ -23,7 +23,6 @@import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { logger } from '../_lib/usage.js';import { presignGet, putObject, publicUrl } from '../_lib/r2.js';import { renderGlbToPng } from '../_lib/render-glb.js';@@ -35,6 +34,7 @@ import {failRegenJob,thumbnailKeyFor,} from '../_lib/x402/thumbnail-regen.js';+import { requireCron } from '../_lib/cron-auth.js';export const maxDuration = 120;@@ -45,15 +45,6 @@ const BACKGROUND = (process.env.THUMBNAIL_RENDER_BG || '#0a0a0a').trim();// Source GLB presign lifetime — long enough for chromium to fetch the bytes.const SOURCE_TTL_SECONDS = 120;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { json(res, 503, { error: 'CRON_SECRET unset' }); return false; }- const auth = req.headers['authorization'] || '';- const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(token, secret)) { json(res, 401, { error: 'unauthorized' }); return false; }- return true;-}-async function renderOne(job) {const t0 = Date.now();// 1. Re-presign the durable source key (the loop's downloadUrl has expired).diff --git a/api/cron/avaturn-seed-cron.js b/api/cron/avaturn-seed-cron.jsindex 59ab3d5de..d014b1d79 100644--- a/api/cron/avaturn-seed-cron.js+++ b/api/cron/avaturn-seed-cron.js@@ -23,7 +23,6 @@import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { OG_USERNAMES } from '../_lib/seed-prompts.js';import {circuitState,@@ -39,6 +38,7 @@ import { pickDiversityProfile, describeProfile } from '../_lib/avaturn-seed.js';import { pickBaseBody, pickColorway, pickScale, recolorGlb } from '../_lib/studio-avatar.js';import { composeStudioAvatar } from '../_lib/avatar-composer/index.js';import { randomUUID } from 'node:crypto';+import { requireCron } from '../_lib/cron-auth.js';const CIRCUIT_NAME = 'avaturn-seed';const CIRCUIT_THRESHOLD = 3;@@ -49,21 +49,6 @@ const SLOT_TTL_MS = 280_000;// Origin the rigged base bodies are served from (/avatars/*.glb).const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- res.status(503).json({ error: 'not_configured', message: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- res.status(401).json({ error: 'unauthorized' });- return false;- }- return true;-}-// Try to claim `word` as a username, skipping to the next free numbered slot.// Returns the claimed username or null. (Mirrors the forge seeder's helper.)async function claimUsername(word) {diff --git a/api/cron/changelog-push.js b/api/cron/changelog-push.jsindex c5a102ffb..626d5c98e 100644--- a/api/cron/changelog-push.js+++ b/api/cron/changelog-push.js@@ -22,24 +22,8 @@// remain for previews (--dry-run) and backfills only.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { acquireLock, releaseLock, loadFeed, pushTelegramLane } from '../_lib/changelog-push.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;diff --git a/api/cron/coin-intel-observe.js b/api/cron/coin-intel-observe.jsindex eca3fc7fc..5e76f4846 100644--- a/api/cron/coin-intel-observe.js+++ b/api/cron/coin-intel-observe.js@@ -19,10 +19,10 @@import WebSocket from 'ws';import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { finalizeObservation } from '../../workers/agent-sniper/intel/finalize.js';import { pumpPortalWsUrl, handlePumpPortalAck } from '../_lib/pumpportal.js';import { subscribePumpOnchainTrades } from '../_lib/pump-onchain-trades.js';+import { requireCron } from '../_lib/cron-auth.js';const LAMPORTS_PER_SOL = 1_000_000_000;const NETWORK = 'mainnet';@@ -37,18 +37,6 @@ const USE_LLM = process.env.COIN_INTEL_LLM === '1' || process.env.COIN_INTEL_LLMconst solToLamports = (sol) => Math.round((Number(sol) || 0) * LAMPORTS_PER_SOL);-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-// Off-hot-path metadata fetch (description/socials) — best-effort, never blocks.async function fetchMeta(uri) {if (!uri) return null;diff --git a/api/cron/commit-feed-push.js b/api/cron/commit-feed-push.jsindex 89a362a5e..8e759649f 100644--- a/api/cron/commit-feed-push.js+++ b/api/cron/commit-feed-push.js@@ -18,24 +18,8 @@// A DB lock (app_settings) keeps overlapping ticks from double-posting.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { acquireLock, releaseLock, pushTelegramLane } from '../_lib/commit-feed-push.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;diff --git a/api/cron/copy-fanout.js b/api/cron/copy-fanout.jsindex dcc4d8993..8caf1feeb 100644--- a/api/cron/copy-fanout.js+++ b/api/cron/copy-fanout.js@@ -19,11 +19,11 @@// (subscription_id, leader_position_id, direction) when leader_position_id is not null// (subscription_id, leader_oracle_action_id, direction) when leader_oracle_action_id is not null-import { error, json, method, wrapCron } from '../_lib/http.js';+import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { planCopyOrder } from '../_lib/copy-engine.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORKS = ['mainnet', 'devnet'];const lamToSol = (l) => (l == null ? 0 : Number(BigInt(l)) / 1e9);@@ -72,15 +72,6 @@ async function agentName(agentId) {} catch { return null; }}-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-// Best-effort coin context for the safety gate. pump.fun's public coin endpoint// gives a live USD market cap; richer signals (dev holding, liquidity, honeypot)// are left null and the engine treats them as "unknown". Oracle score is mergeddiff --git a/api/cron/custody-attest.js b/api/cron/custody-attest.jsindex 317e2547d..9af43a41c 100644--- a/api/cron/custody-attest.js+++ b/api/cron/custody-attest.js@@ -11,19 +11,9 @@// 'pending'/'anchor_failed' and can be re-anchored later — the snapshot never// 500s on a missing key.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { runAttestationEpoch } from '../_lib/custody-proof.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;diff --git a/api/cron/db-retention.js b/api/cron/db-retention.jsindex bf4628925..c4713f3c4 100644--- a/api/cron/db-retention.js+++ b/api/cron/db-retention.js@@ -63,9 +63,9 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql, isDbCapacityError } from '../_lib/db.js';import { sendOpsAlert } from '../_lib/alerts.js';+import { requireCron } from '../_lib/cron-auth.js';// Mint-keyed satellites of pump_coin_intel, deleted before the master so no run// orphans a satellite row. Every name here is a fixed constant (never user input),@@ -156,21 +156,6 @@ function clampInt(raw, min, max, dflt) {return Math.min(max, Math.max(min, n));}-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-async function dbSizeMb() {const [{ mb }] = await sql`SELECT (pg_database_size(current_database()) / 1048576.0)::int AS mb`;return Number(mb) || 0;diff --git a/api/cron/dead-man-switch.js b/api/cron/dead-man-switch.jsindex e8c88e180..cfc71873e 100644--- a/api/cron/dead-man-switch.js+++ b/api/cron/dead-man-switch.js@@ -14,25 +14,9 @@// changes agent_identities.user_id. Owner activity (a login, a trade, an explicit// check-in) cancels everything — the switch is always defeatable by being alive.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { runDeadManSweep } from '../_lib/agent-recovery.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;diff --git a/api/cron/economy-rebalance.js b/api/cron/economy-rebalance.jsindex 086bc8350..dc27a2406 100644--- a/api/cron/economy-rebalance.js+++ b/api/cron/economy-rebalance.js@@ -15,28 +15,13 @@// and the ECONOMY_REBALANCE_* tuning knobs.import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { solanaConnection } from '../_lib/solana/connection.js';import { SOLANA_SIGNERS, resolveSignerPubkey, loadSignerKeypair } from '../_lib/solana-signers.js';import { solUsdPrice } from '../_lib/avatar-wallet.js';import { planRebalance, executeSwap, REBALANCE, USDC_WALLETS } from '../_lib/economy-rebalance.js';import { USDC_MINT_BY_NETWORK } from '../_lib/vault-jupiter.js';import { logAudit } from '../_lib/audit.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- json(res, 503, { error: 'not_configured', message: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- json(res, 401, { error: 'unauthorized' });- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';const NETWORK = 'mainnet';const USDC_MINT = USDC_MINT_BY_NETWORK[NETWORK];diff --git a/api/cron/economy-reconcile.js b/api/cron/economy-reconcile.jsindex d0064fd01..edc9ce7ab 100644--- a/api/cron/economy-reconcile.js+++ b/api/cron/economy-reconcile.js@@ -23,7 +23,6 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sendOpsAlert } from '../_lib/alerts.js';import { withDbRetry } from '../_lib/db-retry.js';import { sql } from '../_lib/db.js';@@ -31,6 +30,7 @@ import { ECONOMY_MASTER_ADDRESS, RESERVE_SOL } from '../_lib/economy-master.js';import { SOLANA_SIGNERS, resolveSignerPubkey } from '../_lib/solana-signers.js';import { verifyChain } from '../_lib/economy-ledger.js';import { getSolBalance } from '../_lib/avatar-wallet.js';+import { requireCron } from '../_lib/cron-auth.js';// How many recent on-chain signatures to scan per run, and how far back to// re-verify our own recorded transfers. A low-activity funder makes both cheap.@@ -41,21 +41,6 @@ const LEDGER_VERIFY_WINDOW_HOURS = 72;const OUTBOUND_FEE_FLOOR_SOL = 0.0005;const LAMPORTS_PER_SOL = 1_000_000_000;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-async function upsertVerdict({ source, sourceRef, txSig, network, amountAtomic, dbStatus, chainStatus, reconciled, discrepancy, detail, runId }) {try {await withDbRetry(() => sql`diff --git a/api/cron/economy-tick.js b/api/cron/economy-tick.jsindex 3b353bdec..5e67412bf 100644--- a/api/cron/economy-tick.js+++ b/api/cron/economy-tick.js@@ -25,9 +25,9 @@import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { logger } from '../_lib/usage.js';import { cacheSet } from '../_lib/cache.js';+import { requireCron } from '../_lib/cron-auth.js';const log = logger('economy-tick');@@ -106,15 +106,6 @@ const TARGETS = [const CALL_TIMEOUT_MS = 60_000;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { json(res, 503, { error: 'not_configured', message: 'CRON_SECRET unset' }); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { json(res, 401, { error: 'unauthorized' }); return false; }- return true;-}-// Fire one engine over HTTP with the cron bearer. A non-2xx, a 404 (the deployed// build may lag a newly-added engine), or a timeout is reported per-target and// never throws — one dead engine must not stop the others.diff --git a/api/cron/fact-check-benchmark.js b/api/cron/fact-check-benchmark.jsindex 890edad70..96956e4b3 100644--- a/api/cron/fact-check-benchmark.js+++ b/api/cron/fact-check-benchmark.js@@ -22,7 +22,6 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import {acquireLock,buildReport,@@ -35,6 +34,7 @@ import {savePublishedRun,scoreResults,} from '../_lib/fact-check-benchmark.js';+import { requireCron } from '../_lib/cron-auth.js';// Cloud Scheduler gives every job a 320s attempt deadline. Stop issuing claims// at 240s so the scoring, the publish, and the response all land inside it.@@ -45,21 +45,6 @@ const RUN_DEADLINE_MS = Number(process.env.FACT_CHECK_BENCHMARK_DEADLINE_MS) ||// and trips the refusal for no gain.const CONCURRENCY = Number(process.env.FACT_CHECK_BENCHMARK_CONCURRENCY) || 6;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/flush-usage-events.js b/api/cron/flush-usage-events.jsindex 9642f052e..90e69708a 100644--- a/api/cron/flush-usage-events.js+++ b/api/cron/flush-usage-events.js@@ -11,27 +11,11 @@// Kept as a concrete file (not [name].js) so the import graph stays minimal —// no shared SDK, skills, or data bundles needed for a telemetry flush.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { flushUsageBuffer } from '../_lib/usage.js';import { flushAuditBuffer } from '../_lib/x402/audit-log.js';import { sendOpsAlert } from '../_lib/alerts.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;diff --git a/api/cron/forge-finalize.js b/api/cron/forge-finalize.jsindex f034a43c1..ceca14a63 100644--- a/api/cron/forge-finalize.js+++ b/api/cron/forge-finalize.js@@ -28,11 +28,12 @@// rows, markFailed is guarded by status != 'done', and the batch is bounded so// overlapping ticks just split the work.//-// Auth: CRON_SECRET header, same pattern as every other cron in /api/cron/.+// Auth: the shared, fail-closed cron gate (api/_lib/cron-auth.js), same as every+// other cron in /api/cron/.import { sql } from '../_lib/db.js';import { cors, json, wrapCron } from '../_lib/http.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { requireCron } from '../_lib/cron-auth.js';import { materializeCreation, markFailed, forgeStoreEnabled, createCreation } from '../_lib/forge-store.js';import { notifyForgeComplete, notifyForgeFailed } from '../_lib/forge-notify.js';import { createRegenProvider as createGcpProvider } from '../_providers/gcp.js';@@ -71,25 +72,6 @@ const CRON_HOP_TTL_S = 2 * 3600;// so attended and unattended recovery share one once-per-job budget.const NVCF_ALIAS_TTL_S = 3600;-export function requireCron(req, res) {- const secret = process.env.CRON_SECRET;- if (!secret) {- // Fail closed, same as the rest of /api/cron: an unset CRON_SECRET must- // never silently open the endpoint — a misconfigured deploy would- // otherwise let anyone trigger the finalize sweep on demand.- res.writeHead(503, { 'content-type': 'application/json' });- res.end(JSON.stringify({ error: 'not_configured', error_description: 'CRON_SECRET unset' }));- return true; // handled- }- const provided = req.headers['x-cron-secret'] || req.headers['authorization']?.replace(/^Bearer\s+/i, '');- if (!provided || !constantTimeEquals(provided, secret)) {- res.writeHead(401, { 'content-type': 'application/json' });- res.end(JSON.stringify({ error: 'unauthorized' }));- return true; // handled- }- return false;-}-// The async GCP worker lanes wrap their upstream task in a base64url JSON// envelope ({ mode, taskId, baseUrl, resultKey }): see api/_providers/gcp.js.// That shape is the reliable discriminator between "a worker we can poll" and@@ -225,7 +207,7 @@ async function tryCronRedispatch(row, ageMinutes) {export default wrapCron(async (req, res) => {cors(req, res, { methods: 'GET,POST,OPTIONS' });if (req.method?.toUpperCase() === 'OPTIONS') return;- if (requireCron(req, res)) return;+ if (!requireCron(req, res)) return;if (!forgeStoreEnabled()) {return json(res, 200, { enabled: false, swept: 0 });}diff --git a/api/cron/forge-off-crown.js b/api/cron/forge-off-crown.jsindex d2af80f45..76f35939a 100644--- a/api/cron/forge-off-crown.js+++ b/api/cron/forge-off-crown.js@@ -25,25 +25,9 @@// Runs Monday 00:07 UTC (just after the week rolls over). Auth: CRON_SECRET.import { json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { forgeOffWeekStart, forgeStoreEnabled } from '../_lib/forge-store.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- res.status(503).json({ error: 'not_configured', message: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- res.status(401).json({ error: 'unauthorized' });- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';// The Monday that starts the week we are crowning. Default: the week that just// completed (the previous Monday relative to now). `weekParam` (YYYY-MM-DD)diff --git a/api/cron/forge-seed-cron.js b/api/cron/forge-seed-cron.jsindex a457438db..231138db4 100644--- a/api/cron/forge-seed-cron.js+++ b/api/cron/forge-seed-cron.js@@ -55,13 +55,13 @@import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { SEED_PROMPTS, OG_USERNAMES, composeSeedPrompt } from '../_lib/seed-prompts.js';import { evaluateSeedAsset, inProcessTransport, quarantineReject } from '../_lib/seed-quality.js';import { getObjectBuffer, publicUrl } from '../_lib/r2.js';import { isFreeBackend } from '../_lib/forge-tiers.js';import { circuitState, circuitRecordFailure, circuitRecordSuccess } from '../_lib/forge-scale.js';import { randomUUID } from 'node:crypto';+import { requireCron } from '../_lib/cron-auth.js';const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';// Must be comfortably shorter than the function's maxDuration (70 s in vercel.json)@@ -122,21 +122,6 @@ const CIRCUIT_BASE_MS = 10 * 60_000; // 10 min × consecutive failuresconst noteCircuitFailure = () =>circuitRecordFailure(CIRCUIT_NAME, { threshold: CIRCUIT_THRESHOLD, baseMs: CIRCUIT_BASE_MS });-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- res.status(503).json({ error: 'not_configured', message: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- res.status(401).json({ error: 'unauthorized' });- return false;- }- return true;-}-async function fetchJson(url, options = {}) {let res;try {diff --git a/api/cron/forge-smoke.js b/api/cron/forge-smoke.jsindex 695d5b48d..d0ac8d668 100644--- a/api/cron/forge-smoke.js+++ b/api/cron/forge-smoke.js@@ -31,9 +31,9 @@ import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { cacheGet, cacheSet } from '../_lib/cache.js';import { sendOpsAlert } from '../_lib/alerts.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { llmComplete } from '../_lib/llm.js';import { fetchRedisDailyCommands, evaluateRedisBurn, redisBurnAlert } from '../_lib/redis-usage.js';+import { requireCron } from '../_lib/cron-auth.js';const SMOKE_PROMPT = 'a small wooden toy boat with a striped sail';const SUBMIT_TIMEOUT_MS = 90_000;@@ -42,21 +42,6 @@ const POLL_DEADLINE_MS = 180_000;const LAST_STATUS_KEY = 'forge-smoke:last';const LAST_STATUS_TTL_S = 7 * 24 * 60 * 60;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-// Never throws: a timeout or network failure comes back as status 0 so every// caller's non-200 branch reports it as a failed check instead of the// rejection escaping Promise.all and 500ing the whole cron run.diff --git a/api/cron/forge-thumbnail-backfill.js b/api/cron/forge-thumbnail-backfill.jsindex 43090c8b8..fdafb8022 100644--- a/api/cron/forge-thumbnail-backfill.js+++ b/api/cron/forge-thumbnail-backfill.js@@ -29,10 +29,10 @@import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { logger } from '../_lib/usage.js';import { forgeStoreEnabled } from '../_lib/forge-store.js';import { renderBatch, coverage } from '../_lib/forge-thumbs.js';+import { requireCron } from '../_lib/cron-auth.js';export const maxDuration = 120;@@ -41,21 +41,6 @@ const log = logger('forge-thumbnail-backfill');const RENDER_BATCH = Math.max(0, Number(process.env.FORGE_THUMBNAIL_RENDER_BATCH || 8));const CONCURRENCY = Math.max(1, Number(process.env.FORGE_THUMBNAIL_CONCURRENCY || 2));-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- res.status(503).json({ error: 'not_configured', message: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- res.status(401).json({ error: 'unauthorized' });- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!requireCron(req, res)) return;diff --git a/api/cron/free-model-audit.js b/api/cron/free-model-audit.jsindex 0447d357b..b6caa4173 100644--- a/api/cron/free-model-audit.js+++ b/api/cron/free-model-audit.js@@ -16,27 +16,11 @@// died: mirror isLiveFreeModel()'s semantics, report status 'unknown', and flag// nothing dead. Never call a model dead on our own outage.-import { json, error, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { MODEL_CATALOG, DEFAULT_FREE_MODEL, OPENROUTER_SIBLINGS } from '../_lib/chat-models.js';import { listFreeModels } from '../_lib/openrouter-free.js';import { sendOpsAlert } from '../_lib/alerts.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';/*** Every OpenRouter `:free` id hardcoded in the codebase, with the constantsdiff --git a/api/cron/garment-catalog-audit.js b/api/cron/garment-catalog-audit.jsindex cfdfd7231..6d742f8e5 100644--- a/api/cron/garment-catalog-audit.js+++ b/api/cron/garment-catalog-audit.js@@ -21,8 +21,7 @@// `npm run audit:garments`, run on demand after seeding or placement changes.import { error, json, method, reportServerError, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { requireCron } from '../_lib/cron-auth.js';const CATALOG_URL = 'https://storage.googleapis.com/three-ws-garments/garments/catalog.json';const SPEC_URI = 'https://three.ws/specs/garment-manifest-v1';@@ -41,21 +40,6 @@ const SHA256_RE = /^[0-9a-f]{64}$/;// catalog is re-verified every few days without ever fetching every GLB.const HASH_SAMPLE = 5;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-function structuralErrors(m) {const errs = [];if (m?.spec !== SPEC_URI) errs.push('unknown spec');diff --git a/api/cron/garment-job-sweep.js b/api/cron/garment-job-sweep.jsindex 291a2e961..c49442f10 100644--- a/api/cron/garment-job-sweep.js+++ b/api/cron/garment-job-sweep.js@@ -20,22 +20,7 @@import { error, json, method, reportServerError, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;diff --git a/api/cron/gcp-burn-report.js b/api/cron/gcp-burn-report.jsindex 626a9f25f..950f5f11f 100644--- a/api/cron/gcp-burn-report.js+++ b/api/cron/gcp-burn-report.js@@ -21,26 +21,10 @@// deps don't share a cold start with the heavy SDK bundles.import { json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { error } from '../_lib/http.js';import { sendOpsAlert } from '../_lib/alerts.js';import { buildBurnReport, billingConfigured, BillingUnavailableError, usd, PROGRAM_LANES } from '../_lib/gcp-billing.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';const STATUS_EMOJI = { runaway: '🔴', underutilized: '🟡', 'on-track': '🟢', idle: '⚪', unknown: '⚪' };diff --git a/api/cron/gmgn-seed.js b/api/cron/gmgn-seed.jsindex 9d8249a54..72719a3bf 100644--- a/api/cron/gmgn-seed.js+++ b/api/cron/gmgn-seed.js@@ -20,10 +20,9 @@// This runs once/day at off-peak hours — wallet rankings don't change minute-to-minute.// The per-run cap and respectful delays make it a good citizen even without auth.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORK = 'mainnet';const CHAIN = 'sol';@@ -33,18 +32,6 @@ const FETCH_TIMEOUT_MS = 8000;// Be respectful: 300ms between gmgn requests so we don't hammer them.const INTER_REQUEST_DELAY_MS = 300;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-// gmgn tab → our label. smart_degen/pump_smart = proven smart money buyers.// launchpad_smart = launch specialists. renowned = KOL (community influence).// snipe_bot = sniper (high win rate but different risk profile). top_dev = creators.diff --git a/api/cron/gpu-keepwarm.js b/api/cron/gpu-keepwarm.jsindex 77b4721bd..831ba9aed 100644--- a/api/cron/gpu-keepwarm.js+++ b/api/cron/gpu-keepwarm.js@@ -24,7 +24,7 @@// set without a deploy, which is the one-flag change to make when quota lands.import { error, json, method, wrapCron } from '../_lib/http.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { requireCron } from '../_lib/cron-auth.js';// Every self-host GPU lane that scales to zero. `safeByDefault` records whether// warming it contends for a pool that a busier lane needs first (see above).@@ -52,22 +52,6 @@ const PING_TIMEOUT_MS = 8_000;// is what booted it, which is exactly the cold start a user would have paid.const WARM_LATENCY_MS = 1_200;-// Matches the local cron guard every other handler in this directory uses.-function requireCron(req, res) {- const secret = process.env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-function selectedLaneIds() {const raw = String(process.env.FORGE_KEEPWARM_LANES || '').trim();if (!raw) return KEEPWARM_LANES.filter((l) => l.safeByDefault).map((l) => l.id);diff --git a/api/cron/intel-learn.js b/api/cron/intel-learn.jsindex e6754c3cb..824ec5b75 100644--- a/api/cron/intel-learn.js+++ b/api/cron/intel-learn.js@@ -13,25 +13,13 @@// pump_coin_outcomes, pump_intel_weights). Mainnet-only — pump_coin_* are// mainnet. Idempotent + bounded so a frequent cron can never run away.-import { error, json, method, wrapCron } from '../_lib/http.js';+import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { labelOutcomes, trainWeights } from '../../workers/agent-sniper/intel/learn.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORK = 'mainnet';-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/irl-reap.js b/api/cron/irl-reap.jsindex 55caea281..9ec232e44 100644--- a/api/cron/irl-reap.js+++ b/api/cron/irl-reap.js@@ -40,10 +40,9 @@// Runs hourly. Idempotent: re-running deletes nothing new once the table is clean.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { sendOpsAlert } from '../_lib/alerts.js';+import { requireCron } from '../_lib/cron-auth.js';// A single hourly run that deletes more than this many rows is anomalous: a steady// state reaps a handful of expired anon pins + their trail, so a four-figure sweep@@ -61,21 +60,6 @@ export function isReapSpike(counts, threshold = REAP_SPIKE_THRESHOLD) {return reapTotal(counts) >= threshold;}-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/kol-tracker-refresh.js b/api/cron/kol-tracker-refresh.jsindex 0a98da39f..c446b8583 100644--- a/api/cron/kol-tracker-refresh.js+++ b/api/cron/kol-tracker-refresh.js@@ -9,24 +9,8 @@// Idempotent and cheap: getKolTracker's own cache checks make a warm run mostly// no-ops.-import { error, json, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { json, wrapCron } from '../_lib/http.js';+import { requireCron } from '../_lib/cron-auth.js';const WINDOWS = ['24h', '7d', '30d'];diff --git a/api/cron/launcher-claimer.js b/api/cron/launcher-claimer.jsindex 81b2ac0ba..001bac62b 100644--- a/api/cron/launcher-claimer.js+++ b/api/cron/launcher-claimer.js@@ -19,9 +19,9 @@import { json, error, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { createSession } from '../_lib/auth.js';+import { requireCron } from '../_lib/cron-auth.js';const CLAIM_THRESHOLD_SOL = 0.01;const ORIGIN = env.APP_ORIGIN || 'https://three.ws';@@ -53,15 +53,6 @@ async function ensureSchema() {_schemaDone = true;}-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-// Create a session as an agent's owner, then make a fetch call to an internal API// path. The agent's owner session is required because collect-creator-fee-agent// verifies the caller owns the agent.diff --git a/api/cron/launcher-tick.js b/api/cron/launcher-tick.jsindex 14999d85e..9e685f937 100644--- a/api/cron/launcher-tick.js+++ b/api/cron/launcher-tick.js@@ -8,25 +8,9 @@// cadence gate, and the circuit breaker. With no master wallet funded, each tick// records a clean 'skipped' run instead of minting.-import { json, error, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { runLauncherTick } from '../_lib/launcher-engine.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;diff --git a/api/cron/leaderboard-rollup.js b/api/cron/leaderboard-rollup.jsindex 422ed2db5..b86e73ea1 100644--- a/api/cron/leaderboard-rollup.js+++ b/api/cron/leaderboard-rollup.js@@ -13,28 +13,12 @@// top-10 for a week earns the badge once, on day one.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { unlockBadge, BADGES } from '../_lib/streaks.js';+import { requireCron } from '../_lib/cron-auth.js';const METRICS = ['creations', 'remixes_received', 'launches', 'followers', 'walk_distance'];-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-async function top10UserIds(metric) {if (metric === 'creations') {const rows = await sql`diff --git a/api/cron/mirror-fanout.js b/api/cron/mirror-fanout.jsindex 285841c17..5d1348231 100644--- a/api/cron/mirror-fanout.js+++ b/api/cron/mirror-fanout.js@@ -11,24 +11,14 @@// in the recent window are scanned, and each edge processes at most N events.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { syncFollow } from '../_lib/agent-mirror.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORKS = ['mainnet', 'devnet'];const MAX_FOLLOWS_PER_RUN = 120;const MAX_EVENTS_PER_FOLLOW = 15;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-async function fanout(network, stats) {// Candidate edges: enabled, not killed by the follower's agent-wide switch, and// whose leader has at least one confirmed trade newer than the edge cursor.diff --git a/api/cron/news-archive-append.js b/api/cron/news-archive-append.jsindex fc6d033f2..b43e90a72 100644--- a/api/cron/news-archive-append.js+++ b/api/cron/news-archive-append.js@@ -17,32 +17,16 @@// ?dry_run=1 computes and reports without writing.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { getGcpAccessToken } from '../_lib/gcp-auth.js';import { getNews } from '../_lib/news.js';import { geckoFetch } from '../_lib/coingecko.js';import { excerptText } from '../_lib/news-rights.js';+import { requireCron } from '../_lib/cron-auth.js';const BUCKET = 'three-ws-news-archive';const API = `https://storage.googleapis.com/storage/v1/b/${BUCKET}/o`;const UPLOAD = `https://storage.googleapis.com/upload/storage/v1/b/${BUCKET}/o`;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-// ── GCS helpers (JSON API, no client-library dependency) ────────────────────async function gcsGetObject(token, name) {diff --git a/api/cron/oracle-calibrate.js b/api/cron/oracle-calibrate.jsindex b6912c920..86087a26e 100644--- a/api/cron/oracle-calibrate.js+++ b/api/cron/oracle-calibrate.js@@ -19,10 +19,9 @@// arm's entry threshold toward the conviction band that realized wins. Additive// and idempotent.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';+import { requireCron } from '../_lib/cron-auth.js';const BANDS = [{ lo: 0, hi: 30 }, { lo: 30, hi: 50 }, { lo: 50, hi: 70 }, { lo: 70, hi: 85 }, { lo: 85, hi: 101 },@@ -31,15 +30,6 @@ const MIN_BAND_SAMPLE = 5;const FACTOR_MIN = 0.7;const FACTOR_MAX = 1.3;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));export default wrapCron(async (req, res) => {diff --git a/api/cron/oracle-digest.js b/api/cron/oracle-digest.jsindex a8d42d42a..5b5be0cd0 100644--- a/api/cron/oracle-digest.js+++ b/api/cron/oracle-digest.js@@ -15,27 +15,15 @@// Fire-and-forget per recipient: one failure never blocks others. Respects// CRON_SECRET auth.-import { error, json, method, wrapCron } from '../_lib/http.js';+import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { gmgnTokenUrl, referralUrl, TERMINAL_LABELS } from '../../src/shared/trading-terminals.js';+import { requireCron } from '../_lib/cron-auth.js';const TIER_EMOJI = { prime: '🟣', strong: '🔵', lean: '🟡', watch: '⚪', avoid: '🔴' };const ALERT_TIMEOUT_MS = 5000;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-function esc(s) {return String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');}diff --git a/api/cron/oracle-realized-labels.js b/api/cron/oracle-realized-labels.jsindex 7d2305b57..8babbd666 100644--- a/api/cron/oracle-realized-labels.js+++ b/api/cron/oracle-realized-labels.js@@ -13,19 +13,9 @@// realized label when present, so Oracle learns what actually makes money. A// closed trade's PnL never changes, so re-deriving is cheap and idempotent.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;diff --git a/api/cron/oracle-score.js b/api/cron/oracle-score.jsindex e00c3b22c..306f1c022 100644--- a/api/cron/oracle-score.js+++ b/api/cron/oracle-score.js@@ -21,31 +21,19 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { loadConfig } from '../../workers/oracle/config.js';import { runScorePass } from '../../workers/oracle/score-loop.js';import { actOnFreshCoins, freshlyScored } from '../../workers/oracle/agent-loop.js';import { runSettlePass } from '../../workers/oracle/settle-loop.js';import { alertNewHighConviction } from '../_lib/oracle/alerts.js';import { purgeOldHistory, purgeQuoteMints } from '../_lib/oracle/store.js';+import { requireCron } from '../_lib/cron-auth.js';// How far back the agent pass looks for scored coins. Wider than the cron// cadence so a missed tick still catches up; the per-(agent,mint) dedup makes// the overlap harmless.const AGENT_WINDOW_SEC = 15 * 60;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/payment-session-sweep.js b/api/cron/payment-session-sweep.jsindex 6199e843c..4e927a521 100644--- a/api/cron/payment-session-sweep.js+++ b/api/cron/payment-session-sweep.js@@ -11,43 +11,23 @@// • All rows updated atomically per-session; a crash mid-batch leaves the// remaining sessions to be picked up on the next tick.//-// Auth: requires CRON_SECRET header matching the CRON_SECRET env var. Same pattern-// as every other cron in /api/cron/.+// Auth: the shared, fail-closed cron gate (api/_lib/cron-auth.js), same as every+// other cron in /api/cron/.import { sql } from '../_lib/db.js';import { creditAccount } from '../_lib/credits.js';import { atomicsToUsd } from '../_lib/pay/spend-governor.js';import { cors, json, wrapCron } from '../_lib/http.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { requireCron } from '../_lib/cron-auth.js';export const maxDuration = 30;const BATCH_LIMIT = Number(process.env.PAYMENT_SESSION_SWEEP_BATCH) || 100;-export function requireCron(req, res) {- const secret = process.env.CRON_SECRET;- if (!secret) {- // Fail closed, same as the rest of /api/cron: an unset CRON_SECRET must- // never silently open the endpoint. This sweep moves money (it refunds- // session budgets into credit balances), so a misconfigured deploy- // would otherwise expose unauthenticated money-moving on demand.- res.writeHead(503, { 'content-type': 'application/json' });- res.end(JSON.stringify({ error: 'not_configured', error_description: 'CRON_SECRET unset' }));- return true; // handled- }- const provided = req.headers['x-cron-secret'] || req.headers['authorization']?.replace(/^Bearer\s+/i, '');- if (!provided || !constantTimeEquals(provided, secret)) {- res.writeHead(401, { 'content-type': 'application/json' });- res.end(JSON.stringify({ error: 'unauthorized' }));- return true; // handled- }- return false;-}-export default wrapCron(async (req, res) => {cors(req, res, { methods: 'GET,POST,OPTIONS' });if (req.method?.toUpperCase() === 'OPTIONS') return;- if (requireCron(req, res)) return;+ if (!requireCron(req, res)) return;const t0 = Date.now();diff --git a/api/cron/pulse-tick.js b/api/cron/pulse-tick.jsindex 12f29f10a..762e6e2d7 100644--- a/api/cron/pulse-tick.js+++ b/api/cron/pulse-tick.js@@ -5,25 +5,9 @@// agent pool and has those agents transact with one another on-chain, so the live// money feed reflects real wallet activity.-import { json, error, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { runCirculationTick } from '../_lib/circulation.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;diff --git a/api/cron/quality-bench.js b/api/cron/quality-bench.jsindex 8e6dca94d..9097bef4e 100644--- a/api/cron/quality-bench.js+++ b/api/cron/quality-bench.js@@ -17,8 +17,8 @@import { readFile, readdir } from 'node:fs/promises';import path from 'node:path';import { error, json, method, wrapCron } from '../_lib/http.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { loadCatalog, runOne } from '../_lib/quality-bench.js';+import { requireCron } from '../_lib/cron-auth.js';export const maxDuration = 300;@@ -32,21 +32,6 @@ const REGRESSION_THRESHOLD = 1.0;const BENCH_DIR = path.join(process.cwd(), 'data', 'quality-bench');const RUNS_DIR = path.join(BENCH_DIR, 'runs');-function requireCron(req, res) {- const secret = process.env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-async function loadPrompts() {const raw = JSON.parse(await readFile(path.join(BENCH_DIR, 'prompts.json'), 'utf8'));return raw.prompts;diff --git a/api/cron/quota-check.js b/api/cron/quota-check.jsindex 2a8e258d2..db2a19bc5 100644--- a/api/cron/quota-check.js+++ b/api/cron/quota-check.js@@ -20,28 +20,13 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sendOpsAlert } from '../_lib/alerts.js';import { getRedis } from '../_lib/redis.js';+import { requireCron } from '../_lib/cron-auth.js';const QUOTA_WARN_PCT = 70;const QUOTA_CRITICAL_PCT = 90;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-async function checkUpstashQuota() {const apiKey = process.env.UPSTASH_MANAGEMENT_API_KEY;const email = process.env.UPSTASH_MANAGEMENT_API_EMAIL;diff --git a/api/cron/radar-watchlist.js b/api/cron/radar-watchlist.jsindex 2ec84f26d..e5144329e 100644--- a/api/cron/radar-watchlist.js+++ b/api/cron/radar-watchlist.js@@ -10,10 +10,10 @@// Idempotent + bounded. Mainnet-only (pump.fun). Reads the graph, writes only the// radar's own table.-import { error, json, method, wrapCron } from '../_lib/http.js';+import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { recomputeWatchlist } from '../../workers/agent-sniper/radar-watchlist.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORK = 'mainnet';@@ -32,18 +32,6 @@ function radarCfg() {};}-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/recompute-reputation.js b/api/cron/recompute-reputation.jsindex 0dc2f7dc9..12ad2f1aa 100644--- a/api/cron/recompute-reputation.js+++ b/api/cron/recompute-reputation.js@@ -15,31 +15,14 @@// Standalone (not [name].js) so the import graph stays minimal.import { json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { listStaleAgents, recomputeAgents } from '../_lib/trust/reputation-store.js';+import { requireCron } from '../_lib/cron-auth.js';// How many agents to recompute per tick. Each is a handful of indexed DB reads// plus (for full mode) one cached price + light RPC; 40 fits comfortably in the// cron budget and, at a 10-minute cadence, rolls a few thousand agents per hour.const BATCH = 40;-// Vercel cron invokes with `Authorization: Bearer <CRON_SECRET>`; manual probes-// may use `X-Cron-Secret: <CRON_SECRET>`. Accept either, constant-time.-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- json(res, 503, { ok: false, reason: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';- const header = req.headers['x-cron-secret'] || '';- if (constantTimeEquals(bearer, secret) || constantTimeEquals(header, secret)) return true;- json(res, 401, { ok: false, error: 'invalid cron secret' });- return false;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/reconcile-decisions.js b/api/cron/reconcile-decisions.jsindex 731f9e117..6b7772c8b 100644--- a/api/cron/reconcile-decisions.js+++ b/api/cron/reconcile-decisions.js@@ -13,13 +13,12 @@// GET /api/ledger/verify/:agentId. Anomalies (a sudden hit-rate collapse) raise an// ops alert.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { sendOpsAlert } from '../_lib/alerts.js';import { recordOutcome, computeReputation, getReputationRecords } from '../_lib/reasoning-ledger.js';import { anchorLedgerHead, latestAnchoredAnchor } from '../_lib/ledger-anchor.js';+import { requireCron } from '../_lib/cron-auth.js';const LAMPORTS_PER_SOL = 1e9;const MAX_RECONCILE = 1000; // decisions resolved per run@@ -27,15 +26,6 @@ const MAX_ANCHOR_AGENTS = 25; // agents whose head is committed on-chain per runconst ANOMALY_MIN_SAMPLE = 10;const ANOMALY_HIT_RATE = 0.25;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/reconstruct-sweep.js b/api/cron/reconstruct-sweep.jsindex bd61d2e6a..663d26d84 100644--- a/api/cron/reconstruct-sweep.js+++ b/api/cron/reconstruct-sweep.js@@ -26,12 +26,11 @@// They are a rounding error in practice (1 of the last ~100 reconstruct jobs).import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { getRegenProviderForMode } from '../_lib/regen-provider.js';import { finalizeReconstructStage, pollRiggingStage } from '../_lib/reconstruct-finalize.js';import { isAllowedProviderResultUrl } from '../_lib/provider-result-url.js';+import { requireCron } from '../_lib/cron-auth.js';// The browser polls every few seconds while the tab is open, so a row that has// been untouched for 3 minutes is either abandoned or wedged — never a job@@ -58,21 +57,6 @@ const MISMATCH_MAX_AGE = '24 hours';// first so the backlog drains FIFO and nothing is perpetually overtaken.const BATCH = 50;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-function hostOf(raw) {try { return new URL(raw).hostname; } catch { return 'unparseable'; }}diff --git a/api/cron/reflect-sweep.js b/api/cron/reflect-sweep.jsindex 582ee24b1..1f727df6a 100644--- a/api/cron/reflect-sweep.js+++ b/api/cron/reflect-sweep.js@@ -16,8 +16,8 @@import { sql } from '../_lib/db.js';import { env } from '../_lib/env.js';import { cors, error, json, method, wrapCron } from '../_lib/http.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { runReflection } from '../_lib/reflection.js';+import { requireCron } from '../_lib/cron-auth.js';export const maxDuration = 120;@@ -26,21 +26,6 @@ export const maxDuration = 120;const BATCH_LIMIT = Number(process.env.REFLECT_SWEEP_BATCH) || 12;const TIME_BUDGET_MS = 100_000;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;diff --git a/api/cron/relayer-balance-check.js b/api/cron/relayer-balance-check.jsindex a73a8a50b..3b679476e 100644--- a/api/cron/relayer-balance-check.js+++ b/api/cron/relayer-balance-check.js@@ -23,27 +23,12 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sendOpsAlert } from '../_lib/alerts.js';import { SOLANA_SIGNERS, resolveSignerPubkey } from '../_lib/solana-signers.js';+import { requireCron } from '../_lib/cron-auth.js';const LAMPORTS_PER_SOL = 1_000_000_000;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/rewards-distribute.js b/api/cron/rewards-distribute.jsindex 5f757c257..d8a29579d 100644--- a/api/cron/rewards-distribute.js+++ b/api/cron/rewards-distribute.js@@ -18,27 +18,12 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { TOKEN_MINT, ATOMICS_PER_TOKEN, treasuryWalletOrNull, rewardsWalletOrNull } from '../_lib/token/config.js';import { fetchHolderBalances } from '../_lib/coin/holders.js';import { getBalances } from '../_lib/balances.js';import { computeRewardsDistribution } from '../_lib/token/rewards.js';import { recordRewardsDistribution } from '../_lib/token/payments.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';// Read the rewards pool's current $THREE balance (atomics). Returns 0n on any// failure so the cron degrades to "nothing to distribute" rather than erroring.diff --git a/api/cron/signal-fanout.js b/api/cron/signal-fanout.jsindex 8d1bbe7ef..833c87c6e 100644--- a/api/cron/signal-fanout.js+++ b/api/cron/signal-fanout.js@@ -19,25 +19,15 @@// activity emit, and each subscription delivers at most N emissions per run.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { syncFeedEmissions, deliverSubscription } from '../_lib/signal-engine.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORKS = ['mainnet', 'devnet'];const MAX_FEEDS_PER_RUN = 120;const MAX_SUBS_PER_RUN = 200;const MAX_EVENTS_PER_SUB = 12;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-// PASS 1 — generate emissions from publishers' real positions.async function emitPass(network, stats) {// Only feeds whose publisher has a position opened/closed past the relevantdiff --git a/api/cron/sketchfab-showcase.js b/api/cron/sketchfab-showcase.jsindex fae705fd9..d98730439 100644--- a/api/cron/sketchfab-showcase.js+++ b/api/cron/sketchfab-showcase.js@@ -37,7 +37,6 @@import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';-import { constantTimeEquals } from '../_lib/crypto.js';import {DENY_SQL_PATTERN,GLB_MAX_BYTES,@@ -50,24 +49,10 @@ import {uploadModel,} from '../_lib/sketchfab.js';import { moderateAnonInput } from '../_lib/moderation.js';+import { requireCron } from '../_lib/cron-auth.js';const MAX_ATTEMPTS = 3;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- res.status(503).json({ error: 'not_configured', message: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- res.status(401).json({ error: 'unauthorized' });- return false;- }- return true;-}-function uploadsPerRun() {const n = Number(env.SKETCHFAB_UPLOADS_PER_RUN || 2);if (!Number.isFinite(n)) return 2;diff --git a/api/cron/smart-money-graph.js b/api/cron/smart-money-graph.jsindex 194844360..f5afad3e0 100644--- a/api/cron/smart-money-graph.js+++ b/api/cron/smart-money-graph.js@@ -11,25 +11,12 @@// Idempotent + bounded so a frequent cron can never run away. Mainnet-only// (pump_coin_* live on mainnet). Reads/writes only the graph's own tables.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { recomputeWalletGraph } from '../../workers/agent-sniper/recompute-wallet-graph.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORK = 'mainnet';-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/smart-money-rollup.js b/api/cron/smart-money-rollup.jsindex 271db71a0..987a1b402 100644--- a/api/cron/smart-money-rollup.js+++ b/api/cron/smart-money-rollup.js@@ -17,12 +17,11 @@// (pump_coin_wallets / pumpfun_graduations are mainnet). Idempotent + bounded so// a 5-minute cron can never run away.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { attributeCoin, computeReputation } from '../../src/pump/wallet-reputation.js';import { computeCoinSmartMoney } from '../../src/pump/smart-money-score.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORK = 'mainnet';const JUDGE_AFTER_HOURS = 6; // a coin must be this old before "never graduated" = dud@@ -32,21 +31,6 @@ const TOP_WALLETS = 60; // per coin, cap wallets folded/scoredconst LIVE_WINDOW_HOURS = 3; // score coins launched within this windowconst LIVE_COINS = 150;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/sniper-evolve.js b/api/cron/sniper-evolve.jsindex 8ec6174f6..76a210c73 100644--- a/api/cron/sniper-evolve.js+++ b/api/cron/sniper-evolve.js@@ -18,17 +18,8 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { runEvolve } from '../../scripts/sniper-evolve.mjs';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;diff --git a/api/cron/sniper-loops-health.js b/api/cron/sniper-loops-health.jsindex d0d5b9ab0..9c19f8715 100644--- a/api/cron/sniper-loops-health.js+++ b/api/cron/sniper-loops-health.js@@ -14,23 +14,13 @@// this watchdog exists to catch.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { sendOpsAlert } from '../_lib/alerts.js';import { LOOPS, classifyLlmRouting, classifyLoopHealth, describeStale, findWalletlessArms, isFallbackAnswer } from '../_lib/sniper-loops-health.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORK = 'mainnet';-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-// One freshest-row probe per loop. Table/column names come from the static// LOOPS declaration (never user input), so the interpolation here is safe; the// only runtime value, the network, is parameterized.diff --git a/api/cron/sniper-optimize.js b/api/cron/sniper-optimize.jsindex d26bfd3a9..c1ed8a13c 100644--- a/api/cron/sniper-optimize.js+++ b/api/cron/sniper-optimize.js@@ -30,11 +30,11 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { recordDecision } from '../_lib/reasoning-ledger.js';import { proposeAdjustments } from '../_lib/sniper-optimizer.js';import { classifyAutonomy, describeTier } from '../_lib/sniper-autonomy.js';+import { requireCron } from '../_lib/cron-auth.js';const WINDOWS = { '24h': '24 hours', '7d': '7 days', '30d': '30 days' };@@ -78,15 +78,6 @@ async function applyProposal(strategyId, field, value) {}}-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-// Per-arm real trading record over the window, including the exit-reason// distribution the optimizer's rules key on. Real fills only (the 'SIMULATED'// sentinel is excluded) so a shadow-mode fleet still produces proposals from itsdiff --git a/api/cron/solana-autodeploy.js b/api/cron/solana-autodeploy.jsindex ef9677f54..a3ad7176e 100644--- a/api/cron/solana-autodeploy.js+++ b/api/cron/solana-autodeploy.js@@ -29,7 +29,6 @@ import { LAMPORTS_PER_SOL } from '@solana/web3.js';import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { publishFeedEvent } from '../_lib/feed.js';import {authoritySecret,@@ -45,6 +44,7 @@ import {EST_MINT_LAMPORTS,EST_REGISTER_LAMPORTS,} from '../_lib/onchain-deploy.js';+import { requireCron } from '../_lib/cron-auth.js';// Per-tick caps. Each mint is ~0.004 SOL + one tx; at a 10-min cadence this lands// hundreds of agents/day without any run going long or draining the authority@@ -58,20 +58,6 @@ const BUDGET_MS = 110_000;// ~2 ops/sec — stay well within RPC rate limits, matching the admin runners.const sleep = (ms) => new Promise((r) => setTimeout(r, ms));-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- json(res, 503, { ok: false, reason: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';- const header = req.headers['x-cron-secret'] || '';- if (constantTimeEquals(bearer, secret) || constantTimeEquals(header, secret)) return true;- json(res, 401, { ok: false, error: 'invalid cron secret' });- return false;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/strategy-fanout.js b/api/cron/strategy-fanout.jsindex 75c97e5da..5178ef71d 100644--- a/api/cron/strategy-fanout.js+++ b/api/cron/strategy-fanout.js@@ -12,21 +12,11 @@// exits still mark-to-market while killed but never initiate a trade.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sweepStrategies } from '../_lib/agent-strategy-runtime.js';+import { requireCron } from '../_lib/cron-auth.js';const NETWORKS = ['mainnet', 'devnet'];-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/three-buy-loop.js b/api/cron/three-buy-loop.jsindex 9c63dd914..e91796253 100644--- a/api/cron/three-buy-loop.js+++ b/api/cron/three-buy-loop.js@@ -36,7 +36,6 @@ import { getMint } from '@solana/spl-token';import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { getRedis } from '../_lib/redis.js';import { solanaConnection } from '../_lib/solana/connection.js';@@ -54,6 +53,7 @@ import {SPENT_STATUSES,} from '../_lib/token/microbuy.js';import { usdToUsdcAtomics } from '../_lib/token/buyback-math.js';+import { requireCron } from '../_lib/cron-auth.js';const log = logger('three-buy-loop');const ORIGIN = () => (env.APP_ORIGIN || 'https://three.ws').replace(/\/+$/, '');@@ -90,15 +90,6 @@ const sweepEveryN = () => {return Number.isFinite(n) && n > 0 ? Math.floor(n) : 30; // ~ every 30 min};-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { json(res, 503, { error: 'CRON_SECRET unset' }); return false; }- const auth = req.headers['authorization'] || '';- const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(token, secret)) { json(res, 401, { error: 'unauthorized' }); return false; }- return true;-}-// A monotonic tick counter so the periodic sweep fires on a stable cadence across// warm instances (Redis INCR, in-memory fallback — mirrors the ring tick).const TICK_SEQ_KEY = 'three:microbuy:tick:seq';diff --git a/api/cron/three-holders-snapshot.js b/api/cron/three-holders-snapshot.jsindex 27252f855..d7ebc4078 100644--- a/api/cron/three-holders-snapshot.js+++ b/api/cron/three-holders-snapshot.js@@ -18,11 +18,11 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { refreshThreeHolderSnapshot } from '../_lib/coin/three-holders.js';import { isRpcRateLimited } from '../_lib/coin/holders.js';import { isDbUnavailableError } from '../_lib/db.js';import { cacheGet, cacheSet } from '../_lib/cache.js';+import { requireCron } from '../_lib/cron-auth.js';// After a rate-limited scan, hold off further refresh attempts for this long.// The per-page retries inside fetchHolderBalances already burn ~90s against a@@ -32,22 +32,6 @@ import { cacheGet, cacheSet } from '../_lib/cache.js';const RATE_LIMIT_COOLDOWN_KEY = 'three-holders:rate-limit-cooldown';const RATE_LIMIT_COOLDOWN_S = 600;-// Vercel cron invokes with `Authorization: Bearer <CRON_SECRET>`; manual probes-// may use `X-Cron-Secret: <CRON_SECRET>`. Accept either, constant-time.-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';- const header = req.headers['x-cron-secret'] || '';- if (constantTimeEquals(bearer, secret) || constantTimeEquals(header, secret)) return true;- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/three-market-refresh.js b/api/cron/three-market-refresh.jsindex 840654def..5cb8fd087 100644--- a/api/cron/three-market-refresh.js+++ b/api/cron/three-market-refresh.js@@ -18,26 +18,10 @@// Kept as a concrete file (not [name].js) so this lightweight refresh never// shares a cold start with the heavy SDK bundles.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';import { fetchTokenMarketData } from '../_lib/market/token-market.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;diff --git a/api/cron/trader-score-attest.js b/api/cron/trader-score-attest.jsindex 871c9cf8c..4ea776ced 100644--- a/api/cron/trader-score-attest.js+++ b/api/cron/trader-score-attest.js@@ -10,23 +10,13 @@// exactly which wallets WOULD be attested and why it skipped — rather than 500ing.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { getLeaderboard, getTraderStats } from '../_lib/trader-stats.js';import { attestTraderScore } from '../_lib/trader-score-attest.js';+import { requireCron } from '../_lib/cron-auth.js';const TOP_N = 25;const NETWORKS = ['mainnet', 'devnet'];-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/treasury-sweepback.js b/api/cron/treasury-sweepback.jsindex b62ac4fbe..fbde13e7d 100644--- a/api/cron/treasury-sweepback.js+++ b/api/cron/treasury-sweepback.js@@ -28,26 +28,11 @@import { randomUUID } from 'node:crypto';import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sendOpsAlert } from '../_lib/alerts.js';import { sweepBack } from '../_lib/economy-sweepback.js';import { ECONOMY_MASTER_ADDRESS } from '../_lib/economy-master.js';import { recordSweepback } from '../_lib/economy-ledger.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.jsindex 24686dd03..5f50c39e3 100644--- a/api/cron/treasury-topup.js+++ b/api/cron/treasury-topup.js@@ -29,7 +29,6 @@import { randomUUID } from 'node:crypto';import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sendOpsAlert } from '../_lib/alerts.js';import { SOLANA_SIGNERS, resolveSignerPubkey } from '../_lib/solana-signers.js';import { sweepTopUps, RESERVE_SOL, RUN_CAP_SOL, PER_TOPUP_MAX_SOL, ECONOMY_MASTER_ADDRESS } from '../_lib/economy-master.js';@@ -37,6 +36,7 @@ import { recordSweep, recordAgentReclaim } from '../_lib/economy-ledger.js';import { refuelMasterFromUsdc } from '../_lib/economy-fuel.js';import { topUpUsdcEngines } from '../_lib/economy-usdc-topup.js';import { reclaimIdleSol, reclaimIdleAgentSol } from '../_lib/economy-sweepback.js';+import { requireCron } from '../_lib/cron-auth.js';const LAMPORTS_PER_SOL = 1_000_000_000;// How high to lift an engine when it falls below its floor, unless the spec@@ -44,21 +44,6 @@ const LAMPORTS_PER_SOL = 1_000_000_000;// a hot wallet we deliberately keep thin.const DEFAULT_REFILL_MULTIPLE = 3;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/uptime-check.js b/api/cron/uptime-check.jsindex aa459c38c..95555f149 100644--- a/api/cron/uptime-check.js+++ b/api/cron/uptime-check.js@@ -19,8 +19,8 @@ import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { cacheGet, cacheSet } from '../_lib/cache.js';import { sendOpsAlert } from '../_lib/alerts.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { gatherSubsystemHealth } from '../_lib/ops/subsystem-health.js';+import { requireCron } from '../_lib/cron-auth.js';// The surfaces that constitute "the platform is up". Each is a cheap public// GET — no auth, no side effects, no spend.@@ -122,21 +122,6 @@ async function probe(target, origin) {}}-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;if (!requireCron(req, res)) return;diff --git a/api/cron/vanity-inventory-replenish.js b/api/cron/vanity-inventory-replenish.jsindex 5061f54e3..302280107 100644--- a/api/cron/vanity-inventory-replenish.js+++ b/api/cron/vanity-inventory-replenish.js@@ -27,25 +27,10 @@import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sendOpsAlert } from '../_lib/alerts.js';import { inventoryStats, sweepExpiredSecrets, isDbUnavailableError } from '../_lib/vanity-inventory-store.js';import { getGcpAccessToken, gcpAuthConfigured } from '../_lib/gcp-auth.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';// Below this many available items platform-wide, fire a replenishment run.// Overridable so ops can tune the shelf depth without a redeploy.diff --git a/api/cron/wallet-intents.js b/api/cron/wallet-intents.jsindex b0d241fad..dd40bfc11 100644--- a/api/cron/wallet-intents.js+++ b/api/cron/wallet-intents.js@@ -11,25 +11,9 @@// Nothing here exposes a key: the engine decrypts only at signing, audit-logs// every recovery, and writes a custody event stamped with the intent_id.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrapCron } from '../_lib/http.js';import { runIntentSweep } from '../_lib/wallet-intents.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const token = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';- if (!constantTimeEquals(token, secret)) {- error(res, 401, 'unauthorized', 'cron secret required');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrapCron(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;diff --git a/api/cron/wallets-leak-scan.js b/api/cron/wallets-leak-scan.jsindex e62b93799..2b247bef1 100644--- a/api/cron/wallets-leak-scan.js+++ b/api/cron/wallets-leak-scan.js@@ -17,26 +17,17 @@import { randomUUID } from 'node:crypto';import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sql } from '../_lib/db.js';import { sendOpsAlert } from '../_lib/alerts.js';import { SOLANA_SIGNERS, resolveSignerPubkey } from '../_lib/solana-signers.js';import { ringAllowedAddresses } from '../_lib/x402/ring-allowlist.js';import { classifyWalletDebits } from './x402-ring-leak-scan.js';import { runTripwire, lastActivityMs } from '../_lib/financial-tripwire.js';+import { requireCron } from '../_lib/cron-auth.js';const SIG_LIMIT = 100;const CANONICAL_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-async function ensureSchema() {await sql`CREATE TABLE IF NOT EXISTS wallet_scan_cursor (diff --git a/api/cron/world-health.js b/api/cron/world-health.jsindex 73bd90fbe..c7d11082e 100644--- a/api/cron/world-health.js+++ b/api/cron/world-health.js@@ -17,8 +17,8 @@import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { sendOpsAlert } from '../_lib/alerts.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { cacheSet } from '../_lib/cache.js';+import { requireCron } from '../_lib/cron-auth.js';// Where this cron parks its last outcome so the platform health gatherer// (api/_lib/ops/subsystem-health.js → /healthz + /status) can read it without@@ -35,23 +35,6 @@ const FETCH_TIMEOUT_MS = 10_000;const ASSET_TIMEOUT_MS = 8_000;const ASSET_CONCURRENCY = 10;-// Vercel cron invokes with `Authorization: Bearer <CRON_SECRET>`; manual probes-// may use `X-Cron-Secret: <CRON_SECRET>`. Accept either, constant-time. 503 if-// the secret is unset (misconfiguration), 403 if presented and wrong/absent.-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- json(res, 503, { error: 'not_configured', error_description: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';- const header = req.headers['x-cron-secret'] || '';- if (constantTimeEquals(bearer, secret) || constantTimeEquals(header, secret)) return true;- json(res, 403, { error: 'forbidden', error_description: 'invalid cron secret' });- return false;-}-// A 404/410 is the world's own answer: the asset is genuinely gone. Every other// failure (timeout, socket error, 5xx, 429) describes the network or the CDN at// this instant, not the scene, so it must not be reported as a missing asset.diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.jsindex 864a353a3..b9b01ea21 100644--- a/api/cron/x402-autonomous-loop.js+++ b/api/cron/x402-autonomous-loop.js@@ -33,7 +33,6 @@ import {import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { getRedis } from '../_lib/redis.js';import { sql } from '../_lib/db.js';import { solanaConnection } from '../_lib/solana/connection.js';@@ -52,6 +51,7 @@ import {import { assertRingSpendInvariants } from '../_lib/x402/ring-allowlist.js';import { SPONSOR_SOL_FLOOR_LAMPORTS } from '../_lib/x402/self-facilitator.js';import { sendOpsAlert } from '../_lib/alerts.js';+import { requireCron } from '../_lib/cron-auth.js';const log = logger('x402-autonomous-loop');@@ -100,15 +100,6 @@ const COOLDOWN_PREFIX = 'x402:auto:last:';// Redis key for daily spend accumulator (resets each UTC calendar day).const DAILY_SPEND_KEY = () => `x402:auto:daily:${new Date().toISOString().slice(0, 10)}`;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { json(res, 503, { error: 'CRON_SECRET unset' }); return false; }- const auth = req.headers['authorization'] || '';- const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(token, secret)) { json(res, 401, { error: 'unauthorized' }); return false; }- return true;-}-async function recordLog(runId, entry, { amountAtomic, txSig, responseData, durationMs, success, errorMsg, signalData, valueExtracted, endpointUrl }) {try {await sql`diff --git a/api/cron/x402-directory-registrar.js b/api/cron/x402-directory-registrar.jsindex d84fe2e77..119cab75a 100644--- a/api/cron/x402-directory-registrar.js+++ b/api/cron/x402-directory-registrar.js@@ -21,29 +21,13 @@// docs/x402-distribution.md. One-off/local batches: scripts/x402-register-directories.mjs.import { json, wrapCron, method, error } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { getCatalog } from '../_lib/service-catalog/index.js';+import { requireCron } from '../_lib/cron-auth.js';const FOUR02INDEX_REGISTER = 'https://402index.io/api/v1/register';const WINDOW = 8;const HOUR_MS = 3_600_000;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}-async function serves402(entry) {try {const r = await fetch(entry.endpoint, {diff --git a/api/cron/x402-ring-leak-scan.js b/api/cron/x402-ring-leak-scan.jsindex abbe3d444..6fea33c2d 100644--- a/api/cron/x402-ring-leak-scan.js+++ b/api/cron/x402-ring-leak-scan.js@@ -34,11 +34,11 @@ import { randomUUID } from 'node:crypto';import { json, wrapCron, method, error } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { sendOpsAlert } from '../_lib/alerts.js';import { withDbRetry } from '../_lib/db-retry.js';import { sql } from '../_lib/db.js';import { ringAllowedAddresses, ringRoleWallets } from '../_lib/x402/ring-allowlist.js';+import { requireCron } from '../_lib/cron-auth.js';// ── Tuning ────────────────────────────────────────────────────────────────────const SIG_SCAN_LIMIT = 100; // hard per-wallet-per-run cap (task constraint)@@ -50,15 +50,6 @@ const SOL_RESIDUAL_FLOOR_LAMPORTS = 5_000;const FEE_DIVERGENCE_THRESHOLD = 0.20;const CANONICAL_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }- return true;-}-// ── Pure classification (exported for tests) ──────────────────────────────────/**diff --git a/api/cron/x402-ring-tick.js b/api/cron/x402-ring-tick.jsindex 94a79c76f..0ce88ad5c 100644--- a/api/cron/x402-ring-tick.js+++ b/api/cron/x402-ring-tick.js@@ -44,7 +44,6 @@ import {import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { getRedis } from '../_lib/redis.js';import { sql } from '../_lib/db.js';import { solanaConnection } from '../_lib/solana/connection.js';@@ -72,6 +71,7 @@ import {gateOnRingConfig,} from '../_lib/x402/ring-tick-plan.js';import { runTickPicks } from '../_lib/x402/ring-tick-exec.js';+import { requireCron } from '../_lib/cron-auth.js';const log = logger('x402-ring-tick');@@ -89,15 +89,6 @@ const CHEAP_CURSOR_KEY = 'x402:ring:tick:cheap';let _memTickSeq = 0;let _memCheapCursor = 0;-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) { json(res, 503, { error: 'CRON_SECRET unset' }); return false; }- const auth = req.headers['authorization'] || '';- const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(token, secret)) { json(res, 401, { error: 'unauthorized' }); return false; }- return true;-}-// Advance the durable per-minute counter (Redis INCR, in-memory fallback).async function nextTickSeq(redis) {if (redis) {diff --git a/api/cron/x402-seed-cron.js b/api/cron/x402-seed-cron.jsindex 450b046db..82ea22d47 100644--- a/api/cron/x402-seed-cron.js+++ b/api/cron/x402-seed-cron.js@@ -33,12 +33,12 @@ import {import { json, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';import { getRedis, isRedisAuthError } from '../_lib/redis.js';import { solanaConnection } from '../_lib/solana/connection.js';import { logger } from '../_lib/usage.js';import { SPONSOR_SOL_FLOOR_LAMPORTS } from '../_lib/x402/self-facilitator.js';import { readPayerUsdcAtomic } from './x402-autonomous-loop.js';+import { requireCron } from '../_lib/cron-auth.js';const log = logger('x402-seed-cron');@@ -57,21 +57,6 @@ const STYLES = ['twerk', 'spin', 'climb', 'combo',];-function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- res.status(503).json({ error: 'not_configured', message: 'CRON_SECRET unset' });- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- res.status(401).json({ error: 'unauthorized' });- return false;- }- return true;-}-function loadSeedKeypair() {// Dedicated seeder key — allows a separate wallet funded only for seeding// without touching the shared agent/demo wallet.diff --git a/api/labor/tick.js b/api/labor/tick.jsindex 9e2730301..a710fd14c 100644--- a/api/labor/tick.js+++ b/api/labor/tick.js@@ -5,27 +5,11 @@// • delivered/verifying jobs (settle now)// Authenticated with the Vercel cron Bearer secret. No-op (503) if unset.-import { error, json, method, wrap } from '../_lib/http.js';-import { env } from '../_lib/env.js';-import { constantTimeEquals } from '../_lib/crypto.js';+import { json, method, wrap } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { ensureLaborTables, getBounty, getJob } from '../_lib/agent-labor.js';import { runAutopilot, runSettlement } from '../_lib/labor-settle.js';--function requireCron(req, res) {- const secret = process.env.CRON_SECRET || env.CRON_SECRET;- if (!secret) {- error(res, 503, 'not_configured', 'CRON_SECRET unset');- return false;- }- const auth = req.headers['authorization'] || '';- const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';- if (!constantTimeEquals(presented, secret)) {- error(res, 401, 'unauthorized', 'invalid cron secret');- return false;- }- return true;-}+import { requireCron } from '../_lib/cron-auth.js';export default wrap(async (req, res) => {if (!method(req, res, ['POST', 'GET'])) return;diff --git a/tests/cron-auth-fail-closed.test.js b/tests/cron-auth-fail-closed.test.jsindex b13249f62..430f19f79 100644--- a/tests/cron-auth-fail-closed.test.js+++ b/tests/cron-auth-fail-closed.test.js@@ -1,89 +1,121 @@-// Regression guard for the 2026-07-23 audit finding: payment-session-sweep-// and forge-finalize failed OPEN when CRON_SECRET was unset ("allow in dev"),-// the only two handlers in /api/cron with an inverted posture. An unset-// CRON_SECRET on a misconfigured deploy would have exposed unauthenticated-// triggering of a money-moving sweep (session-budget refunds) and the forge-// finalize batch. Both must now fail closed with 503, like the other 66.+// Regression guard for the cron gate.+//+// 2026-07-23 audit: payment-session-sweep and forge-finalize failed OPEN when+// CRON_SECRET was unset ("allow in dev"), the only two handlers in /api/cron+// with an inverted posture. An unset CRON_SECRET on a misconfigured deploy would+// have exposed unauthenticated triggering of a money-moving sweep (session-budget+// refunds) and the forge finalize batch.+//+// 2026-08-06 (security review L8): the gate was copy-pasted into 78 files in+// eleven spellings, two of them with inverted return semantics. It now lives in+// exactly one module, so this suite tests that module — and asserts no handler+// has grown its own copy again, which is the failure mode that made a fail-open+// paste plausible in the first place.-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { requireCron as requireCronSweep } from '../api/cron/payment-session-sweep.js';-import { requireCron as requireCronFinalize } from '../api/cron/forge-finalize.js';+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { readFileSync, readdirSync, statSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { requireCron, isCronAuthorized } from '../api/_lib/cron-auth.js';++const API_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'api');function mockRes() {- return {- writeHead: vi.fn().mockReturnThis(),- end: vi.fn(),+ const res = {+ statusCode: 0,+ headersSent: false,+ writableEnded: false,+ headers: {},+ body: null,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(payload) { this.writableEnded = true; this.body = payload ? JSON.parse(payload) : null; },};+ return res;}-const handlers = [- ['payment-session-sweep', requireCronSweep],- ['forge-finalize', requireCronFinalize],-];+function walk(dir, out = []) {+ for (const entry of readdirSync(dir)) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) walk(full, out);+ else if (full.endsWith('.js')) out.push(full);+ }+ return out;+}-describe('cron auth fails closed', () => {- beforeEach(() => {- delete process.env.CRON_SECRET;+describe('cron auth', () => {+ beforeEach(() => { delete process.env.CRON_SECRET; });+ afterEach(() => { delete process.env.CRON_SECRET; });++ it('fails closed (503) when CRON_SECRET is unset', () => {+ const res = mockRes();+ expect(requireCron({ headers: {} }, res)).toBe(false);+ expect(res.statusCode).toBe(503);});- afterEach(() => {- delete process.env.CRON_SECRET;++ it('fails closed even when a credential is presented and CRON_SECRET is unset', () => {+ const res = mockRes();+ expect(requireCron({ headers: { 'x-cron-secret': 'anything' } }, res)).toBe(false);+ expect(res.statusCode).toBe(503);});- for (const [name, requireCron] of handlers) {- describe(name, () => {- it('503s and runs nothing when CRON_SECRET is unset', () => {- const res = mockRes();- const handled = requireCron({ headers: {} }, res);- expect(handled).toBe(true);- expect(res.writeHead).toHaveBeenCalledWith(503, expect.anything());- });+ it('401s when the secret is set but nothing is presented', () => {+ process.env.CRON_SECRET = 'test-cron-secret';+ const res = mockRes();+ expect(requireCron({ headers: {} }, res)).toBe(false);+ expect(res.statusCode).toBe(401);+ });- it('503s even when a header is presented but CRON_SECRET is unset', () => {- const res = mockRes();- const handled = requireCron(- { headers: { 'x-cron-secret': 'anything' } },- res,- );- expect(handled).toBe(true);- expect(res.writeHead).toHaveBeenCalledWith(503, expect.anything());- });+ it('401s on a wrong secret', () => {+ process.env.CRON_SECRET = 'test-cron-secret';+ const res = mockRes();+ expect(requireCron({ headers: { 'x-cron-secret': 'wrong' } }, res)).toBe(false);+ expect(res.statusCode).toBe(401);+ });- it('401s when the secret is set but no header is presented', () => {- process.env.CRON_SECRET = 'test-cron-secret';- const res = mockRes();- expect(requireCron({ headers: {} }, res)).toBe(true);- expect(res.writeHead).toHaveBeenCalledWith(401, expect.anything());- });+ it('401s on a near-miss (prefix of the real secret)', () => {+ process.env.CRON_SECRET = 'test-cron-secret';+ const res = mockRes();+ expect(requireCron({ headers: { authorization: 'Bearer test-cron-secre' } }, res)).toBe(false);+ expect(res.statusCode).toBe(401);+ });- it('401s on a wrong secret', () => {- process.env.CRON_SECRET = 'test-cron-secret';- const res = mockRes();- expect(- requireCron({ headers: { 'x-cron-secret': 'wrong' } }, res),- ).toBe(true);- expect(res.writeHead).toHaveBeenCalledWith(401, expect.anything());- });+ it('admits the correct secret via x-cron-secret', () => {+ process.env.CRON_SECRET = 'test-cron-secret';+ const res = mockRes();+ expect(requireCron({ headers: { 'x-cron-secret': 'test-cron-secret' } }, res)).toBe(true);+ expect(res.writableEnded).toBe(false);+ });- it('admits the correct secret via x-cron-secret', () => {- process.env.CRON_SECRET = 'test-cron-secret';- const res = mockRes();- expect(- requireCron({ headers: { 'x-cron-secret': 'test-cron-secret' } }, res),- ).toBe(false);- expect(res.writeHead).not.toHaveBeenCalled();- });+ it('admits the correct secret via Bearer, scheme case-insensitively', () => {+ process.env.CRON_SECRET = 'test-cron-secret';+ for (const scheme of ['Bearer', 'bearer', 'BEARER']) {+ const res = mockRes();+ expect(requireCron({ headers: { authorization: `${scheme} test-cron-secret` } }, res)).toBe(true);+ expect(res.writableEnded).toBe(false);+ }+ });- it('admits the correct secret via Bearer', () => {- process.env.CRON_SECRET = 'test-cron-secret';- const res = mockRes();- expect(- requireCron(- { headers: { authorization: 'Bearer test-cron-secret' } },- res,- ),- ).toBe(false);- expect(res.writeHead).not.toHaveBeenCalled();- });- });- }+ it('never treats an x-vercel-cron header as authorization', () => {+ process.env.CRON_SECRET = 'test-cron-secret';+ const res = mockRes();+ expect(requireCron({ headers: { 'x-vercel-cron': '1' } }, res)).toBe(false);+ expect(res.statusCode).toBe(401);+ });++ it('isCronAuthorized answers without writing a response', () => {+ expect(isCronAuthorized({ headers: { 'x-cron-secret': 'anything' } })).toBe(false);+ process.env.CRON_SECRET = 'test-cron-secret';+ expect(isCronAuthorized({ headers: { 'x-cron-secret': 'test-cron-secret' } })).toBe(true);+ expect(isCronAuthorized({ headers: {} })).toBe(false);+ });+});++describe('cron auth has exactly one implementation', () => {+ it('no handler under api/ declares its own requireCron', () => {+ const offenders = walk(API_DIR)+ .filter((f) => !f.endsWith(join('_lib', 'cron-auth.js')))+ .filter((f) => /function\s+requireCron\s*\(/.test(readFileSync(f, 'utf8')))+ .map((f) => f.slice(API_DIR.length + 1));+ expect(offenders).toEqual([]);+ });});