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): finish Instagram sign-in only for the person who started it

spacesdrive79bcaa60fb0a
diff --git a/backend/controllers/instagramAuthController.ts b/backend/controllers/instagramAuthController.ts
index 20f0ae2..e087fd6 100644
--- a/backend/controllers/instagramAuthController.ts
+++ b/backend/controllers/instagramAuthController.ts
@@ -1,9 +1,9 @@
import { controller, servicesFor } from './http.ts';
-import { queryParams } from '../middleware/validate.ts';
+import { jsonBody, queryParams } from '../middleware/validate.ts';
import { requestLogger } from '../middleware/requestContext.ts';
-import { parseInstagramCallback } from '../validators/instagramAuthValidators.ts';
+import { parseInstagramCallback, parseInstagramComplete } from '../validators/instagramAuthValidators.ts';
import { errorFields } from '../lib/logger.ts';
-import type { InstagramAuthUrlResponse } from '../../shared/types/instagram.ts';
+import type { InstagramAuthUrlResponse, InstagramConnectCompleteResponse } from '../../shared/types/instagram.ts';
// protected: the signed state carries the user id to the public callback
export const getInstagramAuthUrl = controller.createHandlers(async c => {
@@ -11,7 +11,9 @@ export const getInstagramAuthUrl = controller.createHandlers(async c => {
return c.json({ url } satisfies InstagramAuthUrlResponse);
});
-// public: Instagram sends the browser here, so every outcome is a redirect back to the accounts page
+// public: Instagram sends the browser here. The state proves the sign-in came from this app, but not who opened the
+// link, so the code goes back to the app in the fragment, which never reaches a server or a referrer, and the
+// signed-in person finishes the connection through the complete route
export const handleInstagramCallback = controller.createHandlers(queryParams(parseInstagramCallback), async c => {
const { code, state, error, errorReason } = c.req.valid('query');
const connect = servicesFor(c).instagramConnect;
@@ -21,12 +23,17 @@ export const handleInstagramCallback = controller.createHandlers(queryParams(par
if (!connect.configured) return backToAccounts('ig_error=not_configured');
try {
- const userId = await connect.userIdFromState(state);
- if (!userId) return backToAccounts('ig_error=invalid_state');
- const outcome = await connect.connect(userId, code);
- return backToAccounts(outcome === 'reconnected' ? 'ig_connected=reconnected' : 'ig_connected=true');
+ if (!await connect.userIdFromState(state)) return backToAccounts('ig_error=invalid_state');
} catch (err) {
- requestLogger(c).error('instagram connection failed', errorFields(err));
- return backToAccounts(`ig_error=${encodeURIComponent((err as Error).message.substring(0, 100))}`);
+ requestLogger(c).error('instagram callback failed', errorFields(err));
+ return backToAccounts('ig_error=invalid_state');
}
+ return c.redirect(`${connect.accountsPageUrl}#ig_code=${encodeURIComponent(code)}&ig_state=${encodeURIComponent(state)}`);
+});
+
+// protected: connects the account only when the sign-in was started by the person now signed in
+export const completeInstagramConnection = controller.createHandlers(jsonBody(parseInstagramComplete), async c => {
+ const { code, state } = c.req.valid('json');
+ const outcome = await servicesFor(c).instagramConnect.completeForUser(c.get('userId'), code, state);
+ return c.json({ success: true, outcome } satisfies InstagramConnectCompleteResponse);
});
diff --git a/backend/lib/rateLimit/rules.ts b/backend/lib/rateLimit/rules.ts
index 497a299..115f606 100644
--- a/backend/lib/rateLimit/rules.ts
+++ b/backend/lib/rateLimit/rules.ts
@@ -48,6 +48,7 @@ export const QUOTA_ROUTES: readonly RouteMatcher[] = [
{ methods: ['POST'], path: /^\/api\/accounts\/(instagram|refresh-all)$/ },
{ methods: ['POST'], path: /^\/api\/accounts\/[^/]+\/(refresh|refresh-ig-token)$/ },
{ methods: ['POST'], path: /^\/api\/resolve-channel$/ },
+ { methods: ['POST'], path: /^\/api\/auth\/instagram\/complete$/ },
{ methods: ['POST'], path: /^\/api\/tracked-content$/ },
{ methods: ['POST'], path: /^\/api\/tracked-content\/[^/]+\/refresh$/ },
{ methods: ['GET', 'POST'], path: /^\/api\/process-scheduled$/ },
diff --git a/backend/routes/instagramAuthRoutes.ts b/backend/routes/instagramAuthRoutes.ts
index bc5f14e..a7f43c2 100644
--- a/backend/routes/instagramAuthRoutes.ts
+++ b/backend/routes/instagramAuthRoutes.ts
@@ -1,9 +1,10 @@
import { Hono } from 'hono';
-import { getInstagramAuthUrl } from '../controllers/instagramAuthController.ts';
+import { completeInstagramConnection, getInstagramAuthUrl } from '../controllers/instagramAuthController.ts';
import type { AppEnv } from '../types/app.ts';
const router = new Hono<AppEnv>();
router.get('/auth/instagram/url', ...getInstagramAuthUrl);
+router.post('/auth/instagram/complete', ...completeInstagramConnection);
export default router;
diff --git a/backend/services/instagramConnectService.ts b/backend/services/instagramConnectService.ts
index 8a9344c..4951152 100644
--- a/backend/services/instagramConnectService.ts
+++ b/backend/services/instagramConnectService.ts
@@ -2,7 +2,7 @@ import { buildAuthorizationUrl, exchangeCodeForToken, isOAuthConfigured, upgrade
import { fetchInstagramProfile } from './instagram/instagramApi.ts';
import { buildInstagramAccount, tokenExpiryIso } from './accountFactory.ts';
import { verifyOAuthState } from '../lib/oauthState.ts';
-import { NotConfiguredError, ValidationError, isUniqueViolation } from '../lib/errors.ts';
+import { ForbiddenError, NotConfiguredError, ValidationError, isUniqueViolation } from '../lib/errors.ts';
import type { ConfiguredInstagramOAuth } from './instagram/instagramOAuth.ts';
import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { AuditRepository } from '../repositories/auditRepository.ts';
@@ -25,6 +25,8 @@ export interface InstagramConnectService {
authorizationUrl(userId: string): Promise<string>;
userIdFromState(state: string): Promise<string | null>;
connect(userId: string, code: string): Promise<InstagramConnectOutcome>;
+ // the signed-in person finishes a sign-in only they started, so a consent link sent by someone else connects nothing
+ completeForUser(userId: string, code: string, state: string): Promise<InstagramConnectOutcome>;
}
// connects an account through Instagram's OAuth: the user id travels in the signed state, not in a session
@@ -37,7 +39,7 @@ export function createInstagramConnectService({ accounts, audit, config, context
return oauth;
}
- return {
+ const service: InstagramConnectService = {
configured: isOAuthConfigured(oauth),
accountsPageUrl: `${oauth.frontendUrl}/accounts`,
@@ -77,5 +79,13 @@ export function createInstagramConnectService({ accounts, audit, config, context
await audit.recordForUser(userId, { action: 'account.connected', subjectType: 'account', subjectId: account.id, details: { platform: 'instagram' } });
return 'connected';
},
+
+ async completeForUser(userId, code, state) {
+ const startedBy = await verifyOAuthState(state, configured().appSecret);
+ if (!startedBy) throw new ValidationError('This Instagram sign-in expired or was changed. Connect the account again.');
+ if (startedBy !== userId) throw new ForbiddenError('This Instagram sign-in was started from a different Twiligent account. Start it again from your Accounts page.');
+ return service.connect(userId, code);
+ },
};
+ return service;
}
diff --git a/backend/tests/fixtures/instagramAuth.callback.golden.json b/backend/tests/fixtures/instagramAuth.callback.golden.json
index 7682ddc..0348667 100644
--- a/backend/tests/fixtures/instagramAuth.callback.golden.json
+++ b/backend/tests/fixtures/instagramAuth.callback.golden.json
@@ -33,37 +33,7 @@
{
"status": 302,
"body": "",
- "location": "https://app.example.com/accounts?ig_connected=true"
- },
- {
- "status": 302,
- "body": "",
- "location": "https://app.example.com/accounts?ig_connected=true"
- },
- {
- "status": 302,
- "body": "",
- "location": "https://app.example.com/accounts?ig_connected=reconnected"
- },
- {
- "status": 302,
- "body": "",
- "location": "https://app.example.com/accounts?ig_error=Could%20not%20get%20Instagram%20User%20ID.%20Account%20must%20be%20a%20Business%20or%20Creator%20account."
- },
- {
- "status": 302,
- "body": "",
- "location": "https://app.example.com/accounts?ig_error=Invalid%20authorization%20code"
- },
- {
- "status": 302,
- "body": "",
- "location": "https://app.example.com/accounts?ig_error=%7B%22unexpected%22%3A%22xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
- },
- {
- "status": 302,
- "body": "",
- "location": "https://app.example.com/accounts?ig_error=Instagram%20API%20unreachable%20(getaddrinfo%20ENOTFOUND%20api.instagram.com)"
+ "location": "https://app.example.com/accounts#ig_code=good%23_&ig_state=dXNlci0xOjE3ODgyNjQwMDAwMDA.kPwa14uVn6c44E1UPm5jQWV7kLuUxf75IOfMu8CrWTo"
},
{
"status": 302,
@@ -71,280 +41,7 @@
"location": "http://localhost:5173/accounts?ig_error=not_configured"
}
],
- "requests": [
- {
- "url": "https://api.instagram.com/oauth/access_token",
- "method": "POST",
- "headers": {
- "Content-Type": "application/x-www-form-urlencoded"
- },
- "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=good"
- },
- {
- "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_GOOD",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=LONG&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- },
- {
- "url": "https://api.instagram.com/oauth/access_token",
- "method": "POST",
- "headers": {
- "Content-Type": "application/x-www-form-urlencoded"
- },
- "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=fallback"
- },
- {
- "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_FALLBACK",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=SHORT_FALLBACK&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- },
- {
- "url": "https://api.instagram.com/oauth/access_token",
- "method": "POST",
- "headers": {
- "Content-Type": "application/x-www-form-urlencoded"
- },
- "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=dup"
- },
- {
- "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_DUP",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=SHORT_DUP&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- },
- {
- "url": "https://api.instagram.com/oauth/access_token",
- "method": "POST",
- "headers": {
- "Content-Type": "application/x-www-form-urlencoded"
- },
- "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=noid"
- },
- {
- "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_NOID",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=SHORT_NOID&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- },
- {
- "url": "https://api.instagram.com/oauth/access_token",
- "method": "POST",
- "headers": {
- "Content-Type": "application/x-www-form-urlencoded"
- },
- "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=bad"
- },
- {
- "url": "https://api.instagram.com/oauth/access_token",
- "method": "POST",
- "headers": {
- "Content-Type": "application/x-www-form-urlencoded"
- },
- "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=weird"
- },
- {
- "url": "https://api.instagram.com/oauth/access_token",
- "method": "POST",
- "headers": {
- "Content-Type": "application/x-www-form-urlencoded"
- },
- "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=offline"
- }
- ],
- "calls": [
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "user_id",
- "user-1"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ]
- ]
- },
- {
- "type": "insert",
- "table": "accounts",
- "values": {
- "id": "00000000-0000-4000-8000-000000000001",
- "user_id": "user-1",
- "platform": "instagram",
- "data": {
- "igUserId": "5000",
- "username": "longlived",
- "title": "Long Lived",
- "biography": "B",
- "website": "W",
- "profilePictureUrl": "P",
- "followersCount": 10,
- "followsCount": 2,
- "mediaCount": 3,
- "accessToken": "LONG",
- "tokenExpiresAt": "2026-10-31T11:59:04.000Z",
- "addedAt": "2026-09-01T12:00:00.000Z",
- "lastUpdated": "2026-09-01T12:00:00.000Z"
- }
- },
- "filters": []
- },
- {
- "type": "insert",
- "table": "audit_events",
- "values": {
- "id": "00000000-0000-4000-8000-000000000002",
- "user_id": "user-1",
- "action": "account.connected",
- "subject_type": "account",
- "subject_id": "00000000-0000-4000-8000-000000000001",
- "details": {
- "platform": "instagram"
- }
- },
- "filters": []
- },
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "user_id",
- "user-1"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ]
- ]
- },
- {
- "type": "insert",
- "table": "accounts",
- "values": {
- "id": "00000000-0000-4000-8000-000000000003",
- "user_id": "user-1",
- "platform": "instagram",
- "data": {
- "igUserId": "5001",
- "username": "fallback",
- "title": "fallback",
- "biography": "",
- "website": "",
- "profilePictureUrl": "",
- "followersCount": 0,
- "followsCount": 0,
- "mediaCount": 0,
- "accessToken": "SHORT_FALLBACK",
- "tokenExpiresAt": null,
- "addedAt": "2026-09-01T12:00:00.000Z",
- "lastUpdated": "2026-09-01T12:00:00.000Z"
- }
- },
- "filters": []
- },
- {
- "type": "insert",
- "table": "audit_events",
- "values": {
- "id": "00000000-0000-4000-8000-000000000004",
- "user_id": "user-1",
- "action": "account.connected",
- "subject_type": "account",
- "subject_id": "00000000-0000-4000-8000-000000000003",
- "details": {
- "platform": "instagram"
- }
- },
- "filters": []
- },
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "user_id",
- "user-1"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ]
- ]
- },
- {
- "type": "rpc",
- "table": "merge_account_data",
- "values": {
- "p_id": "ig1",
- "p_user_id": "user-1",
- "p_patch": {
- "accessToken": "SHORT_DUP",
- "tokenExpiresAt": null,
- "lastUpdated": "2026-09-01T12:00:00.000Z"
- }
- },
- "filters": []
- },
- {
- "type": "insert",
- "table": "audit_events",
- "values": {
- "id": "00000000-0000-4000-8000-000000000005",
- "user_id": "user-1",
- "action": "account.reconnected",
- "subject_type": "account",
- "subject_id": "ig1",
- "details": {
- "platform": "instagram"
- }
- },
- "filters": []
- }
- ],
- "logs": [
- [
- "error",
- "{\"level\":\"error\",\"message\":\"instagram connection failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"error\":\"Could not get Instagram User ID. Account must be a Business or Creator account.\",\"errorName\":\"ValidationError\"}"
- ],
- [
- "error",
- "{\"level\":\"error\",\"message\":\"instagram connection failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"error\":\"Invalid authorization code\",\"errorName\":\"UpstreamError\"}"
- ],
- [
- "error",
- "{\"level\":\"error\",\"message\":\"instagram connection failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"error\":\"{\\\"unexpected\\\":\\\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\\"}\",\"errorName\":\"UpstreamError\"}"
- ],
- [
- "error",
- "{\"level\":\"error\",\"message\":\"instagram connection failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"error\":\"Instagram API unreachable (getaddrinfo ENOTFOUND api.instagram.com)\",\"errorName\":\"UpstreamError\",\"cause\":\"getaddrinfo ENOTFOUND api.instagram.com\"}"
- ]
- ]
+ "requests": [],
+ "calls": [],
+ "logs": []
}
diff --git a/backend/tests/fixtures/instagramAuth.complete.golden.json b/backend/tests/fixtures/instagramAuth.complete.golden.json
new file mode 100644
index 0000000..6f45d7c
--- /dev/null
+++ b/backend/tests/fixtures/instagramAuth.complete.golden.json
@@ -0,0 +1,380 @@
+{
+ "responses": [
+ {
+ "status": 200,
+ "body": "{\"success\":true,\"outcome\":\"connected\"}"
+ },
+ {
+ "status": 200,
+ "body": "{\"success\":true,\"outcome\":\"reconnected\"}"
+ },
+ {
+ "status": 200,
+ "body": "{\"success\":true,\"outcome\":\"connected\"}"
+ },
+ {
+ "status": 200,
+ "body": "{\"success\":true,\"outcome\":\"reconnected\"}"
+ },
+ {
+ "status": 400,
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Could not get Instagram User ID. Account must be a Business or Creator account.\",\"requestId\":\"req-test\"}"
+ },
+ {
+ "status": 502,
+ "body": "{\"success\":false,\"code\":\"UPSTREAM_ERROR\",\"message\":\"Invalid authorization code\",\"requestId\":\"req-test\"}"
+ },
+ {
+ "status": 502,
+ "body": "{\"success\":false,\"code\":\"UPSTREAM_ERROR\",\"message\":\"{\\\"unexpected\\\":\\\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\\"}\",\"requestId\":\"req-test\"}"
+ },
+ {
+ "status": 502,
+ "body": "{\"success\":false,\"code\":\"UPSTREAM_ERROR\",\"message\":\"Instagram API unreachable (getaddrinfo ENOTFOUND api.instagram.com)\",\"requestId\":\"req-test\"}"
+ },
+ {
+ "status": 503,
+ "body": "{\"success\":false,\"code\":\"NOT_CONFIGURED\",\"message\":\"Instagram App credentials not configured on server\",\"requestId\":\"req-test\"}"
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://api.instagram.com/oauth/access_token",
+ "method": "POST",
+ "headers": {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=good"
+ },
+ {
+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_GOOD",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/me?access_token=LONG&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
+ "method": "GET"
+ },
+ {
+ "url": "https://api.instagram.com/oauth/access_token",
+ "method": "POST",
+ "headers": {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=good"
+ },
+ {
+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_GOOD",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/me?access_token=LONG&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
+ "method": "GET"
+ },
+ {
+ "url": "https://api.instagram.com/oauth/access_token",
+ "method": "POST",
+ "headers": {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=fallback"
+ },
+ {
+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_FALLBACK",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/me?access_token=SHORT_FALLBACK&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
+ "method": "GET"
+ },
+ {
+ "url": "https://api.instagram.com/oauth/access_token",
+ "method": "POST",
+ "headers": {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=dup"
+ },
+ {
+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_DUP",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/me?access_token=SHORT_DUP&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
+ "method": "GET"
+ },
+ {
+ "url": "https://api.instagram.com/oauth/access_token",
+ "method": "POST",
+ "headers": {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=noid"
+ },
+ {
+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_NOID",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/me?access_token=SHORT_NOID&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
+ "method": "GET"
+ },
+ {
+ "url": "https://api.instagram.com/oauth/access_token",
+ "method": "POST",
+ "headers": {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=bad"
+ },
+ {
+ "url": "https://api.instagram.com/oauth/access_token",
+ "method": "POST",
+ "headers": {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=weird"
+ },
+ {
+ "url": "https://api.instagram.com/oauth/access_token",
+ "method": "POST",
+ "headers": {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=offline"
+ }
+ ],
+ "calls": [
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ],
+ [
+ "platform",
+ [
+ "youtube",
+ "instagram"
+ ],
+ "in"
+ ]
+ ]
+ },
+ {
+ "type": "insert",
+ "table": "accounts",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000001",
+ "user_id": "user-1",
+ "platform": "instagram",
+ "data": {
+ "igUserId": "5000",
+ "username": "longlived",
+ "title": "Long Lived",
+ "biography": "B",
+ "website": "W",
+ "profilePictureUrl": "P",
+ "followersCount": 10,
+ "followsCount": 2,
+ "mediaCount": 3,
+ "accessToken": "LONG",
+ "tokenExpiresAt": "2026-10-31T11:59:04.000Z",
+ "addedAt": "2026-09-01T12:00:00.000Z",
+ "lastUpdated": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": []
+ },
+ {
+ "type": "insert",
+ "table": "audit_events",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000002",
+ "user_id": "user-1",
+ "action": "account.connected",
+ "subject_type": "account",
+ "subject_id": "00000000-0000-4000-8000-000000000001",
+ "details": {
+ "platform": "instagram"
+ }
+ },
+ "filters": []
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ],
+ [
+ "platform",
+ [
+ "youtube",
+ "instagram"
+ ],
+ "in"
+ ]
+ ]
+ },
+ {
+ "type": "rpc",
+ "table": "merge_account_data",
+ "values": {
+ "p_id": "00000000-0000-4000-8000-000000000001",
+ "p_user_id": "user-1",
+ "p_patch": {
+ "accessToken": "LONG",
+ "tokenExpiresAt": "2026-10-31T11:59:04.000Z",
+ "lastUpdated": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": []
+ },
+ {
+ "type": "insert",
+ "table": "audit_events",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000003",
+ "user_id": "user-1",
+ "action": "account.reconnected",
+ "subject_type": "account",
+ "subject_id": "00000000-0000-4000-8000-000000000001",
+ "details": {
+ "platform": "instagram"
+ }
+ },
+ "filters": []
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ],
+ [
+ "platform",
+ [
+ "youtube",
+ "instagram"
+ ],
+ "in"
+ ]
+ ]
+ },
+ {
+ "type": "insert",
+ "table": "accounts",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000004",
+ "user_id": "user-1",
+ "platform": "instagram",
+ "data": {
+ "igUserId": "5001",
+ "username": "fallback",
+ "title": "fallback",
+ "biography": "",
+ "website": "",
+ "profilePictureUrl": "",
+ "followersCount": 0,
+ "followsCount": 0,
+ "mediaCount": 0,
+ "accessToken": "SHORT_FALLBACK",
+ "tokenExpiresAt": null,
+ "addedAt": "2026-09-01T12:00:00.000Z",
+ "lastUpdated": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": []
+ },
+ {
+ "type": "insert",
+ "table": "audit_events",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000005",
+ "user_id": "user-1",
+ "action": "account.connected",
+ "subject_type": "account",
+ "subject_id": "00000000-0000-4000-8000-000000000004",
+ "details": {
+ "platform": "instagram"
+ }
+ },
+ "filters": []
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "user_id",
+ "user-1"
+ ],
+ [
+ "platform",
+ [
+ "youtube",
+ "instagram"
+ ],
+ "in"
+ ]
+ ]
+ },
+ {
+ "type": "rpc",
+ "table": "merge_account_data",
+ "values": {
+ "p_id": "ig1",
+ "p_user_id": "user-1",
+ "p_patch": {
+ "accessToken": "SHORT_DUP",
+ "tokenExpiresAt": null,
+ "lastUpdated": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": []
+ },
+ {
+ "type": "insert",
+ "table": "audit_events",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000006",
+ "user_id": "user-1",
+ "action": "account.reconnected",
+ "subject_type": "account",
+ "subject_id": "ig1",
+ "details": {
+ "platform": "instagram"
+ }
+ },
+ "filters": []
+ }
+ ],
+ "logs": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"UPSTREAM_ERROR\",\"status\":502,\"error\":\"Invalid authorization code\",\"errorName\":\"UpstreamError\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"UPSTREAM_ERROR\",\"status\":502,\"error\":\"{\\\"unexpected\\\":\\\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\\"}\",\"errorName\":\"UpstreamError\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"UPSTREAM_ERROR\",\"status\":502,\"error\":\"Instagram API unreachable (getaddrinfo ENOTFOUND api.instagram.com)\",\"errorName\":\"UpstreamError\",\"cause\":\"getaddrinfo ENOTFOUND api.instagram.com\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"Instagram App credentials not configured on server\",\"errorName\":\"NotConfiguredError\"}"
+ ]
+ ]
+}
diff --git a/backend/tests/routes/instagramAuthRoutes.test.ts b/backend/tests/routes/instagramAuthRoutes.test.ts
index b9e099b..7e08962 100644
--- a/backend/tests/routes/instagramAuthRoutes.test.ts
+++ b/backend/tests/routes/instagramAuthRoutes.test.ts
@@ -2,7 +2,8 @@
process.removeAllListeners('warning');
import { test, describe, before, after, beforeEach, afterEach, mock } from 'node:test';
-import { getInstagramAuthUrl, handleInstagramCallback } from '../../controllers/instagramAuthController.ts';
+import assert from 'node:assert/strict';
+import { completeInstagramConnection, getInstagramAuthUrl, handleInstagramCallback } from '../../controllers/instagramAuthController.ts';
import { createOAuthState } from '../../lib/oauthState.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
@@ -66,11 +67,12 @@ afterEach(() => {
mock.restoreAll();
});
-function buildApp(supabase: FakeSupabase) {
+function buildApp(supabase: FakeSupabase, userId = 'user-1') {
return mountWithContext(app => {
app.get('/url', ...getInstagramAuthUrl);
app.get('/callback', ...handleInstagramCallback);
- }, { supabase, userId: 'user-1' });
+ app.post('/complete', ...completeInstagramConnection);
+ }, { supabase, userId });
}
describe('instagram oauth golden output', () => {
@@ -85,7 +87,7 @@ describe('instagram oauth golden output', () => {
assertGolden({ responses, logs: logLines }, 'instagramAuth.url');
});
- test('handles every callback outcome', async () => {
+ test('the callback only checks the state and hands the code to the app, connecting nothing itself', async () => {
const supabase = fakeSupabase([accountRow({ id: 'ig1', platform: 'instagram', igUserId: '1789', username: 'ribbon' })]);
const app = buildApp(supabase);
const validState = encodeURIComponent(await createOAuthState('user-1', 'APPSECRET'));
@@ -103,16 +105,41 @@ describe('instagram oauth golden output', () => {
'/callback?code=good&state=no-separator',
`/callback?code=good&state=${validState}x`,
`/callback?code=good%23_&state=${validState}`,
- `/callback?code=fallback&state=${validState}`,
- `/callback?code=dup&state=${validState}`,
- `/callback?code=noid&state=${validState}`,
- `/callback?code=bad&state=${validState}`,
- `/callback?code=weird&state=${validState}`,
- `/callback?code=offline&state=${validState}`,
];
const responses = [];
for (const path of paths) responses.push(await callRoute(app, 'GET', path, { env: ENV }));
responses.push(await callRoute(app, 'GET', `/callback?code=good&state=${validState}`, { env: {} }));
assertGolden({ responses, requests: fetchMock!.requests, calls: supabase.calls, logs: logLines }, 'instagramAuth.callback');
});
+
+ test('the signed-in person who started the sign-in completes it, through every exchange outcome', async () => {
+ const supabase = fakeSupabase([accountRow({ id: 'ig1', platform: 'instagram', igUserId: '1789', username: 'ribbon' })]);
+ const app = buildApp(supabase);
+ const state = await createOAuthState('user-1', 'APPSECRET');
+ const responses = [];
+ for (const code of ['good', 'good#_', 'fallback', 'dup', 'noid', 'bad', 'weird', 'offline']) {
+ responses.push(await callRoute(app, 'POST', '/complete', { json: { code, state }, env: ENV }));
+ }
+ responses.push(await callRoute(app, 'POST', '/complete', { json: { code: 'good', state }, env: {} }));
+ assertGolden({ responses, requests: fetchMock!.requests, calls: supabase.calls, logs: logLines }, 'instagramAuth.complete');
+ });
+});
+
+describe('instagram sign-in started by someone else', () => {
+ test('a consent link made by one person and completed by another connects nothing and calls Instagram never', async () => {
+ const supabase = fakeSupabase();
+ const attackersState = await createOAuthState('attacker', 'APPSECRET');
+ const victim = buildApp(supabase, 'victim');
+ const response = await callRoute(victim, 'POST', '/complete', { json: { code: 'good', state: attackersState }, env: ENV });
+ assert.equal(response.status, 403);
+ assert.equal(fetchMock!.requests.length, 0);
+ assert.equal(supabase.table.length, 0);
+ });
+
+ test('a tampered or expired state is refused before any exchange', async () => {
+ const app = buildApp(fakeSupabase());
+ const response = await callRoute(app, 'POST', '/complete', { json: { code: 'good', state: 'forged.state' }, env: ENV });
+ assert.equal(response.status, 400);
+ assert.equal(fetchMock!.requests.length, 0);
+ });
});
diff --git a/backend/validators/instagramAuthValidators.ts b/backend/validators/instagramAuthValidators.ts
index af84da7..253816f 100644
--- a/backend/validators/instagramAuthValidators.ts
+++ b/backend/validators/instagramAuthValidators.ts
@@ -1,5 +1,6 @@
-import { optionalString } from './fields.ts';
+import { optionalString, requiredString } from './fields.ts';
import type { Fields } from './fields.ts';
+import type { InstagramConnectCompleteRequest } from '../../shared/types/instagram.ts';
export interface InstagramCallbackQuery {
code?: string;
@@ -17,3 +18,11 @@ export function parseInstagramCallback(query: Fields): InstagramCallbackQuery {
errorReason: optionalString(query, 'error_reason') || undefined,
};
}
+
+// the code and state the callback forwarded; the service checks that the state belongs to the caller
+export function parseInstagramComplete(body: Fields): InstagramConnectCompleteRequest {
+ return {
+ code: requiredString(body, 'code', 'The Instagram sign-in code is missing. Connect the account again.'),
+ state: requiredString(body, 'state', 'The Instagram sign-in state is missing. Connect the account again.'),
+ };
+}
diff --git a/shared/types/instagram.ts b/shared/types/instagram.ts
index 49f99f6..3e8fce0 100644
--- a/shared/types/instagram.ts
+++ b/shared/types/instagram.ts
@@ -239,3 +239,15 @@ export interface InstagramTokenRefreshResponse {
export interface InstagramAuthUrlResponse {
url: string;
}
+
+// body of POST /api/auth/instagram/complete: what Instagram's callback handed back to the app
+export interface InstagramConnectCompleteRequest {
+ code: string;
+ state: string;
+}
+
+// POST /api/auth/instagram/complete
+export interface InstagramConnectCompleteResponse {
+ success: true;
+ outcome: 'connected' | 'reconnected';
+}