Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(reddit): add automatic session refresh with encrypted password storage
spacesdrive562948b32112
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 45fa079..2dc7a6d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,16 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Added+**Reddit Automatic Session Refresh**+- `backend/lib/crypto.js` - AES-256-GCM encrypt/decrypt using `crypto.subtle` (Web Crypto API, no npm dependency)+- `POST /api/accounts/reddit` now accepts `password` instead of `cookie`; logs in to Reddit automatically, encrypts the password with `REDDIT_ENCRYPTION_KEY`, and stores `cookie`, `cookieAcquiredAt`, `cookieExpiresAt` in `accounts.data`+- `loginToReddit(username, password)` in `backend/services/reddit.js` - authenticates via `ssl.reddit.com/api/login` and returns `{ cookie, cookieAcquiredAt, cookieExpiresAt }`+- `autoRefreshRedditSessions(supabase, encryptionKey)` in `backend/services/reddit.js` - cron handler that re-logs in any Reddit account whose cookie is older than 23 hours; runs on the `0 0 * * *` trigger alongside Instagram token refresh+- `ensureFreshCookie()` in `backend/routes/reddit.js` - per-request freshness check before analytics/posts fetch; auto-re-logins if cookie is stale and credentials are stored+- `safeAccount()` and `safeRedditAccount()` now also strip `encryptedPassword` from all API responses+- Account Manager Reddit tab changed from manual cookie paste to username + password; shows session status badge on each Reddit account card (active / expired / public)+- New Worker secret: `REDDIT_ENCRYPTION_KEY` (optional; Reddit auto-refresh disabled if absent)+**Reddit Integration**- `POST /api/accounts/reddit` - add Reddit account by username with optional session cookie- `GET /api/accounts/:id/reddit-analytics` - full analytics: profile, score stats, subreddit breakdown, posting time patterns, monthly breakdown, virality and consistency scoresdiff --git a/DECISIONS.md b/DECISIONS.mdindex 472f401..03703b0 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -310,3 +310,27 @@ Records every significant architectural decision, the alternatives considered, a- `reddit_session` cookies expire when the user's Reddit session ends - the user must re-enter the cookie if it expires- Reddit's public API has stricter rate limits (60 req/10min without auth) than the OAuth API (600 req/10min)- No token refresh cron - unlike Instagram, Reddit session cookies cannot be programmatically refreshed++---++## ADR-014: Reddit password stored AES-256-GCM encrypted for automatic session refresh++**Date:** 2026-07-10+**Status:** Accepted++**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.++**Alternatives considered:**+- Plaintext password storage: simpler but violates the principle that credentials at rest must not be recoverable without a key+- OAuth 2.0 (script app): requires app registration, client credentials as Worker secrets, token grant flow - higher complexity with no benefit for a self-hosted single-operator deployment++**Reasoning:**+- `crypto.subtle` AES-GCM is available natively in Cloudflare Workers - no npm dependency needed+- The encryption key (`REDDIT_ENCRYPTION_KEY`) never leaves the Worker environment; it is never stored in Supabase or returned by any API endpoint+- AES-GCM is authenticated encryption - tampering with the ciphertext is detectable+- Keeps the auto-refresh architecture consistent with Instagram's token refresh pattern++**Trade-offs:**+- If `REDDIT_ENCRYPTION_KEY` is lost, all stored Reddit passwords are unrecoverable - users would need to re-add their accounts with a new password+- A compromised Worker environment (leaked `REDDIT_ENCRYPTION_KEY` + DB access) allows decryption of all stored passwords+- Reddit's unofficial login API (`ssl.reddit.com/api/login`) is not a documented endpoint and could change without noticediff --git a/backend/lib/crypto.js b/backend/lib/crypto.jsnew file mode 100644index 0000000..f7cf777--- /dev/null+++ b/backend/lib/crypto.js@@ -0,0 +1,38 @@+// AES-256-GCM encryption using the Web Crypto API (built into Cloudflare Workers).+// Key is a 64-char hex string (32 bytes). Ciphertext format: "<iv_hex>:<ciphertext_hex>"++function hexToBuffer(hex) {+ 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) {+ return [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');+}++async function importKey(keyHex) {+ return crypto.subtle.importKey('raw', hexToBuffer(keyHex), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);+}++export async function encryptPassword(plaintext, keyHex) {+ const key = await importKey(keyHex);+ const iv = crypto.getRandomValues(new Uint8Array(12));+ const ciphertext = await crypto.subtle.encrypt(+ { name: 'AES-GCM', iv },+ key,+ new TextEncoder().encode(plaintext)+ );+ return `${bufferToHex(iv.buffer)}:${bufferToHex(ciphertext)}`;+}++export async function decryptPassword(encrypted, keyHex) {+ 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);+}diff --git a/backend/routes/accounts.js b/backend/routes/accounts.jsindex 5664e6d..263f3be 100644--- a/backend/routes/accounts.js+++ b/backend/routes/accounts.js@@ -3,9 +3,10 @@ import {getAccounts, getAccountById, createAccount, updateAccount, deleteAccount,} from '../lib/db.js';import { deleteVideosCache, deleteIGCache, deleteRedditCache } from '../lib/cache.js';+import { encryptPassword } from '../lib/crypto.js';import { fetchInstagramProfile, exchangeForLongLivedToken, refreshLongLivedToken } from '../services/instagram.js';import { resolveChannelId, fetchChannelData } from '../services/youtube.js';-import { fetchRedditProfile, safeRedditAccount } from '../services/reddit.js';+import { fetchRedditProfile, loginToReddit, safeRedditAccount } from '../services/reddit.js';const app = new Hono();@@ -13,6 +14,7 @@ function safeAccount(account) {const copy = { ...account };delete copy.accessToken;delete copy.cookie;+ delete copy.encryptedPassword;return copy;}@@ -86,13 +88,27 @@ app.post('/accounts', async (c) => {app.post('/accounts/reddit', async (c) => {try {- const { username, cookie } = await c.req.json();+ const { username, password } = await c.req.json();if (!username) return c.json({ success: false, message: 'Username is required' }, 400);const supabase = c.get('supabase');const userId = c.get('userId');+ const cleanUsername = username.replace(/^u\//i, '').trim();- const profile = await fetchRedditProfile(username.replace(/^u\//i, '').trim(), cookie || null);+ let cookieData = {};+ let encryptedPassword = null;++ if (password) {+ const encKey = c.env.REDDIT_ENCRYPTION_KEY;+ if (!encKey) {+ return c.json({ success: false, message: 'REDDIT_ENCRYPTION_KEY is not configured on the server - run: wrangler secret put REDDIT_ENCRYPTION_KEY' }, 500);+ }+ const loginResult = await loginToReddit(cleanUsername, password);+ cookieData = loginResult;+ encryptedPassword = await encryptPassword(password, encKey);+ }++ const profile = await fetchRedditProfile(cleanUsername, cookieData.cookie ?? null);const accounts = await getAccounts(supabase, userId);if (accounts.find(a => a.platform === 'reddit' && a.username === profile.username)) {@@ -109,7 +125,8 @@ app.post('/accounts/reddit', async (c) => {commentKarma: profile.commentKarma,iconUrl: profile.iconUrl,createdAt: profile.createdAt,- cookie: cookie || null,+ encryptedPassword,+ ...cookieData,addedAt: new Date().toISOString(),lastUpdated: new Date().toISOString(),};diff --git a/backend/routes/reddit.js b/backend/routes/reddit.jsindex 9ea0cde..8213736 100644--- a/backend/routes/reddit.js+++ b/backend/routes/reddit.js@@ -1,10 +1,35 @@import { Hono } from 'hono';-import { getAccountById } from '../lib/db.js';+import { getAccountById, updateAccount } from '../lib/db.js';import { getRedditCache, setRedditCache } from '../lib/cache.js';-import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from '../services/reddit.js';+import { decryptPassword } from '../lib/crypto.js';+import {+ fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics, loginToReddit,+} from '../services/reddit.js';const router = new Hono();+// Re-login if the stored session cookie is older than 23 hours.+// Falls back silently to the existing cookie on any error.+const COOKIE_MAX_AGE_MS = 23 * 60 * 60 * 1000;++async function ensureFreshCookie(account, supabase, userId, encryptionKey) {+ if (!account.encryptedPassword || !account.cookieAcquiredAt || !encryptionKey) {+ return account.cookie ?? null;+ }+ const age = Date.now() - new Date(account.cookieAcquiredAt).getTime();+ if (age < COOKIE_MAX_AGE_MS) return account.cookie ?? null;++ try {+ const password = await decryptPassword(account.encryptedPassword, encryptionKey);+ const { cookie, cookieAcquiredAt, cookieExpiresAt } = await loginToReddit(account.username, password);+ await updateAccount(supabase, account.id, { cookie, cookieAcquiredAt, cookieExpiresAt, lastUpdated: new Date().toISOString() }, userId);+ return cookie;+ } catch (err) {+ console.error(`Reddit cookie refresh failed for u/${account.username}:`, err.message);+ return account.cookie ?? null;+ }+}+// Full analytics: profile + computed stats + recent postsrouter.get('/accounts/:id/reddit-analytics', async (c) => {const id = c.req.param('id');@@ -18,9 +43,10 @@ router.get('/accounts/:id/reddit-analytics', async (c) => {const cached = await getRedditCache(redis, userId, id);if (cached) return c.json(cached);+ const cookie = await ensureFreshCookie(account, supabase, userId, c.env.REDDIT_ENCRYPTION_KEY);const [profile, posts] = await Promise.all([- fetchRedditProfile(account.username, account.cookie ?? null),- fetchRedditPosts(account.username, account.cookie ?? null, 100),+ fetchRedditProfile(account.username, cookie),+ fetchRedditPosts(account.username, cookie, 100),]);const analytics = computeRedditAnalytics(profile, posts);const result = { profile, analytics, posts };@@ -46,7 +72,8 @@ router.get('/accounts/:id/reddit-posts', async (c) => {const cached = await getRedditCache(redis, userId, id);if (cached?.posts) return c.json(cached.posts);- const posts = await fetchRedditPosts(account.username, account.cookie ?? null, 100);+ const cookie = await ensureFreshCookie(account, supabase, userId, c.env.REDDIT_ENCRYPTION_KEY);+ const posts = await fetchRedditPosts(account.username, cookie, 100);return c.json(posts);} catch (err) {console.error(`GET /accounts/${id}/reddit-posts:`, err.message);diff --git a/backend/server.js b/backend/server.jsindex b181dd3..bce511e 100644--- a/backend/server.js+++ b/backend/server.js@@ -13,6 +13,7 @@ import redditRouter from './routes/reddit.js';import { urlHandler, callbackHandler } from './routes/instagramAuth.js';import { processScheduledPosts } from './utils/scheduler.js';import { autoRefreshInstagramTokens } from './services/instagram.js';+import { autoRefreshRedditSessions } from './services/reddit.js';const app = new Hono();@@ -75,6 +76,7 @@ export default {ctx.waitUntil(processScheduledPosts(supabase));} else if (event.cron === '0 0 * * *') {ctx.waitUntil(autoRefreshInstagramTokens(supabase));+ ctx.waitUntil(autoRefreshRedditSessions(supabase, env.REDDIT_ENCRYPTION_KEY));}},};diff --git a/backend/services/reddit.js b/backend/services/reddit.jsindex 002c2a7..d53244d 100644--- a/backend/services/reddit.js+++ b/backend/services/reddit.js@@ -1,4 +1,6 @@// fetch is a global in Cloudflare Workers - no import needed.+import { decryptPassword } from '../lib/crypto.js';+import { getAccounts, updateAccount } from '../lib/db.js';const REDDIT_BASE = 'https://www.reddit.com';const USER_AGENT = 'Twiligent/1.0 (social analytics dashboard; personal use)';@@ -244,5 +246,75 @@ export function computeRedditAnalytics(profile, posts) {export function safeRedditAccount(account) {const copy = { ...account };delete copy.cookie;+ delete copy.encryptedPassword;return copy;}++// Log in to Reddit using the old JSON API (returns session cookie in body, no redirect needed).+export async function loginToReddit(username, password) {+ const body = new URLSearchParams({ user: username, passwd: password, api_type: 'json' });+ const res = await fetch('https://ssl.reddit.com/api/login', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ 'User-Agent': USER_AGENT,+ },+ body: body.toString(),+ });++ if (res.status === 429) throw new Error('Reddit rate limit - try again in a few minutes');+ if (!res.ok) throw new Error(`Reddit login request failed with status ${res.status}`);++ const data = await res.json();+ const errors = data?.json?.errors ?? [];+ if (errors.length > 0) {+ const [[code, message]] = errors;+ if (code === 'WRONG_PASSWORD') throw new Error('Incorrect Reddit password');+ if (code === 'RATELIMIT') throw new Error('Too many login attempts - wait a few minutes and try again');+ if (code === 'BAD_CAPTCHA') throw new Error('CAPTCHA required - try again in a few minutes');+ throw new Error(message || 'Reddit login failed');+ }++ const cookieValue = data?.json?.data?.cookie;+ if (!cookieValue) throw new Error('Login succeeded but Reddit returned no session cookie');++ return {+ cookie: cookieValue,+ cookieAcquiredAt: new Date().toISOString(),+ // Reddit session cookies from this API last approximately 24 hours+ cookieExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),+ };+}++// Cron handler: refresh Reddit session cookies for accounts with stored credentials+// whose cookie is approaching expiry (older than 23 hours).+export async function autoRefreshRedditSessions(supabase, encryptionKey) {+ if (!encryptionKey) return;++ let accounts;+ try {+ accounts = await getAccounts(supabase);+ } catch (err) {+ console.error('autoRefreshRedditSessions: failed to query accounts:', err.message);+ return;+ }++ const threshold = 23 * 60 * 60 * 1000;+ const stale = accounts.filter(a =>+ a.platform === 'reddit' &&+ a.encryptedPassword &&+ a.cookieAcquiredAt &&+ (Date.now() - new Date(a.cookieAcquiredAt).getTime()) > threshold+ );++ for (const account of stale) {+ try {+ const password = await decryptPassword(account.encryptedPassword, encryptionKey);+ const { cookie, cookieAcquiredAt, cookieExpiresAt } = await loginToReddit(account.username, password);+ await updateAccount(supabase, account.id, { cookie, cookieAcquiredAt, cookieExpiresAt, lastUpdated: new Date().toISOString() });+ console.log(`Refreshed Reddit session for u/${account.username}`);+ } catch (err) {+ console.error(`Failed to refresh Reddit session for u/${account.username}:`, err.message);+ }+ }+}diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.mdindex 1e79777..f8408b7 100644--- a/docs/architecture/backend/CRON.md+++ b/docs/architecture/backend/CRON.md@@ -28,9 +28,11 @@ Both cron triggers invoke the `scheduled` export from `backend/server.js`.**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+### `0 0 * * *` - Instagram Token Auto-Refresh + Reddit Session Refresh-**Function:** `autoRefreshInstagramTokens(supabase)` in `backend/services/instagram.js`+Two functions run in parallel via `ctx.waitUntil()`:++**1. `autoRefreshInstagramTokens(supabase)` in `backend/services/instagram.js`****What it does:**1. Queries all accounts with `platform = 'instagram'`@@ -44,6 +46,21 @@ Both cron triggers invoke the `scheduled` export from `backend/server.js`.- 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(supabase, encryptionKey)` in `backend/services/reddit.js`**++**What it does:**+1. Queries all accounts with `platform = 'reddit'` that have `encryptedPassword` set+2. For each, checks if `cookieAcquiredAt` is older than 23 hours+3. If stale: decrypts the stored password using `REDDIT_ENCRYPTION_KEY` and calls `loginToReddit(username, password)`+4. Updates `cookie`, `cookieAcquiredAt`, and `cookieExpiresAt` in Supabase+5. Logs success or error per account; never throws - failures are non-fatal++**Cookie lifecycle:**+- Reddit session cookies obtained via `ssl.reddit.com/api/login` last approximately 24 hours+- The daily cron refreshes cookies older than 23 hours+- If `REDDIT_ENCRYPTION_KEY` is not set, this function exits immediately (no-op)+- Accounts without a stored encrypted password (public-only access) are skipped+## The `ctx.waitUntil()` PatternCron handlers use `ctx.waitUntil()` to run work after the handler returns:diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.mdindex 44b7a51..86b6fd1 100644--- a/docs/architecture/cloudflare/WORKERS.md+++ b/docs/architecture/cloudflare/WORKERS.md@@ -49,6 +49,7 @@ All secrets are set via `wrangler secret put <NAME>`. They are available at runt| `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` | Optional | 64-char hex (32 bytes) AES-256-GCM key for encrypting Reddit passwords; Reddit auto-refresh disabled if absent |### Setting secretsdiff --git a/frontend/src/features/accounts/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsxindex ca81de3..953a801 100644--- a/frontend/src/features/accounts/AccountManager.jsx+++ b/frontend/src/features/accounts/AccountManager.jsx@@ -11,6 +11,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import {Plus, Trash2, RefreshCw, Search, Users, CheckCircle2,Tv, Camera, Link2, Info, ExternalLink, MessageSquare,+ Lock, Unlock, Globe,} from 'lucide-react';import MainCard from '../../components/MainCard';import { useAppContext } from '../../context/AppContext';@@ -28,7 +29,7 @@ export default function AccountManager() {const [adding, setAdding] = useState(false);const [connecting, setConnecting] = useState(false);const [redditUsername, setRedditUsername] = useState('');- const [redditCookie, setRedditCookie] = useState('');+ const [redditPassword, setRedditPassword] = useState('');const [addingReddit, setAddingReddit] = useState(false);const [refreshingId, setRefreshingId] = useState(null);@@ -135,10 +136,8 @@ export default function AccountManager() {if (!redditUsername.trim()) return;setAddingReddit(true);try {- await api.addRedditAccount(redditUsername.trim(), redditCookie.trim() || null);+ await api.addRedditAccount(redditUsername.trim(), redditPassword.trim() || null);showToast('Reddit account added');- setRedditUsername('');- setRedditCookie('');closeDialog();loadAccounts();} catch (err) {@@ -153,7 +152,7 @@ export default function AccountManager() {setResolved(null);setInput('');setRedditUsername('');- setRedditCookie('');+ setRedditPassword('');};const ytAccounts = accounts.filter(a => a.platform !== 'instagram' && a.platform !== 'reddit');@@ -381,7 +380,7 @@ export default function AccountManager() {<TabsContent value="reddit" className="space-y-4 mt-4"><p className="text-sm text-muted-foreground">- Enter your Reddit username to track your public post analytics.+ Enter your Reddit username. Add your password to enable automatic session refresh.</p><div className="space-y-3"><div className="relative">@@ -396,20 +395,21 @@ export default function AccountManager() {</div><div className="space-y-1.5"><label className="text-xs font-medium text-muted-foreground">- Session Cookie (optional - for private accounts or higher rate limits)+ Password (optional - enables automatic session refresh)</label><Inputtype="password"- value={redditCookie}- onChange={e => setRedditCookie(e.target.value)}- placeholder="reddit_session cookie value"+ value={redditPassword}+ onChange={e => setRedditPassword(e.target.value)}+ placeholder="Reddit password"+ onKeyDown={e => e.key === 'Enter' && handleAddReddit()}/></div></div><Alert><Info className="h-4 w-4" /><AlertDescription className="text-xs">- Public accounts work without a cookie. To get your session cookie, open Reddit in a browser, open DevTools (F12), go to Application > Cookies, and copy the <code className="bg-muted px-1 rounded">reddit_session</code> value.+ Public accounts work without a password - analytics are fetched from Reddit's public API. Adding your password stores it encrypted on the server and enables automatic session refresh every 24 hours for private accounts or higher rate limits.</AlertDescription></Alert></TabsContent>@@ -471,6 +471,28 @@ function AccountCard({ acct, platform, metrics, refreshingId, onRefresh, onDelet))}</div>+ {isReddit && (+ <div className="flex items-center gap-1.5 text-xs">+ {acct.cookieExpiresAt ? (+ new Date(acct.cookieExpiresAt) > new Date() ? (+ <>+ <Lock className="h-3 w-3 text-green-500" />+ <span className="text-green-600">Session active - auto-refresh on</span>+ </>+ ) : (+ <>+ <Unlock className="h-3 w-3 text-red-500" />+ <span className="text-red-600">Session expired - refresh account</span>+ </>+ )+ ) : (+ <>+ <Globe className="h-3 w-3 text-muted-foreground" />+ <span className="text-muted-foreground">Public access only</span>+ </>+ )}+ </div>+ )}{acct.lastUpdated && (<p className="text-xs text-muted-foreground">Updated {timeAgo(acct.lastUpdated)}</p>)}diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 99199ae..a68d0c6 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -61,7 +61,7 @@ export const api = {publishIGContainer: (id, containerId) => request(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId }) }),// Reddit accounts- addRedditAccount: (username, cookie) => request('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, cookie }) }),+ addRedditAccount: (username, password) => request('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, password }) }),getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),getRedditPosts: (id) => request(`/accounts/${id}/reddit-posts`),