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.

fix(reddit): fix 403 login error and add two-factor authentication support

spacesdrived2a8a78b14ef
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2dc7a6d..028b6c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,17 @@ 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 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`
diff --git a/backend/lib/crypto.js b/backend/lib/crypto.js
index f7cf777..98d471c 100644
--- a/backend/lib/crypto.js
+++ b/backend/lib/crypto.js
@@ -1,5 +1,5 @@
-// 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>"
+// AES-256-GCM encryption and TOTP generation using the Web Crypto API (built into Cloudflare Workers).
+// AES 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);
@@ -36,3 +36,45 @@ export async function decryptPassword(encrypted, keyHex) {
);
return new TextDecoder().decode(plaintext);
}
+
+// TOTP (RFC 6238) using HMAC-SHA1 via crypto.subtle. No npm dependency.
+// base32Secret is the raw Base32 string from the authenticator app QR code.
+function base32Decode(base32) {
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
+ const cleaned = base32.toUpperCase().replace(/[^A-Z2-7]/g, '');
+ let bits = 0, value = 0;
+ const output = [];
+ 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) {
+ 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/accounts.js b/backend/routes/accounts.js
index 263f3be..442eea6 100644
--- a/backend/routes/accounts.js
+++ b/backend/routes/accounts.js
@@ -12,9 +12,11 @@ const app = new Hono();
function safeAccount(account) {
const copy = { ...account };
+ copy.hasTotpSecret = !!copy.encryptedTotpSecret;
delete copy.accessToken;
delete copy.cookie;
delete copy.encryptedPassword;
+ delete copy.encryptedTotpSecret;
return copy;
}
@@ -88,7 +90,7 @@ app.post('/accounts', async (c) => {
app.post('/accounts/reddit', async (c) => {
try {
- const { username, password } = await c.req.json();
+ const { username, password, totpSecret } = await c.req.json();
if (!username) return c.json({ success: false, message: 'Username is required' }, 400);
const supabase = c.get('supabase');
@@ -97,15 +99,17 @@ app.post('/accounts/reddit', async (c) => {
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);
+ 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);
@@ -126,6 +130,7 @@ app.post('/accounts/reddit', async (c) => {
iconUrl: profile.iconUrl,
createdAt: profile.createdAt,
encryptedPassword,
+ encryptedTotpSecret,
...cookieData,
addedAt: new Date().toISOString(),
lastUpdated: new Date().toISOString(),
diff --git a/backend/routes/reddit.js b/backend/routes/reddit.js
index 8213736..df7ad6a 100644
--- a/backend/routes/reddit.js
+++ b/backend/routes/reddit.js
@@ -21,7 +21,10 @@ async function ensureFreshCookie(account, supabase, userId, encryptionKey) {
try {
const password = await decryptPassword(account.encryptedPassword, encryptionKey);
- const { cookie, cookieAcquiredAt, cookieExpiresAt } = await loginToReddit(account.username, password);
+ 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) {
diff --git a/backend/services/reddit.js b/backend/services/reddit.js
index d53244d..98c37b5 100644
--- a/backend/services/reddit.js
+++ b/backend/services/reddit.js
@@ -1,5 +1,5 @@
// fetch is a global in Cloudflare Workers - no import needed.
-import { decryptPassword } from '../lib/crypto.js';
+import { decryptPassword, generateTOTP } from '../lib/crypto.js';
import { getAccounts, updateAccount } from '../lib/db.js';
const REDDIT_BASE = 'https://www.reddit.com';
@@ -242,22 +242,38 @@ export function computeRedditAnalytics(profile, posts) {
};
}
-// Strips the session cookie before any API response - treat cookie like an access token.
+// Strips sensitive fields before any API response. Exposes hasTotpSecret as a boolean so the
+// frontend can show 2FA status without revealing the secret itself.
export function safeRedditAccount(account) {
const copy = { ...account };
+ copy.hasTotpSecret = !!copy.encryptedTotpSecret;
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).
-export async function loginToReddit(username, password) {
- const body = new URLSearchParams({ user: username, passwd: password, api_type: 'json' });
+// 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': USER_AGENT,
+ 'User-Agent': LOGIN_USER_AGENT,
+ 'Origin': 'https://ssl.reddit.com',
+ 'Referer': 'https://www.reddit.com/',
},
body: body.toString(),
});
@@ -270,6 +286,7 @@ export async function loginToReddit(username, password) {
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');
@@ -310,7 +327,10 @@ export async function autoRefreshRedditSessions(supabase, encryptionKey) {
for (const account of stale) {
try {
const password = await decryptPassword(account.encryptedPassword, encryptionKey);
- const { cookie, cookieAcquiredAt, cookieExpiresAt } = await loginToReddit(account.username, password);
+ 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) {
diff --git a/frontend/src/features/accounts/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsx
index 953a801..b782113 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,
+ Lock, Unlock, Globe, ShieldCheck,
} from 'lucide-react';
import MainCard from '../../components/MainCard';
import { useAppContext } from '../../context/AppContext';
@@ -28,9 +28,10 @@ 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 [addingReddit, setAddingReddit] = useState(false);
+ const [redditUsername, setRedditUsername] = useState('');
+ const [redditPassword, setRedditPassword] = useState('');
+ const [redditTotpSecret, setRedditTotpSecret] = useState('');
+ const [addingReddit, setAddingReddit] = useState(false);
const [refreshingId, setRefreshingId] = useState(null);
// Handle Instagram OAuth redirect result (?ig_connected=true or ?ig_error=...)
@@ -136,7 +137,11 @@ export default function AccountManager() {
if (!redditUsername.trim()) return;
setAddingReddit(true);
try {
- await api.addRedditAccount(redditUsername.trim(), redditPassword.trim() || null);
+ await api.addRedditAccount(
+ redditUsername.trim(),
+ redditPassword.trim() || null,
+ redditTotpSecret.trim() || null,
+ );
showToast('Reddit account added');
closeDialog();
loadAccounts();
@@ -153,6 +158,7 @@ export default function AccountManager() {
setInput('');
setRedditUsername('');
setRedditPassword('');
+ setRedditTotpSecret('');
};
const ytAccounts = accounts.filter(a => a.platform !== 'instagram' && a.platform !== 'reddit');
@@ -405,11 +411,28 @@ export default function AccountManager() {
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 - 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.
+ 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.
</AlertDescription>
</Alert>
</TabsContent>
@@ -472,24 +495,32 @@ 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>
- </>
+ <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>
+ </>
+ )
) : (
<>
- <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>
</>
- )
- ) : (
- <>
- <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>
)}
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index a68d0c6..4bba00f 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) => request('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, password }) }),
+ addRedditAccount: (username, password, totpSecret) => request('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, password, totpSecret }) }),
getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),
getRedditPosts: (id) => request(`/accounts/${id}/reddit-posts`),