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): remove the pasted-token and manual token refresh routes

spacesdrive1d9c75f94801
diff --git a/backend/controllers/accountController.ts b/backend/controllers/accountController.ts
index 2f996f2..a7a0ce8 100644
--- a/backend/controllers/accountController.ts
+++ b/backend/controllers/accountController.ts
@@ -1,12 +1,11 @@
import { controller, pathParam, servicesFor } from './http.ts';
import { jsonBody } from '../middleware/validate.ts';
-import { parseChannelInput, parseInstagramToken } from '../validators/accountValidators.ts';
+import { parseChannelInput } from '../validators/accountValidators.ts';
import { safeAccount } from '../lib/safeAccount.ts';
import type {
AccountListResponse, AccountRefreshAllResponse, AccountResponse, SuccessResponse, YouTubeAccountAddResponse,
} from '../../shared/types/domain.ts';
import type { ResolveChannelResponse } from '../../shared/types/youtube.ts';
-import type { InstagramTokenRefreshResponse } from '../../shared/types/instagram.ts';
// stored credentials never leave the Worker: every account in a response goes through safeAccount()
@@ -25,11 +24,6 @@ export const addYouTubeAccount = controller.createHandlers(jsonBody(parseChannel
return c.json({ success: true, account } satisfies YouTubeAccountAddResponse);
});
-export const addInstagramAccount = controller.createHandlers(jsonBody(parseInstagramToken), async c => {
- const account = await servicesFor(c).accounts.addInstagram(c.get('userId'), c.req.valid('json').accessToken);
- return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
-});
-
export const refreshAllAccounts = controller.createHandlers(async c => {
const { accounts, results } = await servicesFor(c).accounts.refreshAll(c.get('userId'));
return c.json({
@@ -45,11 +39,6 @@ export const refreshAccount = controller.createHandlers(async c => {
return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
});
-export const refreshInstagramToken = controller.createHandlers(async c => {
- const expiresAt = await servicesFor(c).accounts.refreshInstagramToken(c.get('userId'), pathParam(c, 'id'));
- return c.json({ success: true, message: 'Token refreshed for another 60 days', expiresAt } satisfies InstagramTokenRefreshResponse);
-});
-
export const deleteAccount = controller.createHandlers(async c => {
await servicesFor(c).accounts.remove(c.get('userId'), pathParam(c, 'id'));
return c.json({ success: true } satisfies SuccessResponse);
diff --git a/backend/lib/rateLimit/rules.ts b/backend/lib/rateLimit/rules.ts
index 9c96c51..296816d 100644
--- a/backend/lib/rateLimit/rules.ts
+++ b/backend/lib/rateLimit/rules.ts
@@ -51,8 +51,8 @@ interface RouteMatcher {
// paths are matched on the full request path, after the /api prefix
export const QUOTA_ROUTES: readonly RouteMatcher[] = [
{ methods: ['POST'], path: /^\/api\/accounts$/ },
- { methods: ['POST'], path: /^\/api\/accounts\/(instagram|refresh-all)$/ },
- { methods: ['POST'], path: /^\/api\/accounts\/[^/]+\/(refresh|refresh-ig-token)$/ },
+ { methods: ['POST'], path: /^\/api\/accounts\/refresh-all$/ },
+ { methods: ['POST'], path: /^\/api\/accounts\/[^/]+\/refresh$/ },
{ methods: ['POST'], path: /^\/api\/resolve-channel$/ },
{ methods: ['POST'], path: /^\/api\/auth\/instagram\/complete$/ },
{ methods: ['POST'], path: /^\/api\/tracked-content$/ },
diff --git a/backend/routes/accountRoutes.ts b/backend/routes/accountRoutes.ts
index b5bc35b..0f4c6a7 100644
--- a/backend/routes/accountRoutes.ts
+++ b/backend/routes/accountRoutes.ts
@@ -1,7 +1,6 @@
import { Hono } from 'hono';
import {
- listAccounts, resolveChannel, addYouTubeAccount, addInstagramAccount,
- refreshAllAccounts, refreshAccount, refreshInstagramToken, deleteAccount,
+ listAccounts, resolveChannel, addYouTubeAccount, refreshAllAccounts, refreshAccount, deleteAccount,
} from '../controllers/accountController.ts';
import type { AppEnv } from '../types/app.ts';
@@ -10,9 +9,7 @@ const router = new Hono<AppEnv>();
router.get('/accounts', ...listAccounts);
router.post('/resolve-channel', ...resolveChannel);
router.post('/accounts', ...addYouTubeAccount);
-router.post('/accounts/instagram', ...addInstagramAccount);
router.post('/accounts/refresh-all', ...refreshAllAccounts);
-router.post('/accounts/:id/refresh-ig-token', ...refreshInstagramToken);
router.post('/accounts/:id/refresh', ...refreshAccount);
router.delete('/accounts/:id', ...deleteAccount);
diff --git a/backend/services/accountService.ts b/backend/services/accountService.ts
index 9dff205..bd9ae55 100644
--- a/backend/services/accountService.ts
+++ b/backend/services/accountService.ts
@@ -1,7 +1,6 @@
import { resolveChannelId, fetchChannelData } from './youtube/youtubeChannels.ts';
import { fetchInstagramProfile } from './instagram/instagramApi.ts';
-import { exchangeForLongLivedToken, refreshLongLivedToken } from './instagram/instagramTokens.ts';
-import { buildYouTubeAccount, buildInstagramAccount } from './accountFactory.ts';
+import { buildYouTubeAccount } from './accountFactory.ts';
import { ConflictError, NotConfiguredError, NotFoundError, ValidationError, isUniqueViolation } from '../lib/errors.ts';
import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';
@@ -29,19 +28,11 @@ export interface AccountService {
list(userId: string): Promise<Account[]>;
resolveChannel(input: string): Promise<YouTubeChannelData>;
addYouTube(userId: string, input: string): Promise<NewAccount>;
- addInstagram(userId: string, accessToken: string): Promise<Account>;
refresh(userId: string, accountId: string): Promise<Account>;
refreshAll(userId: string): Promise<RefreshAllOutcome>;
- refreshInstagramToken(userId: string, accountId: string): Promise<string>;
remove(userId: string, accountId: string): Promise<void>;
}
-interface PastedToken {
- token: string;
- expiresIn: number;
-}
-
-const DEFAULT_TOKEN_LIFETIME_S = 5184000;
export const NO_YOUTUBE_KEY_MESSAGE = 'YouTube API key not configured on server';
const NO_TOKEN_MESSAGE = 'No access token stored - reconnect this Instagram account';
const NO_CHANNEL_MESSAGE = 'No YouTube channel ID stored - delete this channel and add it again';
@@ -75,10 +66,9 @@ function youtubeUpdates(channelData: YouTubeChannelData, full: boolean): Partial
}
const CHANNEL_ADDED = 'This channel is already added';
-const INSTAGRAM_ADDED = 'This Instagram account is already added';
export function createAccountService({ accounts, cache, audit, config, context }: AccountServiceDeps): AccountService {
- const { signal, log } = context;
+ const { signal } = context;
function youtubeKey(): string {
if (!config.youtubeApiKey) throw new NotConfiguredError(NO_YOUTUBE_KEY_MESSAGE);
@@ -101,19 +91,6 @@ export function createAccountService({ accounts, cache, audit, config, context }
return account;
}
- // a pasted token may already be long-lived, so a failed exchange keeps it as is
- async function exchangePastedToken(accessToken: string): Promise<PastedToken> {
- const appSecret = config.instagram.appSecret;
- if (!appSecret) return { token: accessToken, expiresIn: 0 };
- try {
- const longToken = await exchangeForLongLivedToken(accessToken, appSecret, signal);
- return { token: longToken.accessToken, expiresIn: longToken.expiresIn };
- } catch (err) {
- log.info('token exchange skipped; the token may already be long-lived', { reason: (err as Error).message });
- return { token: accessToken, expiresIn: 0 };
- }
- }
-
// the platform call needs these fields; a missing one is reported before any request goes out
async function fetchProfileUpdates(account: Account, full: boolean): Promise<Partial<Account>> {
if (account.platform === 'instagram') {
@@ -151,22 +128,6 @@ export function createAccountService({ accounts, cache, audit, config, context }
return account;
},
- async addInstagram(userId, accessToken) {
- const { token, expiresIn } = await exchangePastedToken(accessToken);
- const profile = await fetchInstagramProfile(null, token, signal);
- if (!profile.igUserId) {
- throw new ValidationError('Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.');
- }
- const existing = await accounts.listForUser(userId);
- if (existing.find(account => account.platform === 'instagram' && account.igUserId === profile.igUserId)) {
- throw new ConflictError(INSTAGRAM_ADDED);
- }
-
- const account = buildInstagramAccount(profile, token, expiresIn);
- await createUnlessAdded(account, userId, INSTAGRAM_ADDED);
- return account;
- },
-
async refresh(userId, accountId) {
const account = await findOwned(userId, accountId);
const updates = { lastUpdated: new Date().toISOString(), ...await fetchProfileUpdates(account, true) };
@@ -184,17 +145,6 @@ export function createAccountService({ accounts, cache, audit, config, context }
return { accounts: await accounts.listForUser(userId), results };
},
- async refreshInstagramToken(userId, accountId) {
- const account = await accounts.findForUser(accountId, userId);
- if (!account || account.platform !== 'instagram') throw new NotFoundError('Instagram account not found');
- if (!account.accessToken) throw new ValidationError(NO_TOKEN_MESSAGE);
-
- const refreshed = await refreshLongLivedToken(account.accessToken, signal);
- const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || DEFAULT_TOKEN_LIFETIME_S) * 1000).toISOString();
- await accounts.updateForUser(account.id, { accessToken: refreshed.accessToken, tokenExpiresAt }, userId);
- return tokenExpiresAt;
- },
-
// removing an account also removes its automation rules, received comments and reply history (foreign keys)
async remove(userId, accountId) {
const account = await findOwned(userId, accountId);
diff --git a/backend/services/instagram/instagramTokens.ts b/backend/services/instagram/instagramTokens.ts
index 09b56d3..2038f35 100644
--- a/backend/services/instagram/instagramTokens.ts
+++ b/backend/services/instagram/instagramTokens.ts
@@ -26,16 +26,6 @@ function toTokenResult(data: IssuedToken): InstagramTokenResult {
};
}
-export async function exchangeForLongLivedToken(shortToken: string, appSecret: string, signal?: AbortSignal): Promise<InstagramTokenResult> {
- const data = await igFetch<InstagramApiToken>('/access_token', {
- grant_type: 'ig_exchange_token',
- client_secret: appSecret,
- access_token: shortToken,
- }, 1, signal);
- if (!data.access_token) throw new UpstreamError('Failed to exchange token - check Instagram App Secret');
- return toTokenResult(data as IssuedToken);
-}
-
export async function refreshLongLivedToken(longToken: string, signal?: AbortSignal): Promise<InstagramTokenResult> {
const data = await igFetch<InstagramApiToken>('/refresh_access_token', {
grant_type: 'ig_refresh_token',
diff --git a/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json b/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json
deleted file mode 100644
index 6b5a5c2..0000000
--- a/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json
+++ /dev/null
@@ -1,205 +0,0 @@
-{
- "responses": [
- {
- "status": 400,
- "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Access token is required\",\"requestId\":\"req-test\"}"
- },
- {
- "status": 200,
- "body": "{\"success\":true,\"account\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"platform\":\"instagram\",\"igUserId\":\"3000\",\"username\":\"fresh\",\"title\":\"fresh\",\"biography\":\"\",\"website\":\"\",\"profilePictureUrl\":\"\",\"followersCount\":5,\"followsCount\":0,\"mediaCount\":1,\"tokenExpiresAt\":\"2026-09-01T13:23:20.000Z\",\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\"}}"
- },
- {
- "status": 200,
- "body": "{\"success\":true,\"account\":{\"id\":\"00000000-0000-4000-8000-000000000002\",\"platform\":\"instagram\",\"igUserId\":\"3001\",\"username\":\"shorty\",\"title\":\"Shorty\",\"biography\":\"\",\"website\":\"\",\"profilePictureUrl\":\"\",\"followersCount\":0,\"followsCount\":0,\"mediaCount\":0,\"tokenExpiresAt\":null,\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\"}}"
- },
- {
- "status": 409,
- "body": "{\"success\":false,\"code\":\"CONFLICT\",\"message\":\"This Instagram account is already added\",\"requestId\":\"req-test\"}"
- },
- {
- "status": 409,
- "body": "{\"success\":false,\"code\":\"CONFLICT\",\"message\":\"This Instagram account is already added\",\"requestId\":\"req-test\"}"
- },
- {
- "status": 400,
- "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.\",\"requestId\":\"req-test\"}"
- },
- {
- "status": 502,
- "body": "{\"success\":false,\"code\":\"UPSTREAM_ERROR\",\"message\":\"Invalid OAuth access token\",\"requestId\":\"req-test\"}"
- }
- ],
- "requests": [
- {
- "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=IGSECRET&access_token=SHORT",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=LONGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=IGSECRET&access_token=SHORTONLY",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=SHORTONLY&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=SHORTONLY&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=IGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=NOID&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=BROKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
- }
- ],
- "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": "3000",
- "username": "fresh",
- "title": "fresh",
- "biography": "",
- "website": "",
- "profilePictureUrl": "",
- "followersCount": 5,
- "followsCount": 0,
- "mediaCount": 1,
- "accessToken": "LONGTOKEN",
- "tokenExpiresAt": "2026-09-01T13:23:20.000Z",
- "addedAt": "2026-09-01T12:00:00.000Z",
- "lastUpdated": "2026-09-01T12:00:00.000Z"
- }
- },
- "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-000000000002",
- "user_id": "user-1",
- "platform": "instagram",
- "data": {
- "igUserId": "3001",
- "username": "shorty",
- "title": "Shorty",
- "biography": "",
- "website": "",
- "profilePictureUrl": "",
- "followersCount": 0,
- "followsCount": 0,
- "mediaCount": 0,
- "accessToken": "SHORTONLY",
- "tokenExpiresAt": null,
- "addedAt": "2026-09-01T12:00:00.000Z",
- "lastUpdated": "2026-09-01T12:00:00.000Z"
- }
- },
- "filters": []
- },
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "user_id",
- "user-1"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ]
- ]
- },
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "user_id",
- "user-1"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ]
- ]
- }
- ],
- "redis": [],
- "logs": [
- [
- "log",
- "{\"level\":\"info\",\"message\":\"token exchange skipped; the token may already be long-lived\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"reason\":\"Invalid platform app\"}"
- ],
- [
- "error",
- "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"UPSTREAM_ERROR\",\"status\":502,\"error\":\"Invalid OAuth access token\",\"errorName\":\"UpstreamError\"}"
- ]
- ]
-}
diff --git a/backend/tests/fixtures/accountsRoutes.dbFailure.golden.json b/backend/tests/fixtures/accountsRoutes.dbFailure.golden.json
index ee1ef25..8052080 100644
--- a/backend/tests/fixtures/accountsRoutes.dbFailure.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.dbFailure.golden.json
@@ -16,14 +16,6 @@
"status": 500,
"body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
},
- {
- "status": 500,
- "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
- },
- {
- "status": 500,
- "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
- },
{
"status": 500,
"body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
@@ -37,10 +29,6 @@
{
"url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCnnnnnnnnnnnnnnnnnnnnnn&key=YTKEY",
"method": "GET"
- },
- {
- "url": "https://graph.instagram.com/v25.0/me?access_token=IGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
- "method": "GET"
}
],
"calls": [],
@@ -62,14 +50,6 @@
"error",
"{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
],
- [
- "error",
- "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
- ],
- [
- "error",
- "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
- ],
[
"error",
"{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
diff --git a/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json b/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json
index aa380d7..824e484 100644
--- a/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json
@@ -31,26 +31,6 @@
{
"status": 404,
"body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Account not found\",\"requestId\":\"req-test\"}"
- },
- {
- "status": 404,
- "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Instagram account not found\",\"requestId\":\"req-test\"}"
- },
- {
- "status": 404,
- "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Instagram account not found\",\"requestId\":\"req-test\"}"
- },
- {
- "status": 400,
- "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"No access token stored - reconnect this Instagram account\",\"requestId\":\"req-test\"}"
- },
- {
- "status": 200,
- "body": "{\"success\":true,\"message\":\"Token refreshed for another 60 days\",\"expiresAt\":\"2026-09-02T12:00:00.000Z\"}"
- },
- {
- "status": 502,
- "body": "{\"success\":false,\"code\":\"UPSTREAM_ERROR\",\"message\":\"Token cannot be refreshed\",\"requestId\":\"req-test\"}"
}
],
"requests": [
@@ -65,14 +45,6 @@
{
"url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCmissingmissingmissing0&key=YTKEY",
"method": "GET"
- },
- {
- "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=IGTOKEN",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=IGTOKEN2",
- "method": "GET"
}
],
"calls": [
@@ -307,134 +279,6 @@
"user-1"
]
]
- },
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "id",
- "nope"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ],
- [
- "user_id",
- "user-1"
- ]
- ]
- },
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "id",
- "yt1"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ],
- [
- "user_id",
- "user-1"
- ]
- ]
- },
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "id",
- "ig2"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ],
- [
- "user_id",
- "user-1"
- ]
- ]
- },
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "id",
- "ig1"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ],
- [
- "user_id",
- "user-1"
- ]
- ]
- },
- {
- "type": "rpc",
- "table": "merge_account_data",
- "values": {
- "p_id": "ig1",
- "p_user_id": "user-1",
- "p_patch": {
- "accessToken": "IGTOKEN2",
- "tokenExpiresAt": "2026-09-02T12:00:00.000Z"
- }
- },
- "filters": []
- },
- {
- "type": "select",
- "table": "accounts",
- "columns": "id, platform, data",
- "filters": [
- [
- "id",
- "ig1"
- ],
- [
- "platform",
- [
- "youtube",
- "instagram"
- ],
- "in"
- ],
- [
- "user_id",
- "user-1"
- ]
- ]
}
],
"redis": [],
@@ -442,10 +286,6 @@
[
"error",
"{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"YouTube API key not configured on server\",\"errorName\":\"NotConfiguredError\"}"
- ],
- [
- "error",
- "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"UPSTREAM_ERROR\",\"status\":502,\"error\":\"Token cannot be refreshed\",\"errorName\":\"UpstreamError\"}"
]
]
}
diff --git a/backend/tests/fixtures/instagramTokens.exchange.golden.json b/backend/tests/fixtures/instagramTokens.exchange.golden.json
deleted file mode 100644
index 4b32c5a..0000000
--- a/backend/tests/fixtures/instagramTokens.exchange.golden.json
+++ /dev/null
@@ -1,64 +0,0 @@
-{
- "outcomes": [
- {
- "value": {
- "accessToken": "LONG",
- "tokenType": "Bearer",
- "expiresIn": 3600
- }
- },
- {
- "value": {
- "accessToken": "LONG2",
- "tokenType": "bearer",
- "expiresIn": 5184000
- }
- },
- {
- "error": "Failed to exchange token - check Instagram App Secret"
- },
- {
- "value": {
- "accessToken": "REFRESHED",
- "tokenType": "bearer",
- "expiresIn": 7200
- }
- },
- {
- "value": {
- "accessToken": "REFRESHED2",
- "tokenType": "bearer",
- "expiresIn": 5184000
- }
- },
- {
- "error": "Failed to refresh token"
- }
- ],
- "requests": [
- {
- "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=SECRET&access_token=SHORT",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=SECRET&access_token=SHORT",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=SECRET&access_token=SHORT",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=LONG",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=LONG",
- "method": "GET"
- },
- {
- "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=LONG",
- "method": "GET"
- }
- ]
-}
diff --git a/backend/tests/fixtures/instagramTokens.refresh.golden.json b/backend/tests/fixtures/instagramTokens.refresh.golden.json
new file mode 100644
index 0000000..cc81026
--- /dev/null
+++ b/backend/tests/fixtures/instagramTokens.refresh.golden.json
@@ -0,0 +1,35 @@
+{
+ "outcomes": [
+ {
+ "value": {
+ "accessToken": "REFRESHED",
+ "tokenType": "bearer",
+ "expiresIn": 7200
+ }
+ },
+ {
+ "value": {
+ "accessToken": "REFRESHED2",
+ "tokenType": "bearer",
+ "expiresIn": 5184000
+ }
+ },
+ {
+ "error": "Failed to refresh token"
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=LONG",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=LONG",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=LONG",
+ "method": "GET"
+ }
+ ]
+}
diff --git a/backend/tests/middleware/rateLimit.test.ts b/backend/tests/middleware/rateLimit.test.ts
index 2a761a4..c9e3515 100644
--- a/backend/tests/middleware/rateLimit.test.ts
+++ b/backend/tests/middleware/rateLimit.test.ts
@@ -123,10 +123,8 @@ test('quota and publish routes match the endpoints that spend platform API calls
const quota = (method: string, path: string) => matchesRoute(QUOTA_ROUTES, method, path);
assert.equal(quota('POST', '/api/accounts'), true);
assert.equal(quota('GET', '/api/accounts'), false);
- assert.equal(quota('POST', '/api/accounts/instagram'), true);
assert.equal(quota('POST', '/api/accounts/refresh-all'), true);
assert.equal(quota('POST', '/api/accounts/abc123/refresh'), true);
- assert.equal(quota('POST', '/api/accounts/abc123/refresh-ig-token'), true);
assert.equal(quota('POST', '/api/resolve-channel'), true);
assert.equal(quota('POST', '/api/tracked-content'), true);
assert.equal(quota('PUT', '/api/tracked-content/abc'), false);
diff --git a/backend/tests/routes/accountRoutes.test.ts b/backend/tests/routes/accountRoutes.test.ts
index 487b11e..02f2b83 100644
--- a/backend/tests/routes/accountRoutes.test.ts
+++ b/backend/tests/routes/accountRoutes.test.ts
@@ -128,18 +128,6 @@ describe('accounts routes golden output', () => {
]), 'accountsRoutes.addYouTube');
});
- test('adds Instagram accounts with and without a long-lived exchange', async () => {
- assertGolden(await runScenario([
- ['POST', '/accounts/instagram', {}],
- ['POST', '/accounts/instagram', { accessToken: 'SHORT' }],
- ['POST', '/accounts/instagram', { accessToken: 'SHORTONLY' }],
- ['POST', '/accounts/instagram', { accessToken: 'SHORTONLY' }, {}],
- ['POST', '/accounts/instagram', { accessToken: 'IGTOKEN' }, {}],
- ['POST', '/accounts/instagram', { accessToken: 'NOID' }, {}],
- ['POST', '/accounts/instagram', { accessToken: 'BROKEN' }, {}],
- ]), 'accountsRoutes.addInstagram');
- });
-
test('refreshes every account and reports each result', async () => {
assertGolden(await runScenario([
['POST', '/accounts/refresh-all'],
@@ -148,7 +136,7 @@ describe('accounts routes golden output', () => {
]), 'accountsRoutes.refreshAll');
});
- test('refreshes one account or one Instagram token', async () => {
+ test('refreshes one account', async () => {
assertGolden(await runScenario([
['POST', '/accounts/nope/refresh'],
['POST', '/accounts/ig1/refresh'],
@@ -158,11 +146,6 @@ describe('accounts routes golden output', () => {
['POST', '/accounts/yt1/refresh', undefined, {}],
['POST', '/accounts/yt2/refresh'],
['POST', '/accounts/other/refresh'],
- ['POST', '/accounts/nope/refresh-ig-token'],
- ['POST', '/accounts/yt1/refresh-ig-token'],
- ['POST', '/accounts/ig2/refresh-ig-token'],
- ['POST', '/accounts/ig1/refresh-ig-token'],
- ['POST', '/accounts/ig1/refresh-ig-token'],
]), 'accountsRoutes.refreshOne');
});
@@ -180,10 +163,8 @@ describe('accounts routes golden output', () => {
assertGolden(await runScenario([
['GET', '/accounts'],
['POST', '/accounts', { input: '@creator' }],
- ['POST', '/accounts/instagram', { accessToken: 'IGTOKEN' }, {}],
['POST', '/accounts/refresh-all'],
['POST', '/accounts/ig1/refresh'],
- ['POST', '/accounts/ig1/refresh-ig-token'],
['DELETE', '/accounts/ig1'],
], { supabase: brokenSupabase }), 'accountsRoutes.dbFailure');
});
diff --git a/backend/tests/services/accountService.test.ts b/backend/tests/services/accountService.test.ts
index 67738b1..1c20f5c 100644
--- a/backend/tests/services/accountService.test.ts
+++ b/backend/tests/services/accountService.test.ts
@@ -17,33 +17,37 @@ function accountsFailingWith(cause: unknown): AccountRepository {
} as unknown as AccountRepository;
}
+const CHANNEL_ID = 'UCabcdefghijklmnopqrstuv';
+
function service(accounts: AccountRepository) {
return createAccountService({
accounts,
cache: {} as AnalyticsCacheRepository,
audit: {} as AuditRepository,
- config: readConfig({} as Env),
+ config: readConfig({ YOUTUBE_API_KEY: 'KEY' } as Env),
context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },
});
}
-function instagramAnswers(t: { after(fn: () => void): void }) {
- const fetch = mock.method(globalThis, 'fetch', async () => Response.json({ user_id: '1789', username: 'ribbon' }));
+// a channel id needs no lookup, so one channels.list answer is the whole conversation with YouTube
+function youtubeAnswers(t: { after(fn: () => void): void }) {
+ const channel = { id: CHANNEL_ID, snippet: { title: 'Cooking', publishedAt: '2020-01-01T00:00:00Z' }, statistics: {}, contentDetails: { relatedPlaylists: { uploads: 'UUabc' } } };
+ const fetch = mock.method(globalThis, 'fetch', async () => Response.json({ items: [channel] }));
t.after(() => fetch.mock.restore());
}
test('an add that loses a race to the same account gets the usual already added answer, not a database error', async t => {
- instagramAnswers(t);
+ youtubeAnswers(t);
const accounts = accountsFailingWith({ code: '23505', message: 'duplicate key value violates unique constraint "accounts_identity_key"' });
- await assert.rejects(service(accounts).addInstagram('user-1', 'IGTOKEN'), (err: Error) => {
+ await assert.rejects(service(accounts).addYouTube('user-1', CHANNEL_ID), (err: Error) => {
assert.ok(err instanceof ConflictError);
- assert.equal(err.message, 'This Instagram account is already added');
+ assert.equal(err.message, 'This channel is already added');
return true;
});
});
test('any other failed insert stays a database error', async t => {
- instagramAnswers(t);
+ youtubeAnswers(t);
const accounts = accountsFailingWith({ code: '08006', message: 'connection failure' });
- await assert.rejects(service(accounts).addInstagram('user-1', 'IGTOKEN'), DatabaseError);
+ await assert.rejects(service(accounts).addYouTube('user-1', CHANNEL_ID), DatabaseError);
});
diff --git a/backend/tests/services/instagram/instagramTokens.test.ts b/backend/tests/services/instagram/instagramTokens.test.ts
index c2d35f5..0982ee5 100644
--- a/backend/tests/services/instagram/instagramTokens.test.ts
+++ b/backend/tests/services/instagram/instagramTokens.test.ts
@@ -1,5 +1,5 @@
import { test, describe, before, after, afterEach, mock } from 'node:test';
-import { exchangeForLongLivedToken, refreshLongLivedToken } from '../../../services/instagram/instagramTokens.ts';
+import { refreshLongLivedToken } from '../../../services/instagram/instagramTokens.ts';
import { assertGolden } from '../../fixtures/golden.ts';
import { installFetch, reply } from '../../fixtures/fakeFetch.ts';
import type { FetchMock } from '../../fixtures/fakeFetch.ts';
@@ -22,25 +22,19 @@ async function outcomeOf(promise: Promise<unknown>) {
}
}
-describe('token exchange and refresh golden output', () => {
- test('exchange and refresh map the response and reject a missing token', async () => {
+describe('token refresh golden output', () => {
+ test('refresh maps the response and rejects a missing token', async () => {
const bodies = [
- { access_token: 'LONG', token_type: 'Bearer', expires_in: 3600 },
- { access_token: 'LONG2' },
- { token_type: 'bearer' },
{ access_token: 'REFRESHED', expires_in: 7200 },
{ access_token: 'REFRESHED2' },
{},
];
fetchMock = installFetch((_request, count) => reply(bodies[count - 1]));
const outcomes = [
- await outcomeOf(exchangeForLongLivedToken('SHORT', 'SECRET')),
- await outcomeOf(exchangeForLongLivedToken('SHORT', 'SECRET')),
- await outcomeOf(exchangeForLongLivedToken('SHORT', 'SECRET')),
await outcomeOf(refreshLongLivedToken('LONG')),
await outcomeOf(refreshLongLivedToken('LONG')),
await outcomeOf(refreshLongLivedToken('LONG')),
];
- assertGolden({ outcomes, requests: fetchMock.requests }, 'instagramTokens.exchange');
+ assertGolden({ outcomes, requests: fetchMock.requests }, 'instagramTokens.refresh');
});
});
diff --git a/backend/tests/validators/accountValidators.test.ts b/backend/tests/validators/accountValidators.test.ts
index fd654a3..c190154 100644
--- a/backend/tests/validators/accountValidators.test.ts
+++ b/backend/tests/validators/accountValidators.test.ts
@@ -1,14 +1,9 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { parseChannelInput, parseInstagramToken } from '../../validators/accountValidators.ts';
+import { parseChannelInput } from '../../validators/accountValidators.ts';
import { ValidationError } from '../../lib/errors.ts';
test('the channel body keeps the trimmed input and asks for one when it is missing', () => {
assert.deepEqual(parseChannelInput({ input: ' @creator ' }), { input: '@creator' });
assert.throws(() => parseChannelInput({ input: ' ' }), new ValidationError('Enter a channel URL, @handle or channel ID'));
});
-
-test('the Instagram token body keeps the trimmed token and refuses an empty one', () => {
- assert.deepEqual(parseInstagramToken({ accessToken: ' TOKEN ' }), { accessToken: 'TOKEN' });
- assert.throws(() => parseInstagramToken({}), new ValidationError('Access token is required'));
-});
diff --git a/backend/validators/accountValidators.ts b/backend/validators/accountValidators.ts
index 158d0ab..b80a288 100644
--- a/backend/validators/accountValidators.ts
+++ b/backend/validators/accountValidators.ts
@@ -5,14 +5,6 @@ export interface ChannelInput {
input: string;
}
-export interface InstagramTokenInput {
- accessToken: string;
-}
-
export function parseChannelInput(body: Fields): ChannelInput {
return { input: requiredString(body, 'input', 'Enter a channel URL, @handle or channel ID') };
}
-
-export function parseInstagramToken(body: Fields): InstagramTokenInput {
- return { accessToken: requiredString(body, 'accessToken', 'Access token is required') };
-}
diff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.md
index 6bbec14..c1c58ad 100644
--- a/docs/architecture/backend/MIDDLEWARE.md
+++ b/docs/architecture/backend/MIDDLEWARE.md
@@ -144,9 +144,9 @@ export async function requireAuth(c: AppContext, next: Next): Promise<void> {
`jsonBody(parse)` and `queryParams(parse)` wrap Hono's `validator`. Each parser in `backend/validators/` reads fields with the helpers in `validators/fields.ts` and throws `ValidationError` (400). For a query, a repeated key keeps its first value. The controller reads the parsed result with `c.req.valid('json')` or `c.req.valid('query')`.
```ts
-export const addInstagramAccount = controller.createHandlers(jsonBody(parseInstagramToken), async c => {
- const account = await servicesFor(c).accounts.addInstagram(c.get('userId'), c.req.valid('json').accessToken);
- return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
+export const addYouTubeAccount = controller.createHandlers(jsonBody(parseChannelInput), async c => {
+ const account = await servicesFor(c).accounts.addYouTube(c.get('userId'), c.req.valid('json').input);
+ return c.json({ success: true, account } satisfies YouTubeAccountAddResponse);
});
```
diff --git a/docs/architecture/backend/RATE_LIMITING.md b/docs/architecture/backend/RATE_LIMITING.md
index c384b92..8d8e300 100644
--- a/docs/architecture/backend/RATE_LIMITING.md
+++ b/docs/architecture/backend/RATE_LIMITING.md
@@ -33,7 +33,7 @@ Defined in `backend/lib/rateLimit/rules.ts`.
|---|---|---|---|---|
| `ip` | Every `/api` request and `/mcp` | Client IP; IPv6 by /64 | Sliding window counter | 300 per minute |
| `user` | Every protected request | User id from the verified JWT | Token bucket | Bursts of 120, refills 2 per second |
-| `quota` | `POST /accounts`, `/accounts/instagram`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/accounts/:id/refresh-ig-token`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `GET` or `POST /process-scheduled`, `POST /automations/accounts/:accountId/subscribe` | User id | Sliding window log | 30 per 10 minutes |
+| `quota` | `POST /accounts`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `GET` or `POST /process-scheduled`, `POST /automations/accounts/:accountId/subscribe` | User id | Sliding window log | 30 per 10 minutes |
| `publish` | `POST /accounts/:id/ig-media-publish`, `/accounts/:id/ig-publish` | User id | Leaking bucket | 50 deep, drains 1 every 15 seconds |
| `mcp` | `POST /mcp`, after `requireMcpAuth` | User id from the access token or OAuth token | Token bucket | Bursts of 60, refills 1 per second |
| `oauth` | `GET /auth/instagram/callback` | Client IP | Fixed window counter | 10 per 10 minutes |
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 795b1df..4d1b8b4 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -98,8 +98,6 @@ Controllers call `AccountService` (`services/accountService.ts`); the Instagram
| DELETE | `/api/accounts/:id` | `accountRoutes.ts`, `accountController.deleteAccount` | Remove account and delete its Redis cache entries |
| POST | `/api/accounts/refresh-all` | `accountRoutes.ts`, `accountController.refreshAllAccounts` | Refresh stats for every account; one failure does not stop the rest, and `results` reports each account's outcome |
| POST | `/api/accounts/:id/refresh` | `accountRoutes.ts`, `accountController.refreshAccount` | Refresh a single account's stats |
-| POST | `/api/accounts/instagram` | `accountRoutes.ts`, `accountController.addInstagramAccount` | Add Instagram account via a raw access token (for manual setup); 409 when already added |
-| POST | `/api/accounts/:id/refresh-ig-token` | `accountRoutes.ts`, `accountController.refreshInstagramToken` | Extend Instagram long-lived token (valid up to 60 days; refresh when < 15 days remain) |
### Analytics
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 7c9e7c7..8777955 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -29,7 +29,7 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from
| Service (key in `Services`) | File | Repositories | Methods |
|---|---|---|---|
-| `accounts` | `accountService.ts` | accounts, cache | `list`, `resolveChannel`, `addYouTube`, `addInstagram`, `refresh`, `refreshAll`, `refreshInstagramToken`, `remove` |
+| `accounts` | `accountService.ts` | accounts, cache | `list`, `resolveChannel`, `addYouTube`, `refresh`, `refreshAll`, `remove` |
| `youtubeAnalytics` | `youtubeAnalyticsService.ts` | accounts, cache | `channelAnalytics`, `channelVideos`, `comparison`, `videoLibrary` |
| `instagramAnalytics` | `instagramAnalyticsService.ts` | accounts, cache | `analytics`, `media` |
| `publishing` | `publishingService.ts` | accounts | `cloudinaryConfig`, `publishingLimit`, `createContainer`, `containerStatus`, `publishContainer` |
@@ -80,7 +80,7 @@ The flow is in `docs/architecture/data-flows/AUTOMATION.md`. The rules the servi
`AccountService`:
-- `addYouTube` and `addInstagram` throw `ConflictError` (409) for an account the user already has. `addInstagram` tries the long-lived token exchange when `INSTAGRAM_APP_SECRET` is set and keeps the pasted token if it fails.
+- `addYouTube` throws `ConflictError` (409) for a channel the user already has. Instagram accounts are added only through the OAuth connection (`instagramConnect`).
- `refresh` and `refreshAll` check the fields the platform call needs first (an Instagram token, a YouTube channel id) and throw `ValidationError` (400) when one is missing; a missing YouTube key is a `NotConfiguredError` (503). A single refresh updates more fields than refresh-all. `refreshAll` uses `Promise.allSettled`, so one failure does not stop the rest, and its `results` line up with the account list by index.
- `remove` deletes the account row and its cache entries. The database removes the account's scheduled posts with it (the foreign keys in `docs/architecture/database/SCHEMA.md`).
- Account updates go through `merge_account_data`, one statement in the database, so a token refresh and an analytics refresh on the same account never undo each other. A field passed as `undefined` keeps its stored value.
@@ -146,7 +146,7 @@ There is no barrel: services and tests import each module directly, and each mod
| Module | Contents |
|---|---|
| `instagramApi.ts` | `igFetch(endpoint, params, retries, signal)` GET transport (through the Instagram circuit breaker, 15 s timeout, one retry on a network blip, never after the request signal aborted; no API version prefix for `/oauth`, `/access_token`, `/refresh_access_token`), `igPost(endpoint, params, signal)` (never retried, so a publish cannot run twice), `readGraphResponse` and `fetchInstagramProfile` |
-| `instagramTokens.ts` | `exchangeForLongLivedToken`, `refreshLongLivedToken` |
+| `instagramTokens.ts` | `refreshLongLivedToken` |
| `instagramOAuth.ts` | `isOAuthConfigured`, `buildAuthorizationUrl`, `exchangeCodeForToken`, `upgradeToLongLivedToken` |
| `instagramMedia.ts` | `classifyInstagramMedia`, `extractInstagramViews`, `normalizeInstagramMedia`, paged `fetchInstagramMedia` |
| `instagramContentTypes.ts` | `CONTENT_TYPES`, `summarizeContentTypes`, per type stats used by the analytics |
@@ -163,7 +163,6 @@ A Graph API error becomes an `UpstreamError` (502) with Instagram's message; a c
| Function | Purpose |
|---|---|
| `fetchInstagramProfile(igUserId, accessToken, signal)` | Fetches the profile for an account id, or for `/me` when `igUserId` is null |
-| `exchangeForLongLivedToken(shortToken, appSecret, signal)` | Short-lived -> 60-day long-lived token |
| `refreshLongLivedToken(accessToken, signal)` | Extends a long-lived token; call before expiry. The daily cron calls it through `tokenRefresh.refreshExpiringInstagramTokens()` for every token expiring within 15 days |
| `fetchInstagramMedia(igUserId, accessToken, limit, signal)` | Paginates media (50 per page, 10 pages max) up to `limit` (default 500), requesting `views` insights inline; returns normalized items |
| `classifyInstagramMedia(raw)` | Returns `'reel'`, `'post'`, or `'video'` for a raw Graph API media item |
diff --git a/docs/guidelines/TYPESCRIPT.md b/docs/guidelines/TYPESCRIPT.md
index 4a01743..43de22e 100644
--- a/docs/guidelines/TYPESCRIPT.md
+++ b/docs/guidelines/TYPESCRIPT.md
@@ -65,9 +65,9 @@ When a route's response changes, change its type in `shared/types` first. The ty
```ts
// controllers: createHandlers keeps the validator's types, so c.req.valid() is typed
-export const addInstagramAccount = controller.createHandlers(jsonBody(parseInstagramToken), async c => {
- const account = await servicesFor(c).accounts.addInstagram(c.get('userId'), c.req.valid('json').accessToken);
- return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
+export const addYouTubeAccount = controller.createHandlers(jsonBody(parseChannelInput), async c => {
+ const account = await servicesFor(c).accounts.addYouTube(c.get('userId'), c.req.valid('json').input);
+ return c.json({ success: true, account } satisfies YouTubeAccountAddResponse);
});
// services: an interface for the contract and one for the dependencies, built by a factory
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index 833ca30..f9dfb89 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -10,7 +10,7 @@ import type {
import type {
CloudinaryConfigResponse, InstagramAnalyticsResponse, InstagramAuthUrlResponse, InstagramConnectCompleteResponse, InstagramContainerStatusResponse,
InstagramMediaPublishRequest, InstagramMediaPublishResponse, InstagramMediaResponse, InstagramPublishingLimitResponse, InstagramPublishRequest,
- InstagramPublishResponse, InstagramTokenRefreshResponse,
+ InstagramPublishResponse,
} from '@shared/types/instagram.ts';
import type {
AutomationAccountResponse, AutomationActivityItemResponse, AutomationActivityResponse, AutomationOverviewResponse,
@@ -130,8 +130,6 @@ export const api = {
// 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' }),
getIGAnalytics: (id: string) => request<InstagramAnalyticsResponse>(`/accounts/${id}/ig-analytics`),
getIGMedia: (id: string, fresh = false) => request<InstagramMediaResponse>(`/accounts/${id}/ig-media${fresh ? '?fresh=1' : ''}`),
diff --git a/shared/types/instagram.ts b/shared/types/instagram.ts
index f9e2f94..df2d7fc 100644
--- a/shared/types/instagram.ts
+++ b/shared/types/instagram.ts
@@ -229,13 +229,6 @@ export interface InstagramMediaResponse {
fetchedAt: string;
}
-// POST /api/accounts/:id/refresh-ig-token
-export interface InstagramTokenRefreshResponse {
- success: true;
- message: string;
- expiresAt: string;
-}
-
// GET /api/auth/instagram/url
export interface InstagramAuthUrlResponse {
url: string;