Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
fix(api): name a missing Supabase secret instead of an internal error
spacesdriveed9524ea1f19
diff --git a/backend/jobs/scheduled.ts b/backend/jobs/scheduled.tsindex 14dfd88..4b2ee88 100644--- a/backend/jobs/scheduled.ts+++ b/backend/jobs/scheduled.ts@@ -1,7 +1,7 @@import { createServices } from '../container.ts';import { getSupabase } from '../database/supabase.ts';import { getRedis, getRateLimitRedis } from '../database/redis.ts';-import { readConfig } from '../lib/config.ts';+import { coreSecretsMessage, missingCoreSecrets, readConfig } from '../lib/config.ts';import { FREE_PLAN_SUBREQUESTS } from '../lib/automationDelivery.ts';import { createLogger } from '../lib/logger.ts';import type { Services } from '../container.ts';@@ -64,6 +64,12 @@ async function dispatch(services: Services, context: RequestContext): Promise<vo// the cron entry point: the same services the API uses, built from the Worker env instead of a requestexport async function runScheduledJob(cron: string, env: Env, scheduledTime = Date.now()): Promise<void> {const context = cronContext(cron);+ // nothing can run without the database, so the log says which secret is missing instead of a client error+ const missing = missingCoreSecrets(env);+ if (missing.length > 0) {+ context.log.error('cron run skipped', { reason: coreSecretsMessage(missing) });+ return;+ }const clients = { supabase: getSupabase(env), redis: getRedis(env), rateLimitRedis: getRateLimitRedis(env) };const services = createServices(clients, readConfig(env), context);const started = Date.now();diff --git a/backend/lib/config.ts b/backend/lib/config.tsindex 3e8ea41..569c5da 100644--- a/backend/lib/config.ts+++ b/backend/lib/config.ts@@ -87,6 +87,25 @@ function allowedOrigins(env: Env): string[] {return [...new Set(listed)];}+// no request or cron run can work without the database and token checks, so these are checked before anything else+const CORE_SECRETS = ['SUPABASE_URL', 'SUPABASE_SERVICE_KEY', 'SUPABASE_ANON_KEY'] as const;++// the core secrets that are not set, or for the url not a web address+export function missingCoreSecrets(env: Partial<Env>): string[] {+ return CORE_SECRETS.filter(name => {+ const value = cleanSecret(env[name]);+ if (!value) return true;+ return name === 'SUPABASE_URL' && !(/^https?:\/\//.test(value) && originOf(value));+ });+}++export function coreSecretsMessage(missing: string[]): string {+ const names = missing.join(', ');+ const subject = missing.length === 1 ? `the ${names} Worker secret is` : `the ${names} Worker secrets are`;+ const object = missing.length === 1 ? 'it' : 'them';+ return `The server is not set up: ${subject} missing or invalid. Set ${object} with wrangler secret put, then deploy again.`;+}+// a Worker served from localhost is a development instance, so the local Vite server may call it tooexport function corsOrigins(config: AppConfig, requestUrl: string): string[] {const local = LOCAL_HOSTNAMES.includes(new URL(requestUrl).hostname);diff --git a/backend/middleware/clients.ts b/backend/middleware/clients.tsindex d062fb7..adc0cfe 100644--- a/backend/middleware/clients.ts+++ b/backend/middleware/clients.ts@@ -1,10 +1,16 @@import type { Next } from 'hono';import { getSupabase } from '../database/supabase.ts';import { getRedis, getRateLimitRedis } from '../database/redis.ts';+import { coreSecretsMessage, missingCoreSecrets } from '../lib/config.ts';+import { NotConfiguredError } from '../lib/errors.ts';import type { AppContext } from '../types/app.ts';// the clients are stateless HTTP clients, so creating them per request is cheap and safeexport async function injectClients(c: AppContext, next: Next): Promise<void> {+ // without the core secrets the Supabase client cannot be built, so say which one is missing instead of a bare 500+ const missing = missingCoreSecrets(c.env);+ if (missing.length > 0) throw new NotConfiguredError(coreSecretsMessage(missing));+c.set('supabase', getSupabase(c.env));c.set('redis', getRedis(c.env));c.set('rateLimitRedis', getRateLimitRedis(c.env));diff --git a/backend/tests/jobs/scheduled.test.ts b/backend/tests/jobs/scheduled.test.tsindex ad287b7..30f0d2a 100644--- a/backend/tests/jobs/scheduled.test.ts+++ b/backend/tests/jobs/scheduled.test.ts@@ -1,7 +1,8 @@-import { test } from 'node:test';+import { test, mock } from 'node:test';import assert from 'node:assert/strict';import { readFileSync } from 'node:fs';-import { DAILY_CRON, EVERY_FIVE_MINUTES_CRON, EVERY_MINUTE_CRON, cronPlan } from '../../jobs/scheduled.ts';+import type { Env } from '../../types/env.ts';+import { DAILY_CRON, EVERY_FIVE_MINUTES_CRON, EVERY_MINUTE_CRON, cronPlan, runScheduledJob } from '../../jobs/scheduled.ts';const at = (time: string) => Date.parse(`2026-10-16T${time}:00Z`);@@ -27,3 +28,13 @@ test('the crons in wrangler.toml are the ones the Worker dispatches', () => {assert.match(toml, /crons = \["\* \* \* \* \*", "\*\/5 \* \* \* \*", "0 0 \* \* \*"\]/);assert.deepEqual([EVERY_MINUTE_CRON, EVERY_FIVE_MINUTES_CRON, DAILY_CRON], ['* * * * *', '*/5 * * * *', '0 0 * * *']);});++test('a cron run without the Supabase secrets logs which are missing and stops instead of failing', async t => {+ const written = mock.method(console, 'error', () => {});+ t.after(() => written.mock.restore());+ await runScheduledJob(EVERY_MINUTE_CRON, { SUPABASE_URL: 'https://project.supabase.co' } as Env);+ assert.equal(written.mock.callCount(), 1);+ const line = JSON.parse(String(written.mock.calls[0].arguments[0]));+ assert.equal(line.message, 'cron run skipped');+ assert.match(line.reason, /SUPABASE_SERVICE_KEY, SUPABASE_ANON_KEY Worker secrets are missing/);+});diff --git a/backend/tests/lib/config.test.ts b/backend/tests/lib/config.test.tsindex c2888f7..94cd502 100644--- a/backend/tests/lib/config.test.ts+++ b/backend/tests/lib/config.test.ts@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { corsOrigins, readConfig } from '../../lib/config.ts';+import { coreSecretsMessage, corsOrigins, missingCoreSecrets, readConfig } from '../../lib/config.ts';import type { Env } from '../../types/env.ts';const BOM = String.fromCharCode(0xfeff);@@ -73,3 +73,18 @@ test('webhooks are signed with the Instagram app secret first and the Meta app sassert.equal(automation.paused, true);assert.equal(config({ AUTOMATION_PAUSED: 'yes' }).automation.paused, false);});++const CORE = { SUPABASE_URL: 'https://project.supabase.co', SUPABASE_SERVICE_KEY: 'service', SUPABASE_ANON_KEY: 'anon' };++test('the core Supabase secrets count as missing when unset, blank or, for the url, not a web address', () => {+ assert.deepEqual(missingCoreSecrets(CORE), []);+ assert.deepEqual(missingCoreSecrets({}), ['SUPABASE_URL', 'SUPABASE_SERVICE_KEY', 'SUPABASE_ANON_KEY']);+ assert.deepEqual(missingCoreSecrets({ ...CORE, SUPABASE_SERVICE_KEY: `${BOM} ` }), ['SUPABASE_SERVICE_KEY']);+ assert.deepEqual(missingCoreSecrets({ ...CORE, SUPABASE_URL: 'project.supabase.co' }), ['SUPABASE_URL']);+ assert.deepEqual(missingCoreSecrets({ ...CORE, SUPABASE_URL: 'http://' }), ['SUPABASE_URL']);+});++test('the missing secrets message names each secret and says how to set it', () => {+ assert.equal(coreSecretsMessage(['SUPABASE_URL']), 'The server is not set up: the SUPABASE_URL Worker secret is missing or invalid. Set it with wrangler secret put, then deploy again.');+ assert.match(coreSecretsMessage(['SUPABASE_URL', 'SUPABASE_ANON_KEY']), /the SUPABASE_URL, SUPABASE_ANON_KEY Worker secrets are missing or invalid\. Set them with/);+});diff --git a/backend/tests/middleware/clients.test.ts b/backend/tests/middleware/clients.test.tsnew file mode 100644index 0000000..5feea90--- /dev/null+++ b/backend/tests/middleware/clients.test.ts@@ -0,0 +1,34 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { Hono } from 'hono';+import { injectClients } from '../../middleware/clients.ts';+import { errorHandler } from '../../middleware/errorHandler.ts';+import type { AppEnv } from '../../types/app.ts';++const CORE = { SUPABASE_URL: 'https://project.supabase.co', SUPABASE_SERVICE_KEY: 'service', SUPABASE_ANON_KEY: 'anon' };++function app(): Hono<AppEnv> {+ const app = new Hono<AppEnv>();+ app.onError(errorHandler);+ app.use('*', async (c, next) => { c.set('requestId', 'req-test'); await next(); });+ app.use('*', injectClients);+ app.get('/ping', c => c.json({ hasClient: c.get('supabase') !== undefined }));+ return app;+}++test('a missing Supabase secret answers NOT_CONFIGURED naming the secret instead of an internal error', async () => {+ const response = await app().request('/ping', {}, { ...CORE, SUPABASE_SERVICE_KEY: '' });+ assert.equal(response.status, 503);+ assert.deepEqual(await response.json(), {+ success: false,+ code: 'NOT_CONFIGURED',+ message: 'The server is not set up: the SUPABASE_SERVICE_KEY Worker secret is missing or invalid. Set it with wrangler secret put, then deploy again.',+ requestId: 'req-test',+ });+});++test('with the core secrets set the request gets its clients', async () => {+ const response = await app().request('/ping', {}, CORE);+ assert.equal(response.status, 200);+ assert.deepEqual(await response.json(), { hasClient: true });+});