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.

refactor(api): add the foundation for a layered request pipeline

spacesdrive7957722e5991
diff --git a/backend/lib/redis.ts b/backend/database/redis.ts
similarity index 100%
rename from backend/lib/redis.ts
rename to backend/database/redis.ts
diff --git a/backend/lib/supabase.ts b/backend/database/supabase.ts
similarity index 100%
rename from backend/lib/supabase.ts
rename to backend/database/supabase.ts
diff --git a/backend/lib/config.ts b/backend/lib/config.ts
new file mode 100644
index 0000000..07781aa
--- /dev/null
+++ b/backend/lib/config.ts
@@ -0,0 +1,76 @@
+import type { Env } from '../types/env.ts';
+
+const DEFAULT_BACKEND_URL = 'http://localhost:8787';
+const DEFAULT_FRONTEND_URL = 'http://localhost:5173';
+const DEV_ORIGINS = ['http://localhost:5173', 'http://127.0.0.1:5173'];
+const CALLBACK_PATH = '/api/auth/instagram/callback';
+
+export interface CloudinaryConfig {
+ cloudName: string;
+ uploadPreset: string;
+}
+
+// appId and appSecret are undefined when the Worker secrets are not set
+export interface InstagramOAuthConfig {
+ frontendUrl: string;
+ redirectUri: string;
+ appId: string | undefined;
+ appSecret: string | undefined;
+}
+
+export interface AppConfig {
+ youtubeApiKey: string | undefined;
+ instagram: InstagramOAuthConfig;
+ cloudinary: CloudinaryConfig | null;
+ allowedOrigins: string[];
+}
+
+// pasted secrets can carry a byte order mark or stray whitespace
+export function cleanSecret(value: string | undefined): string | undefined {
+ return value?.replace(/^\uFEFF/, '').trim() || undefined;
+}
+
+function cleanUrl(value: string | undefined, fallback: string): string {
+ return (value || fallback).replace(/^\uFEFF/, '').trim();
+}
+
+function originOf(url: string): string | null {
+ try {
+ return new URL(url).origin;
+ } catch {
+ // a malformed entry is skipped rather than allowing everything
+ return null;
+ }
+}
+
+// FRONTEND_URL and any ALLOWED_ORIGINS; the local Vite server only when neither is set
+function allowedOrigins(env: Env): string[] {
+ const listed = [env.FRONTEND_URL, ...(env.ALLOWED_ORIGINS ?? '').split(',')]
+ .map(value => cleanSecret(value))
+ .filter((value): value is string => !!value)
+ .map(originOf)
+ .filter((origin): origin is string => origin !== null);
+ return listed.length > 0 ? [...new Set(listed)] : DEV_ORIGINS;
+}
+
+export function readInstagramOAuthConfig(env: Env): InstagramOAuthConfig {
+ const frontendUrl = cleanUrl(env.FRONTEND_URL, DEFAULT_FRONTEND_URL).replace(/\/$/, '');
+ const backendUrl = cleanUrl(env.BACKEND_URL, DEFAULT_BACKEND_URL).replace(/\/$/, '');
+ return {
+ frontendUrl,
+ redirectUri: `${backendUrl}${CALLBACK_PATH}`,
+ appId: cleanSecret(env.INSTAGRAM_APP_ID),
+ appSecret: cleanSecret(env.INSTAGRAM_APP_SECRET),
+ };
+}
+
+export function readConfig(env: Env): AppConfig {
+ const cloudName = cleanSecret(env.CLOUDINARY_CLOUD_NAME);
+ const uploadPreset = cleanSecret(env.CLOUDINARY_UPLOAD_PRESET);
+ return {
+ youtubeApiKey: cleanSecret(env.YOUTUBE_API_KEY),
+ instagram: readInstagramOAuthConfig(env),
+ cloudinary: cloudName && uploadPreset ? { cloudName, uploadPreset } : null,
+ allowedOrigins: allowedOrigins(env),
+ };
+}
diff --git a/backend/lib/errors.ts b/backend/lib/errors.ts
new file mode 100644
index 0000000..0b2a1a8
--- /dev/null
+++ b/backend/lib/errors.ts
@@ -0,0 +1,89 @@
+import { redactUrls } from './redact.ts';
+import type { ApiErrorCode } from '../../shared/types/domain.ts';
+
+// services throw these; middleware/errorHandler.ts maps each code to a status and the one error body
+export class AppError extends Error {
+ readonly code: ApiErrorCode;
+
+ constructor(code: ApiErrorCode, message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = new.target.name;
+ this.code = code;
+ }
+}
+
+export class ValidationError extends AppError {
+ constructor(message: string) {
+ super('VALIDATION_ERROR', message);
+ }
+}
+
+export class UnauthorizedError extends AppError {
+ constructor(message: string) {
+ super('UNAUTHORIZED', message);
+ }
+}
+
+export class ForbiddenError extends AppError {
+ constructor(message: string) {
+ super('FORBIDDEN', message);
+ }
+}
+
+export class NotFoundError extends AppError {
+ constructor(message: string) {
+ super('NOT_FOUND', message);
+ }
+}
+
+export class ConflictError extends AppError {
+ constructor(message: string) {
+ super('CONFLICT', message);
+ }
+}
+
+export class NotConfiguredError extends AppError {
+ constructor(message: string) {
+ super('NOT_CONFIGURED', message);
+ }
+}
+
+export interface UpstreamDetails {
+ // the platform's own error reason, such as YouTube's playlistNotFound
+ reason?: string;
+ status?: number;
+ cause?: unknown;
+}
+
+// keeps the platform's wording, which users can act on, but never a url that may carry a key or token
+export class UpstreamError extends AppError {
+ readonly reason: string;
+ readonly upstreamStatus: number | undefined;
+
+ constructor(message: string, { reason = '', status, cause }: UpstreamDetails = {}) {
+ super('UPSTREAM_ERROR', redactUrls(message), { cause });
+ this.reason = reason;
+ this.upstreamStatus = status;
+ }
+}
+
+export class UpstreamTimeoutError extends AppError {
+ constructor(platform: string, cause?: unknown) {
+ super('UPSTREAM_TIMEOUT', `${platform} took too long to answer. Try again in a moment.`, { cause });
+ }
+}
+
+// the driver's message can name tables and constraints, so it goes to the log and the client gets a plain one
+export class DatabaseError extends AppError {
+ readonly operation: string;
+
+ constructor(operation: string, cause: unknown) {
+ super('DATABASE_ERROR', 'The database request failed. Try again in a moment.', { cause });
+ this.operation = operation;
+ }
+}
+
+export function isAbortError(err: unknown): boolean {
+ const name = (err as Error | undefined)?.name;
+ return name === 'AbortError' || name === 'TimeoutError';
+}
diff --git a/backend/lib/logger.ts b/backend/lib/logger.ts
new file mode 100644
index 0000000..ecb34f5
--- /dev/null
+++ b/backend/lib/logger.ts
@@ -0,0 +1,39 @@
+import { redactUrls } from './redact.ts';
+
+export type LogFields = Record<string, unknown>;
+
+export interface Logger {
+ info(message: string, fields?: LogFields): void;
+ warn(message: string, fields?: LogFields): void;
+ error(message: string, fields?: LogFields): void;
+ with(fields: LogFields): Logger;
+}
+
+type Level = 'info' | 'warn' | 'error';
+
+const WRITERS: Record<Level, (line: string) => void> = {
+ info: line => console.log(line),
+ warn: line => console.warn(line),
+ error: line => console.error(line),
+};
+
+// one JSON object per line, which Workers Logs indexes field by field
+export function createLogger(base: LogFields = {}): Logger {
+ const write = (level: Level, message: string, fields: LogFields = {}) => {
+ WRITERS[level](JSON.stringify({ level, message, ...base, ...fields }));
+ };
+ return {
+ info: (message, fields) => write('info', message, fields),
+ warn: (message, fields) => write('warn', message, fields),
+ error: (message, fields) => write('error', message, fields),
+ with: fields => createLogger({ ...base, ...fields }),
+ };
+}
+
+// the message and the message of its cause, with urls removed; never the stack, which can hold request data
+export function errorFields(err: unknown): LogFields {
+ const error = err as Error & { cause?: unknown };
+ const fields: LogFields = { error: redactUrls(String(error?.message ?? err)), errorName: error?.name };
+ if (error?.cause !== undefined) fields.cause = redactUrls(String((error.cause as Error)?.message ?? error.cause));
+ return fields;
+}
diff --git a/backend/lib/redact.ts b/backend/lib/redact.ts
new file mode 100644
index 0000000..e7fc73d
--- /dev/null
+++ b/backend/lib/redact.ts
@@ -0,0 +1,4 @@
+// platform errors can echo the request url, which carries the api key or access token
+export function redactUrls(message: string): string {
+ return message.replace(/https?:\/\/[^\s)]+/g, '[url]');
+}
diff --git a/backend/middleware/auth.ts b/backend/middleware/auth.ts
index 13be8dd..792dc91 100644
--- a/backend/middleware/auth.ts
+++ b/backend/middleware/auth.ts
@@ -1,5 +1,5 @@
import type { Next } from 'hono';
-import { getSupabaseAuth } from '../lib/supabase.ts';
+import { getSupabaseAuth } from '../database/supabase.ts';
import type { AppContext } from '../types/app.ts';
export async function requireAuth(c: AppContext, next: Next) {
diff --git a/backend/middleware/errorHandler.ts b/backend/middleware/errorHandler.ts
new file mode 100644
index 0000000..ffbb0c8
--- /dev/null
+++ b/backend/middleware/errorHandler.ts
@@ -0,0 +1,62 @@
+import { HTTPException } from 'hono/http-exception';
+import type { ContentfulStatusCode } from 'hono/utils/http-status';
+import { AppError } from '../lib/errors.ts';
+import { errorFields } from '../lib/logger.ts';
+import { requestLogger } from './requestContext.ts';
+import type { AppContext } from '../types/app.ts';
+import type { ApiErrorCode, ApiFailure } from '../../shared/types/domain.ts';
+
+const STATUS_BY_CODE: Record<ApiErrorCode, ContentfulStatusCode> = {
+ VALIDATION_ERROR: 400,
+ UNAUTHORIZED: 401,
+ FORBIDDEN: 403,
+ NOT_FOUND: 404,
+ CONFLICT: 409,
+ RATE_LIMITED: 429,
+ UPSTREAM_ERROR: 502,
+ UPSTREAM_TIMEOUT: 504,
+ NOT_CONFIGURED: 503,
+ DATABASE_ERROR: 500,
+ INTERNAL_ERROR: 500,
+};
+
+const CODE_BY_STATUS: Partial<Record<number, ApiErrorCode>> = {
+ 400: 'VALIDATION_ERROR', 401: 'UNAUTHORIZED', 403: 'FORBIDDEN', 404: 'NOT_FOUND', 409: 'CONFLICT', 429: 'RATE_LIMITED',
+};
+
+const INTERNAL_MESSAGE = 'The server could not complete the request. Try again, and quote the request id if it keeps failing.';
+
+export function statusOf(code: ApiErrorCode): ContentfulStatusCode {
+ return STATUS_BY_CODE[code];
+}
+
+export function errorBody(c: AppContext, code: ApiErrorCode, message: string): ApiFailure {
+ return { success: false, code, message, requestId: c.get('requestId') };
+}
+
+// last in the pipeline: every error thrown by a controller, service, repository or middleware ends here
+export function errorHandler(err: Error, c: AppContext): Response {
+ const log = requestLogger(c);
+
+ if (err instanceof AppError) {
+ const status = statusOf(err.code);
+ const fields = { code: err.code, status, ...errorFields(err) };
+ if (status >= 500) log.error('request failed', fields);
+ else log.warn('request rejected', fields);
+ return c.json(errorBody(c, err.code, err.message), status);
+ }
+
+ // hono's own errors, such as a malformed JSON body in a validator
+ if (err instanceof HTTPException) {
+ const code = CODE_BY_STATUS[err.status] ?? 'INTERNAL_ERROR';
+ log.warn('request rejected', { code, status: err.status, ...errorFields(err) });
+ return c.json(errorBody(c, code, err.message || 'The request could not be processed'), err.status);
+ }
+
+ log.error('unhandled error', { code: 'INTERNAL_ERROR', status: 500, ...errorFields(err) });
+ return c.json(errorBody(c, 'INTERNAL_ERROR', INTERNAL_MESSAGE), 500);
+}
+
+export function notFoundHandler(c: AppContext): Response {
+ return c.json(errorBody(c, 'NOT_FOUND', `No API route matches ${c.req.method} ${c.req.path}`), 404);
+}
diff --git a/backend/middleware/requestContext.ts b/backend/middleware/requestContext.ts
new file mode 100644
index 0000000..9a69d32
--- /dev/null
+++ b/backend/middleware/requestContext.ts
@@ -0,0 +1,31 @@
+import type { Next } from 'hono';
+import { createLogger } from '../lib/logger.ts';
+import type { Logger } from '../lib/logger.ts';
+import type { AppContext } from '../types/app.ts';
+import type { RequestContext } from '../types/context.ts';
+
+// platform calls past this point are abandoned; the browser has long given up by then
+const REQUEST_DEADLINE_MS = 30_000;
+
+// runs after hono's requestId(): adds the cancellation signal and writes one access log line per request
+export async function requestContext(c: AppContext, next: Next): Promise<void> {
+ c.set('signal', AbortSignal.any([c.req.raw.signal, AbortSignal.timeout(REQUEST_DEADLINE_MS)]));
+ const started = Date.now();
+ await next();
+ requestLogger(c).info('request', {
+ method: c.req.method,
+ path: c.req.path,
+ status: c.res.status,
+ durationMs: Date.now() - started,
+ });
+}
+
+// bound to the request id, and to the user id once requireAuth has verified it
+export function requestLogger(c: AppContext): Logger {
+ return createLogger({ requestId: c.get('requestId'), userId: c.get('userId') });
+}
+
+// what a controller hands to services: request metadata without any Hono type
+export function requestContextOf(c: AppContext): RequestContext {
+ return { requestId: c.get('requestId'), signal: c.get('signal'), log: requestLogger(c) };
+}
diff --git a/backend/middleware/validate.ts b/backend/middleware/validate.ts
new file mode 100644
index 0000000..5f90742
--- /dev/null
+++ b/backend/middleware/validate.ts
@@ -0,0 +1,17 @@
+import { validator } from 'hono/validator';
+import { objectBody } from '../validators/fields.ts';
+import type { Fields } from '../validators/fields.ts';
+
+// runs before the controller; a parser throws ValidationError, which the error handler answers with a 400
+export function jsonBody<T>(parse: (body: Fields) => T) {
+ return validator('json', value => parse(objectBody(value)));
+}
+
+// repeated keys keep their first value, as c.req.query(name) does
+export function queryParams<T>(parse: (query: Fields) => T) {
+ return validator('query', value => {
+ const first: Fields = {};
+ for (const [key, entry] of Object.entries(value)) first[key] = Array.isArray(entry) ? entry[0] : entry;
+ return parse(first);
+ });
+}
diff --git a/backend/repositories/accountRepository.ts b/backend/repositories/accountRepository.ts
new file mode 100644
index 0000000..2c70159
--- /dev/null
+++ b/backend/repositories/accountRepository.ts
@@ -0,0 +1,82 @@
+import { execute, maybeRow, rows } from './query.ts';
+import { NotFoundError } from '../lib/errors.ts';
+import type { SupabaseClient } from '../types/app.ts';
+import type { Account, NewAccount, Platform } from '../../shared/types/domain.ts';
+
+interface AccountRow {
+ id: string;
+ platform: Platform;
+ data: Omit<Account, 'id' | 'platform'>;
+}
+
+const COLUMNS = 'id, platform, data';
+
+function toAccount(row: AccountRow): Account {
+ return { id: row.id, platform: row.platform, ...row.data };
+}
+
+// methods named ...ForUser filter by the verified user id; the others reach every user and are only for cron jobs
+export interface AccountRepository {
+ listForUser(userId: string): Promise<Account[]>;
+ listAll(): Promise<Account[]>;
+ findForUser(id: string, userId: string): Promise<Account | null>;
+ findById(id: string): Promise<Account | null>;
+ create(account: NewAccount, userId: string): Promise<void>;
+ updateForUser(id: string, updates: Partial<Account>, userId: string): Promise<void>;
+ updateById(id: string, updates: Partial<Account>): Promise<void>;
+ deleteForUser(id: string, userId: string): Promise<void>;
+}
+
+export function createAccountRepository(db: SupabaseClient): AccountRepository {
+ async function find(id: string, userId: string | null): Promise<Account | null> {
+ const row = await maybeRow<AccountRow>('accounts.find', () => {
+ const query = db.from('accounts').select(COLUMNS).eq('id', id);
+ return (userId ? query.eq('user_id', userId) : query).maybeSingle();
+ });
+ return row ? toAccount(row) : null;
+ }
+
+ // merges into data, so fields the update does not name are kept
+ async function update(id: string, updates: Partial<Account>, userId: string | null): Promise<void> {
+ const current = await find(id, userId);
+ if (!current) throw new NotFoundError('Account not found');
+ const { id: _id, platform: currentPlatform, ...currentData } = current;
+ const { platform: newPlatform, ...dataUpdates } = updates;
+ await execute('accounts.update', () => {
+ const query = db.from('accounts').update({
+ platform: newPlatform || currentPlatform,
+ data: { ...currentData, ...dataUpdates },
+ }).eq('id', id);
+ return userId ? query.eq('user_id', userId) : query;
+ });
+ }
+
+ return {
+ async listForUser(userId) {
+ const found = await rows<AccountRow>('accounts.listForUser', () => db.from('accounts').select(COLUMNS).eq('user_id', userId));
+ return found.map(toAccount);
+ },
+
+ async listAll() {
+ const found = await rows<AccountRow>('accounts.listAll', () => db.from('accounts').select(COLUMNS));
+ return found.map(toAccount);
+ },
+
+ findForUser: (id, userId) => find(id, userId),
+
+ findById: id => find(id, null),
+
+ async create(account, userId) {
+ const { id, platform, ...rest } = account;
+ await execute('accounts.create', () => db.from('accounts').insert({ id, user_id: userId, platform: platform || 'youtube', data: rest }));
+ },
+
+ updateForUser: (id, updates, userId) => update(id, updates, userId),
+
+ updateById: (id, updates) => update(id, updates, null),
+
+ async deleteForUser(id, userId) {
+ await execute('accounts.delete', () => db.from('accounts').delete().eq('id', id).eq('user_id', userId));
+ },
+ };
+}
diff --git a/backend/repositories/analyticsCacheRepository.ts b/backend/repositories/analyticsCacheRepository.ts
new file mode 100644
index 0000000..0aeb376
--- /dev/null
+++ b/backend/repositories/analyticsCacheRepository.ts
@@ -0,0 +1,104 @@
+import type { Redis } from '../types/app.ts';
+import type { VideosCacheData } from '../../shared/types/youtube.ts';
+import type { IGCacheData } from '../../shared/types/instagram.ts';
+import type { RedditCacheData } from '../../shared/types/reddit.ts';
+
+// stats change constantly, so cached analytics expire instead of going stale
+const ANALYTICS_TTL_SECONDS = 6 * 60 * 60;
+
+// after a failure this isolate skips redis for a while, so an outage costs one timeout, not one per call
+const CACHE_COOLDOWN_MS = 30_000;
+
+// bump on cache shape changes so old entries miss (v2: hidden counts are null)
+const VIDEOS_CACHE_VERSION = 2;
+const IG_CACHE_VERSION = 2;
+
+type Versioned<T> = T & { version: number };
+
+let cacheDownUntil = 0;
+
+export function resetCacheState(): void {
+ cacheDownUntil = 0;
+}
+
+// every method is a no-op without redis and never throws: the cache is optional
+export interface AnalyticsCacheRepository {
+ readonly enabled: boolean;
+ getVideos(userId: string, accountId: string): Promise<Versioned<VideosCacheData> | null>;
+ setVideos(userId: string, accountId: string, data: VideosCacheData): Promise<void>;
+ getInstagramMedia(userId: string, accountId: string): Promise<Versioned<IGCacheData> | null>;
+ setInstagramMedia(userId: string, accountId: string, data: IGCacheData): Promise<void>;
+ getReddit(userId: string, accountId: string): Promise<RedditCacheData | null>;
+ setReddit(userId: string, accountId: string, data: RedditCacheData): Promise<void>;
+ deleteAllForAccount(userId: string, accountId: string): Promise<void>;
+}
+
+export function createAnalyticsCacheRepository(redis: Redis | null): AnalyticsCacheRepository {
+ const available = (): boolean => redis !== null && Date.now() >= cacheDownUntil;
+ const markDown = (): void => {
+ cacheDownUntil = Date.now() + CACHE_COOLDOWN_MS;
+ };
+
+ async function readKey<T>(key: string): Promise<T | null> {
+ if (!redis || !available()) return null;
+ try {
+ return await redis.get<T>(key);
+ } catch {
+ // a cache miss falls back to the live api
+ markDown();
+ return null;
+ }
+ }
+
+ async function writeKey(key: string, value: unknown): Promise<void> {
+ if (!redis || !available()) return;
+ try {
+ await redis.set(key, value, { ex: ANALYTICS_TTL_SECONDS });
+ } catch {
+ // a failed write only costs a refetch next time
+ markDown();
+ }
+ }
+
+ async function deleteKey(key: string): Promise<void> {
+ if (!redis || !available()) return;
+ try {
+ await redis.del(key);
+ } catch {
+ // the entry still expires on its own ttl
+ markDown();
+ }
+ }
+
+ return {
+ enabled: redis !== null,
+
+ async getVideos(userId, accountId) {
+ const cached = await readKey<Versioned<VideosCacheData>>(`videos:${userId}:${accountId}`);
+ return cached?.version === VIDEOS_CACHE_VERSION ? cached : null;
+ },
+
+ setVideos: (userId, accountId, data) => writeKey(`videos:${userId}:${accountId}`, { ...data, version: VIDEOS_CACHE_VERSION }),
+
+ async getInstagramMedia(userId, accountId) {
+ const cached = await readKey<Versioned<IGCacheData>>(`ig:${userId}:${accountId}`);
+ return cached?.version === IG_CACHE_VERSION ? cached : null;
+ },
+
+ setInstagramMedia: (userId, accountId, data) => writeKey(`ig:${userId}:${accountId}`, { ...data, version: IG_CACHE_VERSION }),
+
+ async getReddit(userId, accountId) {
+ return (await readKey<RedditCacheData>(`reddit:${userId}:${accountId}`)) || null;
+ },
+
+ setReddit: (userId, accountId, data) => writeKey(`reddit:${userId}:${accountId}`, data),
+
+ async deleteAllForAccount(userId, accountId) {
+ await Promise.all([
+ deleteKey(`videos:${userId}:${accountId}`),
+ deleteKey(`ig:${userId}:${accountId}`),
+ deleteKey(`reddit:${userId}:${accountId}`),
+ ]);
+ },
+ };
+}
diff --git a/backend/repositories/query.ts b/backend/repositories/query.ts
new file mode 100644
index 0000000..c91c1af
--- /dev/null
+++ b/backend/repositories/query.ts
@@ -0,0 +1,30 @@
+import { DatabaseError } from '../lib/errors.ts';
+
+interface QueryResult {
+ data: unknown;
+ error: unknown;
+ count?: number | null;
+}
+
+// builds and runs one query; a thrown error and a returned error both become a DatabaseError named after the operation
+export async function execute(operation: string, build: () => PromiseLike<QueryResult>): Promise<QueryResult> {
+ let result: QueryResult;
+ try {
+ result = await build();
+ } catch (err) {
+ throw new DatabaseError(operation, err);
+ }
+ if (result.error) throw new DatabaseError(operation, result.error);
+ return result;
+}
+
+export async function rows<T>(operation: string, build: () => PromiseLike<QueryResult>): Promise<T[]> {
+ const { data } = await execute(operation, build);
+ return (data ?? []) as T[];
+}
+
+// null when no row matches; only a failed query throws
+export async function maybeRow<T>(operation: string, build: () => PromiseLike<QueryResult>): Promise<T | null> {
+ const { data } = await execute(operation, build);
+ return (data ?? null) as T | null;
+}
diff --git a/backend/repositories/scheduledPostRepository.ts b/backend/repositories/scheduledPostRepository.ts
new file mode 100644
index 0000000..b6e7d46
--- /dev/null
+++ b/backend/repositories/scheduledPostRepository.ts
@@ -0,0 +1,142 @@
+import { execute, maybeRow, rows } from './query.ts';
+import type { SupabaseClient } from '../types/app.ts';
+import type { PostStatus, ScheduledPost } from '../../shared/types/domain.ts';
+
+interface ScheduledPostRow {
+ id: string;
+ account_id: string;
+ status: PostStatus;
+ scheduled_at: string;
+ data: Partial<ScheduledPost> | null;
+}
+
+interface PostColumnUpdates {
+ status?: PostStatus;
+ scheduled_at?: string;
+ data?: Partial<ScheduledPost>;
+}
+
+export interface DeleteAllResult {
+ deleted: number;
+ kept: number;
+}
+
+const COLUMNS = 'id, account_id, status, scheduled_at, data';
+
+function toPost(row: ScheduledPostRow): ScheduledPost {
+ return {
+ id: row.id,
+ accountId: row.account_id,
+ status: row.status,
+ scheduledAt: row.scheduled_at,
+ ...(row.data || {}),
+ };
+}
+
+// methods named ...ForUser filter by the verified user id; listDue, claim and updateById serve the schedulers across all users
+export interface ScheduledPostRepository {
+ listForUser(userId: string): Promise<ScheduledPost[]>;
+ findForUser(id: string, userId: string): Promise<ScheduledPost | null>;
+ listDue(): Promise<ScheduledPost[]>;
+ claim(id: string): Promise<boolean>;
+ create(post: ScheduledPost, userId: string): Promise<void>;
+ updateForUser(id: string, updates: Partial<ScheduledPost>, userId: string): Promise<void>;
+ updateById(id: string, updates: Partial<ScheduledPost>): Promise<void>;
+ deleteForUser(id: string, userId: string): Promise<void>;
+ deleteAllForUser(userId: string): Promise<DeleteAllResult>;
+}
+
+export function createScheduledPostRepository(db: SupabaseClient): ScheduledPostRepository {
+ // status and scheduledAt are columns; every other field is merged into data
+ async function update(id: string, updates: Partial<ScheduledPost>, userId: string | null): Promise<void> {
+ const { status, scheduledAt, accountId: _accountId, ...dataUpdates } = updates;
+ const columns: PostColumnUpdates = {};
+ if (status !== undefined) columns.status = status;
+ if (scheduledAt !== undefined) columns.scheduled_at = scheduledAt;
+
+ if (Object.keys(dataUpdates).length > 0) {
+ const current = await rows<Pick<ScheduledPostRow, 'data'>>('scheduledPosts.readData', () => {
+ const query = db.from('scheduled_posts').select('data').eq('id', id);
+ return userId ? query.eq('user_id', userId) : query;
+ });
+ columns.data = { ...(current[0]?.data || {}), ...dataUpdates };
+ }
+
+ await execute('scheduledPosts.update', () => {
+ const query = db.from('scheduled_posts').update(columns).eq('id', id);
+ return userId ? query.eq('user_id', userId) : query;
+ });
+ }
+
+ return {
+ async listForUser(userId) {
+ const found = await rows<ScheduledPostRow>('scheduledPosts.listForUser', () => db
+ .from('scheduled_posts')
+ .select(COLUMNS)
+ .order('scheduled_at', { ascending: true })
+ .eq('user_id', userId));
+ return found.map(toPost);
+ },
+
+ async findForUser(id, userId) {
+ const row = await maybeRow<ScheduledPostRow>('scheduledPosts.findForUser', () => db
+ .from('scheduled_posts')
+ .select(COLUMNS)
+ .eq('id', id)
+ .eq('user_id', userId)
+ .maybeSingle());
+ return row ? toPost(row) : null;
+ },
+
+ async listDue() {
+ const found = await rows<ScheduledPostRow>('scheduledPosts.listDue', () => db
+ .from('scheduled_posts')
+ .select(COLUMNS)
+ .eq('status', 'pending')
+ .lte('scheduled_at', new Date().toISOString()));
+ return found.map(toPost);
+ },
+
+ // atomic pending to publishing; false means the other scheduler claimed it first
+ async claim(id) {
+ const claimed = await rows<{ id: string }>('scheduledPosts.claim', () => db
+ .from('scheduled_posts')
+ .update({ status: 'publishing' })
+ .eq('id', id)
+ .eq('status', 'pending')
+ .select('id'));
+ return claimed.length > 0;
+ },
+
+ async create(post, userId) {
+ const { id, accountId, status, scheduledAt, ...rest } = post;
+ await execute('scheduledPosts.create', () => db.from('scheduled_posts').insert({
+ id,
+ user_id: userId,
+ account_id: accountId,
+ status: status || 'pending',
+ scheduled_at: scheduledAt,
+ data: rest,
+ }));
+ },
+
+ updateForUser: (id, updates, userId) => update(id, updates, userId),
+
+ updateById: (id, updates) => update(id, updates, null),
+
+ async deleteForUser(id, userId) {
+ await execute('scheduledPosts.delete', () => db.from('scheduled_posts').delete().eq('id', id).eq('user_id', userId));
+ },
+
+ // posts being published right now are kept, so a publish never loses its row
+ async deleteAllForUser(userId) {
+ const total = await execute('scheduledPosts.count', () => db
+ .from('scheduled_posts').select('*', { count: 'exact', head: true }).eq('user_id', userId));
+ const keeping = await execute('scheduledPosts.countPublishing', () => db
+ .from('scheduled_posts').select('*', { count: 'exact', head: true }).eq('status', 'publishing').eq('user_id', userId));
+ await execute('scheduledPosts.deleteAll', () => db.from('scheduled_posts').delete().neq('status', 'publishing').eq('user_id', userId));
+ const kept = keeping.count || 0;
+ return { deleted: (total.count || 0) - kept, kept };
+ },
+ };
+}
diff --git a/backend/repositories/settingsRepository.ts b/backend/repositories/settingsRepository.ts
new file mode 100644
index 0000000..ecf228d
--- /dev/null
+++ b/backend/repositories/settingsRepository.ts
@@ -0,0 +1,32 @@
+import { execute, maybeRow } from './query.ts';
+import type { SupabaseClient } from '../types/app.ts';
+
+export type Settings = Record<string, unknown>;
+
+// rows are keyed by (user_id, key); every saved value lives under 'api_keys'
+const SETTINGS_KEY = 'api_keys';
+
+export interface SettingsRepository {
+ getForUser(userId: string): Promise<Settings>;
+ saveForUser(settings: Settings, userId: string): Promise<void>;
+}
+
+export function createSettingsRepository(db: SupabaseClient): SettingsRepository {
+ return {
+ async getForUser(userId) {
+ const row = await maybeRow<{ value: Settings | null }>('settings.get', () => db
+ .from('settings')
+ .select('value')
+ .eq('key', SETTINGS_KEY)
+ .eq('user_id', userId)
+ .maybeSingle());
+ return { ...(row?.value ?? {}) };
+ },
+
+ async saveForUser(settings, userId) {
+ await execute('settings.save', () => db
+ .from('settings')
+ .upsert({ user_id: userId, key: SETTINGS_KEY, value: settings }, { onConflict: 'user_id,key' }));
+ },
+ };
+}
diff --git a/backend/repositories/trackedPostRepository.ts b/backend/repositories/trackedPostRepository.ts
new file mode 100644
index 0000000..293f219
--- /dev/null
+++ b/backend/repositories/trackedPostRepository.ts
@@ -0,0 +1,131 @@
+import { execute, maybeRow, rows } from './query.ts';
+import { NotFoundError } from '../lib/errors.ts';
+import type { SupabaseClient } from '../types/app.ts';
+import type { TrackedPost } from '../../shared/types/domain.ts';
+
+interface TrackedPostRow {
+ id: string;
+ account_id: string | null;
+ url: string;
+ label: string | null;
+ category: string | null;
+ content_type: string | null;
+ created_at: string;
+ updated_at: string;
+ data: Record<string, unknown> | null;
+}
+
+export interface NewTrackedPost {
+ id: string;
+ accountId?: string | null;
+ url: string;
+ label?: string;
+ category?: string;
+ contentType?: string;
+}
+
+export interface TrackedPostUpdates {
+ label?: string;
+ category?: string;
+ accountId?: string | null;
+ data?: Record<string, unknown>;
+}
+
+interface TrackedPostColumnUpdates {
+ updated_at: string;
+ label?: string;
+ category?: string;
+ account_id?: string | null;
+ data?: Record<string, unknown>;
+}
+
+const COLUMNS = 'id, account_id, url, label, category, content_type, created_at, updated_at, data';
+
+function toTrackedPost(row: TrackedPostRow): TrackedPost {
+ return {
+ id: row.id,
+ accountId: row.account_id,
+ url: row.url,
+ label: row.label || '',
+ category: row.category || '',
+ contentType: row.content_type || 'reddit',
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ ...(row.data || {}),
+ };
+}
+
+// every method is scoped to the verified user
+export interface TrackedPostRepository {
+ listForUser(userId: string): Promise<TrackedPost[]>;
+ findForUser(id: string, userId: string): Promise<TrackedPost | null>;
+ create(post: NewTrackedPost, userId: string): Promise<void>;
+ updateForUser(id: string, updates: TrackedPostUpdates, userId: string): Promise<void>;
+ patchDataForUser(id: string, patch: Record<string, unknown>, userId: string): Promise<void>;
+ deleteForUser(id: string, userId: string): Promise<void>;
+}
+
+export function createTrackedPostRepository(db: SupabaseClient): TrackedPostRepository {
+ return {
+ async listForUser(userId) {
+ const found = await rows<TrackedPostRow>('trackedPosts.listForUser', () => db
+ .from('tracked_posts')
+ .select(COLUMNS)
+ .eq('user_id', userId)
+ .order('created_at', { ascending: false }));
+ return found.map(toTrackedPost);
+ },
+
+ async findForUser(id, userId) {
+ const row = await maybeRow<TrackedPostRow>('trackedPosts.findForUser', () => db
+ .from('tracked_posts')
+ .select(COLUMNS)
+ .eq('id', id)
+ .eq('user_id', userId)
+ .maybeSingle());
+ return row ? toTrackedPost(row) : null;
+ },
+
+ async create(post, userId) {
+ const { id, accountId, url, label, category, contentType } = post;
+ await execute('trackedPosts.create', () => db.from('tracked_posts').insert({
+ id,
+ user_id: userId,
+ account_id: accountId || null,
+ url,
+ label: label || '',
+ category: category || '',
+ content_type: contentType || 'reddit',
+ }));
+ },
+
+ async updateForUser(id, updates, userId) {
+ const columns: TrackedPostColumnUpdates = { updated_at: new Date().toISOString() };
+ if (updates.label !== undefined) columns.label = updates.label;
+ if (updates.category !== undefined) columns.category = updates.category;
+ if (updates.accountId !== undefined) columns.account_id = updates.accountId || null;
+ if (updates.data !== undefined) columns.data = updates.data;
+ await execute('trackedPosts.update', () => db.from('tracked_posts').update(columns).eq('id', id).eq('user_id', userId));
+ },
+
+ // merges into data so manual fields and live refresh fields survive each other
+ async patchDataForUser(id, patch, userId) {
+ const row = await maybeRow<Pick<TrackedPostRow, 'data'>>('trackedPosts.readData', () => db
+ .from('tracked_posts')
+ .select('data')
+ .eq('id', id)
+ .eq('user_id', userId)
+ .maybeSingle());
+ if (!row) throw new NotFoundError('Tracked content not found');
+ await execute('trackedPosts.patchData', () => db
+ .from('tracked_posts')
+ .update({ data: { ...(row.data || {}), ...patch }, updated_at: new Date().toISOString() })
+ .eq('id', id)
+ .eq('user_id', userId));
+ },
+
+ async deleteForUser(id, userId) {
+ await execute('trackedPosts.delete', () => db.from('tracked_posts').delete().eq('id', id).eq('user_id', userId));
+ },
+ };
+}
diff --git a/backend/server.ts b/backend/server.ts
index 69853ee..fe27485 100644
--- a/backend/server.ts
+++ b/backend/server.ts
@@ -1,7 +1,7 @@
import { Hono } from 'hono';
import { cors } from 'hono/cors';
-import { getSupabase } from './lib/supabase.ts';
-import { getRedis, getRateLimitRedis } from './lib/redis.ts';
+import { getSupabase } from './database/supabase.ts';
+import { getRedis, getRateLimitRedis } from './database/redis.ts';
import { requireAuth } from './middleware/auth.ts';
import { rateLimit, clientIp, userKey, RATE_LIMIT_HEADERS } from './middleware/rateLimit.ts';
import { RATE_LIMIT_RULES, QUOTA_ROUTES, PUBLISH_ROUTES, matchesRoute } from './lib/rateLimit/rules.ts';
diff --git a/backend/tests/fixtures/fakeSupabase.ts b/backend/tests/fixtures/fakeSupabase.ts
index 2f06c98..e0fd7b6 100644
--- a/backend/tests/fixtures/fakeSupabase.ts
+++ b/backend/tests/fixtures/fakeSupabase.ts
@@ -1,9 +1,9 @@
-// in-memory stand-in for the supabase query builder calls made by lib/db.js; records every call
+// in-memory stand-in for the supabase query builder calls made by the repositories; records every call
import type { SupabaseClient } from '../../types/app.ts';
export type Row = Record<string, unknown>;
-type Filter = [column: string, value: unknown, operator?: 'lte'];
+type Filter = [column: string, value: unknown, operator?: 'lte' | 'neq'];
interface Action {
type: 'select' | 'update' | 'insert' | 'upsert' | 'delete';
@@ -24,8 +24,10 @@ interface FakeQuery {
select(): FakeQuery;
eq(column: string, value: unknown): FakeQuery;
lte(column: string, value: unknown): FakeQuery;
+ neq(column: string, value: unknown): FakeQuery;
order(): FakeQuery;
single(): Promise<QueryResult>;
+ maybeSingle(): Promise<QueryResult>;
then(resolve: (result: QueryResult) => unknown, reject?: (reason: unknown) => unknown): Promise<unknown>;
}
@@ -40,6 +42,7 @@ function copy<T>(value: T): T {
function matchesFilter(row: Row, [column, value, operator]: Filter) {
if (operator === 'lte') return (row[column] as string) <= (value as string);
+ if (operator === 'neq') return row[column] !== value;
return row[column] === value;
}
@@ -64,7 +67,15 @@ function queryBuilder(action: Action, run: Run): FakeQuery {
filters.push([column, value, 'lte']);
return query;
},
+ neq(column: string, value: unknown) {
+ filters.push([column, value, 'neq']);
+ return query;
+ },
order() { return query; },
+ maybeSingle() {
+ const found = run(action, filters);
+ return Promise.resolve({ data: found[0] ?? null, error: null });
+ },
single() {
const found = run(action, filters);
if (found.length === 0) return Promise.resolve({ data: null, error: { message: 'no rows' } });
diff --git a/backend/tests/lib/config.test.ts b/backend/tests/lib/config.test.ts
new file mode 100644
index 0000000..e1ef600
--- /dev/null
+++ b/backend/tests/lib/config.test.ts
@@ -0,0 +1,36 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readConfig } from '../../lib/config.ts';
+import type { Env } from '../../types/env.ts';
+
+const BOM = String.fromCharCode(0xfeff);
+
+function config(env: Partial<Env>) {
+ return readConfig(env as Env);
+}
+
+test('secrets lose a byte order mark and whitespace, and blank ones count as unset', () => {
+ assert.equal(config({ YOUTUBE_API_KEY: `${BOM} KEY \n` }).youtubeApiKey, 'KEY');
+ assert.equal(config({ YOUTUBE_API_KEY: `${BOM} ` }).youtubeApiKey, undefined);
+ assert.deepEqual(config({ CLOUDINARY_CLOUD_NAME: 'cloud', CLOUDINARY_UPLOAD_PRESET: ' preset ' }).cloudinary, { cloudName: 'cloud', uploadPreset: 'preset' });
+ assert.equal(config({ CLOUDINARY_CLOUD_NAME: 'cloud' }).cloudinary, null);
+});
+
+test('CORS allows FRONTEND_URL and ALLOWED_ORIGINS by origin, and the Vite server only when neither is set', () => {
+ assert.deepEqual(config({}).allowedOrigins, ['http://localhost:5173', 'http://127.0.0.1:5173']);
+ assert.deepEqual(config({ FRONTEND_URL: 'https://app.example.com/' }).allowedOrigins, ['https://app.example.com']);
+ assert.deepEqual(
+ config({ FRONTEND_URL: 'https://app.example.com', ALLOWED_ORIGINS: ' https://preview.example.pages.dev , not a url,https://app.example.com/x' }).allowedOrigins,
+ ['https://app.example.com', 'https://preview.example.pages.dev'],
+ );
+});
+
+test('the Instagram OAuth urls drop trailing slashes', () => {
+ const { instagram } = config({ FRONTEND_URL: 'https://app.example.com/', BACKEND_URL: 'https://api.example.com/', INSTAGRAM_APP_ID: 'ID' });
+ assert.deepEqual(instagram, {
+ frontendUrl: 'https://app.example.com',
+ redirectUri: 'https://api.example.com/api/auth/instagram/callback',
+ appId: 'ID',
+ appSecret: undefined,
+ });
+});
diff --git a/backend/tests/middleware/errorHandler.test.ts b/backend/tests/middleware/errorHandler.test.ts
new file mode 100644
index 0000000..c6309b4
--- /dev/null
+++ b/backend/tests/middleware/errorHandler.test.ts
@@ -0,0 +1,80 @@
+import { test, describe, beforeEach, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import { Hono } from 'hono';
+import { requestId } from 'hono/request-id';
+import { errorHandler, notFoundHandler } from '../../middleware/errorHandler.ts';
+import { jsonBody } from '../../middleware/validate.ts';
+import { requiredString } from '../../validators/fields.ts';
+import { ConflictError, DatabaseError, NotFoundError, UpstreamError, ValidationError } from '../../lib/errors.ts';
+import type { AppEnv } from '../../types/app.ts';
+
+let logLines: string[] = [];
+
+beforeEach(() => {
+ logLines = [];
+ for (const method of ['log', 'warn', 'error'] as const) {
+ mock.method(console, method, (line: string) => logLines.push(line));
+ }
+});
+afterEach(() => mock.restoreAll());
+
+function buildApp() {
+ const app = new Hono<AppEnv>();
+ app.use(requestId({ generator: () => 'req-1' }));
+ app.onError(errorHandler);
+ app.notFound(notFoundHandler);
+ app.get('/not-found', () => { throw new NotFoundError('Account not found'); });
+ app.get('/conflict', () => { throw new ConflictError('This channel is already added'); });
+ app.get('/upstream', () => { throw new UpstreamError('Quota exceeded for https://www.googleapis.com/youtube/v3/videos?key=SECRET'); });
+ app.get('/database', () => { throw new DatabaseError('accounts.list', new Error('duplicate key value violates constraint')); });
+ app.get('/crash', () => { throw new TypeError('Cannot read properties of undefined'); });
+ app.post('/body', jsonBody(body => ({ name: requiredString(body, 'name', 'Name is required') })), c => c.json(c.req.valid('json')));
+ app.get('/validation', () => { throw new ValidationError('Pick a date in the future'); });
+ return app;
+}
+
+async function call(path: string, init?: RequestInit) {
+ const response = await buildApp().request(path, init);
+ return { status: response.status, body: await response.json() as Record<string, unknown> };
+}
+
+describe('error handler', () => {
+ test('each application error gets its status and the one error body', async () => {
+ assert.deepEqual(await call('/not-found'), { status: 404, body: { success: false, code: 'NOT_FOUND', message: 'Account not found', requestId: 'req-1' } });
+ assert.deepEqual(await call('/conflict'), { status: 409, body: { success: false, code: 'CONFLICT', message: 'This channel is already added', requestId: 'req-1' } });
+ assert.deepEqual(await call('/validation'), { status: 400, body: { success: false, code: 'VALIDATION_ERROR', message: 'Pick a date in the future', requestId: 'req-1' } });
+ });
+
+ test('platform errors keep their wording without the url', async () => {
+ assert.deepEqual(await call('/upstream'), { status: 502, body: { success: false, code: 'UPSTREAM_ERROR', message: 'Quota exceeded for [url]', requestId: 'req-1' } });
+ });
+
+ test('database and unexpected errors hide their details from the client but log them with the request id', async () => {
+ const database = await call('/database');
+ assert.deepEqual(database, { status: 500, body: { success: false, code: 'DATABASE_ERROR', message: 'The database request failed. Try again in a moment.', requestId: 'req-1' } });
+ const crash = await call('/crash');
+ assert.equal(crash.status, 500);
+ assert.equal(crash.body.code, 'INTERNAL_ERROR');
+ assert.equal(JSON.stringify(crash.body).includes('Cannot read'), false);
+
+ const logged = logLines.map(line => JSON.parse(line) as Record<string, unknown>);
+ assert.deepEqual(logged.map(line => [line.level, line.requestId, line.cause ?? line.error]), [
+ ['error', 'req-1', 'duplicate key value violates constraint'],
+ ['error', 'req-1', 'Cannot read properties of undefined'],
+ ]);
+ });
+
+ test('validation runs before the handler: missing fields and malformed JSON are 400s', async () => {
+ const json = (body: string) => ({ method: 'POST', body, headers: { 'Content-Type': 'application/json' } });
+ assert.deepEqual(await call('/body', json('{"name":" Ribbon "}')), { status: 200, body: { name: 'Ribbon' } });
+ assert.deepEqual(await call('/body', json('{}')), { status: 400, body: { success: false, code: 'VALIDATION_ERROR', message: 'Name is required', requestId: 'req-1' } });
+ assert.deepEqual(await call('/body', json('[1]')), { status: 400, body: { success: false, code: 'VALIDATION_ERROR', message: 'The request body must be a JSON object', requestId: 'req-1' } });
+ const malformed = await call('/body', json('{not json'));
+ assert.equal(malformed.status, 400);
+ assert.equal(malformed.body.code, 'VALIDATION_ERROR');
+ });
+
+ test('an unknown route is a 404 in the same shape', async () => {
+ assert.deepEqual(await call('/nope'), { status: 404, body: { success: false, code: 'NOT_FOUND', message: 'No API route matches GET /nope', requestId: 'req-1' } });
+ });
+});
diff --git a/backend/tests/repositories/accountRepository.test.ts b/backend/tests/repositories/accountRepository.test.ts
new file mode 100644
index 0000000..c02a225
--- /dev/null
+++ b/backend/tests/repositories/accountRepository.test.ts
@@ -0,0 +1,43 @@
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import { createAccountRepository } from '../../repositories/accountRepository.ts';
+import { DatabaseError, NotFoundError } from '../../lib/errors.ts';
+import { fakeSupabase, accountRow } from '../fixtures/fakeSupabase.ts';
+import type { SupabaseClient } from '../../types/app.ts';
+
+const ROWS = [
+ accountRow({ id: 'a1', platform: 'youtube', title: 'Mine' }),
+ accountRow({ id: 'a2', platform: 'reddit', username: 'theirs' }, 'user-2'),
+];
+
+describe('account repository', () => {
+ test('user methods only see the user\'s rows; system methods see every row', async () => {
+ const accounts = createAccountRepository(fakeSupabase(ROWS));
+ assert.deepEqual((await accounts.listForUser('user-1')).map(account => account.id), ['a1']);
+ assert.deepEqual((await accounts.listAll()).map(account => account.id), ['a1', 'a2']);
+ assert.equal(await accounts.findForUser('a2', 'user-1'), null);
+ assert.deepEqual(await accounts.findById('a2'), { id: 'a2', platform: 'reddit', username: 'theirs' });
+ });
+
+ test('an update merges into data and keeps the platform', async () => {
+ const db = fakeSupabase(ROWS);
+ const accounts = createAccountRepository(db);
+ await accounts.updateForUser('a1', { subscriberCount: 5 }, 'user-1');
+ assert.deepEqual(await accounts.findForUser('a1', 'user-1'), { id: 'a1', platform: 'youtube', title: 'Mine', subscriberCount: 5 });
+ assert.deepEqual(db.calls.at(-2)?.filters, [['id', 'a1'], ['user_id', 'user-1']]);
+ });
+
+ test('updating an account the user does not own is not found', async () => {
+ const accounts = createAccountRepository(fakeSupabase(ROWS));
+ await assert.rejects(accounts.updateForUser('a2', { title: 'x' }, 'user-1'), NotFoundError);
+ });
+
+ test('a failing query becomes a DatabaseError that hides the driver message', async () => {
+ const broken = { from() { throw new Error('relation "accounts" does not exist'); } } as unknown as SupabaseClient;
+ const failure = await createAccountRepository(broken).listForUser('user-1').catch((err: unknown) => err);
+ assert.ok(failure instanceof DatabaseError);
+ assert.equal(failure.operation, 'accounts.listForUser');
+ assert.equal(failure.message, 'The database request failed. Try again in a moment.');
+ assert.equal((failure.cause as Error).message, 'relation "accounts" does not exist');
+ });
+});
diff --git a/backend/tests/repositories/analyticsCacheRepository.test.ts b/backend/tests/repositories/analyticsCacheRepository.test.ts
new file mode 100644
index 0000000..680b7cd
--- /dev/null
+++ b/backend/tests/repositories/analyticsCacheRepository.test.ts
@@ -0,0 +1,99 @@
+import { test, beforeEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import { createAnalyticsCacheRepository, resetCacheState } from '../../repositories/analyticsCacheRepository.ts';
+import type { Redis } from '../../types/app.ts';
+import type { VideosCacheData, YouTubeVideo } from '../../../shared/types/youtube.ts';
+import type { IGCacheData } from '../../../shared/types/instagram.ts';
+import type { RedditCacheData } from '../../../shared/types/reddit.ts';
+
+type MemoryRedis = Redis & { store: Map<string, unknown> };
+
+function memoryRedis(): MemoryRedis {
+ const store = new Map<string, unknown>();
+ return {
+ store,
+ get: async (key: string) => store.get(key) ?? null,
+ set: async (key: string, value: unknown, options: unknown) => { store.set(key, value); store.set(`${key}:options`, options); },
+ del: async (key: string) => { store.delete(key); },
+ } as unknown as MemoryRedis;
+}
+
+const failingRedis = {
+ get: async () => { throw new Error('down'); },
+ set: async () => { throw new Error('down'); },
+ del: async () => { throw new Error('down'); },
+} as unknown as Redis;
+
+beforeEach(() => resetCacheState());
+
+test('every method is a no-op without redis', async () => {
+ const cache = createAnalyticsCacheRepository(null);
+ assert.equal(cache.enabled, false);
+ assert.equal(await cache.getVideos('u', 'a'), null);
+ assert.equal(await cache.getInstagramMedia('u', 'a'), null);
+ assert.equal(await cache.getReddit('u', 'a'), null);
+ assert.equal(await cache.setVideos('u', 'a', {} as VideosCacheData), undefined);
+ assert.equal(await cache.deleteAllForAccount('u', 'a'), undefined);
+});
+
+test('redis failures fall back silently', async () => {
+ const cache = createAnalyticsCacheRepository(failingRedis);
+ assert.equal(await cache.getVideos('u', 'a'), null);
+ assert.equal(await cache.getReddit('u', 'a'), null);
+ assert.equal(await cache.setVideos('u', 'a', { videos: [] } as unknown as VideosCacheData), undefined);
+ assert.equal(await cache.setReddit('u', 'a', {} as RedditCacheData), undefined);
+ assert.equal(await cache.deleteAllForAccount('u', 'a'), undefined);
+});
+
+test('video entries round-trip with a version and a 6 hour expiry', async () => {
+ const redis = memoryRedis();
+ const cache = createAnalyticsCacheRepository(redis);
+ await cache.setVideos('u', 'a', { videos: [1] as unknown as YouTubeVideo[] } as VideosCacheData);
+
+ assert.deepEqual(await cache.getVideos('u', 'a'), { videos: [1], version: 2 });
+ assert.deepEqual(redis.store.get('videos:u:a:options'), { ex: 21600 });
+});
+
+test('entries written by older code read as a miss', async () => {
+ const redis = memoryRedis();
+ redis.store.set('videos:u:a', { videos: [1] });
+ redis.store.set('ig:u:a', { media: [], version: 1 });
+ const cache = createAnalyticsCacheRepository(redis);
+
+ assert.equal(await cache.getVideos('u', 'a'), null);
+ assert.equal(await cache.getInstagramMedia('u', 'a'), null);
+});
+
+test('deleting an account removes all three of its entries', async () => {
+ const redis = memoryRedis();
+ const cache = createAnalyticsCacheRepository(redis);
+ await cache.setInstagramMedia('u', 'a', { media: [] } as unknown as IGCacheData);
+ await cache.setVideos('u', 'a', { videos: [] } as unknown as VideosCacheData);
+ await cache.setReddit('u', 'a', { posts: [] } as unknown as RedditCacheData);
+ await cache.setVideos('u', 'other', { videos: [] } as unknown as VideosCacheData);
+ await cache.deleteAllForAccount('u', 'a');
+
+ assert.equal(await cache.getVideos('u', 'a'), null);
+ assert.equal(await cache.getInstagramMedia('u', 'a'), null);
+ assert.equal(await cache.getReddit('u', 'a'), null);
+ assert.deepEqual(await cache.getVideos('u', 'other'), { videos: [], version: 2 });
+});
+
+test('after a failure redis is skipped for 30 seconds, then tried again', async () => {
+ mock.timers.enable({ apis: ['Date'], now: 1_000_000 });
+ try {
+ let calls = 0;
+ const flaky = createAnalyticsCacheRepository({ get: async () => { calls++; throw new Error('down'); } } as unknown as Redis);
+ const healthy = createAnalyticsCacheRepository(memoryRedis());
+ await healthy.setVideos('u', 'a', { videos: [] } as unknown as VideosCacheData);
+
+ assert.equal(await flaky.getVideos('u', 'a'), null);
+ assert.equal(await healthy.getVideos('u', 'a'), null);
+ assert.equal(calls, 1);
+
+ mock.timers.tick(30_000);
+ assert.deepEqual(await healthy.getVideos('u', 'a'), { videos: [], version: 2 });
+ } finally {
+ mock.timers.reset();
+ }
+});
diff --git a/backend/tests/validators/fields.test.ts b/backend/tests/validators/fields.test.ts
new file mode 100644
index 0000000..d66a5bb
--- /dev/null
+++ b/backend/tests/validators/fields.test.ts
@@ -0,0 +1,30 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ objectBody, requiredString, optionalString, optionalBoolean, optionalNumber, optionalArray, isString, presentField,
+} from '../../validators/fields.ts';
+import { ValidationError } from '../../lib/errors.ts';
+
+test('strings are trimmed, and a blank required string is missing', () => {
+ assert.equal(requiredString({ name: ' Ribbon ' }, 'name'), 'Ribbon');
+ assert.throws(() => requiredString({ name: ' ' }, 'name', 'Name is required'), new ValidationError('Name is required'));
+ assert.throws(() => requiredString({}, 'name'), { message: 'name is required' });
+ assert.throws(() => optionalString({ name: 3 }, 'name'), { message: 'name must be text' });
+ assert.equal(optionalString({ name: null }, 'name'), undefined);
+});
+
+test('booleans, numbers and lists are checked by type', () => {
+ assert.equal(optionalBoolean({ flag: false }, 'flag'), false);
+ assert.throws(() => optionalBoolean({ flag: 'yes' }, 'flag'), { message: 'flag must be true or false' });
+ assert.equal(optionalNumber({ offset: 2.5 }, 'offset'), 2.5);
+ assert.throws(() => optionalNumber({ offset: Number.NaN }, 'offset'), { message: 'offset must be a number' });
+ assert.deepEqual(optionalArray({ tags: ['a'] }, 'tags', isString, 'names'), ['a']);
+ assert.throws(() => optionalArray({ tags: ['a', 1] }, 'tags', isString, 'names'), { message: 'tags must be a list of names' });
+});
+
+test('the body must be an object, and a field sent as null is still present', () => {
+ assert.throws(() => objectBody([]), { message: 'The request body must be a JSON object' });
+ assert.throws(() => objectBody(null), ValidationError);
+ assert.equal(presentField({ imageUrl: null }, 'imageUrl'), true);
+ assert.equal(presentField({}, 'imageUrl'), false);
+});
diff --git a/backend/types/app.ts b/backend/types/app.ts
index bad2c9c..bac91f7 100644
--- a/backend/types/app.ts
+++ b/backend/types/app.ts
@@ -5,12 +5,18 @@ import type { Env } from './env.ts';
export type { SupabaseClient, Redis };
-// set by the client middleware in server.ts for every request, and by requireAuth under /api
+// small request-scoped values only: identity, tracing, cancellation, and the per-request clients
export interface AppVariables {
+ // set by hono's requestId() and returned in X-Request-Id
+ requestId: string;
+ // set by requestContext: aborts on client disconnect or at the request deadline
+ signal: AbortSignal;
+ // set by the clients middleware for every request
supabase: SupabaseClient;
redis: Redis | null;
// a separate client that fails fast; see getRateLimitRedis()
rateLimitRedis: Redis | null;
+ // set by requireAuth on protected routes, from the verified JWT only
userId: string;
userEmail: string | undefined;
}
diff --git a/backend/types/context.ts b/backend/types/context.ts
new file mode 100644
index 0000000..88d31b0
--- /dev/null
+++ b/backend/types/context.ts
@@ -0,0 +1,9 @@
+import type { Logger } from '../lib/logger.ts';
+
+// the request metadata services may read, free of Hono types so a cron job can build one too
+export interface RequestContext {
+ requestId: string;
+ // aborts when the client disconnects or the deadline passes; platform calls hand it to fetch
+ signal: AbortSignal;
+ log: Logger;
+}
diff --git a/backend/types/env.ts b/backend/types/env.ts
index 80e18eb..a957ef1 100644
--- a/backend/types/env.ts
+++ b/backend/types/env.ts
@@ -10,6 +10,8 @@ export interface Env {
CLOUDINARY_UPLOAD_PRESET?: string;
BACKEND_URL?: string;
FRONTEND_URL?: string;
+ // comma-separated extra browser origins allowed by CORS, besides FRONTEND_URL
+ ALLOWED_ORIGINS?: string;
UPSTASH_REDIS_REST_URL?: string;
UPSTASH_REDIS_REST_TOKEN?: string;
}
diff --git a/backend/validators/fields.ts b/backend/validators/fields.ts
new file mode 100644
index 0000000..3b86f09
--- /dev/null
+++ b/backend/validators/fields.ts
@@ -0,0 +1,62 @@
+import { ValidationError } from '../lib/errors.ts';
+
+export type Fields = Record<string, unknown>;
+
+export function objectBody(value: unknown): Fields {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ throw new ValidationError('The request body must be a JSON object');
+ }
+ return value as Fields;
+}
+
+function isMissing(value: unknown): value is null | undefined {
+ return value === undefined || value === null;
+}
+
+// trimmed; an empty or blank value counts as missing
+export function requiredString(fields: Fields, name: string, message = `${name} is required`): string {
+ const value = optionalString(fields, name);
+ if (!value) throw new ValidationError(message);
+ return value;
+}
+
+export function optionalString(fields: Fields, name: string): string | undefined {
+ const value = fields[name];
+ if (isMissing(value)) return undefined;
+ if (typeof value !== 'string') throw new ValidationError(`${name} must be text`);
+ return value.trim();
+}
+
+export function optionalBoolean(fields: Fields, name: string): boolean | undefined {
+ const value = fields[name];
+ if (isMissing(value)) return undefined;
+ if (typeof value !== 'boolean') throw new ValidationError(`${name} must be true or false`);
+ return value;
+}
+
+export function optionalNumber(fields: Fields, name: string): number | undefined {
+ const value = fields[name];
+ if (isMissing(value)) return undefined;
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw new ValidationError(`${name} must be a number`);
+ return value;
+}
+
+export function optionalArray<T>(fields: Fields, name: string, isItem: (item: unknown) => item is T, itemDescription: string): T[] | undefined {
+ const value = fields[name];
+ if (isMissing(value)) return undefined;
+ if (!Array.isArray(value) || !value.every(isItem)) throw new ValidationError(`${name} must be a list of ${itemDescription}`);
+ return value;
+}
+
+export function isString(item: unknown): item is string {
+ return typeof item === 'string';
+}
+
+export function isObject(item: unknown): item is Fields {
+ return typeof item === 'object' && item !== null && !Array.isArray(item);
+}
+
+// a field the client may send as a value, as null to clear it, or leave out to keep it
+export function presentField(fields: Fields, name: string): boolean {
+ return Object.prototype.hasOwnProperty.call(fields, name) && fields[name] !== undefined;
+}
diff --git a/shared/types/domain.ts b/shared/types/domain.ts
index ba3f702..0300c9c 100644
--- a/shared/types/domain.ts
+++ b/shared/types/domain.ts
@@ -276,10 +276,18 @@ export interface KeysStatusResponse {
cloudinary: KeyStatus;
}
-// the failure body most routes send; request() only passes it on when the status is 2xx
+export type ApiErrorCode =
+ | 'VALIDATION_ERROR' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | 'CONFLICT' | 'RATE_LIMITED'
+ | 'UPSTREAM_ERROR' | 'UPSTREAM_TIMEOUT' | 'NOT_CONFIGURED' | 'DATABASE_ERROR' | 'INTERNAL_ERROR';
+
+// the one body every failed request gets, from the error handler or the rate limiter, always with a 4xx or 5xx status
export interface ApiFailure {
success: false;
+ code: ApiErrorCode;
message: string;
+ requestId?: string;
+ // seconds, on 429 only
+ retryAfter?: number;
}
// DELETE /api/accounts/:id, DELETE /api/tracked-content/:id and PUT /api/settings/github