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(settings): store only the GitHub repository in settings
spacesdriveeba9c14f9a1b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7c59c57..bbddd42 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -62,6 +62,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Fixed+- Saving the scheduling repository in Settings erased the stored GitHub token and then reported `configured: false` and `patSet: false`. The unused token is no longer stored or reported: `GET /api/settings/github` returns only `repoOwner`, `repoName` and `branch`- Refreshing or loading an account without the field its platform needs (a YouTube channel id or uploads playlist, a Reddit username) called the platform with `undefined`; it now answers with a message that says to re-add the account. Channel analytics also refuse accounts on other platforms, and the analytics response no longer carries `bannerUrl` and `isLinked`, which are not account fields- Publishing and scheduling checked too little before calling Instagram: a missing Instagram app secret made the OAuth callback fail with a server error, posts for an account without a token or on another platform called `/undefined/media`, and a Reel still processing after the last status check was published anyway. Each case now fails with a message that says what to fix, and `GET /api/cloudinary-config` answers 503 instead of 200 when Cloudinary is not configured- The Instagram sign-in state is now checked in constant timediff --git a/DECISIONS.md b/DECISIONS.mdindex 2989205..95d4aea 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -276,7 +276,7 @@ Records every significant architectural decision, the alternatives considered, a## ADR-012: GitHub settings stored in Supabase `settings` table**Date:** 2024 (initial)-**Status:** Accepted+**Status:** Amended by ADR-031 (2026-10-14): only the repository is stored, no token**Decision:** GitHub PAT and repo config for the future "push to GitHub" feature are stored in the `settings` table as `key='api_keys'`.@@ -641,3 +641,18 @@ Records every significant architectural decision, the alternatives considered, a- Type stripping means no enums, namespaces or parameter properties, and type-only imports must be marked. The compiler enforces all three.- Node 22.18 is now the minimum for running tests and the publisher locally, and the GitHub Actions publisher moved from Node 20 to 24.- Some boundaries (external API JSON, test fakes) are typed by a single cast at the point where data enters, which the type checker trusts.++---++## ADR-031: GitHub settings store the repository only++**Date:** 2026-10-14+**Status:** Accepted++**Decision:** `PUT /api/settings/github` stores `{ repoOwner, repoName, branch }` under `settings.github` and nothing else; `GET` returns those three fields. The `pat` field and the derived `configured` and `patSet` flags are removed from the route and from `GitHubSettingsRequest` and `GitHubSettingsResponse`. Saving rewrites `settings.github` whole, so a token stored by an older version is deleted the next time the repository is saved.++**Context:** The Settings page stopped asking for a GitHub token because nothing read it (ADR-012's push feature was never built). Each save then wrote `pat: undefined`, which erased the stored token and made `configured` and `patSet` always false, so the response described something that no longer existed.++**Trade-offs:**+- The planned GitHub archive feature (ROADMAP.md) will need to add a token field again, with masked responses and a decision on where the secret lives.+- An unused secret is no longer kept in plaintext in the database.diff --git a/ROADMAP.md b/ROADMAP.mdindex 391876c..ac1305d 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -100,7 +100,7 @@ Bulk scheduling exists through the upload form (`features/publishing/Bulk*`), onPush published Instagram post data (caption, media URL, timestamp, engagement) to a GitHub repository as JSON or Markdown, for archiving and portfolio sites.-The backend still has `GET` and `PUT /api/settings/github` storing a token and repository in the `settings` table, but the Settings page no longer shows the field because nothing used it. Building this feature means restoring that form and adding `backend/services/github`.+`GET` and `PUT /api/settings/github` store only the repository (ADR-031). Building this feature means adding a token field back, with masked responses, and a `backend/services/github` client.---diff --git a/backend/routes/settings.ts b/backend/routes/settings.tsindex 1024ef1..0e0c2d0 100644--- a/backend/routes/settings.ts+++ b/backend/routes/settings.ts@@ -6,27 +6,24 @@ import type { GitHubSettingsRequest, GitHubSettingsResponse, SuccessResponse } fconst app = new Hono<AppEnv>();app.get('/settings/github', async (c) => {- const supabase = c.get('supabase');- const userId = c.get('userId');- const settings = await getSettings(supabase, userId);+ const settings = await getSettings(c.get('supabase'), c.get('userId'));const github = (settings.github || {}) as GitHubSettingsRequest;return c.json({- configured: !!(github.pat && github.repoOwner && github.repoName),repoOwner: github.repoOwner || '',repoName: github.repoName || '',branch: github.branch || 'main',- patSet: !!github.pat,} satisfies GitHubSettingsResponse);});+// rewrites settings.github whole, so a token saved by older versions is droppedapp.put('/settings/github', async (c) => {const supabase = c.get('supabase');const userId = c.get('userId');- const { pat, repoOwner, repoName, branch } = await c.req.json() as GitHubSettingsRequest;+ const { repoOwner, repoName, branch } = await c.req.json() as GitHubSettingsRequest;const current = await getSettings(supabase, userId);- const update = { ...current, github: { pat, repoOwner, repoName, branch: branch || 'main' } };- await saveSettings(supabase, update, userId);+ const github: GitHubSettingsResponse = { repoOwner: repoOwner || '', repoName: repoName || '', branch: branch || 'main' };+ await saveSettings(supabase, { ...current, github }, userId);return c.json({ success: true } satisfies SuccessResponse);});diff --git a/backend/tests/fixtures/fakeSupabase.ts b/backend/tests/fixtures/fakeSupabase.tsindex 7df3301..2f06c98 100644--- a/backend/tests/fixtures/fakeSupabase.ts+++ b/backend/tests/fixtures/fakeSupabase.ts@@ -6,10 +6,11 @@ export type Row = Record<string, unknown>;type Filter = [column: string, value: unknown, operator?: 'lte'];interface Action {- type: 'select' | 'update' | 'insert' | 'delete';+ type: 'select' | 'update' | 'insert' | 'upsert' | 'delete';table: string;columns?: string;values?: Row;+ onConflict?: string;}export type SupabaseCall = Action & { filters: Filter[] };@@ -85,6 +86,13 @@ export function fakeSupabase(rows: Row[] = []): FakeSupabase {const found = table.filter(row => inTable(row, action.table) && matchesFilters(row, filters));if (action.type === 'update') found.forEach(row => Object.assign(row, copy(action.values)));if (action.type === 'insert') table.push(copy(action.values!));+ if (action.type === 'upsert') {+ const values = action.values!;+ const keys = (action.onConflict ?? 'id').split(',');+ const existing = table.find(row => inTable(row, action.table) && keys.every(key => row[key] === values[key]));+ if (existing) Object.assign(existing, copy(values));+ else table.push({ _table: action.table, ...copy(values) });+ }if (action.type === 'delete') {found.forEach(row => table.splice(table.indexOf(row), 1));}@@ -99,6 +107,7 @@ export function fakeSupabase(rows: Row[] = []): FakeSupabase {select: (columns: string) => queryBuilder({ type: 'select', table: name, columns }, run),update: (values: Row) => queryBuilder({ type: 'update', table: name, values }, run),insert: (values: Row) => queryBuilder({ type: 'insert', table: name, values }, run),+ upsert: (values: Row, options: { onConflict?: string } = {}) => queryBuilder({ type: 'upsert', table: name, values, onConflict: options.onConflict }, run),delete: () => queryBuilder({ type: 'delete', table: name }, run),};},diff --git a/backend/tests/routes/settings.test.ts b/backend/tests/routes/settings.test.tsnew file mode 100644index 0000000..f0280b1--- /dev/null+++ b/backend/tests/routes/settings.test.ts@@ -0,0 +1,35 @@+import { test, describe } from 'node:test';+import assert from 'node:assert/strict';+import settingsRouter from '../../routes/settings.ts';+import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';+import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';++function settingsRow(value: Record<string, unknown>) {+ return tableRow('settings', { user_id: 'user-1', key: 'api_keys', value });+}++describe('GitHub settings routes', () => {+ test('reports the stored repository and never a token', async () => {+ const supabase = fakeSupabase([settingsRow({ github: { pat: 'OLDTOKEN', repoOwner: 'me', repoName: 'twiligent', branch: 'dev' } })]);+ const app = mountWithContext(app => app.route('/', settingsRouter), { supabase, userId: 'user-1' });+ const response = await callRoute(app, 'GET', '/settings/github');+ assert.deepEqual(JSON.parse(response.body), { repoOwner: 'me', repoName: 'twiligent', branch: 'dev' });+ });++ test('saving the repository keeps other settings and drops an old token', async () => {+ const supabase = fakeSupabase([settingsRow({ other: 1, github: { pat: 'OLDTOKEN', repoOwner: 'old', repoName: 'repo' } })]);+ const app = mountWithContext(app => app.route('/', settingsRouter), { supabase, userId: 'user-1' });+ const saved = await callRoute(app, 'PUT', '/settings/github', { json: { repoOwner: 'me', repoName: 'twiligent' } });+ assert.deepEqual(JSON.parse(saved.body), { success: true });++ assert.deepEqual(supabase.table[0].value, { other: 1, github: { repoOwner: 'me', repoName: 'twiligent', branch: 'main' } });+ const response = await callRoute(app, 'GET', '/settings/github');+ assert.deepEqual(JSON.parse(response.body), { repoOwner: 'me', repoName: 'twiligent', branch: 'main' });+ });++ test('a user without settings gets empty values', async () => {+ const app = mountWithContext(app => app.route('/', settingsRouter), { supabase: fakeSupabase([]), userId: 'user-1' });+ const response = await callRoute(app, 'GET', '/settings/github');+ assert.deepEqual(JSON.parse(response.body), { repoOwner: '', repoName: '', branch: 'main' });+ });+});diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.mdindex 399da6d..b7bec44 100644--- a/docs/architecture/OVERVIEW.md+++ b/docs/architecture/OVERVIEW.md@@ -98,7 +98,7 @@ Cloudflare scheduler fires cron trigger|---|---|---|| User accounts (auth) | Supabase Auth | Built-in JWT issuance || YouTube/Instagram accounts | `accounts` table, `data` jsonb | Flexible schema across platforms |-| User settings (GitHub PAT) | `settings` table, `value` jsonb | Generic key-value per user |+| User settings (GitHub repository) | `settings` table, `value` jsonb | Generic key-value per user || Scheduled posts | `scheduled_posts` table | Queryable by status + scheduled_at || Video/media analytics | Upstash Redis (`videos:` / `ig:` keys) | Avoids repeated heavy API calls || Media files (for publishing) | Cloudinary CDN | Instagram requires public URL |diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex f5881e3..c7579e3 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -96,8 +96,8 @@ Link detection and the manual views and image checks live in `services/trackedCo### Settings| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/settings/github` | `routes/settings.ts` | Retrieve GitHub PAT + repo config for the current user |-| PUT | `/api/settings/github` | `routes/settings.ts` | Save GitHub PAT + repo config |+| GET | `/api/settings/github` | `routes/settings.ts` | Retrieve the scheduling repository (`repoOwner`, `repoName`, `branch`) for the current user |+| PUT | `/api/settings/github` | `routes/settings.ts` | Save the scheduling repository; rewrites `settings.github`, dropping any token an older version stored |## Adding a New Routediff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdindex bea4e5d..806272e 100644--- a/docs/architecture/database/SCHEMA.md+++ b/docs/architecture/database/SCHEMA.md@@ -89,7 +89,7 @@ This means each user can have one row per `key`. Upserts use `onConflict: 'user_}```-The `api_keys` setting currently stores GitHub PAT and repo for the planned GitHub push feature. This key name is generic enough to accommodate future per-user configuration values.+The `api_keys` setting currently stores the GitHub repository (`github: { repoOwner, repoName, branch }`) used to build the scheduling guide links. No token is stored (ADR-031). This key name is generic enough to accommodate future per-user configuration values.---diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.mdindex d72aa8d..2b95311 100644--- a/docs/architecture/database/SECURITY.md+++ b/docs/architecture/database/SECURITY.md@@ -65,12 +65,9 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live**If you add a new route that returns account data, you must call `safeAccount()`.** There is no automatic stripping - it is an explicit step in route handlers.-## GitHub PAT Security+## GitHub Settings-The GitHub Personal Access Token stored in `settings.value.githubPat` is stored in plaintext in Supabase. This is acceptable for a self-hosted deployment where the user controls the Supabase instance, but:-- Never log this value-- Never include it in API responses beyond the settings endpoint-- The `GET /api/settings/github` route should consider returning a masked value (e.g., `ghp_...xxxx`) instead of the full token in the response+`settings.value.github` holds only the repository owner, name and branch. No GitHub token is stored; saving the repository deletes a token left by older versions (ADR-031). If a future feature needs a token again, it must never be logged or returned, and the settings route should report only whether one is set.## Audit Pointsdiff --git a/docs/philosophy/ARCHITECTURE.md b/docs/philosophy/ARCHITECTURE.mdindex 929b09e..22d968b 100644--- a/docs/philosophy/ARCHITECTURE.md+++ b/docs/philosophy/ARCHITECTURE.md@@ -32,7 +32,7 @@ Redis is optional infrastructure. The cache layer always catches errors and retuPlatform API credentials (Instagram app secret, YouTube API key) are Worker secrets - not in code, not in the database, not in the frontend. The only credential that goes near the frontend is the Supabase anon key, which is public by design.-User-specific tokens (Instagram access tokens, GitHub PATs) live in `accounts.data` in the database. They are read by the Worker and never returned to the frontend. See `ADR-004`.+User-specific credentials (Instagram access tokens, Reddit session cookies) live in `accounts.data` in the database. They are read by the Worker and never returned to the frontend. See `ADR-004`.### 6. Schemas bend before tables multiplydiff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.mdindex 9a49708..4644229 100644--- a/docs/philosophy/SECURITY.md+++ b/docs/philosophy/SECURITY.md@@ -11,7 +11,6 @@| YouTube API key | Worker secret | Worker only | **Never** || Cloudinary credentials | Worker secrets | Worker only | **Never** || User's Instagram access token | `accounts.data.accessToken` in DB | Worker only | **Never** |-| User's GitHub PAT | `settings` table in DB | Worker only | **Never** || Supabase JWT secret | Supabase (internal) | Supabase JWT verification | **Never** |## The Service Role Keydiff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex 96f0e72..4f3ab23 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -24,6 +24,7 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that| `backend/services/youtube.ts` | `backend/tests/services/youtube.test.ts` || `backend/routes/accounts.ts` | `backend/tests/routes/accounts.test.ts` || `backend/routes/publishing.ts` | `backend/tests/routes/publishing.test.ts` |+| `backend/routes/settings.ts` | `backend/tests/routes/settings.test.ts` || `backend/utils/scheduler.ts` | `backend/tests/utils/scheduler.test.ts` || `frontend/src/lib/accounts.ts` | `frontend/tests/lib/accounts.test.ts` || `frontend/src/features/analytics/overview/overviewStats.ts` | `frontend/tests/features/analytics/overview/overviewStats.test.ts` |diff --git a/shared/types/domain.ts b/shared/types/domain.tsindex 90214e7..ba3f702 100644--- a/shared/types/domain.ts+++ b/shared/types/domain.ts@@ -251,21 +251,18 @@ export interface OverviewResponse {analyticsCache: OverviewAnalyticsCache;}-// body of PUT /api/settings/github, stored as is under settings.github+// body of PUT /api/settings/github; the repository fills the scheduling guide linksexport interface GitHubSettingsRequest {- pat?: string;repoOwner?: string;repoName?: string;branch?: string;}-// GET /api/settings/github; the token itself is never sent back+// GET /api/settings/github, exactly what is stored under settings.githubexport interface GitHubSettingsResponse {- configured: boolean;repoOwner: string;repoName: string;branch: string;- patSet: boolean;}export interface KeyStatus {