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(backend): trim route handlers, rename results and fix comments
spacesdrive7d758b8222c5
diff --git a/backend/routes/analytics.js b/backend/routes/analytics.jsindex 52a3129..982d71e 100644--- a/backend/routes/analytics.js+++ b/backend/routes/analytics.js@@ -8,6 +8,24 @@ import { backfillChannelData } from '../services/accountRefresh.js';const app = new Hono();+// api errors can echo request urls that carry the api key or access token+function redactUrls(message) {+ return message.replace(/https?:\/\/[^\s)]+/g, '[url]');+}++async function storeInstagramSnapshot({ supabase, redis, userId, id }, account, profile, media) {+ await Promise.all([+ setIGCache(redis, userId, id, { media, fetchedAt: new Date().toISOString() }),+ updateAccount(supabase, account.id, {+ followersCount: profile.followersCount,+ followsCount: profile.followsCount,+ mediaCount: profile.mediaCount,+ profilePictureUrl: profile.profilePictureUrl,+ lastUpdated: new Date().toISOString(),+ }, userId),+ ]);+}+app.get('/accounts/:id/analytics', async (c) => {try {const supabase = c.get('supabase');@@ -31,8 +49,7 @@ app.get('/accounts/:id/analytics', async (c) => {videoCount: videos.length,});} catch (err) {- const safe = err.message.replace(/https?:\/\/[^\s)]+/g, '[url]');- return c.json({ success: false, message: safe }, 400);+ return c.json({ success: false, message: redactUrls(err.message) }, 400);}});@@ -77,7 +94,6 @@ app.get('/comparison', async (c) => {app.get('/accounts/:id/ig-analytics', async (c) => {try {const supabase = c.get('supabase');- const redis = c.get('redis');const userId = c.get('userId');const id = c.req.param('id');@@ -93,31 +109,20 @@ app.get('/accounts/:id/ig-analytics', async (c) => {fetchInstagramProfile(account.igUserId, account.accessToken),fetchInstagramMedia(account.igUserId, account.accessToken, 500),]);-- await Promise.all([- setIGCache(redis, userId, id, { media, fetchedAt: new Date().toISOString() }),- updateAccount(supabase, account.id, {- followersCount: profile.followersCount,- followsCount: profile.followsCount,- mediaCount: profile.mediaCount,- profilePictureUrl: profile.profilePictureUrl,- lastUpdated: new Date().toISOString(),- }, userId),- ]);+ await storeInstagramSnapshot({ supabase, redis: c.get('redis'), userId, id }, account, profile, media);const analytics = computeInstagramAnalytics(profile, media);- const { accessToken: _, ...safeAcc } = account;+ const { accessToken: _, ...publicAccount } = account;return c.json({success: true,profile: { ...profile },- account: safeAcc,+ account: publicAccount,analytics,mediaCount: media.length,});} catch (err) {- const safe = err.message.replace(/https?:\/\/[^\s)]+/g, '[url]');- return c.json({ success: false, message: safe }, 400);+ return c.json({ success: false, message: redactUrls(err.message) }, 400);}});@@ -147,8 +152,7 @@ app.get('/accounts/:id/ig-media', async (c) => {return c.json({ success: true, media, fetchedAt });} catch (err) {- const safe = err.message.replace(/https?:\/\/[^\s)]+/g, '[url]');- return c.json({ success: false, message: safe }, 400);+ return c.json({ success: false, message: redactUrls(err.message) }, 400);}});@@ -161,15 +165,15 @@ app.get('/videos/all', async (c) => {const accounts = await getAccounts(supabase, userId);const allVideos = [];- for (const acct of accounts) {- if (channelId && acct.id !== channelId) continue;- const cached = await getVideosCache(redis, userId, acct.id);+ for (const account of accounts) {+ if (channelId && account.id !== channelId) continue;+ const cached = await getVideosCache(redis, userId, account.id);if (cached && cached.videos) {- allVideos.push(...cached.videos.map(v => ({- ...v,- channelTitle: acct.title || acct.channelTitle,- channelId: acct.id,- channelThumbnail: acct.thumbnails?.default || '',+ allVideos.push(...cached.videos.map(video => ({+ ...video,+ channelTitle: account.title || account.channelTitle,+ channelId: account.id,+ channelThumbnail: account.thumbnails?.default || '',})));}}@@ -180,7 +184,7 @@ app.get('/videos/all', async (c) => {success: true,videos,total: videos.length,- channels: accounts.map(a => ({ id: a.id, title: a.title })),+ channels: accounts.map(account => ({ id: account.id, title: account.title })),});} catch (err) {return c.json({ success: false, message: err.message }, 500);diff --git a/backend/routes/instagramAuth.js b/backend/routes/instagramAuth.jsindex 3281d01..2d8c6da 100644--- a/backend/routes/instagramAuth.js+++ b/backend/routes/instagramAuth.js@@ -1,4 +1,4 @@-import { verifyOAuthState } from '../lib/cache.js';+import { verifyOAuthState } from '../lib/oauthState.js';import {readInstagramOAuthConfig, buildAuthorizationUrl, connectInstagramFromOAuth,} from '../services/instagramOAuth.js';diff --git a/backend/routes/trackedContent.js b/backend/routes/trackedContent.jsindex 3fc802b..2b38550 100644--- a/backend/routes/trackedContent.js+++ b/backend/routes/trackedContent.js@@ -18,11 +18,22 @@ const router = new Hono();async function redditCookieFor(supabase, accountId, userId) {if (!accountId) return { cookie: null };const account = await getAccountById(supabase, accountId, userId);- if (!account || account.platform !== 'reddit') return { notFound: true };+ if (!account || account.platform !== 'reddit') return { isNotFound: true };return { cookie: account.cookie || null };}-// List all tracked content for the current user+// returns the fetched data, or an error response the handler sends unchanged+async function fetchNewTrackedData(c, contentType, url, accountId) {+ if (contentType === 'youtube') {+ const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^/, '').trim();+ if (!apiKey) return { response: c.json({ error: 'YouTube API key not configured on this server' }, 400) };+ return { data: await fetchTrackedYouTubeData(url, apiKey) };+ }+ const reddit = await redditCookieFor(c.get('supabase'), accountId, c.get('userId'));+ if (reddit.isNotFound) return { response: c.json({ error: 'Reddit account not found' }, 404) };+ return { data: await fetchTrackedPostData(url, reddit.cookie) };+}+router.get('/tracked-content', async (c) => {const userId = c.get('userId');const supabase = c.get('supabase');@@ -35,7 +46,6 @@ router.get('/tracked-content', async (c) => {}});-// Add a new tracked content item (Reddit post or YouTube video)router.post('/tracked-content', async (c) => {const userId = c.get('userId');const supabase = c.get('supabase');@@ -48,17 +58,8 @@ router.post('/tracked-content', async (c) => {if (!contentType) return c.json({ error: 'Only Reddit and YouTube URLs are supported' }, 400);try {- let fetchedData;-- if (contentType === 'youtube') {- const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^/, '').trim();- if (!apiKey) return c.json({ error: 'YouTube API key not configured on this server' }, 400);- fetchedData = await fetchTrackedYouTubeData(url.trim(), apiKey);- } else {- const reddit = await redditCookieFor(supabase, accountId, userId);- if (reddit.notFound) return c.json({ error: 'Reddit account not found' }, 404);- fetchedData = await fetchTrackedPostData(url.trim(), reddit.cookie);- }+ const fetched = await fetchNewTrackedData(c, contentType, url.trim(), accountId);+ if (fetched.response) return fetched.response;const id = Date.now().toString(36) + Math.random().toString(36).slice(2);await createTrackedPost(supabase, {@@ -69,7 +70,7 @@ router.post('/tracked-content', async (c) => {category,contentType,}, userId);- await updateTrackedPost(supabase, id, { data: fetchedData }, userId);+ await updateTrackedPost(supabase, id, { data: fetched.data }, userId);const created = await getTrackedPostById(supabase, id, userId);return c.json(created, 201);@@ -94,15 +95,15 @@ router.put('/tracked-content/:id', async (c) => {const isYouTube = (existing.contentType || 'reddit') === 'youtube';if (manualViews !== undefined) {- const views = manualViewsPatch(manualViews, isYouTube);- if (views.error) return c.json({ error: views.error }, 400);- await patchTrackedPostData(supabase, id, views.patch, userId);+ const viewsResult = manualViewsPatch(manualViews, isYouTube);+ if (viewsResult.error) return c.json({ error: viewsResult.error }, 400);+ await patchTrackedPostData(supabase, id, viewsResult.patch, userId);}if (imageUrl !== undefined) {- const image = imageUrlPatch(imageUrl, isYouTube);- if (image.error) return c.json({ error: image.error }, 400);- await patchTrackedPostData(supabase, id, image.patch, userId);+ const imageResult = imageUrlPatch(imageUrl, isYouTube);+ if (imageResult.error) return c.json({ error: imageResult.error }, 400);+ await patchTrackedPostData(supabase, id, imageResult.patch, userId);}const updates = {};@@ -121,7 +122,6 @@ router.put('/tracked-content/:id', async (c) => {}});-// Delete a tracked content itemrouter.delete('/tracked-content/:id', async (c) => {const id = c.req.param('id');const userId = c.get('userId');@@ -137,7 +137,6 @@ router.delete('/tracked-content/:id', async (c) => {}});-// Refresh live data for a single tracked content itemrouter.post('/tracked-content/:id/refresh', async (c) => {const id = c.req.param('id');const userId = c.get('userId');diff --git a/backend/server.js b/backend/server.jsindex baafa61..754fb1a 100644--- a/backend/server.js+++ b/backend/server.js@@ -35,7 +35,7 @@ app.use('*', async (c, next) => {app.get('/api/health', (c) => c.json({ status: 'ok', timestamp: new Date().toISOString() }));-// public: the oauth redirect carries no jwt, so the user comes from the redis state token+// public: the oauth redirect carries no jwt, so the user comes from the signed hmac state tokenapp.get('/api/auth/instagram/callback', callbackHandler);const api = new Hono();diff --git a/backend/services/accountRefresh.js b/backend/services/accountRefresh.jsindex ac6f1d0..a55aac3 100644--- a/backend/services/accountRefresh.js+++ b/backend/services/accountRefresh.js@@ -68,8 +68,8 @@ export async function backfillChannelData(supabase, account, apiKey, userId) {lastUpdated: new Date().toISOString(),}, userId);Object.assign(account, channelData);- } catch (e) {- console.error('Failed to backfill channel data:', e.message);+ } catch (err) {+ console.error('Failed to backfill channel data:', err.message);}}diff --git a/backend/services/instagramApi.js b/backend/services/instagramApi.jsindex 1dcd7a1..dca1cc5 100644--- a/backend/services/instagramApi.js+++ b/backend/services/instagramApi.js@@ -1,5 +1,3 @@-// fetch is a global in Cloudflare Workers - no import needed.-const IG_GRAPH_URL = 'https://graph.instagram.com';const IG_API_VERSION = 'v25.0';const REQUEST_TIMEOUT_MS = 15000;diff --git a/backend/services/instagramOAuth.js b/backend/services/instagramOAuth.jsindex 1bed7f0..b504cd4 100644--- a/backend/services/instagramOAuth.js+++ b/backend/services/instagramOAuth.js@@ -1,4 +1,4 @@-import { createOAuthState } from '../lib/cache.js';+import { createOAuthState } from '../lib/oauthState.js';import { createAccount, getAccounts } from '../lib/db.js';import { fetchInstagramProfile } from './instagramApi.js';import { buildInstagramAccount } from './accountFactory.js';diff --git a/backend/services/youtubeApi.js b/backend/services/youtubeApi.jsindex 68f5cd9..9a9fb1b 100644--- a/backend/services/youtubeApi.js+++ b/backend/services/youtubeApi.js@@ -1,5 +1,3 @@-// fetch is a global in Cloudflare Workers - no import needed.-// adds the key to the caller's params object, as callers always pass a fresh oneexport async function ytFetch(endpoint, params, apiKey) {const url = new URL(`https://www.googleapis.com/youtube/v3/${endpoint}`);diff --git a/backend/services/youtubeLibrary.js b/backend/services/youtubeLibrary.jsindex 4797aae..d9242d3 100644--- a/backend/services/youtubeLibrary.js+++ b/backend/services/youtubeLibrary.js@@ -28,9 +28,9 @@ export function channelMetrics(account) {export function accountComparison(accounts) {const sorted = {- bySubscribers: [...accounts].sort((a, b) => b.subscriberCount - a.subscriberCount),- byViews: [...accounts].sort((a, b) => b.viewCount - a.viewCount),- byVideos: [...accounts].sort((a, b) => b.videoCount - a.videoCount),+ bySubscribers: [...accounts].sort((first, second) => second.subscriberCount - first.subscriberCount),+ byViews: [...accounts].sort((first, second) => second.viewCount - first.viewCount),+ byVideos: [...accounts].sort((first, second) => second.videoCount - first.videoCount),};const totals = accounts.reduce((acc, account) => ({@@ -64,11 +64,11 @@ export function filterAndSortVideos(videos, { search, minViews, maxViews, sort,const sortField = sort || 'viewCount';const sortOrder = order === 'asc' ? 1 : -1;- result.sort((a, b) => {- const aVal = a[sortField] ?? 0;- const bVal = b[sortField] ?? 0;- if (typeof aVal === 'string') return sortOrder * aVal.localeCompare(bVal);- return sortOrder * (bVal - aVal);+ result.sort((first, second) => {+ const firstValue = first[sortField] ?? 0;+ const secondValue = second[sortField] ?? 0;+ if (typeof firstValue === 'string') return sortOrder * firstValue.localeCompare(secondValue);+ return sortOrder * (secondValue - firstValue);});return result;}diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.mdindex b74a78b..9d029d7 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 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.+The `createOAuthState()` and `verifyOAuthState()` functions live in `lib/oauthState.js`; `services/instagramOAuth.js` and `routes/instagramAuth.js` import them from there directly, and `cache.js` still re-exports them. 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/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.mdindex 6048d54..a64399d 100644--- a/docs/architecture/database/SECURITY.md+++ b/docs/architecture/database/SECURITY.md@@ -57,7 +57,10 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live**Protection mechanisms:**1. Stored only in the Supabase `accounts` table (server-side)2. Never returned in API responses - `safeAccount()` strips it-3. Only used by: `services/instagram.js` (for API calls) and `utils/scheduler.js` (for cron publishing)+3. Only used server-side, by these modules:+ - Graph API calls: `services/instagramApi.js`, `services/instagramMedia.js` and `services/instagramPublishing.js` (the token is passed in as `access_token`)+ - Obtaining and storing tokens: `services/instagramTokens.js` (long-lived exchange and refresh), `services/instagramOAuth.js` (OAuth code exchange), `services/accountConnect.js` and `services/accountFactory.js` (pasted tokens and new account rows)+ - Reading the stored token: `routes/publishing.js` and `utils/scheduler.js` (publishing), `routes/analytics.js` (Instagram analytics and media), `services/accountRefresh.js` (profile refresh) and `services/overviewSummary.js` (overview cache warm-up)4. The `GET /api/accounts` endpoint passes all accounts through `safeAccount()` before returning**If you add a new route that returns account data, you must call `safeAccount()`.** There is no automatic stripping - it is an explicit step in route handlers.