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(reddit): remove broken auto-login, use public API and manual cookie
spacesdrived430e9ba5570
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 028b6c7..312ad66 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,16 +9,15 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Added-**Reddit 2FA Support and Login Fix**-- `loginToReddit` now sends `Origin`, `Referer`, and a browser User-Agent to satisfy Reddit's login endpoint, resolving the 403 error from server IPs-- `generateTOTP(base32Secret)` added to `backend/lib/crypto.js` - RFC 6238 TOTP via `crypto.subtle` HMAC-SHA1, no npm dependency-- `POST /api/accounts/reddit` accepts optional `totpSecret` (Base32 setup key from authenticator app); stored AES-256-GCM encrypted as `encryptedTotpSecret`-- `loginToReddit(username, password, totpSecret)` generates the current 6-digit code and appends it as `password:123456` when a TOTP secret is stored-- `TWO_FA_REQUIRED` Reddit error code is now caught and returns a clear message directing the user to enter their TOTP secret-- `safeAccount()` and `safeRedditAccount()` strip `encryptedTotpSecret` and expose `hasTotpSecret: boolean` so the frontend shows 2FA status without revealing the secret-- `ensureFreshCookie` and `autoRefreshRedditSessions` decrypt and pass `totpSecret` to `loginToReddit` so 2FA accounts auto-refresh correctly-- AccountManager Reddit tab shows TOTP secret field when a password is entered-- AccountCard shows a 2FA badge when `hasTotpSecret` is true+**Reddit Login Fix - Remove Broken Auto-Login**+- Removed `loginToReddit` password-based auto-login; Reddit's `ssl.reddit.com/api/login` blocks all server/datacenter IPs and cannot be used from Cloudflare Workers+- `POST /api/accounts/reddit` now accepts `{ username, cookie }` - cookie is optional and manually provided by the user from browser DevTools for private accounts+- Public Reddit accounts work without any session cookie - all analytics data is fetched from Reddit's public JSON API which requires no authentication+- `autoRefreshRedditSessions` replaced with a no-op; session cookies must be refreshed manually by re-adding the account+- AccountManager Reddit tab updated: password and TOTP fields removed; replaced with optional session cookie field with clear browser DevTools instructions+- AccountCard badge shows "Session cookie stored" or "Public access" based on `hasCookie`+- `safeAccount` and `safeRedditAccount` now expose `hasCookie: boolean` instead of `hasTotpSecret`+- `generateTOTP` remains in `crypto.js` for potential future use**Reddit Automatic Session Refresh**- `backend/lib/crypto.js` - AES-256-GCM encrypt/decrypt using `crypto.subtle` (Web Crypto API, no npm dependency)diff --git a/backend/routes/accounts.js b/backend/routes/accounts.jsindex 442eea6..e720e2a 100644--- a/backend/routes/accounts.js+++ b/backend/routes/accounts.js@@ -3,16 +3,15 @@ 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, loginToReddit, safeRedditAccount } from '../services/reddit.js';+import { fetchRedditProfile, safeRedditAccount } from '../services/reddit.js';const app = new Hono();function safeAccount(account) {const copy = { ...account };- copy.hasTotpSecret = !!copy.encryptedTotpSecret;+ copy.hasCookie = !!copy.cookie;delete copy.accessToken;delete copy.cookie;delete copy.encryptedPassword;@@ -90,29 +89,14 @@ app.post('/accounts', async (c) => {app.post('/accounts/reddit', async (c) => {try {- const { username, password, totpSecret } = await c.req.json();+ const { username, cookie } = 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();- let cookieData = {};- let encryptedPassword = null;- let encryptedTotpSecret = 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, totpSecret || null);- cookieData = loginResult;- encryptedPassword = await encryptPassword(password, encKey);- if (totpSecret) encryptedTotpSecret = await encryptPassword(totpSecret, encKey);- }-- const profile = await fetchRedditProfile(cleanUsername, cookieData.cookie ?? null);+ const profile = await fetchRedditProfile(cleanUsername, cookie ?? null);const accounts = await getAccounts(supabase, userId);if (accounts.find(a => a.platform === 'reddit' && a.username === profile.username)) {@@ -129,9 +113,7 @@ app.post('/accounts/reddit', async (c) => {commentKarma: profile.commentKarma,iconUrl: profile.iconUrl,createdAt: profile.createdAt,- encryptedPassword,- encryptedTotpSecret,- ...cookieData,+ ...(cookie ? { cookie } : {}),addedAt: new Date().toISOString(),lastUpdated: new Date().toISOString(),};diff --git a/backend/routes/reddit.js b/backend/routes/reddit.jsindex df7ad6a..a2e4f75 100644--- a/backend/routes/reddit.js+++ b/backend/routes/reddit.js@@ -1,38 +1,10 @@import { Hono } from 'hono';-import { getAccountById, updateAccount } from '../lib/db.js';+import { getAccountById } from '../lib/db.js';import { getRedditCache, setRedditCache } from '../lib/cache.js';-import { decryptPassword } from '../lib/crypto.js';-import {- fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics, loginToReddit,-} from '../services/reddit.js';+import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } 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 totpSecret = account.encryptedTotpSecret- ? await decryptPassword(account.encryptedTotpSecret, encryptionKey)- : null;- const { cookie, cookieAcquiredAt, cookieExpiresAt } = await loginToReddit(account.username, password, totpSecret);- 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');@@ -46,7 +18,7 @@ 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 cookie = account.cookie ?? null;const [profile, posts] = await Promise.all([fetchRedditProfile(account.username, cookie),fetchRedditPosts(account.username, cookie, 100),@@ -75,7 +47,7 @@ router.get('/accounts/:id/reddit-posts', async (c) => {const cached = await getRedditCache(redis, userId, id);if (cached?.posts) return c.json(cached.posts);- const cookie = await ensureFreshCookie(account, supabase, userId, c.env.REDDIT_ENCRYPTION_KEY);+ const cookie = account.cookie ?? null;const posts = await fetchRedditPosts(account.username, cookie, 100);return c.json(posts);} catch (err) {diff --git a/backend/services/reddit.js b/backend/services/reddit.jsindex 98c37b5..2fdf592 100644--- a/backend/services/reddit.js+++ b/backend/services/reddit.js@@ -1,6 +1,6 @@// fetch is a global in Cloudflare Workers - no import needed.-import { decryptPassword, generateTOTP } from '../lib/crypto.js';-import { getAccounts, updateAccount } from '../lib/db.js';+// No crypto or DB imports needed - Reddit uses the public JSON API.+// Session cookies are stored as-is (not encrypted) and used directly in requests.const REDDIT_BASE = 'https://www.reddit.com';const USER_AGENT = 'Twiligent/1.0 (social analytics dashboard; personal use)';@@ -242,99 +242,18 @@ export function computeRedditAnalytics(profile, posts) {};}-// Strips sensitive fields before any API response. Exposes hasTotpSecret as a boolean so the-// frontend can show 2FA status without revealing the secret itself.+// Strips the session cookie before any API response - treat it like an access token.+// Exposes hasCookie as a boolean so the frontend can show session status without the value.export function safeRedditAccount(account) {const copy = { ...account };- copy.hasTotpSecret = !!copy.encryptedTotpSecret;+ copy.hasCookie = !!copy.cookie;delete copy.cookie;delete copy.encryptedPassword;delete copy.encryptedTotpSecret;return copy;}-// Browser-like User-Agent required for the login endpoint - Reddit blocks custom UAs on ssl.reddit.com.-const LOGIN_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';--// Log in to Reddit using the old JSON API (returns session cookie in body, no redirect needed).-// When the account has 2FA enabled, pass the Base32 TOTP secret as totpSecret and the current-// 6-digit code is appended to the password automatically: "password:123456"-export async function loginToReddit(username, password, totpSecret = null) {- let passwd = password;- if (totpSecret) {- const code = await generateTOTP(totpSecret);- passwd = `${password}:${code}`;- }-- const body = new URLSearchParams({ user: username, passwd, 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': LOGIN_USER_AGENT,- 'Origin': 'https://ssl.reddit.com',- 'Referer': 'https://www.reddit.com/',- },- 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 === 'TWO_FA_REQUIRED') throw new Error('This account has two-factor authentication enabled. Enter your TOTP secret when adding the account to enable automatic login.');- 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 totpSecret = account.encryptedTotpSecret- ? await decryptPassword(account.encryptedTotpSecret, encryptionKey)- : null;- const { cookie, cookieAcquiredAt, cookieExpiresAt } = await loginToReddit(account.username, password, totpSecret);- 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);- }- }-}+// No-op: Reddit auto-refresh via automated login is not supported from server IPs.+// Reddit's login endpoint (ssl.reddit.com/api/login) blocks datacenter IPs.+// Session cookies must be refreshed manually by the user via the Account Manager.+export async function autoRefreshRedditSessions() {}diff --git a/frontend/src/features/accounts/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsxindex b782113..3039886 100644--- a/frontend/src/features/accounts/AccountManager.jsx+++ b/frontend/src/features/accounts/AccountManager.jsx@@ -11,7 +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, ShieldCheck,+ Lock, Globe,} from 'lucide-react';import MainCard from '../../components/MainCard';import { useAppContext } from '../../context/AppContext';@@ -28,10 +28,9 @@ export default function AccountManager() {const [resolved, setResolved] = useState(null);const [adding, setAdding] = useState(false);const [connecting, setConnecting] = useState(false);- const [redditUsername, setRedditUsername] = useState('');- const [redditPassword, setRedditPassword] = useState('');- const [redditTotpSecret, setRedditTotpSecret] = useState('');- const [addingReddit, setAddingReddit] = useState(false);+ const [redditUsername, setRedditUsername] = useState('');+ const [redditCookie, setRedditCookie] = useState('');+ const [addingReddit, setAddingReddit] = useState(false);const [refreshingId, setRefreshingId] = useState(null);// Handle Instagram OAuth redirect result (?ig_connected=true or ?ig_error=...)@@ -137,11 +136,7 @@ export default function AccountManager() {if (!redditUsername.trim()) return;setAddingReddit(true);try {- await api.addRedditAccount(- redditUsername.trim(),- redditPassword.trim() || null,- redditTotpSecret.trim() || null,- );+ await api.addRedditAccount(redditUsername.trim(), redditCookie.trim() || null);showToast('Reddit account added');closeDialog();loadAccounts();@@ -157,8 +152,7 @@ export default function AccountManager() {setResolved(null);setInput('');setRedditUsername('');- setRedditPassword('');- setRedditTotpSecret('');+ setRedditCookie('');};const ytAccounts = accounts.filter(a => a.platform !== 'instagram' && a.platform !== 'reddit');@@ -386,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. Add your password to enable automatic session refresh.+ Enter your Reddit username. For public accounts no session cookie is needed.</p><div className="space-y-3"><div className="relative">@@ -401,38 +395,21 @@ export default function AccountManager() {</div><div className="space-y-1.5"><label className="text-xs font-medium text-muted-foreground">- Password (optional - enables automatic session refresh)+ Session cookie (optional - for private accounts only)</label><Inputtype="password"- value={redditPassword}- onChange={e => setRedditPassword(e.target.value)}- placeholder="Reddit password"+ value={redditCookie}+ onChange={e => setRedditCookie(e.target.value)}+ placeholder="reddit_session cookie value"onKeyDown={e => e.key === 'Enter' && handleAddReddit()}/></div>- {redditPassword && (- <div className="space-y-1.5">- <label className="text-xs font-medium text-muted-foreground">- TOTP secret (only if your account has two-factor authentication enabled)- </label>- <Input- type="password"- value={redditTotpSecret}- onChange={e => setRedditTotpSecret(e.target.value)}- placeholder="Base32 secret from your authenticator app"- onKeyDown={e => e.key === 'Enter' && handleAddReddit()}- />- <p className="text-xs text-muted-foreground">- This is the setup key shown when you first enabled 2FA, not the 6-digit code. It looks like JBSWY3DPEHPK3PXP. Leave blank if 2FA is off.- </p>- </div>- )}</div><Alert><Info className="h-4 w-4" /><AlertDescription className="text-xs">- Public accounts work without a password. Adding a password stores it encrypted and enables automatic session refresh every 24 hours. If your account uses two-factor authentication, also enter your TOTP secret so login codes are generated automatically.+ Public Reddit accounts work without a session cookie - analytics are fetched from Reddit's public API. For private accounts, open your browser DevTools while logged in to Reddit, go to Application > Cookies > reddit.com, and copy the value of the <strong>reddit_session</strong> cookie.</AlertDescription></Alert></TabsContent>@@ -495,32 +472,17 @@ function AccountCard({ acct, platform, metrics, refreshingId, onRefresh, onDelet</div>{isReddit && (- <div className="flex flex-col gap-1 text-xs">- <div className="flex items-center gap-1.5">- {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 - re-add account</span>- </>- )- ) : (- <>- <Globe className="h-3 w-3 text-muted-foreground" />- <span className="text-muted-foreground">Public access only</span>- </>- )}- </div>- {acct.hasTotpSecret && (- <div className="flex items-center gap-1.5">- <ShieldCheck className="h-3 w-3 text-blue-500" />- <span className="text-blue-600">2FA enabled</span>- </div>+ <div className="flex items-center gap-1.5 text-xs">+ {acct.hasCookie ? (+ <>+ <Lock className="h-3 w-3 text-green-500" />+ <span className="text-green-600">Session cookie stored</span>+ </>+ ) : (+ <>+ <Globe className="h-3 w-3 text-muted-foreground" />+ <span className="text-muted-foreground">Public access</span>+ </>)}</div>)}diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 4bba00f..99199ae 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, password, totpSecret) => request('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, password, totpSecret }) }),+ addRedditAccount: (username, cookie) => request('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, cookie }) }),getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),getRedditPosts: (id) => request(`/accounts/${id}/reddit-posts`),