Skip to content

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: remove dead code found during the TypeScript migration

spacesdrive15c5e63b4cb6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bbddd42..653b8b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -82,6 +82,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Removed
+- Dead code found during the TypeScript migration: the unused `backend/lib/crypto.ts`, the empty Reddit session refresh in the daily cron and the unread `REDDIT_ENCRYPTION_KEY` secret (delete it from the Worker if it is set), the `scheduled` post status checks (no post ever has it), and fallbacks for fields the API never sends
- The unused GitHub personal access token field and its guide in Settings (nothing used the token)
- Legacy root `public/` dashboard, unmounted `trackedPosts.js` route, unused Redis OAuth helpers, unused shadcn block templates and the unused Geist font package
- Duplicated helpers merged: platform badges and avatars, account paths, chart styling, filter tiers, pagination, Reddit post table, `safeAccount()`, Instagram publishing parameters
diff --git a/DECISIONS.md b/DECISIONS.md
index 95d4aea..ceaa087 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -316,7 +316,7 @@ Records every significant architectural decision, the alternatives considered, a
## ADR-014: Reddit password stored AES-256-GCM encrypted for automatic session refresh
**Date:** 2026-07-10
-**Status:** Accepted
+**Status:** Withdrawn (2026-10-14): Reddit accounts store a browser session cookie instead; the unused `lib/crypto.ts`, the no-op `autoRefreshRedditSessions()` cron call and `REDDIT_ENCRYPTION_KEY` were removed
**Decision:** When a user adds a Reddit account with a password, the password is encrypted using AES-256-GCM via the Web Crypto API (`crypto.subtle`) and stored in `accounts.data.encryptedPassword`. The key is `REDDIT_ENCRYPTION_KEY`, a 32-byte random value stored as a Worker secret (hex string). The daily cron (`0 0 * * *`) decrypts the password and re-logs in when the session cookie is older than 23 hours.
diff --git a/backend/lib/crypto.ts b/backend/lib/crypto.ts
deleted file mode 100644
index 68987d1..0000000
--- a/backend/lib/crypto.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-// web crypto, no npm dependency; 64 hex char key, output "<iv_hex>:<cipher_hex>"
-
-function hexToBuffer(hex: string): ArrayBuffer {
- const bytes = new Uint8Array(hex.length / 2);
- for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
- return bytes.buffer;
-}
-
-function bufferToHex(buf: ArrayBuffer): string {
- return [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');
-}
-
-async function importKey(keyHex: string): Promise<CryptoKey> {
- return crypto.subtle.importKey('raw', hexToBuffer(keyHex), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
-}
-
-export async function encryptPassword(plaintext: string, keyHex: string): Promise<string> {
- const key = await importKey(keyHex);
- const initVector = crypto.getRandomValues(new Uint8Array(12));
- const ciphertext = await crypto.subtle.encrypt(
- { name: 'AES-GCM', iv: initVector },
- key,
- new TextEncoder().encode(plaintext)
- );
- return `${bufferToHex(initVector.buffer)}:${bufferToHex(ciphertext)}`;
-}
-
-export async function decryptPassword(encrypted: string, keyHex: string): Promise<string> {
- const [ivHex, cipherHex] = encrypted.split(':');
- const key = await importKey(keyHex);
- const plaintext = await crypto.subtle.decrypt(
- { name: 'AES-GCM', iv: hexToBuffer(ivHex) },
- key,
- hexToBuffer(cipherHex)
- );
- return new TextDecoder().decode(plaintext);
-}
-
-// totp (rfc 6238) takes the raw base32 secret from the authenticator app qr code
-function base32Decode(base32: string): Uint8Array<ArrayBuffer> {
- const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
- const cleaned = base32.toUpperCase().replace(/[^A-Z2-7]/g, '');
- let bits = 0, value = 0;
- const output: number[] = [];
- for (const char of cleaned) {
- const idx = alphabet.indexOf(char);
- if (idx === -1) continue;
- value = (value << 5) | idx;
- bits += 5;
- if (bits >= 8) {
- output.push((value >>> (bits - 8)) & 0xff);
- bits -= 8;
- }
- }
- return new Uint8Array(output);
-}
-
-export async function generateTOTP(base32Secret: string): Promise<string> {
- const secret = base32Decode(base32Secret);
- const counter = Math.floor(Date.now() / 30000);
- const counterBuf = new ArrayBuffer(8);
- const view = new DataView(counterBuf);
- view.setUint32(0, Math.floor(counter / 0x100000000) >>> 0, false);
- view.setUint32(4, counter >>> 0, false);
-
- const key = await crypto.subtle.importKey(
- 'raw', secret.buffer, { name: 'HMAC', hash: 'SHA-1' }, false, ['sign']
- );
- const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, counterBuf));
- const offset = sig[19] & 0xf;
- const code = (
- ((sig[offset] & 0x7f) << 24) |
- ((sig[offset + 1] & 0xff) << 16) |
- ((sig[offset + 2] & 0xff) << 8) |
- (sig[offset + 3] & 0xff)
- ) % 1_000_000;
- return String(code).padStart(6, '0');
-}
diff --git a/backend/routes/analytics.ts b/backend/routes/analytics.ts
index 43d81e5..c2961d4 100644
--- a/backend/routes/analytics.ts
+++ b/backend/routes/analytics.ts
@@ -22,9 +22,6 @@ interface SnapshotScope {
id: string;
}
-// no stored account has a channelTitle field, so that fallback is always undefined
-type LegacyChannelAccount = Account & { channelTitle?: string };
-
const NO_PLAYLIST_MESSAGE = 'No uploads playlist stored - delete this channel and add it again';
const app = new Hono<AppEnv>();
@@ -192,13 +189,13 @@ app.get('/videos/all', async (c) => {
const accounts = await getAccounts(supabase, userId);
const allVideos: YouTubeLibraryVideo[] = [];
- for (const account of accounts as LegacyChannelAccount[]) {
+ 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(video => ({
...video,
- channelTitle: (account.title || account.channelTitle) as string,
+ channelTitle: account.title || video.channelTitle,
channelId: account.id,
channelThumbnail: account.thumbnails?.default || '',
})));
diff --git a/backend/routes/overview.ts b/backend/routes/overview.ts
index 6aa801d..c2749fe 100644
--- a/backend/routes/overview.ts
+++ b/backend/routes/overview.ts
@@ -9,12 +9,7 @@ const router = new Hono<AppEnv>();
// the client re-polls while syncing, so warming never blocks the response
function runInBackground(c: AppContext, tasks: Promise<void>[]): void {
if (tasks.length === 0) return;
- const ctx = c.executionCtx;
- if (ctx?.waitUntil) {
- ctx.waitUntil(Promise.allSettled(tasks));
- return;
- }
- Promise.allSettled(tasks).catch(() => {});
+ c.executionCtx.waitUntil(Promise.allSettled(tasks));
}
router.get('/overview', async (c) => {
diff --git a/backend/routes/scheduledPosts.ts b/backend/routes/scheduledPosts.ts
index 5c7f278..074957e 100644
--- a/backend/routes/scheduledPosts.ts
+++ b/backend/routes/scheduledPosts.ts
@@ -75,8 +75,7 @@ app.put('/scheduled-posts/:id', async (c) => {
const id = c.req.param('id');
const post = await getPostById(supabase, id, userId);
if (!post) return c.json({ success: false, message: 'Scheduled post not found' }, 404);
- // 'scheduled' is not a PostStatus; nothing writes it, so only pending posts pass
- if (post.status !== 'pending' && (post.status as string) !== 'scheduled') {
+ if (post.status !== 'pending') {
return c.json({ success: false, message: 'Can only edit pending posts' }, 400);
}
diff --git a/backend/server.ts b/backend/server.ts
index 85cb510..69853ee 100644
--- a/backend/server.ts
+++ b/backend/server.ts
@@ -17,7 +17,6 @@ import overviewRouter from './routes/overview.ts';
import { urlHandler, callbackHandler } from './routes/instagramAuth.ts';
import { processScheduledPosts } from './utils/scheduler.ts';
import { autoRefreshInstagramTokens } from './services/instagram.ts';
-import { autoRefreshRedditSessions } from './services/reddit.ts';
import type { AppEnv } from './types/app.ts';
import type { Env } from './types/env.ts';
@@ -79,7 +78,6 @@ export default {
ctx.waitUntil(processScheduledPosts(supabase));
} else if (event.cron === '0 0 * * *') {
ctx.waitUntil(autoRefreshInstagramTokens(supabase));
- ctx.waitUntil(autoRefreshRedditSessions());
}
},
} satisfies ExportedHandler<Env>;
diff --git a/backend/services/reddit.ts b/backend/services/reddit.ts
index b16653d..284635b 100644
--- a/backend/services/reddit.ts
+++ b/backend/services/reddit.ts
@@ -149,9 +149,6 @@ export async function fetchRedditPosts(username: string, cookie: RedditCookie, l
return allPosts.slice(0, limit).map(normalizeRedditPost);
}
-// no-op kept because the server.ts cron handler still calls it
-export async function autoRefreshRedditSessions(): Promise<void> {}
-
function parseRedditPostUrl(rawUrl: string): string {
let parsedUrl: URL;
try {
diff --git a/backend/services/youtubeFormat.ts b/backend/services/youtubeFormat.ts
index 04f70e2..2a0cb75 100644
--- a/backend/services/youtubeFormat.ts
+++ b/backend/services/youtubeFormat.ts
@@ -23,10 +23,7 @@ export function formatDuration(totalSeconds: number): string {
return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m ${seconds}s`;
}
-export function formatVideoSummary(video: VideoSummarySource): YouTubeVideoSummary;
-export function formatVideoSummary(video: VideoSummarySource | undefined): YouTubeVideoSummary | null;
-export function formatVideoSummary(video: VideoSummarySource | undefined): YouTubeVideoSummary | null {
- if (!video) return null;
+export function formatVideoSummary(video: VideoSummarySource): YouTubeVideoSummary {
return {
videoId: video.videoId, title: video.title, viewCount: video.viewCount,
likeCount: video.likeCount, commentCount: video.commentCount,
diff --git a/backend/tests/fixtures/reddit.errors.golden.json b/backend/tests/fixtures/reddit.errors.golden.json
index 543e5aa..0040626 100644
--- a/backend/tests/fixtures/reddit.errors.golden.json
+++ b/backend/tests/fixtures/reddit.errors.golden.json
@@ -16,8 +16,5 @@
},
{
"error": "Reddit API error"
- },
- {
- "value": "[undefined]"
}
]
diff --git a/backend/tests/services/reddit.test.ts b/backend/tests/services/reddit.test.ts
index 3e984f9..42ba0f6 100644
--- a/backend/tests/services/reddit.test.ts
+++ b/backend/tests/services/reddit.test.ts
@@ -1,5 +1,5 @@
import { test, describe, before, after, afterEach, mock } from 'node:test';
-import { fetchRedditProfile, fetchRedditPosts, fetchTrackedPostData, autoRefreshRedditSessions } from '../../services/reddit.ts';
+import { fetchRedditProfile, fetchRedditPosts, fetchTrackedPostData } from '../../services/reddit.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
import type { FetchMock } from '../fixtures/fakeFetch.ts';
@@ -81,7 +81,6 @@ describe('reddit api golden output', () => {
fetchMock = installFetch((_request, count) => script[count - 1]);
const outcomes = [];
for (let i = 0; i < script.length; i++) outcomes.push(await outcomeOf(fetchRedditProfile('ribbon', 'COOKIE')));
- outcomes.push(await outcomeOf(autoRefreshRedditSessions()));
assertGolden(outcomes, 'reddit.errors');
});
});
diff --git a/backend/types/env.ts b/backend/types/env.ts
index b50f728..80e18eb 100644
--- a/backend/types/env.ts
+++ b/backend/types/env.ts
@@ -12,5 +12,4 @@ export interface Env {
FRONTEND_URL?: string;
UPSTASH_REDIS_REST_URL?: string;
UPSTASH_REDIS_REST_TOKEN?: string;
- REDDIT_ENCRYPTION_KEY?: string;
}
diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.md
index 245364b..3ba978b 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -30,11 +30,9 @@ Both cron triggers invoke the `scheduled` export from `backend/server.ts`.
**Concurrency safety:** The `'publishing'` status acts as a mutex. If the Worker cron and GitHub Actions cron overlap, the second one to claim a post will find it already in `'publishing'` state and skip it (it won't appear in the `status=pending` query).
-### `0 0 * * *` - Instagram Token Auto-Refresh and Reddit Session Hook
+### `0 0 * * *` - Instagram Token Auto-Refresh
-Two functions run in parallel via `ctx.waitUntil()`:
-
-**1. `autoRefreshInstagramTokens(supabase)` in `backend/services/instagram.ts`**
+**`autoRefreshInstagramTokens(supabase)` in `backend/services/instagram.ts`**
**What it does:**
1. Queries all accounts with `platform = 'instagram'`
@@ -48,9 +46,7 @@ Two functions run in parallel via `ctx.waitUntil()`:
- The daily cron refreshes any token expiring within 15 days
- This gives a 15-day window for recovery if the cron fails for a few days
-**2. `autoRefreshRedditSessions()` in `backend/services/reddit.ts`**
-
-This function is currently a no-op: it takes no arguments and returns immediately. Reddit accounts are added with a `reddit_session` cookie copied from the browser (`POST /api/accounts/reddit` with `{ username, cookie }`), and nothing logs in to Reddit or refreshes that cookie on a schedule. When the cookie expires, the user re-adds the account. `REDDIT_ENCRYPTION_KEY` is declared in `Env` but read nowhere.
+Reddit sessions are not refreshed on a schedule. Reddit accounts are added with a `reddit_session` cookie copied from the browser (`POST /api/accounts/reddit` with `{ username, cookie }`); when the cookie expires, the user re-adds the account.
## The `ctx.waitUntil()` Pattern
diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.md
index 193b176..2d5377e 100644
--- a/docs/architecture/cloudflare/WORKERS.md
+++ b/docs/architecture/cloudflare/WORKERS.md
@@ -51,7 +51,6 @@ All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. T
| `FRONTEND_URL` | Yes | Frontend URL (for post-OAuth redirect back to the SPA) |
| `UPSTASH_REDIS_REST_URL` | Optional | Upstash Redis endpoint; caching disabled if absent |
| `UPSTASH_REDIS_REST_TOKEN` | Optional | Upstash auth token |
-| `REDDIT_ENCRYPTION_KEY` | Unused | Declared in `Env` but read nowhere; Reddit accounts store a browser session cookie and no password is encrypted. Do not set it |
### Setting secrets
diff --git a/docs/features/NEW_SCHEDULED_TASK.md b/docs/features/NEW_SCHEDULED_TASK.md
index a60f715..d60ebc9 100644
--- a/docs/features/NEW_SCHEDULED_TASK.md
+++ b/docs/features/NEW_SCHEDULED_TASK.md
@@ -47,7 +47,7 @@ A cron job must never throw for one bad account: catch per account and log, as a
[triggers]
crons = [
"*/15 * * * *", # existing: processScheduledPosts
- "0 0 * * *", # existing: autoRefreshInstagramTokens, autoRefreshRedditSessions
+ "0 0 * * *", # existing: autoRefreshInstagramTokens
"30 3 * * *" # new: autoRefreshMyPlatformTokens (runs at 3:30 AM UTC daily)
]
```
@@ -68,7 +68,6 @@ export default {
ctx.waitUntil(processScheduledPosts(supabase));
} else if (event.cron === '0 0 * * *') {
ctx.waitUntil(autoRefreshInstagramTokens(supabase));
- ctx.waitUntil(autoRefreshRedditSessions());
} else if (event.cron === '30 3 * * *') {
ctx.waitUntil(autoRefreshMyPlatformTokens(supabase));
}
diff --git a/frontend/src/features/analytics/overview/useOverviewData.ts b/frontend/src/features/analytics/overview/useOverviewData.ts
index bd21427..2acc234 100644
--- a/frontend/src/features/analytics/overview/useOverviewData.ts
+++ b/frontend/src/features/analytics/overview/useOverviewData.ts
@@ -7,9 +7,7 @@ const SYNC_POLL_DELAYS = [4000, 8000, 16000];
async function fetchOverview(): Promise<OverviewResponse | null> {
try {
- const data = await api.getOverview();
- // OverviewResponse has no error field; request() already throws on the route's error body
- return data && !(data as OverviewResponse & { error?: string }).error ? data : null;
+ return await api.getOverview();
} catch {
// a failed load keeps the previous overview; the next poll or visit tries again
return null;
diff --git a/frontend/src/features/analytics/videos/videoLibrary.ts b/frontend/src/features/analytics/videos/videoLibrary.ts
index 26ba6b2..b757810 100644
--- a/frontend/src/features/analytics/videos/videoLibrary.ts
+++ b/frontend/src/features/analytics/videos/videoLibrary.ts
@@ -2,22 +2,14 @@ import { VIEW_TIERS, filterByTier, matchesText, engagementPercent, parseIsoDurat
import { fmtNum } from '../../../utils/formatters.ts';
import type { YouTubeVideo } from '../../../../../shared/types/youtube.ts';
-// a video as GET /api/accounts/:id/videos sends it; thumbnail and durationSeconds are fallbacks the route never sets
-export interface ChannelVideo extends YouTubeVideo {
- thumbnail?: string;
- durationSeconds?: number;
-}
-
-// the fields mergeChannelVideos reads from each fulfilled videos request
+// the fields mergeChannelVideos reads from each fulfilled GET /api/accounts/:id/videos
export interface ChannelVideosResult {
- videos?: ChannelVideo[];
- data?: { videos?: ChannelVideo[] };
+ videos: YouTubeVideo[];
}
export interface VideoChannelAccount {
id: string;
title?: string | null;
- channelTitle?: string;
}
export interface LibraryChannel<A extends VideoChannelAccount = VideoChannelAccount> {
@@ -58,16 +50,16 @@ export function mergeChannelVideos<A extends VideoChannelAccount>(channelAccount
if (result.status !== 'fulfilled') return;
const acct = channelAccounts[i];
const res = result.value;
- const channelTitle = acct.title || acct.channelTitle || 'Unknown channel';
+ const channelTitle = acct.title || 'Unknown channel';
channels.push({ id: acct.id, title: channelTitle, account: acct });
- for (const video of res.videos || res.data?.videos || []) {
+ for (const video of res.videos) {
videos.push({
...video,
- thumbnail: video.thumbnail || video.thumbnails?.medium || video.thumbnails?.high || video.thumbnails?.default || '',
+ thumbnail: video.thumbnails?.medium || video.thumbnails?.high || video.thumbnails?.default || '',
channelTitle,
channelId: acct.id,
engagementRate: engagementPercent(video.viewCount, video.likeCount, video.commentCount),
- durationSeconds: video.durationSeconds || parseIsoDuration(video.duration),
+ durationSeconds: parseIsoDuration(video.duration),
});
}
});
diff --git a/frontend/src/features/publishing/ScheduledPostRow.tsx b/frontend/src/features/publishing/ScheduledPostRow.tsx
index 54e1b6a..0739dcb 100644
--- a/frontend/src/features/publishing/ScheduledPostRow.tsx
+++ b/frontend/src/features/publishing/ScheduledPostRow.tsx
@@ -28,8 +28,7 @@ interface ScheduledPostRowProps {
}
function PostActions({ post, isEditing, editor, onDelete }: PostActionsProps) {
- // mirrors the backend edit check, which also accepts a 'scheduled' status
- const canEdit = post.status === 'pending' || (post.status as string) === 'scheduled';
+ const canEdit = post.status === 'pending';
const deleteLabel = post.status === 'published' ? 'Remove record' : 'Delete scheduled post';
return (
<TableCell className="text-right whitespace-nowrap">
diff --git a/frontend/tests/features/analytics/videos/videoLibrary.test.ts b/frontend/tests/features/analytics/videos/videoLibrary.test.ts
index 3805ece..5e1b4c2 100644
--- a/frontend/tests/features/analytics/videos/videoLibrary.test.ts
+++ b/frontend/tests/features/analytics/videos/videoLibrary.test.ts
@@ -53,11 +53,11 @@ test('description and watch links', () => {
});
test('channel videos merge with their channel and skip failed channels', () => {
- const channelAccounts: VideoChannelAccount[] = [{ id: 'c1', title: 'Alpha' }, { id: 'c2', channelTitle: 'Beta' }, { id: 'c3' }];
+ const channelAccounts: VideoChannelAccount[] = [{ id: 'c1', title: 'Alpha' }, { id: 'c2', title: 'Beta' }, { id: 'c3' }];
const results = [
{ status: 'fulfilled', value: { videos: [{ videoId: 'a', viewCount: 200, likeCount: 10, commentCount: 0, duration: 'PT1M5S', thumbnails: { high: 'h.jpg' } }] } },
{ status: 'rejected', reason: new Error('quota') },
- { status: 'fulfilled', value: { data: { videos: [{ videoId: 'b', thumbnail: 't.jpg', durationSeconds: 30 }] } } },
+ { status: 'fulfilled', value: { videos: [{ videoId: 'b', duration: 'PT30S', thumbnails: { default: 't.jpg' } }] } },
] as PromiseSettledResult<ChannelVideosResult>[];
const merged = mergeChannelVideos(channelAccounts, results);
assert.deepEqual(merged.channels.map(channel => [channel.id, channel.title]), [['c1', 'Alpha'], ['c3', 'Unknown channel']]);