Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
refactor(cache): replace empty catches with explicit fallbacks
spacesdrive077821f7f09a
diff --git a/backend/lib/cache.js b/backend/lib/cache.jsindex d61ba04..0bffa1f 100644--- a/backend/lib/cache.js+++ b/backend/lib/cache.js@@ -1,105 +1,80 @@-// All functions accept `redis` as first argument.-// If redis is null (Upstash not configured) or the call fails, all operations-// are silent no-ops - cache failures must never break the main request.+// every helper is a no-op without redis: the cache is optional+export { createOAuthState, verifyOAuthState } from './oauthState.js';-// Platform stats change constantly, so cached analytics expire and refetch rather than going stale.+// stats change constantly, so cached analytics expire instead of going staleconst ANALYTICS_TTL_SECONDS = 6 * 60 * 60;-// Bump when the cached video shape changes so entries written by older code read as a miss.-// v2: likeCount and commentCount are null when YouTube hides them, instead of 0.+// bump a version when the cached shape changes, so old entries read as a miss+// v2: likeCount and commentCount are null when youtube hides themconst VIDEOS_CACHE_VERSION = 2;+const IG_CACHE_VERSION = 2;-export async function getVideosCache(redis, userId, accountId) {+async function readKey(redis, key) {if (!redis) return null;try {- const cached = await redis.get(`videos:${userId}:${accountId}`);- return cached?.version === VIDEOS_CACHE_VERSION ? cached : null;- } catch { return null; }+ return await redis.get(key);+ } catch {+ // a cache miss falls back to the live api+ return null;+ }+}++async function writeKey(redis, key, value) {+ if (!redis) return undefined;+ try {+ await redis.set(key, value, { ex: ANALYTICS_TTL_SECONDS });+ } catch {+ // a failed write only costs a refetch next time+ return undefined;+ }+ return undefined;+}++async function deleteKey(redis, key) {+ if (!redis) return undefined;+ try {+ await redis.del(key);+ } catch {+ // the entry still expires on its own ttl+ return undefined;+ }+ return undefined;+}++export async function getVideosCache(redis, userId, accountId) {+ const cached = await readKey(redis, `videos:${userId}:${accountId}`);+ return cached?.version === VIDEOS_CACHE_VERSION ? cached : null;}export async function setVideosCache(redis, userId, accountId, data) {- if (!redis) return;- try { await redis.set(`videos:${userId}:${accountId}`, { ...data, version: VIDEOS_CACHE_VERSION }, { ex: ANALYTICS_TTL_SECONDS }); } catch { /* non-fatal */ }+ await writeKey(redis, `videos:${userId}:${accountId}`, { ...data, version: VIDEOS_CACHE_VERSION });}export async function deleteVideosCache(redis, userId, accountId) {- if (!redis) return;- try { await redis.del(`videos:${userId}:${accountId}`); } catch { /* non-fatal */ }+ await deleteKey(redis, `videos:${userId}:${accountId}`);}-// Bump when the cached media shape changes so entries written by older code read as a miss.-const IG_CACHE_VERSION = 2;-export async function getIGCache(redis, userId, accountId) {- if (!redis) return null;- try {- const cached = await redis.get(`ig:${userId}:${accountId}`);- return cached?.version === IG_CACHE_VERSION ? cached : null;- } catch { return null; }+ const cached = await readKey(redis, `ig:${userId}:${accountId}`);+ return cached?.version === IG_CACHE_VERSION ? cached : null;}export async function setIGCache(redis, userId, accountId, data) {- if (!redis) return;- try { await redis.set(`ig:${userId}:${accountId}`, { ...data, version: IG_CACHE_VERSION }, { ex: ANALYTICS_TTL_SECONDS }); } catch { /* non-fatal */ }+ await writeKey(redis, `ig:${userId}:${accountId}`, { ...data, version: IG_CACHE_VERSION });}export async function deleteIGCache(redis, userId, accountId) {- if (!redis) return;- try { await redis.del(`ig:${userId}:${accountId}`); } catch { /* non-fatal */ }+ await deleteKey(redis, `ig:${userId}:${accountId}`);}export async function getRedditCache(redis, userId, accountId) {- if (!redis) return null;- try { return (await redis.get(`reddit:${userId}:${accountId}`)) || null; } catch { return null; }+ return (await readKey(redis, `reddit:${userId}:${accountId}`)) || null;}export async function setRedditCache(redis, userId, accountId, data) {- if (!redis) return;- try { await redis.set(`reddit:${userId}:${accountId}`, data, { ex: ANALYTICS_TTL_SECONDS }); } catch { /* non-fatal */ }+ await writeKey(redis, `reddit:${userId}:${accountId}`, data);}export async function deleteRedditCache(redis, userId, accountId) {- if (!redis) return;- try { await redis.del(`reddit:${userId}:${accountId}`); } catch { /* non-fatal */ }-}--// ---- OAuth state via HMAC (no Redis required) ---------------------------------// State format: base64url(userId:timestamp) . base64url(HMAC-SHA256 signature)-// Expires after 10 minutes. Secret is INSTAGRAM_APP_SECRET.--async function hmacSign(secret, message) {- const key = await crypto.subtle.importKey(- 'raw',- new TextEncoder().encode(secret),- { name: 'HMAC', hash: 'SHA-256' },- false,- ['sign'],- );- const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message));- return btoa(String.fromCharCode(...new Uint8Array(sig)))- .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');-}--async function hmacVerify(secret, message, signature) {- const expected = await hmacSign(secret, message);- return expected === signature;-}--export async function createOAuthState(userId, secret) {- const payload = btoa(`${userId}:${Date.now()}`).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');- const sig = await hmacSign(secret, payload);- return `${payload}.${sig}`;-}--export async function verifyOAuthState(state, secret) {- const dot = state.lastIndexOf('.');- if (dot === -1) return null;- const payload = state.slice(0, dot);- const sig = state.slice(dot + 1);- const valid = await hmacVerify(secret, payload, sig);- if (!valid) return null;- const decoded = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));- const [userId, ts] = decoded.split(':');- if (Date.now() - Number(ts) > 10 * 60 * 1000) return null;- return userId;+ await deleteKey(redis, `reddit:${userId}:${accountId}`);}diff --git a/backend/lib/cache.test.js b/backend/lib/cache.test.jsnew file mode 100644index 0000000..18f6ba6--- /dev/null+++ b/backend/lib/cache.test.js@@ -0,0 +1,65 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ getVideosCache, setVideosCache, deleteVideosCache,+ getIGCache, setIGCache, getRedditCache, setRedditCache,+} from './cache.js';++function memoryRedis() {+ const store = new Map();+ return {+ store,+ get: async (key) => store.get(key) ?? null,+ set: async (key, value, options) => { store.set(key, value); store.set(`${key}:options`, options); },+ del: async (key) => { store.delete(key); },+ };+}++const failingRedis = {+ get: async () => { throw new Error('down'); },+ set: async () => { throw new Error('down'); },+ del: async () => { throw new Error('down'); },+};++test('every helper is a no-op without redis', async () => {+ assert.equal(await getVideosCache(null, 'u', 'a'), null);+ assert.equal(await getIGCache(null, 'u', 'a'), null);+ assert.equal(await getRedditCache(null, 'u', 'a'), null);+ assert.equal(await setVideosCache(null, 'u', 'a', {}), undefined);+ assert.equal(await deleteVideosCache(null, 'u', 'a'), undefined);+});++test('redis failures fall back silently', async () => {+ assert.equal(await getVideosCache(failingRedis, 'u', 'a'), null);+ assert.equal(await getRedditCache(failingRedis, 'u', 'a'), null);+ assert.equal(await setVideosCache(failingRedis, 'u', 'a', { videos: [] }), undefined);+ assert.equal(await setRedditCache(failingRedis, 'u', 'a', {}), undefined);+ assert.equal(await deleteVideosCache(failingRedis, 'u', 'a'), undefined);+});++test('video entries round-trip with a version and a 6 hour expiry', async () => {+ const redis = memoryRedis();+ await setVideosCache(redis, 'u', 'a', { videos: [1] });++ assert.deepEqual(await getVideosCache(redis, 'u', 'a'), { videos: [1], version: 2 });+ assert.deepEqual(redis.store.get('videos:u:a:options'), { ex: 21600 });+});++test('entries written by older code read as a miss', async () => {+ const redis = memoryRedis();+ redis.store.set('videos:u:a', { videos: [1] });+ redis.store.set('ig:u:a', { media: [], version: 1 });++ assert.equal(await getVideosCache(redis, 'u', 'a'), null);+ assert.equal(await getIGCache(redis, 'u', 'a'), null);+});++test('delete removes the entry', async () => {+ const redis = memoryRedis();+ await setIGCache(redis, 'u', 'a', { media: [] });+ await setVideosCache(redis, 'u', 'a', { videos: [] });+ await deleteVideosCache(redis, 'u', 'a');++ assert.equal(await getVideosCache(redis, 'u', 'a'), null);+ assert.deepEqual(await getIGCache(redis, 'u', 'a'), { media: [], version: 2 });+});diff --git a/backend/lib/oauthState.js b/backend/lib/oauthState.jsnew file mode 100644index 0000000..8d26118--- /dev/null+++ b/backend/lib/oauthState.js@@ -0,0 +1,45 @@+// state format: base64url(userId:timestamp).base64url(hmac-sha256 signature)+const STATE_TTL_MS = 10 * 60 * 1000;++function toBase64Url(text) {+ return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+}++async function hmacSign(secret, message) {+ const key = await crypto.subtle.importKey(+ 'raw',+ new TextEncoder().encode(secret),+ { name: 'HMAC', hash: 'SHA-256' },+ false,+ ['sign'],+ );+ const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message));+ return toBase64Url(String.fromCharCode(...new Uint8Array(signature)));+}++async function hmacVerify(secret, message, signature) {+ const expected = await hmacSign(secret, message);+ return expected === signature;+}++export async function createOAuthState(userId, secret) {+ const payload = toBase64Url(`${userId}:${Date.now()}`);+ const signature = await hmacSign(secret, payload);+ return `${payload}.${signature}`;+}++export async function verifyOAuthState(state, secret) {+ const separatorIndex = state.lastIndexOf('.');+ if (separatorIndex === -1) return null;++ const payload = state.slice(0, separatorIndex);+ const signature = state.slice(separatorIndex + 1);+ const isValid = await hmacVerify(secret, payload, signature);+ if (!isValid) return null;++ const decoded = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));+ const [userId, createdAt] = decoded.split(':');+ if (Date.now() - Number(createdAt) > STATE_TTL_MS) return null;++ return userId;+}diff --git a/backend/lib/oauthState.test.js b/backend/lib/oauthState.test.jsnew file mode 100644index 0000000..03821b1--- /dev/null+++ b/backend/lib/oauthState.test.js@@ -0,0 +1,35 @@+import { test, mock } from 'node:test';+import assert from 'node:assert/strict';+import { createOAuthState, verifyOAuthState } from './oauthState.js';++test('a state verifies back to its user id', async () => {+ const state = await createOAuthState('user-123', 'secret');+ assert.equal(await verifyOAuthState(state, 'secret'), 'user-123');+});++test('a state signed with another secret is rejected', async () => {+ const state = await createOAuthState('user-123', 'secret');+ assert.equal(await verifyOAuthState(state, 'other-secret'), null);+});++test('a tampered payload is rejected', async () => {+ const state = await createOAuthState('user-123', 'secret');+ const [, signature] = state.split('.');+ const forgedPayload = btoa(`attacker:${Date.now()}`).replace(/=+$/, '');+ assert.equal(await verifyOAuthState(`${forgedPayload}.${signature}`, 'secret'), null);+});++test('a state without a signature is rejected', async () => {+ assert.equal(await verifyOAuthState('no-separator', 'secret'), null);+});++test('a state older than 10 minutes is rejected', async () => {+ mock.timers.enable({ apis: ['Date'], now: 1_000_000 });+ try {+ const state = await createOAuthState('user-123', 'secret');+ mock.timers.tick(10 * 60 * 1000 + 1);+ assert.equal(await verifyOAuthState(state, 'secret'), null);+ } finally {+ mock.timers.reset();+ }+});diff --git a/backend/services/youtube.js b/backend/services/youtube.jsindex 1c26bec..9d37a6f 100644--- a/backend/services/youtube.js+++ b/backend/services/youtube.js@@ -39,25 +39,32 @@ function extractChannelId(input) {return input;}+// returns null when the lookup finds nothing or fails, so the next strategy can run+async function lookupChannelId(endpoint, params, pickId, apiKey) {+ try {+ const data = await ytFetch(endpoint, params, apiKey);+ if (data.items && data.items.length > 0) return pickId(data.items[0]);+ return null;+ } catch {+ return null;+ }+}+export async function resolveChannelId(input, apiKey) {const extracted = extractChannelId(input);if (!extracted) throw new Error('Invalid input');if (/^UC[\w-]{22}$/.test(extracted)) return extracted;- try {- const data = await ytFetch('channels', { part: 'id', forHandle: extracted }, apiKey);- if (data.items && data.items.length > 0) return data.items[0].id;- } catch { }+ // sequential on purpose: a search costs 100 quota units+ const byHandle = await lookupChannelId('channels', { part: 'id', forHandle: extracted }, (item) => item.id, apiKey);+ if (byHandle !== null) return byHandle;- try {- const data = await ytFetch('channels', { part: 'id', forUsername: extracted }, apiKey);- if (data.items && data.items.length > 0) return data.items[0].id;- } catch { }+ const byUsername = await lookupChannelId('channels', { part: 'id', forUsername: extracted }, (item) => item.id, apiKey);+ if (byUsername !== null) return byUsername;- try {- const data = await ytFetch('search', { part: 'snippet', q: extracted, type: 'channel', maxResults: '1' }, apiKey);- if (data.items && data.items.length > 0) return data.items[0].snippet.channelId;- } catch { }+ const searchParams = { part: 'snippet', q: extracted, type: 'channel', maxResults: '1' };+ const bySearch = await lookupChannelId('search', searchParams, (item) => item.snippet.channelId, apiKey);+ if (bySearch !== null) return bySearch;throw new Error('Could not resolve channel. Please provide a valid Channel ID (starts with UC).');}@@ -174,16 +181,19 @@ function formatCompact(n) {}function extractYouTubeVideoId(url) {+ let parsedUrl;try {- const u = new URL(url.trim());- if (u.hostname === 'youtu.be') return u.pathname.slice(1).split('?')[0];- if (u.hostname.includes('youtube.com')) {- if (u.pathname.startsWith('/shorts/')) return u.pathname.split('/')[2];- if (u.pathname.startsWith('/embed/')) return u.pathname.split('/')[2];- return u.searchParams.get('v');- }- } catch {}- return null;+ parsedUrl = new URL(url.trim());+ } catch {+ // not a url at all, so it has no video id+ return null;+ }++ const { hostname, pathname, searchParams } = parsedUrl;+ if (hostname === 'youtu.be') return pathname.slice(1).split('?')[0];+ if (!hostname.includes('youtube.com')) return null;+ if (pathname.startsWith('/shorts/') || pathname.startsWith('/embed/')) return pathname.split('/')[2];+ return searchParams.get('v');}export async function fetchTrackedYouTubeData(videoUrl, apiKey) {diff --git a/backend/services/youtube.test.js b/backend/services/youtube.test.jsnew file mode 100644index 0000000..b764ec0--- /dev/null+++ b/backend/services/youtube.test.js@@ -0,0 +1,77 @@+import { test, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { resolveChannelId, fetchTrackedYouTubeData } from './youtube.js';++const realFetch = globalThis.fetch;+afterEach(() => { globalThis.fetch = realFetch; });++function lookupName({ pathname, searchParams }) {+ if (searchParams.get('forHandle')) return 'forHandle';+ if (searchParams.get('forUsername')) return 'forUsername';+ return pathname.split('/').pop();+}++// answers each youtube endpoint from a table and records the calls+function fakeYouTube(responses) {+ const calls = [];+ globalThis.fetch = async (url) => {+ const lookup = lookupName(new URL(url));+ calls.push(lookup);+ const body = responses[lookup] ?? { items: [] };+ if (body instanceof Error) throw body;+ return { json: async () => body };+ };+ return calls;+}++test('a channel id is returned without calling the api', async () => {+ const calls = fakeYouTube({});+ assert.equal(await resolveChannelId('UCabcdefghijklmnopqrstuv', 'key'), 'UCabcdefghijklmnopqrstuv');+ assert.deepEqual(calls, []);+});++test('a handle resolves through forHandle first', async () => {+ const calls = fakeYouTube({ forHandle: { items: [{ id: 'UC_handle' }] } });+ assert.equal(await resolveChannelId('https://youtube.com/@creator', 'key'), 'UC_handle');+ assert.deepEqual(calls, ['forHandle']);+});++test('lookups fall through in order when earlier ones find nothing or fail', async () => {+ const calls = fakeYouTube({+ forHandle: new Error('network down'),+ forUsername: { error: { message: 'quota exceeded' } },+ search: { items: [{ snippet: { channelId: 'UC_search' } }] },+ });+ assert.equal(await resolveChannelId('creator', 'key'), 'UC_search');+ assert.deepEqual(calls, ['forHandle', 'forUsername', 'search']);+});++test('a search result without a snippet counts as not found', async () => {+ fakeYouTube({ search: { items: [{}] } });+ await assert.rejects(resolveChannelId('creator', 'key'), /Could not resolve channel/);+});++test('an unparseable video link is rejected before any api call', async () => {+ const calls = fakeYouTube({});+ await assert.rejects(fetchTrackedYouTubeData('not a url', 'key'), /could not extract video ID/);+ await assert.rejects(fetchTrackedYouTubeData('https://example.com/watch?v=abc', 'key'), /could not extract video ID/);+ assert.deepEqual(calls, []);+});++test('watch, short, embed and youtu.be links all reach the api with the video id', async () => {+ const ids = [];+ globalThis.fetch = async (url) => {+ ids.push(new URL(url).searchParams.get('id'));+ return { json: async () => ({ items: [] }) };+ };+ const links = [+ 'https://www.youtube.com/watch?v=aaa',+ 'https://youtube.com/shorts/bbb',+ 'https://www.youtube.com/embed/ccc',+ 'https://youtu.be/ddd?t=10',+ ];+ for (const link of links) {+ await assert.rejects(fetchTrackedYouTubeData(link, 'key'), /video not found/);+ }+ assert.deepEqual(ids, ['aaa', 'bbb', 'ccc', 'ddd']);+});diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.mdindex a181c1f..b74a78b 100644--- a/docs/architecture/backend/CACHING.md+++ b/docs/architecture/backend/CACHING.md@@ -69,7 +69,7 @@ return c.json(result);## HMAC OAuth State (Not Redis)-The `createOAuthState()` and `verifyOAuthState()` functions in `cache.js` are **not** Redis-based. They use `crypto.subtle.sign()` (native Web Crypto API in Workers) to create self-verifying state tokens. Redis is not involved.+The `createOAuthState()` and `verifyOAuthState()` functions live in `lib/oauthState.js` and are re-exported from `cache.js` for existing importers. They are **not** Redis-based. They use `crypto.subtle.sign()` (native Web Crypto API in Workers) to create self-verifying state tokens. Redis is not involved.```State format: base64url(userId:timestamp).base64url(HMAC-SHA256-signature)diff --git a/docs/guidelines/CLOUDFLARE_WORKERS.md b/docs/guidelines/CLOUDFLARE_WORKERS.mdindex 01fc32b..089d245 100644--- a/docs/guidelines/CLOUDFLARE_WORKERS.md+++ b/docs/guidelines/CLOUDFLARE_WORKERS.md@@ -99,7 +99,7 @@ async function hmacSign(secret, message) {}```-This pattern is used in `backend/lib/cache.js` for OAuth state tokens.+This pattern is used in `backend/lib/oauthState.js` for OAuth state tokens.## Local Developmentdiff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.mdindex a57cddc..b16f75a 100644--- a/docs/guidelines/ERROR_HANDLING.md+++ b/docs/guidelines/ERROR_HANDLING.md@@ -29,17 +29,18 @@ Supabase errors are objects with `message`, `code`, and `details`. Throwing the### Cache Operations (lib/cache.js)-Always catch and silently ignore - cache failures must never surface to users:+Always catch and fall back silently - cache failures must never surface to users. Every `catch` returns an explicit fallback with a one-line reason, so no catch block is empty:```jstry {- return (await redis.get(key)) || null;+ return await redis.get(key);} catch {+ // a cache miss falls back to the live apireturn null;}```-The empty `catch` block is intentional. Do not log cache errors - they create noise for transient Redis connection issues.+`cache.js` keeps this in three private helpers (`readKey`, `writeKey`, `deleteKey`) that every exported function uses. Do not log cache errors - they create noise for transient Redis connection issues.### Route Handlers (routes/)diff --git a/docs/philosophy/PERFORMANCE.md b/docs/philosophy/PERFORMANCE.mdindex 6c3b5f8..842c9c0 100644--- a/docs/philosophy/PERFORMANCE.md+++ b/docs/philosophy/PERFORMANCE.md@@ -18,9 +18,10 @@ Request| Resource | Cache key | TTL | Note ||---|---|---|---|-| YouTube analytics | `videos:{userId}:{accountId}` | None set (bug - see ROADMAP) | Should be 1 hour |-| Instagram analytics | `ig:{userId}:{accountId}` | None set (bug - see ROADMAP) | Should be 1 hour |-| OAuth state | `oauth_ig:{state}` | 10 minutes | Security-critical - do not extend |+| YouTube analytics | `videos:{userId}:{accountId}` | 6 hours | Versioned; old versions read as a miss |+| Instagram analytics | `ig:{userId}:{accountId}` | 6 hours | Versioned; old versions read as a miss |+| Reddit analytics | `reddit:{userId}:{accountId}` | 6 hours | |+| OAuth state | none (HMAC-signed token, see `lib/oauthState.js`) | 10 minutes | Security-critical - do not extend |Cache invalidation happens on:- Account deletion (explicit `redis.del()`)