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(security): check account ownership for scheduled and tracked posts

spacesdrive3873a20d4734
diff --git a/backend/container.ts b/backend/container.ts
index 6c987df..eea170a 100644
--- a/backend/container.ts
+++ b/backend/container.ts
@@ -71,7 +71,7 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
instagramAnalytics: createInstagramAnalyticsService({ accounts, cache, context }),
redditAnalytics: createRedditAnalyticsService({ accounts, cache, context }),
publishing: createPublishingService({ accounts, config, context }),
- scheduledPosts: createScheduledPostService({ posts, publisher: scheduledPublisher }),
+ scheduledPosts: createScheduledPostService({ accounts, posts, publisher: scheduledPublisher }),
scheduledPublisher,
tokenRefresh: createTokenRefreshService({ accounts, context }),
trackedContent: createTrackedContentService({ accounts, tracked, config, context }),
diff --git a/backend/services/scheduledPostService.ts b/backend/services/scheduledPostService.ts
index dd6e12a..2d632f5 100644
--- a/backend/services/scheduledPostService.ts
+++ b/backend/services/scheduledPostService.ts
@@ -1,4 +1,7 @@
import { NotFoundError, ValidationError } from '../lib/errors.ts';
+import { newRowId } from '../lib/ids.ts';
+import { publishableAccount } from './publishingService.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { ScheduledPostRepository, DeleteAllResult } from '../repositories/scheduledPostRepository.ts';
import type { ScheduledPublisher } from './scheduledPublisher.ts';
import type {
@@ -6,6 +9,7 @@ import type {
} from '../../shared/types/domain.ts';
export interface ScheduledPostDeps {
+ accounts: AccountRepository;
posts: ScheduledPostRepository;
publisher: ScheduledPublisher;
}
@@ -19,10 +23,6 @@ export interface ScheduledPostService {
publishDueNow(): Promise<ScheduledPublishRun>;
}
-export function generateId(): string {
- return Date.now().toString(36) + Math.random().toString(36).substring(2, 8);
-}
-
function futureDate(value: string): string {
const date = new Date(value);
if (Number.isNaN(date.getTime()) || date.getTime() <= Date.now()) {
@@ -31,7 +31,7 @@ function futureDate(value: string): string {
return date.toISOString();
}
-export function createScheduledPostService({ posts, publisher }: ScheduledPostDeps): ScheduledPostService {
+export function createScheduledPostService({ accounts, posts, publisher }: ScheduledPostDeps): ScheduledPostService {
async function findOwned(userId: string, postId: string): Promise<ScheduledPost> {
const post = await posts.findForUser(postId, userId);
if (!post) throw new NotFoundError('Scheduled post not found');
@@ -41,9 +41,12 @@ export function createScheduledPostService({ posts, publisher }: ScheduledPostDe
return {
list: userId => posts.listForUser(userId),
+ // the post may only name one of the user's own Instagram accounts, since the scheduler publishes to it later
async create(userId, request) {
+ const scheduledAt = futureDate(request.scheduledAt);
+ publishableAccount(await accounts.findForUser(request.accountId, userId));
const post: ScheduledPost = {
- id: generateId(),
+ id: newRowId(),
accountId: request.accountId,
platform: request.platform || 'instagram',
mediaType: request.mediaType || 'IMAGE',
@@ -57,7 +60,7 @@ export function createScheduledPostService({ posts, publisher }: ScheduledPostDe
locationId: request.locationId || '',
userTags: request.userTags || [],
altText: request.altText || '',
- scheduledAt: futureDate(request.scheduledAt),
+ scheduledAt,
status: 'pending',
createdAt: new Date().toISOString(),
publishedMediaId: null,
diff --git a/backend/services/trackedContentService.ts b/backend/services/trackedContentService.ts
index f23f023..9cdd76e 100644
--- a/backend/services/trackedContentService.ts
+++ b/backend/services/trackedContentService.ts
@@ -2,6 +2,7 @@ import { fetchTrackedPostData } from './reddit/redditApi.ts';
import { fetchTrackedYouTubeData } from './youtube/youtubeTracked.ts';
import { detectContentType, manualViewsPatch, imageUrlPatch } from './trackedContentRules.ts';
import { NotConfiguredError, NotFoundError, ValidationError } from '../lib/errors.ts';
+import { newRowId } from '../lib/ids.ts';
import type { PatchResult, TrackedContentType } from './trackedContentRules.ts';
import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { TrackedPostRepository, TrackedPostUpdates } from '../repositories/trackedPostRepository.ts';
@@ -44,10 +45,6 @@ export interface TrackedContentService {
type TrackedData = YouTubeTrackedVideoData | RedditTrackedPostData;
-function newTrackedId(): string {
- return Date.now().toString(36) + Math.random().toString(36).slice(2);
-}
-
function patchOrThrow<P>(result: PatchResult<P>): P {
if (result.error !== undefined) throw new ValidationError(result.error);
return result.patch;
@@ -75,6 +72,14 @@ export function createTrackedContentService({ accounts, tracked, config, context
return account?.cookie || null;
}
+ // only Reddit items read through an account, and it must be one of the user's own Reddit accounts
+ async function checkedAccountId(userId: string, accountId: string | null, isYouTube: boolean): Promise<string | null> {
+ if (!accountId) return null;
+ if (isYouTube) throw new ValidationError('YouTube videos are read without an account; remove the account from this item.');
+ await redditCookie(userId, accountId, true);
+ return accountId;
+ }
+
async function fetchData(userId: string, contentType: TrackedContentType, url: string, accountId: string | null | undefined, strict: boolean): Promise<TrackedData> {
if (contentType === 'youtube') return fetchTrackedYouTubeData(url, youtubeKey(), signal);
return fetchTrackedPostData(url, await redditCookie(userId, accountId, strict), signal);
@@ -88,9 +93,9 @@ export function createTrackedContentService({ accounts, tracked, config, context
if (!contentType) throw new ValidationError('Only Reddit and YouTube URLs are supported');
const data = await fetchData(userId, contentType, url, accountId, true);
- const id = newTrackedId();
- await tracked.create({ id, accountId: contentType === 'youtube' ? null : (accountId || null), url, label, category, contentType }, userId);
- await tracked.updateForUser(id, { data: data as unknown as Record<string, unknown> }, userId);
+ const id = newRowId();
+ const fetched = data as unknown as Record<string, unknown>;
+ await tracked.create({ id, accountId: contentType === 'youtube' ? null : (accountId || null), url, label, category, contentType, data: fetched }, userId);
return tracked.findForUser(id, userId);
},
@@ -104,7 +109,7 @@ export function createTrackedContentService({ accounts, tracked, config, context
const updates: TrackedPostUpdates = {};
if (label !== undefined) updates.label = label;
if (category !== undefined) updates.category = category;
- if (accountId !== undefined) updates.accountId = accountId;
+ if (accountId !== undefined) updates.accountId = await checkedAccountId(userId, accountId, isYouTube);
if (Object.keys(updates).length > 0) await tracked.updateForUser(id, updates, userId);
return tracked.findForUser(id, userId);
diff --git a/backend/tests/routes/scheduledPostRoutes.test.ts b/backend/tests/routes/scheduledPostRoutes.test.ts
index 6f4d497..a3c53cf 100644
--- a/backend/tests/routes/scheduledPostRoutes.test.ts
+++ b/backend/tests/routes/scheduledPostRoutes.test.ts
@@ -1,9 +1,10 @@
import { test, describe, before, after, afterEach, mock } from 'node:test';
import assert from 'node:assert/strict';
import scheduledPostRoutes from '../../routes/scheduledPostRoutes.ts';
-import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
+import { accountRow, fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
import type { FakeSupabase } from '../fixtures/fakeSupabase.ts';
import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
+import { mockRowIds } from '../fixtures/rowIds.ts';
const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
@@ -13,14 +14,22 @@ function postRow(id: string, status: string, userId = 'user-1') {
});
}
+const ACCOUNTS = [
+ tableRow('accounts', accountRow({ id: 'ig1', platform: 'instagram', igUserId: 'IG1', accessToken: 'T1' })),
+ tableRow('accounts', accountRow({ id: 'ig-theirs', platform: 'instagram', igUserId: 'IG2', accessToken: 'T2' }, 'user-2')),
+ tableRow('accounts', accountRow({ id: 'yt1', platform: 'youtube', channelId: 'UC1' })),
+ tableRow('accounts', accountRow({ id: 'ig-notoken', platform: 'instagram', igUserId: 'IG3' })),
+];
+
before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
after(() => mock.timers.reset());
afterEach(() => mock.restoreAll());
function setup(rows = [postRow('pending1', 'pending'), postRow('busy', 'publishing'), postRow('done', 'published'), postRow('theirs', 'pending', 'user-2')]) {
mock.method(Math, 'random', () => 0.5);
+ mockRowIds();
mock.method(console, 'warn', () => undefined);
- const supabase = fakeSupabase(rows);
+ const supabase = fakeSupabase([...ACCOUNTS, ...rows]);
const app = mountWithContext(app => app.route('/', scheduledPostRoutes), { supabase, userId: 'user-1' });
const call = async (method: string, path: string, json?: unknown) => {
const response = await callRoute(app, method, path, { json });
@@ -58,7 +67,18 @@ describe('scheduled post routes', () => {
shareToFeed: true, collaborators: [], audioName: '', thumbOffset: null, locationId: '', userTags: [], altText: '',
scheduledAt: '2026-09-03T06:00:00.000Z', status: 'pending', createdAt: '2026-09-01T12:00:00.000Z', publishedMediaId: null, error: null,
});
- assert.equal(supabase.table[0].user_id, 'user-1');
+ assert.equal(supabase.table.find(row => row._table === 'scheduled_posts')?.user_id, 'user-1');
+ });
+
+ test('a post can only be scheduled to an Instagram account the user owns and has a token for', async () => {
+ const { supabase, call } = setup([]);
+ const post = { mediaUrl: 'https://cdn/b.jpg', scheduledAt: '2026-09-03T08:00:00Z' };
+ assert.deepEqual(await call('POST', '/scheduled-posts', { ...post, accountId: 'ig-theirs' }), failure(404, 'NOT_FOUND', 'Instagram account not found'));
+ assert.deepEqual(await call('POST', '/scheduled-posts', { ...post, accountId: 'yt1' }), failure(404, 'NOT_FOUND', 'Instagram account not found'));
+ assert.deepEqual(await call('POST', '/scheduled-posts', { ...post, accountId: 'gone' }), failure(404, 'NOT_FOUND', 'Instagram account not found'));
+ assert.deepEqual(await call('POST', '/scheduled-posts', { ...post, accountId: 'ig-notoken' }),
+ failure(400, 'VALIDATION_ERROR', 'No Instagram access token stored - reconnect this account'));
+ assert.equal(supabase.table.filter(row => row._table === 'scheduled_posts').length, 0);
});
test('only pending posts of the user can be edited, and only the editable fields change', async () => {
@@ -77,6 +97,6 @@ describe('scheduled post routes', () => {
assert.deepEqual(await call('DELETE', '/scheduled-posts/pending1'), { status: 200, body: { success: true, message: 'Scheduled post deleted' } });
const all = await call('DELETE', '/scheduled-posts');
assert.equal(all.status, 200);
- assert.deepEqual(supabase.table.map(row => row.id).sort(), ['busy', 'theirs']);
+ assert.deepEqual(supabase.table.filter(row => row._table === 'scheduled_posts').map(row => row.id).sort(), ['busy', 'theirs']);
});
});
diff --git a/backend/tests/routes/trackedContentRoutes.test.ts b/backend/tests/routes/trackedContentRoutes.test.ts
index 83c4df7..004e03d 100644
--- a/backend/tests/routes/trackedContentRoutes.test.ts
+++ b/backend/tests/routes/trackedContentRoutes.test.ts
@@ -1,4 +1,5 @@
import { test, describe, before, after, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
import type { Mock } from 'node:test';
import trackedContentRouter from '../../routes/trackedContentRoutes.ts';
import { assertGolden } from '../fixtures/golden.ts';
@@ -7,6 +8,7 @@ import type { FetchMock } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow, tableRow } from '../fixtures/fakeSupabase.ts';
import type { Row } from '../fixtures/fakeSupabase.ts';
import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
+import { mockRowIds } from '../fixtures/rowIds.ts';
import type { RouteStep } from '../fixtures/routeHarness.ts';
import type { Env } from '../../types/env.ts';
@@ -24,6 +26,7 @@ function seedRows() {
return [
tableRow('accounts', accountRow({ id: 'rd1', platform: 'reddit', username: 'ribbon', cookie: 'COOKIE' })),
tableRow('accounts', accountRow({ id: 'yt1', platform: 'youtube', channelId: 'UC1' })),
+ tableRow('accounts', accountRow({ id: 'rd-theirs', platform: 'reddit', username: 'other', cookie: 'THEIRS' }, 'user-2')),
trackedRow('t-reddit', 'reddit', { accountId: 'rd1', url: 'https://www.reddit.com/r/webdev/comments/p1/tracked/', data: { title: 'Old', manualViews: 5 } }),
trackedRow('t-youtube', 'youtube', { url: 'https://www.youtube.com/watch?v=abc', data: { title: 'Video' } }),
trackedRow('t-orphan', 'reddit', { accountId: 'gone', url: 'https://www.reddit.com/r/webdev/comments/p1/tracked/' }),
@@ -50,6 +53,7 @@ async function runCalls(calls: RouteStep[], env: Partial<Env> = ENV) {
describe('tracked content routes golden output', () => {
before(() => {
mock.timers.enable({ apis: ['Date'], now: FIXED_NOW });
+ mockRowIds();
let seed = 0;
mock.method(Math, 'random', () => {
seed += 0.125;
@@ -94,6 +98,22 @@ describe('tracked content routes golden output', () => {
assertGolden(result, 'trackedContentRoutes.update');
});
+ test('an item can only move to a Reddit account the user owns, and a YouTube item to no account', async () => {
+ const { responses } = await runCalls([
+ ['PUT', '/tracked-content/t-reddit', { accountId: 'rd-theirs' }],
+ ['PUT', '/tracked-content/t-reddit', { accountId: 'yt1' }],
+ ['PUT', '/tracked-content/t-youtube', { accountId: 'rd1' }],
+ ['PUT', '/tracked-content/t-reddit', { accountId: 'rd1' }],
+ ]);
+ const outcome = responses.map(response => [response.status, (JSON.parse(response.body) as { message?: string }).message ?? 'saved']);
+ assert.deepEqual(outcome, [
+ [404, 'Reddit account not found'],
+ [404, 'Reddit account not found'],
+ [400, 'YouTube videos are read without an account; remove the account from this item.'],
+ [200, 'saved'],
+ ]);
+ });
+
test('list, refresh and delete', async () => {
const result = await runCalls([
['GET', '/tracked-content'],