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(backend): share publishing params and credential stripping
spacesdrivec511f344980c
diff --git a/backend/lib/cache.js b/backend/lib/cache.jsindex f248e20..ce657d6 100644--- a/backend/lib/cache.js+++ b/backend/lib/cache.js@@ -93,16 +93,3 @@ export async function verifyOAuthState(state, secret) {if (Date.now() - Number(ts) > 10 * 60 * 1000) return null;return userId;}--// Legacy Redis-backed OAuth state (used only when Redis is available)-export async function setOAuthState(redis, state, userId) {- if (!redis) return;- await redis.set(`oauth_ig:${state}`, userId, { ex: 600 });-}--export async function getAndDeleteOAuthState(redis, state) {- if (!redis) return null;- const userId = await redis.get(`oauth_ig:${state}`);- if (userId) await redis.del(`oauth_ig:${state}`);- return userId || null;-}diff --git a/backend/lib/safeAccount.js b/backend/lib/safeAccount.jsnew file mode 100644index 0000000..aa40e7c--- /dev/null+++ b/backend/lib/safeAccount.js@@ -0,0 +1,9 @@+// Removes every credential from an account before it leaves the Worker. hasCookie lets the+// frontend show Reddit session status without ever receiving the cookie itself.+const SECRET_FIELDS = ['accessToken', 'cookie', 'encryptedPassword', 'encryptedTotpSecret', 'authToken', 'ct0'];++export function safeAccount(account) {+ const copy = { ...account, hasCookie: !!account.cookie };+ for (const field of SECRET_FIELDS) delete copy[field];+ return copy;+}diff --git a/backend/lib/safeAccount.test.js b/backend/lib/safeAccount.test.jsnew file mode 100644index 0000000..30def9e--- /dev/null+++ b/backend/lib/safeAccount.test.js@@ -0,0 +1,40 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { safeAccount } from './safeAccount.js';+import { buildMediaParams } from '../services/instagram.js';++test('safeAccount strips every credential and reports cookie presence', () => {+ const out = safeAccount({+ id: 'a1', platform: 'reddit', username: 'ribbon', cookie: 'secret', accessToken: 't',+ encryptedPassword: 'p', encryptedTotpSecret: 's', authToken: 'x', ct0: 'y',+ });+ assert.deepEqual(out, { id: 'a1', platform: 'reddit', username: 'ribbon', hasCookie: true });+});++test('safeAccount does not mutate its input', () => {+ const input = { id: 'a1', accessToken: 't' };+ safeAccount(input);+ assert.equal(input.accessToken, 't');+});++test('buildMediaParams builds a Reel container', () => {+ const params = buildMediaParams({+ mediaType: 'REELS', mediaUrl: 'https://cdn/v.mp4', caption: 'hi', shareToFeed: false,+ collaborators: ['a'], thumbOffset: 0, userTags: [],+ }, 'TOKEN');+ assert.deepEqual(params, {+ access_token: 'TOKEN', media_type: 'REELS', video_url: 'https://cdn/v.mp4', caption: 'hi',+ share_to_feed: false, collaborators: '["a"]', thumb_offset: 0,+ });+});++test('buildMediaParams picks video or image for Stories from the file extension', () => {+ assert.equal(buildMediaParams({ mediaType: 'STORIES', mediaUrl: 'https://cdn/s.MOV' }, 't').video_url, 'https://cdn/s.MOV');+ assert.equal(buildMediaParams({ mediaType: 'STORIES', mediaUrl: 'https://cdn/s.jpg' }, 't').image_url, 'https://cdn/s.jpg');+});++test('buildMediaParams treats unknown types as a photo post with alt text', () => {+ assert.deepEqual(buildMediaParams({ mediaType: 'IMAGE', mediaUrl: 'https://cdn/p.jpg', altText: 'A ribbon' }, 't'), {+ access_token: 't', image_url: 'https://cdn/p.jpg', alt_text: 'A ribbon',+ });+});diff --git a/backend/routes/accounts.js b/backend/routes/accounts.jsindex 67719ec..a9978f8 100644--- a/backend/routes/accounts.js+++ b/backend/routes/accounts.js@@ -5,22 +5,11 @@ import {import { deleteVideosCache, deleteIGCache, deleteRedditCache } from '../lib/cache.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 } from '../services/reddit.js';+import { safeAccount } from '../lib/safeAccount.js';const app = new Hono();-function safeAccount(account) {- const copy = { ...account };- copy.hasCookie = !!copy.cookie;- delete copy.accessToken;- delete copy.cookie;- delete copy.encryptedPassword;- delete copy.encryptedTotpSecret;- delete copy.authToken;- delete copy.ct0;- return copy;-}-app.get('/accounts', async (c) => {try {const accounts = await getAccounts(c.get('supabase'), c.get('userId'));@@ -122,7 +111,7 @@ app.post('/accounts/reddit', async (c) => {};await createAccount(supabase, newAccount, userId);- return c.json({ success: true, account: safeRedditAccount(newAccount) });+ return c.json({ success: true, account: safeAccount(newAccount) });} catch (err) {return c.json({ success: false, message: err.message }, 400);}diff --git a/backend/routes/publishing.js b/backend/routes/publishing.jsindex 32ad7c4..1c25cca 100644--- a/backend/routes/publishing.js+++ b/backend/routes/publishing.js@@ -1,5 +1,6 @@import { Hono } from 'hono';import { getAccountById } from '../lib/db.js';+import { buildMediaParams } from '../services/instagram.js';const app = new Hono();@@ -36,54 +37,8 @@ app.post('/accounts/:id/ig-publish', async (c) => {return c.json({ success: false, message: 'Instagram account not found' }, 404);}- const {- mediaType, mediaUrl, caption, coverUrl, shareToFeed, collaborators,- audioName, thumbOffset, locationId, userTags, altText, children,- } = await c.req.json();-const igId = acct.igUserId;- const token = acct.accessToken;- const params = { access_token: token };-- if (mediaType === 'CAROUSEL') {- params.media_type = 'CAROUSEL';- if (caption) params.caption = caption;- if (children?.length) params.children = children.join(',');- if (collaborators?.length) params.collaborators = JSON.stringify(collaborators);- if (locationId) params.location_id = locationId;- } else if (mediaType === 'CAROUSEL_ITEM_IMAGE') {- params.image_url = mediaUrl;- params.is_carousel_item = true;- } else if (mediaType === 'CAROUSEL_ITEM_VIDEO') {- params.media_type = 'VIDEO';- params.video_url = mediaUrl;- params.is_carousel_item = true;- } else if (mediaType === 'REELS') {- params.media_type = 'REELS';- params.video_url = mediaUrl;- if (caption) params.caption = caption;- if (shareToFeed !== undefined) params.share_to_feed = shareToFeed;- if (coverUrl) params.cover_url = coverUrl;- if (collaborators?.length) params.collaborators = JSON.stringify(collaborators);- if (audioName) params.audio_name = audioName;- if (thumbOffset != null) params.thumb_offset = thumbOffset;- if (locationId) params.location_id = locationId;- if (userTags?.length) params.user_tags = JSON.stringify(userTags);- } else if (mediaType === 'STORIES') {- params.media_type = 'STORIES';- if (mediaUrl?.match(/\.(mp4|mov|avi|webm)/i)) {- params.video_url = mediaUrl;- } else {- params.image_url = mediaUrl;- }- if (userTags?.length) params.user_tags = JSON.stringify(userTags);- } else {- params.image_url = mediaUrl;- if (caption) params.caption = caption;- if (locationId) params.location_id = locationId;- if (userTags?.length) params.user_tags = JSON.stringify(userTags);- if (altText) params.alt_text = altText;- }+ const params = buildMediaParams(await c.req.json(), acct.accessToken);const qs = new URLSearchParams(params).toString();const r = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${qs}`, { method: 'POST' });diff --git a/backend/routes/trackedPosts.js b/backend/routes/trackedPosts.jsdeleted file mode 100644index 62930aa..0000000--- a/backend/routes/trackedPosts.js+++ /dev/null@@ -1,126 +0,0 @@-import { Hono } from 'hono';-import {- getTrackedPosts,- getTrackedPostById,- createTrackedPost,- updateTrackedPost,- deleteTrackedPost,- getAccountById,-} from '../lib/db.js';-import { fetchTrackedPostData } from '../services/reddit.js';--const router = new Hono();--// List all tracked posts for the current user-router.get('/reddit/tracked-posts', async (c) => {- const userId = c.get('userId');- const supabase = c.get('supabase');- try {- const posts = await getTrackedPosts(supabase, userId);- return c.json(posts);- } catch (err) {- console.error('GET /reddit/tracked-posts:', err.message);- return c.json({ error: err.message }, 500);- }-});--// Add a new tracked post - fetches live data immediately using the account's cookie-router.post('/reddit/tracked-posts', async (c) => {- const userId = c.get('userId');- const supabase = c.get('supabase');- const body = await c.req.json();- const { url, accountId, label, category } = body;-- if (!url) return c.json({ error: 'url is required' }, 400);-- try {- let cookie = null;- if (accountId) {- const account = await getAccountById(supabase, accountId, userId);- if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);- cookie = account.cookie || null;- }-- const postData = await fetchTrackedPostData(url, cookie);-- const id = Date.now().toString(36) + Math.random().toString(36).slice(2);- await createTrackedPost(supabase, { id, accountId, url, label, category }, userId);- await updateTrackedPost(supabase, id, { data: postData }, userId);-- const created = await getTrackedPostById(supabase, id, userId);- return c.json(created, 201);- } catch (err) {- console.error('POST /reddit/tracked-posts:', err.message);- return c.json({ error: err.message }, 500);- }-});--// Update label or category on a tracked post-router.put('/reddit/tracked-posts/:id', async (c) => {- const id = c.req.param('id');- const userId = c.get('userId');- const supabase = c.get('supabase');- const body = await c.req.json();- const { label, category, accountId } = body;-- try {- const existing = await getTrackedPostById(supabase, id, userId);- if (!existing) return c.json({ error: 'Tracked post not found' }, 404);-- const updates = {};- if (label !== undefined) updates.label = label;- if (category !== undefined) updates.category = category;- if (accountId !== undefined) updates.accountId = accountId;- await updateTrackedPost(supabase, id, updates, userId);-- const updated = await getTrackedPostById(supabase, id, userId);- return c.json(updated);- } catch (err) {- console.error(`PUT /reddit/tracked-posts/${id}:`, err.message);- return c.json({ error: err.message }, 500);- }-});--// Delete a tracked post-router.delete('/reddit/tracked-posts/:id', async (c) => {- const id = c.req.param('id');- const userId = c.get('userId');- const supabase = c.get('supabase');- try {- const existing = await getTrackedPostById(supabase, id, userId);- if (!existing) return c.json({ error: 'Tracked post not found' }, 404);- await deleteTrackedPost(supabase, id, userId);- return c.json({ success: true });- } catch (err) {- console.error(`DELETE /reddit/tracked-posts/${id}:`, err.message);- return c.json({ error: err.message }, 500);- }-});--// Refresh live data for a single tracked post-router.post('/reddit/tracked-posts/:id/refresh', async (c) => {- const id = c.req.param('id');- const userId = c.get('userId');- const supabase = c.get('supabase');- try {- const existing = await getTrackedPostById(supabase, id, userId);- if (!existing) return c.json({ error: 'Tracked post not found' }, 404);-- let cookie = null;- if (existing.accountId) {- const account = await getAccountById(supabase, existing.accountId, userId);- cookie = account?.cookie || null;- }-- const postData = await fetchTrackedPostData(existing.url, cookie);- await updateTrackedPost(supabase, id, { data: postData }, userId);-- const updated = await getTrackedPostById(supabase, id, userId);- return c.json(updated);- } catch (err) {- console.error(`POST /reddit/tracked-posts/${id}/refresh:`, err.message);- return c.json({ error: err.message }, 500);- }-});--export default router;diff --git a/backend/services/instagram.js b/backend/services/instagram.jsindex 737d399..52b4bc4 100644--- a/backend/services/instagram.js+++ b/backend/services/instagram.js@@ -418,3 +418,52 @@ export function computeInstagramAnalytics(profile, media) {viralityScore, consistencyScore,};}++// Graph API container parameters for one media item. Shared by the publish route and the cron+// scheduler; scripts/publish-scheduled.js keeps its own copy because it must stay dependency-free.+export function buildMediaParams(post, accessToken) {+ const { mediaType, mediaUrl, caption, coverUrl, shareToFeed, collaborators, audioName,+ thumbOffset, locationId, userTags, altText, children } = post;+ const params = { access_token: accessToken };++ if (mediaType === 'CAROUSEL') {+ params.media_type = 'CAROUSEL';+ if (caption) params.caption = caption;+ if (children?.length) params.children = children.join(',');+ if (collaborators?.length) params.collaborators = JSON.stringify(collaborators);+ if (locationId) params.location_id = locationId;+ } else if (mediaType === 'CAROUSEL_ITEM_IMAGE') {+ params.image_url = mediaUrl;+ params.is_carousel_item = true;+ } else if (mediaType === 'CAROUSEL_ITEM_VIDEO') {+ params.media_type = 'VIDEO';+ params.video_url = mediaUrl;+ params.is_carousel_item = true;+ } else if (mediaType === 'REELS') {+ params.media_type = 'REELS';+ params.video_url = mediaUrl;+ if (caption) params.caption = caption;+ if (shareToFeed !== undefined) params.share_to_feed = shareToFeed;+ if (coverUrl) params.cover_url = coverUrl;+ if (collaborators?.length) params.collaborators = JSON.stringify(collaborators);+ if (audioName) params.audio_name = audioName;+ if (thumbOffset != null) params.thumb_offset = thumbOffset;+ if (locationId) params.location_id = locationId;+ if (userTags?.length) params.user_tags = JSON.stringify(userTags);+ } else if (mediaType === 'STORIES') {+ params.media_type = 'STORIES';+ if (mediaUrl?.match(/\.(mp4|mov|avi|webm)/i)) {+ params.video_url = mediaUrl;+ } else {+ params.image_url = mediaUrl;+ }+ if (userTags?.length) params.user_tags = JSON.stringify(userTags);+ } else {+ params.image_url = mediaUrl;+ if (caption) params.caption = caption;+ if (locationId) params.location_id = locationId;+ if (userTags?.length) params.user_tags = JSON.stringify(userTags);+ if (altText) params.alt_text = altText;+ }+ return params;+}diff --git a/backend/services/reddit.js b/backend/services/reddit.jsindex e909900..23ce73f 100644--- a/backend/services/reddit.js+++ b/backend/services/reddit.js@@ -245,17 +245,6 @@ export function computeRedditAnalytics(profile, posts) {};}-// Strips the session cookie before any API response.-// Exposes hasCookie as a boolean so the frontend can show session status without the value.-export function safeRedditAccount(account) {- const copy = { ...account };- copy.hasCookie = !!copy.cookie;- delete copy.cookie;- delete copy.encryptedPassword;- delete copy.encryptedTotpSecret;- return copy;-}-// No-op: kept for compatibility with server.js cron handler.export async function autoRefreshRedditSessions() {}diff --git a/backend/utils/scheduler.js b/backend/utils/scheduler.jsindex a4eb4f8..c242e37 100644--- a/backend/utils/scheduler.js+++ b/backend/utils/scheduler.js@@ -1,5 +1,6 @@// fetch is a global in Cloudflare Workers.import { getDuePosts, updatePost, getAccountById } from '../lib/db.js';+import { buildMediaParams } from '../services/instagram.js';export function generateId() {return Date.now().toString(36) + Math.random().toString(36).substring(2, 8);@@ -23,34 +24,7 @@ export async function processScheduledPosts(supabase) {const igId = acct.igUserId;const token = acct.accessToken;- const params = { access_token: token };-- if (post.mediaType === 'REELS') {- params.media_type = 'REELS';- params.video_url = post.mediaUrl;- if (post.caption) params.caption = post.caption;- if (post.shareToFeed !== undefined) params.share_to_feed = post.shareToFeed;- if (post.coverUrl) params.cover_url = post.coverUrl;- if (post.collaborators?.length) params.collaborators = JSON.stringify(post.collaborators);- if (post.audioName) params.audio_name = post.audioName;- if (post.thumbOffset != null) params.thumb_offset = post.thumbOffset;- if (post.locationId) params.location_id = post.locationId;- if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);- } else if (post.mediaType === 'STORIES') {- params.media_type = 'STORIES';- if (post.mediaUrl.match(/\.(mp4|mov|avi|webm)/i)) {- params.video_url = post.mediaUrl;- } else {- params.image_url = post.mediaUrl;- }- if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);- } else {- params.image_url = post.mediaUrl;- if (post.caption) params.caption = post.caption;- if (post.locationId) params.location_id = post.locationId;- if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);- if (post.altText) params.alt_text = post.altText;- }+ const params = buildMediaParams(post, token);const qs = new URLSearchParams(params).toString();const createRes = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${qs}`, { method: 'POST' });