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): add application-only OAuth to bypass datacenter IP block

spacesdrivebe793395511f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 312ad66..bfc5dc5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,10 +9,19 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Added
+**Reddit Application-Only OAuth**
+- Added `REDDIT_CLIENT_ID` and `REDDIT_CLIENT_SECRET` optional Worker secrets for application-only OAuth (client credentials grant)
+- `getAppOnlyToken(env)` in `backend/services/reddit.js` - exchanges client credentials for a bearer token via `POST /api/v1/access_token` with `grant_type=client_credentials`; token cached in isolate memory with expiry
+- When credentials are set, all Reddit API calls use `oauth.reddit.com` with `Authorization: Bearer` header instead of unauthenticated `www.reddit.com` requests; this resolves Reddit's datacenter IP block
+- When credentials are absent, requests fall back to unauthenticated (may 403 depending on Reddit's IP filtering)
+- Fixed User-Agent to proper Reddit-required format: `script:twiligent:v1.0 (by /u/spacesdrive)`
+- Better 403 error message: distinguishes between "account is private or suspended" (authenticated 403) and "Reddit blocked the request - set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET" (unauthenticated 403)
+- `fetchRedditProfile(username, cookie, env)` and `fetchRedditPosts(username, cookie, limit, env)` now accept `env` as an optional last parameter; all call sites updated in `accounts.js` and `routes/reddit.js` to pass `c.env`
+
**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
+- Public Reddit accounts work without any session cookie - all analytics data is fetched from Reddit's public JSON API
- `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`
diff --git a/backend/routes/accounts.js b/backend/routes/accounts.js
index e720e2a..84ed344 100644
--- a/backend/routes/accounts.js
+++ b/backend/routes/accounts.js
@@ -96,7 +96,7 @@ app.post('/accounts/reddit', async (c) => {
const userId = c.get('userId');
const cleanUsername = username.replace(/^u\//i, '').trim();
- const profile = await fetchRedditProfile(cleanUsername, cookie ?? null);
+ const profile = await fetchRedditProfile(cleanUsername, cookie ?? null, c.env);
const accounts = await getAccounts(supabase, userId);
if (accounts.find(a => a.platform === 'reddit' && a.username === profile.username)) {
@@ -204,7 +204,7 @@ app.post('/accounts/refresh-all', async (c) => {
profilePictureUrl: profile.profilePictureUrl,
};
} else if (account.platform === 'reddit') {
- const profile = await fetchRedditProfile(account.username, account.cookie ?? null);
+ const profile = await fetchRedditProfile(account.username, account.cookie ?? null, c.env);
updates = {
...updates,
totalKarma: profile.totalKarma,
@@ -290,7 +290,7 @@ app.post('/accounts/:id/refresh', async (c) => {
website: profile.website,
};
} else if (account.platform === 'reddit') {
- const profile = await fetchRedditProfile(account.username, account.cookie ?? null);
+ const profile = await fetchRedditProfile(account.username, account.cookie ?? null, c.env);
updates = {
...updates,
totalKarma: profile.totalKarma,
diff --git a/backend/routes/reddit.js b/backend/routes/reddit.js
index a2e4f75..934bffb 100644
--- a/backend/routes/reddit.js
+++ b/backend/routes/reddit.js
@@ -20,8 +20,8 @@ router.get('/accounts/:id/reddit-analytics', async (c) => {
const cookie = account.cookie ?? null;
const [profile, posts] = await Promise.all([
- fetchRedditProfile(account.username, cookie),
- fetchRedditPosts(account.username, cookie, 100),
+ fetchRedditProfile(account.username, cookie, c.env),
+ fetchRedditPosts(account.username, cookie, 100, c.env),
]);
const analytics = computeRedditAnalytics(profile, posts);
const result = { profile, analytics, posts };
@@ -48,7 +48,7 @@ router.get('/accounts/:id/reddit-posts', async (c) => {
if (cached?.posts) return c.json(cached.posts);
const cookie = account.cookie ?? null;
- const posts = await fetchRedditPosts(account.username, cookie, 100);
+ const posts = await fetchRedditPosts(account.username, cookie, 100, c.env);
return c.json(posts);
} catch (err) {
console.error(`GET /accounts/${id}/reddit-posts:`, err.message);
diff --git a/backend/services/reddit.js b/backend/services/reddit.js
index 2fdf592..527ae95 100644
--- a/backend/services/reddit.js
+++ b/backend/services/reddit.js
@@ -3,19 +3,56 @@
// 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)';
+const REDDIT_OAUTH_BASE = 'https://oauth.reddit.com';
+// Reddit requires: <platform>:<appid>:<version> (by /u/<username>)
+const USER_AGENT = 'script:twiligent:v1.0 (by /u/spacesdrive)';
-async function redditFetch(path, cookie = null) {
+// Module-level token cache. Cloudflare isolates are reused within a data center,
+// so this reduces token fetches. On fresh isolates it re-fetches transparently.
+let _cachedToken = null;
+let _tokenExpiry = 0;
+
+async function getAppOnlyToken(env) {
+ if (!env?.REDDIT_CLIENT_ID || !env?.REDDIT_CLIENT_SECRET) return null;
+ if (_cachedToken && Date.now() < _tokenExpiry) return _cachedToken;
+ try {
+ const creds = btoa(`${env.REDDIT_CLIENT_ID}:${env.REDDIT_CLIENT_SECRET}`);
+ const res = await fetch('https://www.reddit.com/api/v1/access_token', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Basic ${creds}`,
+ 'User-Agent': USER_AGENT,
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ body: 'grant_type=client_credentials',
+ });
+ if (!res.ok) return null;
+ const data = await res.json();
+ if (!data.access_token) return null;
+ _cachedToken = data.access_token;
+ _tokenExpiry = Date.now() + Math.max(0, (data.expires_in ?? 3600) - 60) * 1000;
+ return _cachedToken;
+ } catch {
+ return null;
+ }
+}
+
+async function redditFetch(path, cookie = null, token = null) {
+ const base = token ? REDDIT_OAUTH_BASE : REDDIT_BASE;
const headers = {
'User-Agent': USER_AGENT,
'Accept': 'application/json',
};
+ if (token) headers['Authorization'] = `Bearer ${token}`;
if (cookie) headers['Cookie'] = `reddit_session=${cookie}`;
- const res = await fetch(`${REDDIT_BASE}${path}`, { headers });
+ const res = await fetch(`${base}${path}`, { headers });
if (res.status === 404) throw new Error('Reddit user not found - check the username');
- if (res.status === 403) throw new Error('Account is private or suspended');
+ if (res.status === 403) {
+ if (token) throw new Error('Account is private or suspended');
+ throw new Error('Reddit blocked the request - set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET on the server to enable authenticated API access');
+ }
if (res.status === 429) throw new Error('Reddit rate limit hit - try again in a moment');
if (!res.ok) throw new Error(`Reddit API ${res.status}: ${res.statusText}`);
@@ -24,8 +61,9 @@ async function redditFetch(path, cookie = null) {
return data;
}
-export async function fetchRedditProfile(username, cookie = null) {
- const data = await redditFetch(`/user/${username}/about.json`, cookie);
+export async function fetchRedditProfile(username, cookie = null, env = null) {
+ const token = await getAppOnlyToken(env);
+ const data = await redditFetch(`/user/${username}/about.json`, cookie, token);
const u = data.data;
return {
username: u.name,
@@ -42,7 +80,8 @@ export async function fetchRedditProfile(username, cookie = null) {
};
}
-export async function fetchRedditPosts(username, cookie = null, limit = 100) {
+export async function fetchRedditPosts(username, cookie = null, limit = 100, env = null) {
+ const token = await getAppOnlyToken(env);
let allPosts = [];
let after = null;
let pages = 0;
@@ -54,7 +93,7 @@ export async function fetchRedditPosts(username, cookie = null, limit = 100) {
});
if (after) qs.set('after', after);
- const data = await redditFetch(`/user/${username}/submitted.json?${qs}`, cookie);
+ const data = await redditFetch(`/user/${username}/submitted.json?${qs}`, cookie, token);
const children = data.data?.children ?? [];
if (children.length === 0) break;
diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.md
index 86b6fd1..5fed48b 100644
--- a/docs/architecture/cloudflare/WORKERS.md
+++ b/docs/architecture/cloudflare/WORKERS.md
@@ -49,7 +49,8 @@ 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 |
+| `REDDIT_CLIENT_ID` | Optional | Reddit script app client ID for application-only OAuth; Reddit API falls back to unauthenticated if absent (may 403) |
+| `REDDIT_CLIENT_SECRET` | Optional | Reddit script app client secret; required alongside `REDDIT_CLIENT_ID` |
### Setting secrets