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): finish Instagram sign-in from the app as the signed-in person
spacesdrivedb0465edaafb
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.mdindex 490b166..01b8167 100644--- a/docs/architecture/frontend/API_LAYER.md+++ b/docs/architecture/frontend/API_LAYER.md@@ -194,6 +194,8 @@ wording (`singleUploadMessage` in `features/publishing/publishHelpers.ts`).The `request()` function automatically attaches the JWT. Components do not need to handle auth tokens - the API layer manages this transparently. If the user is not logged in, the token will be absent and the backend will return 401, which `request()` will throw as an error.+Instagram sign-in finishes through `api.completeInstagramConnection(code, state)`: the public OAuth callback hands the code back in the URL fragment, and this authenticated call lets the Worker check that the signed-in person started the sign-in before it connects anything.+## Base URL| Environment | Value |diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdindex e7662f1..40916d8 100644--- a/docs/architecture/frontend/FEATURES.md+++ b/docs/architecture/frontend/FEATURES.md@@ -54,7 +54,7 @@ frontend/src/│ │ ├── YouTubeAccountFields.tsx, AddAccountFooter.tsx│ │ ├── useAddAccount.ts <- Add dialog state; Back keeps typed fields, Cancel clears them│ │ ├── useAccountRefresh.ts, useAccountDelete.ts-│ │ ├── useInstagramOAuthReturn.ts <- Reads ?ig_connected, ?ig_error and ?add once, then clears them+│ │ ├── useInstagramOAuthReturn.ts <- Finishes a sign-in from #ig_code and #ig_state, reads ?ig_error and ?add, then clears them│ │ ├── platformChoices.ts <- Platform choice titles, descriptions and icons│ │ └── accountManagerData.ts <- Pure OAuth return, error text, card metrics (accountManagerData.test.ts)│ ├── publishing/diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.mdindex f448d40..f3643c0 100644--- a/docs/architecture/frontend/ROUTING.md+++ b/docs/architecture/frontend/ROUTING.md@@ -12,7 +12,7 @@ The app uses React Router 7 in `frontend/src/App.tsx`: a data router from `creat| `/docs/*` | `components/DocsRedirect.tsx` | Public. The docs live on the public site; this route replaces the location with the same path and hash under `https://twiligent.ujjwal.fyi/docs` (`docsUrl()` in `lib/docs.ts`), so old links keep working || `/` (layout) | `AppLayout` (inline) | Protected - redirects to `/login` if unauthenticated || `/` (index) | `Overview.tsx` | Default page after login |-| `/accounts` | `AccountManager.tsx` | Connect and remove accounts. `?add=1` opens the add flow; `?ig_connected` (`true`, or `reconnected` when the account was already there) and `?ig_error` report the Instagram OAuth result |+| `/accounts` | `AccountManager.tsx` | Connect and remove accounts. `?add=1` opens the add flow; Instagram sign-in returns `#ig_code=...&ig_state=...` in the fragment, which the page removes from the address and posts to `api.completeInstagramConnection` (the server connects the account only for the person who started the sign-in), or `?ig_error` when it failed or was cancelled || `/channel/:id` | `ChannelAnalytics.tsx` | `:id` = account.id for YouTube accounts || `/instagram/:id` | `InstagramAnalytics.tsx` | `:id` = account.id for Instagram accounts || `/tracked-content` | `TrackedContent.tsx` | Tracked YouTube videos - add, manage, categorize, refresh |diff --git a/frontend/src/features/accounts/accountManagerData.ts b/frontend/src/features/accounts/accountManagerData.tsindex b7436ce..b6630bd 100644--- a/frontend/src/features/accounts/accountManagerData.ts+++ b/frontend/src/features/accounts/accountManagerData.ts@@ -52,7 +52,20 @@ export function instagramErrorMessage(code: string): string {return IG_ERRORS[code] || `Instagram connection failed: ${code}. ${TESTER_HINT}`;}-// oauth returns ?ig_connected=true, ?ig_connected=reconnected or ?ig_error=...; ?add=1 opens the add flow+export interface InstagramCompletion {+ code: string;+ state: string;+}++// a finished Instagram sign-in comes back as #ig_code=...&ig_state=..., in the fragment so it never reaches a server log+export function readInstagramCompletion(hash: string): InstagramCompletion | null {+ const params = new URLSearchParams(hash.replace(/^#/, ''));+ const code = params.get('ig_code');+ const state = params.get('ig_state');+ return code && state ? { code, state } : null;+}++// a failed or cancelled sign-in returns ?ig_error=...; ?add=1 opens the add flowexport function readOAuthReturn(searchParams: URLSearchParams): OAuthReturn | null {const connected = searchParams.get('ig_connected');const igError = searchParams.get('ig_error');diff --git a/frontend/src/features/accounts/useInstagramOAuthReturn.ts b/frontend/src/features/accounts/useInstagramOAuthReturn.tsindex c2bdb36..f76044b 100644--- a/frontend/src/features/accounts/useInstagramOAuthReturn.ts+++ b/frontend/src/features/accounts/useInstagramOAuthReturn.ts@@ -1,6 +1,7 @@-import { useEffect } from 'react';+import { useEffect, useRef } from 'react';import { useSearchParams } from 'react-router-dom';-import { readOAuthReturn } from './accountManagerData';+import { api } from '../../services/api';+import { readInstagramCompletion, readOAuthReturn } from './accountManagerData';import type { AccountActionDeps } from './useAccountDelete';interface InstagramOAuthReturnDeps extends AccountActionDeps {@@ -9,6 +10,23 @@ interface InstagramOAuthReturnDeps extends AccountActionDeps {export function useInstagramOAuthReturn({ showToast, loadAccounts, setDialogOpen }: InstagramOAuthReturnDeps) {const [searchParams, setSearchParams] = useSearchParams();+ // the code works once, so a second run of the effect (strict mode, a re-render) must not send it again+ const completing = useRef(false);++ // a finished sign-in: the server connects the account only if this person started it+ useEffect(() => {+ const completion = readInstagramCompletion(window.location.hash);+ if (!completion || completing.current) return;+ completing.current = true;+ // out of the address at once, so a reload or a shared link never carries the code+ window.history.replaceState(window.history.state, '', window.location.pathname + window.location.search);+ api.completeInstagramConnection(completion.code, completion.state)+ .then(({ outcome }) => {+ showToast(outcome === 'reconnected' ? 'Instagram account reconnected' : 'Instagram account connected');+ loadAccounts();+ })+ .catch((err: unknown) => showToast(`Couldn't connect Instagram. ${(err as Error).message}`, 'error'));+ }, [showToast, loadAccounts]);useEffect(() => {const result = readOAuthReturn(searchParams);diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.tsindex d81e0ba..9efbf87 100644--- a/frontend/src/services/api.ts+++ b/frontend/src/services/api.ts@@ -8,7 +8,7 @@ import type {TrackedContentItem, TrackedContentUpdateRequest, YouTubeAccountAddResponse,} from '@shared/types/domain.ts';import type {- CloudinaryConfigResponse, InstagramAnalyticsResponse, InstagramAuthUrlResponse, InstagramContainerStatusResponse,+ CloudinaryConfigResponse, InstagramAnalyticsResponse, InstagramAuthUrlResponse, InstagramConnectCompleteResponse, InstagramContainerStatusResponse,InstagramMediaPublishResponse, InstagramMediaResponse, InstagramPublishingLimitResponse, InstagramPublishRequest,InstagramPublishResponse, InstagramTokenRefreshResponse,} from '@shared/types/instagram.ts';@@ -123,6 +123,8 @@ export const api = {// Instagram OAuth - gets the auth URL to redirect the browser togetInstagramAuthUrl: () => request<InstagramAuthUrlResponse>('/auth/instagram/url'),+ // finishes the sign-in Instagram returned in the fragment; the server checks that this person started it+ completeInstagramConnection: (code: string, state: string) => request<InstagramConnectCompleteResponse>('/auth/instagram/complete', { method: 'POST', body: JSON.stringify({ code, state }) }),addInstagramAccount: (accessToken: string) => request<AccountResponse>('/accounts/instagram', { method: 'POST', body: JSON.stringify({ accessToken }) }),refreshIGToken: (id: string) => request<InstagramTokenRefreshResponse>(`/accounts/${id}/refresh-ig-token`, { method: 'POST' }),diff --git a/frontend/tests/features/accounts/accountManagerData.test.ts b/frontend/tests/features/accounts/accountManagerData.test.tsindex 5210ca3..7114458 100644--- a/frontend/tests/features/accounts/accountManagerData.test.ts+++ b/frontend/tests/features/accounts/accountManagerData.test.ts@@ -1,7 +1,7 @@import { test } from 'node:test';import assert from 'node:assert/strict';import {- TESTER_HINT, instagramErrorMessage, readOAuthReturn, accountMetrics, accountCardHandle, visibleSections, channelFieldProblem } from '../../../src/features/accounts/accountManagerData.ts';+ TESTER_HINT, instagramErrorMessage, readInstagramCompletion, readOAuthReturn, accountMetrics, accountCardHandle, visibleSections, channelFieldProblem } from '../../../src/features/accounts/accountManagerData.ts';const params = (query: string) => new URLSearchParams(query);@@ -57,3 +57,10 @@ test('adding a channel with nothing typed points at the channel field', () => {assert.equal(channelFieldProblem(' ')?.field, 'channel');assert.equal(channelFieldProblem('@channel'), null);});++test('a finished Instagram sign-in is read from the fragment, and only with both the code and the state', () => {+ assert.deepEqual(readInstagramCompletion('#ig_code=abc%23_&ig_state=s.sig'), { code: 'abc#_', state: 's.sig' });+ assert.equal(readInstagramCompletion('#ig_code=abc'), null);+ assert.equal(readInstagramCompletion(''), null);+ assert.equal(readInstagramCompletion('#section'), null);+});