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.

feat(youtube): verify a channel already added for analytics instead of connecting a new one

spacesdrive7a589739b847
diff --git a/backend/container.ts b/backend/container.ts
index 116690d..1a69f6d 100644
--- a/backend/container.ts
+++ b/backend/container.ts
@@ -138,7 +138,7 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
// counters on the fail-fast client the rate limits use: without Redis nothing is metered
const youtubeQuota = createYouTubeQuotaService({ quota: createYouTubeQuotaRepository(clients.rateLimitRedis) });
const services: Services = {
- accounts: createAccountService({ accounts, cache, audit, config, context, youtubeQuota }),
+ accounts: createAccountService({ accounts, cache, audit, config, context, youtubeQuota, youtubePublishing: youtubeConnect }),
youtubeAnalytics: createYouTubeAnalyticsService({ accounts, cache, config, context, youtubeQuota }),
instagramAnalytics: createInstagramAnalyticsService({ accounts, cache, context }),
publishing: createPublishingService({ accounts, config, context }),
diff --git a/backend/controllers/youtubeController.ts b/backend/controllers/youtubeController.ts
index 5508201..aca9aaf 100644
--- a/backend/controllers/youtubeController.ts
+++ b/backend/controllers/youtubeController.ts
@@ -1,16 +1,16 @@
import { controller, pathParam, servicesFor } from './http.ts';
import { jsonBody, queryParams } from '../middleware/validate.ts';
import { requestLogger } from '../middleware/requestContext.ts';
-import { parseYouTubeCallback, parseYouTubeComplete, parseYouTubeUpload, parseYouTubeUploadUpdate } from '../validators/youtubeValidators.ts';
+import { parseYouTubeAuthUrl, parseYouTubeCallback, parseYouTubeComplete, parseYouTubeUpload, parseYouTubeUploadUpdate } from '../validators/youtubeValidators.ts';
import { errorFields } from '../lib/logger.ts';
import type { SuccessResponse } from '../../shared/types/domain.ts';
import type {
YouTubeAuthUrlResponse, YouTubeConnectCompleteResponse, YouTubeConnectionListResponse, YouTubeUploadListResponse, YouTubeUploadResponse,
} from '../../shared/types/youtubePublishing.ts';
-// protected: the signed state carries the user id to the public callback
-export const getYouTubeAuthUrl = controller.createHandlers(async c => {
- const url = await servicesFor(c).youtubeConnect.authorizationUrl(c.get('userId'));
+// protected: the signed state carries the user id and the channel's account to the public callback
+export const getYouTubeAuthUrl = controller.createHandlers(queryParams(parseYouTubeAuthUrl), async c => {
+ const url = await servicesFor(c).youtubeConnect.authorizationUrl(c.get('userId'), c.req.valid('query').accountId);
return c.json({ success: true, url } satisfies YouTubeAuthUrlResponse);
});
@@ -31,7 +31,7 @@ export const handleYouTubeCallback = controller.createHandlers(queryParams(parse
return c.redirect(`${connect.accountsPageUrl()}#yt_code=${encodeURIComponent(code)}&yt_state=${encodeURIComponent(state)}`);
});
-// protected: connects the channel only when the sign-in was started by the person now signed in
+// protected: verifies the channel only when the sign-in was started by the person now signed in, for that channel
export const completeYouTubeConnection = controller.createHandlers(jsonBody(parseYouTubeComplete), async c => {
const { code, state } = c.req.valid('json');
const { connection, outcome } = await servicesFor(c).youtubeConnect.completeForUser(c.get('userId'), code, state);
diff --git a/backend/lib/oauthState.ts b/backend/lib/oauthState.ts
index c9a0e7a..c5c426f 100644
--- a/backend/lib/oauthState.ts
+++ b/backend/lib/oauthState.ts
@@ -30,13 +30,19 @@ async function hmacVerify(secret: string, message: string, signature: string): P
return crypto.subtle.verify('HMAC', await hmacKey(secret, 'verify'), signatureBytes, new TextEncoder().encode(message));
}
-export async function createOAuthState(userId: string, secret: string): Promise<string> {
- const payload = toBase64Url(`${userId}:${Date.now()}`);
+// the subject names what the sign-in is for, such as the account it was started from; ids never contain a colon
+export async function createOAuthState(userId: string, secret: string, subject = ''): Promise<string> {
+ const payload = toBase64Url(subject ? `${userId}:${Date.now()}:${subject}` : `${userId}:${Date.now()}`);
const signature = await hmacSign(secret, payload);
return `${payload}.${signature}`;
}
-export async function verifyOAuthState(state: string, secret: string): Promise<string | null> {
+export interface OAuthStateDetails {
+ userId: string;
+ subject: string | null;
+}
+
+export async function readOAuthState(state: string, secret: string): Promise<OAuthStateDetails | null> {
const separatorIndex = state.lastIndexOf('.');
if (separatorIndex === -1) return null;
@@ -47,8 +53,12 @@ export async function verifyOAuthState(state: string, secret: string): Promise<s
const decoded = fromBase64Url(payload);
if (!decoded) return null;
- const [userId, createdAt] = new TextDecoder().decode(decoded).split(':');
+ const [userId, createdAt, subject] = new TextDecoder().decode(decoded).split(':');
if (Date.now() - Number(createdAt) > STATE_TTL_MS) return null;
- return userId;
+ return { userId, subject: subject || null };
+}
+
+export async function verifyOAuthState(state: string, secret: string): Promise<string | null> {
+ return (await readOAuthState(state, secret))?.userId ?? null;
}
diff --git a/backend/mcp/tools/youtubeTools.ts b/backend/mcp/tools/youtubeTools.ts
index 4033ab3..7515175 100644
--- a/backend/mcp/tools/youtubeTools.ts
+++ b/backend/mcp/tools/youtubeTools.ts
@@ -41,8 +41,8 @@ function refuseUnlisted(args: Record<string, unknown>, allowed: string[]): void
export const listYouTubeChannels = defineTool<Record<string, never>>({
name: 'list_youtube_channels',
- title: 'List connected YouTube channels',
- description: 'Lists the YouTube channels connected for publishing, with their status. A channel that needs a new sign-in must be connected again on the Accounts page.',
+ title: 'List YouTube channels verified for publishing',
+ description: 'Lists the YouTube channels verified for publishing, with their status. A channel that needs a new sign-in must be verified again on the Accounts page.',
inputSchema: noInput(),
annotations: READ_ONLY,
permission: 'read',
@@ -82,7 +82,7 @@ export const getYouTubeUpload = defineTool<{ uploadId: string }>({
export const createYouTubeUpload = defineTool<YouTubeUploadRequest>({
name: 'create_youtube_upload',
title: 'Upload a video to YouTube',
- description: 'Queues a video from your media (see list_media and import_media_from_url) for upload to a connected YouTube channel. Twiligent uploads it in the background over the next runs and YouTube processes it; follow it with get_youtube_upload. Asks for a confirmation first when the video will be public, unlisted or scheduled. Sending the same clientRequestId again returns the first job.',
+ description: 'Queues a video from your media (see list_media and import_media_from_url) for upload to a YouTube channel verified for publishing. Twiligent uploads it in the background over the next runs and YouTube processes it; follow it with get_youtube_upload. Asks for a confirmation first when the video will be public, unlisted or scheduled. Sending the same clientRequestId again returns the first job.',
inputSchema: withConfirmation(objectSchema({
connectionId: idProperty('YouTube channel connection'),
mediaId: idProperty('video in your media'),
diff --git a/backend/services/accountService.ts b/backend/services/accountService.ts
index 65724da..b545337 100644
--- a/backend/services/accountService.ts
+++ b/backend/services/accountService.ts
@@ -4,6 +4,7 @@ import { buildYouTubeAccount } from './accountFactory.ts';
import { ConflictError, NotConfiguredError, NotFoundError, RateLimitedError, ValidationError, isUniqueViolation } from '../lib/errors.ts';
import { UNMETERED_YOUTUBE_QUOTA } from './youtubeQuotaService.ts';
import type { YouTubeQuotaService } from './youtubeQuotaService.ts';
+import type { YouTubeConnectService } from './youtubeConnectService.ts';
import type { YouTubeKey } from './youtube/youtubeApi.ts';
import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';
@@ -21,6 +22,7 @@ export interface AccountServiceDeps {
config: AppConfig;
context: RequestContext;
youtubeQuota?: YouTubeQuotaService;
+ youtubePublishing?: Pick<YouTubeConnectService, 'disconnectChannel'>;
}
export interface RefreshAllOutcome {
@@ -71,7 +73,7 @@ function youtubeUpdates(channelData: YouTubeChannelData, full: boolean): Partial
const CHANNEL_ADDED = 'This channel is already added';
-export function createAccountService({ accounts, cache, audit, config, context, youtubeQuota = UNMETERED_YOUTUBE_QUOTA }: AccountServiceDeps): AccountService {
+export function createAccountService({ accounts, cache, audit, config, context, youtubeQuota = UNMETERED_YOUTUBE_QUOTA, youtubePublishing }: AccountServiceDeps): AccountService {
const { signal } = context;
function youtubeKey(): string {
@@ -163,9 +165,11 @@ export function createAccountService({ accounts, cache, audit, config, context,
return { accounts: await accounts.listForUser(userId), results };
},
- // removing an account also removes its automation rules, received comments and reply history (foreign keys)
+ // removing an account also removes its automation rules, received comments and reply history (foreign keys);
+ // a channel verified for publishing has its Google access revoked first, so no upload outlives its card
async remove(userId, accountId) {
const account = await findOwned(userId, accountId);
+ if (account.platform === 'youtube' && account.channelId && youtubePublishing) await youtubePublishing.disconnectChannel(userId, account.channelId);
await Promise.all([
accounts.deleteForUser(accountId, userId),
cache.deleteAllForAccount(userId, accountId),
diff --git a/backend/services/youtube/googleApi.ts b/backend/services/youtube/googleApi.ts
index ab1ceba..a610a94 100644
--- a/backend/services/youtube/googleApi.ts
+++ b/backend/services/youtube/googleApi.ts
@@ -48,7 +48,7 @@ async function send(url: string, init: RequestInit, what: string): Promise<Respo
}
// the signed state names the person who started, so only they can finish the connection
-export async function authorizationUrl(config: YouTubeOAuthConfig, userId: string): Promise<string> {
+export async function authorizationUrl(config: YouTubeOAuthConfig, userId: string, accountId: string): Promise<string> {
const params = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
@@ -58,7 +58,8 @@ export async function authorizationUrl(config: YouTubeOAuthConfig, userId: strin
access_type: 'offline',
prompt: 'consent',
include_granted_scopes: 'true',
- state: await createOAuthState(userId, config.clientSecret),
+ // the state names the channel card the sign-in was started from, so completing it can check Google returned that channel
+ state: await createOAuthState(userId, config.clientSecret, accountId),
});
return `${AUTHORIZE_URL}?${params}`;
}
@@ -116,7 +117,7 @@ export async function fetchMyChannel(accessToken: string, signal?: AbortSignal):
if (!response.ok) throw await googleError(response, 'reading the channel');
const answer = await response.json() as { items?: { id: string; snippet?: { title?: string } }[] };
const channel = answer.items?.[0];
- if (!channel) throw new GoogleApiError('This Google account has no YouTube channel. Create one on YouTube, then connect again.', 404, 'noChannel');
+ if (!channel) throw new GoogleApiError('This Google account has no YouTube channel. Create one on YouTube, then choose Verify again.', 404, 'noChannel');
return { id: channel.id, title: channel.snippet?.title ?? '' };
}
diff --git a/backend/services/youtubeConnectService.ts b/backend/services/youtubeConnectService.ts
index 640f186..a841769 100644
--- a/backend/services/youtubeConnectService.ts
+++ b/backend/services/youtubeConnectService.ts
@@ -1,6 +1,6 @@
import { authorizationUrl, exchangeCode, fetchMyChannel, refreshAccessToken, revokeToken, GoogleApiError } from './youtube/googleApi.ts';
import { decryptToken, encryptToken } from '../lib/tokenCrypto.ts';
-import { verifyOAuthState } from '../lib/oauthState.ts';
+import { readOAuthState, verifyOAuthState } from '../lib/oauthState.ts';
import { ForbiddenError, NotConfiguredError, NotFoundError, ValidationError } from '../lib/errors.ts';
import { connectionSummary } from '../repositories/youtubeConnectionRepository.ts';
import type { StoredYouTubeConnection, YouTubeConnectionRepository } from '../repositories/youtubeConnectionRepository.ts';
@@ -9,6 +9,7 @@ import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { AuditRepository } from '../repositories/auditRepository.ts';
import type { AppConfig, YouTubeOAuthConfig } from '../lib/config.ts';
import type { RequestContext } from '../types/context.ts';
+import type { Account } from '../../shared/types/domain.ts';
import type { YouTubeConnectionSummary } from '../../shared/types/youtubePublishing.ts';
export interface YouTubeConnectDeps {
@@ -23,12 +24,15 @@ export interface YouTubeConnectDeps {
export interface YouTubeConnectService {
configured(): boolean;
accountsPageUrl(): string;
- authorizationUrl(userId: string): Promise<string>;
+ // a sign-in for one of the person's YouTube accounts; completing it accepts only that account's channel
+ authorizationUrl(userId: string, accountId: string): Promise<string>;
// the callback only checks the state's signature; the person who started finishes it while signed in
stateIsValid(state: string): Promise<boolean>;
completeForUser(userId: string, code: string, state: string): Promise<{ connection: YouTubeConnectionSummary; outcome: 'connected' | 'reconnected' }>;
list(userId: string): Promise<YouTubeConnectionSummary[]>;
disconnect(userId: string, id: string): Promise<void>;
+ // the account is being removed, so its channel stops publishing too; nothing happens when it was never verified
+ disconnectChannel(userId: string, channelId: string): Promise<void>;
// a current access token for the runner, refreshed when it is about to expire; null when the connection needs a new sign-in
accessTokenFor(connection: StoredYouTubeConnection): Promise<string | null>;
}
@@ -36,7 +40,7 @@ export interface YouTubeConnectService {
const NOT_CONFIGURED = 'YouTube publishing is not set up on this server. The owner needs to add GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET and TOKEN_ENCRYPTION_KEY.';
// refreshed this long before it expires, so a chunk never goes out with a token that dies on the way
const EXPIRY_MARGIN_MS = 2 * 60 * 1000;
-const RECONNECT_MESSAGE = 'Google no longer accepts this channel\'s sign-in. Connect YouTube again on the Accounts page.';
+const RECONNECT_MESSAGE = 'Google no longer accepts this channel\'s sign-in. Choose Verify again on the channel on the Accounts page.';
export function createYouTubeConnectService({ connections, uploads, accounts, audit, config, context }: YouTubeConnectDeps): YouTubeConnectService {
const { signal, log } = context;
@@ -46,6 +50,21 @@ export function createYouTubeConnectService({ connections, uploads, accounts, au
return config.youtubeOAuth;
}
+ async function youtubeAccount(userId: string, accountId: string): Promise<Account & { channelId: string }> {
+ const account = await accounts.findForUser(accountId, userId);
+ if (!account || account.platform !== 'youtube' || !account.channelId) throw new NotFoundError('No YouTube channel with that id. Add the channel on the Accounts page first.');
+ return { ...account, channelId: account.channelId };
+ }
+
+ async function removeConnection(userId: string, connection: StoredYouTubeConnection): Promise<void> {
+ if (config.youtubeOAuth) {
+ const refresh = await decryptToken(connection.refreshTokenEnc, config.youtubeOAuth.encryptionSecret);
+ if (refresh) await revokeToken(refresh, signal);
+ }
+ await connections.deleteForUser(connection.id, userId);
+ await audit.recordForUser(userId, { action: 'youtube_connection.removed', subjectType: 'youtube_connection', subjectId: connection.id });
+ }
+
async function needsReconnect(connection: StoredYouTubeConnection): Promise<null> {
await connections.markNeedsReconnectById(connection.id);
await uploads.parkForConnection(connection.id, RECONNECT_MESSAGE);
@@ -56,33 +75,44 @@ export function createYouTubeConnectService({ connections, uploads, accounts, au
return {
configured: () => config.youtubeOAuth !== null,
accountsPageUrl: () => oauth().accountsPageUrl,
- authorizationUrl: async userId => authorizationUrl(oauth(), userId),
+ async authorizationUrl(userId, accountId) {
+ const settings = oauth();
+ const account = await youtubeAccount(userId, accountId);
+ return authorizationUrl(settings, userId, account.id);
+ },
stateIsValid: async state => (await verifyOAuthState(state, oauth().clientSecret)) !== null,
async completeForUser(userId, code, state) {
const settings = oauth();
- const startedBy = await verifyOAuthState(state, settings.clientSecret);
- if (!startedBy) throw new ValidationError('This YouTube sign-in link expired or was changed. Start connecting again.');
- // a consent link made by one person and finished by another connects nothing
- if (startedBy !== userId) throw new ForbiddenError('This YouTube sign-in was started by another Twiligent user. Start connecting again from your own account.');
+ const started = await readOAuthState(state, settings.clientSecret);
+ if (!started) throw new ValidationError('This YouTube sign-in link expired or was changed. Choose Verify on the channel again.');
+ // a consent link made by one person and finished by another verifies nothing
+ if (started.userId !== userId) throw new ForbiddenError('This YouTube sign-in was started by another Twiligent user. Choose Verify on the channel from your own account.');
+ if (!started.subject) throw new ValidationError('This YouTube sign-in does not name a channel. Choose Verify on the channel on the Accounts page.');
+ const account = await youtubeAccount(userId, started.subject);
const tokens = await exchangeCode(settings, code, signal);
- if (!tokens.refreshToken) throw new ValidationError('Google did not grant offline access. Connect again and allow every permission YouTube asks for.');
+ if (!tokens.refreshToken) throw new ValidationError('Google did not grant offline access. Choose Verify again and allow every permission YouTube asks for.');
const channel = await fetchMyChannel(tokens.accessToken, signal);
- const analytics = (await accounts.listForUser(userId)).find(account => account.platform === 'youtube' && account.channelId === channel.id);
+ // proof of ownership: Google answers for the channel the signed-in Google account chose, which must be this card's channel
+ if (channel.id !== account.channelId) {
+ await revokeToken(tokens.refreshToken, signal);
+ const wanted = account.title || 'this channel';
+ throw new ValidationError(`Google signed you in to ${channel.title || 'another channel'}, not ${wanted}. Choose Verify again and pick ${wanted} when Google asks which channel to use.`);
+ }
const sealed = {
accessTokenEnc: await encryptToken(tokens.accessToken, settings.encryptionSecret),
accessTokenExpiresAt: tokens.expiresAt,
refreshTokenEnc: await encryptToken(tokens.refreshToken, settings.encryptionSecret),
scopes: tokens.scopes,
channelTitle: channel.title,
- accountId: analytics?.id ?? null,
+ accountId: account.id,
};
const existing = await connections.findByChannelForUser(channel.id, userId);
if (existing) {
const renewed = await connections.reconnectForUser(existing.id, userId, sealed);
- if (!renewed) throw new NotFoundError('The YouTube connection was removed while connecting. Connect again.');
+ if (!renewed) throw new NotFoundError('Publishing for this channel was turned off while verifying. Choose Verify again.');
await uploads.resumeParkedForUser(existing.id, userId);
await audit.recordForUser(userId, { action: 'youtube_connection.reconnected', subjectType: 'youtube_connection', subjectId: existing.id });
return { connection: connectionSummary(renewed), outcome: 'reconnected' };
@@ -102,16 +132,16 @@ export function createYouTubeConnectService({ connections, uploads, accounts, au
list: async userId => (await connections.listForUser(userId)).map(connectionSummary),
+ async disconnectChannel(userId, channelId) {
+ const connection = await connections.findByChannelForUser(channelId, userId);
+ if (connection) await removeConnection(userId, connection);
+ },
+
// Google is told to drop the access as well, so a removed connection cannot be used even with a leaked token
async disconnect(userId, id) {
const connection = await connections.findForUser(id, userId);
if (!connection) throw new NotFoundError('No YouTube connection with that id.');
- if (config.youtubeOAuth) {
- const refresh = await decryptToken(connection.refreshTokenEnc, config.youtubeOAuth.encryptionSecret);
- if (refresh) await revokeToken(refresh, signal);
- }
- await connections.deleteForUser(id, userId);
- await audit.recordForUser(userId, { action: 'youtube_connection.removed', subjectType: 'youtube_connection', subjectId: id });
+ await removeConnection(userId, connection);
},
async accessTokenFor(connection) {
diff --git a/backend/services/youtubeUploadRunner.ts b/backend/services/youtubeUploadRunner.ts
index 5a30340..ac7e6f1 100644
--- a/backend/services/youtubeUploadRunner.ts
+++ b/backend/services/youtubeUploadRunner.ts
@@ -98,7 +98,7 @@ export function createYouTubeUploadRunner({ uploads, connections, connect, ledge
spent += 2;
const token = await connect.accessTokenFor(connection);
if (!token) {
- await release({ state: 'needs_reconnect', lastError: 'Google no longer accepts this channel\'s sign-in. Connect YouTube again on the Accounts page.' });
+ await release({ state: 'needs_reconnect', lastError: 'Google no longer accepts this channel\'s sign-in. Choose Verify again on the channel on the Accounts page.' });
return { jobId: job.id, state, chunks, subrequests: spent };
}
@@ -211,7 +211,7 @@ export function createYouTubeUploadRunner({ uploads, connections, connect, ledge
await release({ state: 'waiting_quota', nextAttemptAt: nextPacificMidnight().toISOString(), lastError: 'YouTube\'s daily allowance is used up; the upload continues after midnight Pacific time.' });
} else if (kind === 'reconnect') {
await connections.markNeedsReconnectById(failed.connectionId);
- await release({ state: 'needs_reconnect', lastError: 'Google no longer accepts this channel\'s sign-in. Connect YouTube again on the Accounts page.' });
+ await release({ state: 'needs_reconnect', lastError: 'Google no longer accepts this channel\'s sign-in. Choose Verify again on the channel on the Accounts page.' });
} else if (kind === 'session_gone') {
// with every byte sent the video may exist; a person checks before a second upload
if (at.confirmed >= failed.sourceBytes) await release({ state: 'needs_review', lastError: LOST_ANSWER });
diff --git a/backend/services/youtubeUploadService.ts b/backend/services/youtubeUploadService.ts
index b1dbe1c..50a2184 100644
--- a/backend/services/youtubeUploadService.ts
+++ b/backend/services/youtubeUploadService.ts
@@ -53,7 +53,7 @@ export function createYouTubeUploadService({ uploads, connections, media, audit,
const problem = metadataProblem({ title: request.title, description: request.description ?? '', tags: request.tags ?? [] });
if (problem) throw new ValidationError(problem);
const connection = await connections.findForUser(request.connectionId, userId);
- if (!connection) throw new NotFoundError('No connected YouTube channel with that id. Connect YouTube on the Accounts page first.');
+ if (!connection) throw new NotFoundError('No YouTube channel verified for publishing with that id. Verify the channel on the Accounts page first.');
const video = await media.findForUser(request.mediaId, userId);
if (!video || video.resourceType !== 'video') throw new NotFoundError('No video with that id in your media.');
if (!video.bytes) throw new ValidationError('The size of this video is unknown, so it cannot be uploaded in parts. Upload it again.');
diff --git a/backend/tests/fixtures/accountsRoutes.delete.golden.json b/backend/tests/fixtures/accountsRoutes.delete.golden.json
index 7d53fbc..1401587 100644
--- a/backend/tests/fixtures/accountsRoutes.delete.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.delete.golden.json
@@ -115,6 +115,21 @@
]
]
},
+ {
+ "type": "select",
+ "table": "youtube_connections",
+ "columns": "id, user_id, account_id, channel_id, channel_title, scopes, status, refresh_token_enc, access_token_enc, access_token_expires_at, created_at",
+ "filters": [
+ [
+ "channel_id",
+ "UCmissingmissingmissing0"
+ ],
+ [
+ "user_id",
+ "user-1"
+ ]
+ ]
+ },
{
"type": "delete",
"table": "accounts",
diff --git a/backend/tests/lib/oauthState.test.ts b/backend/tests/lib/oauthState.test.ts
index 287af50..46d6c10 100644
--- a/backend/tests/lib/oauthState.test.ts
+++ b/backend/tests/lib/oauthState.test.ts
@@ -1,6 +1,6 @@
import { test, mock } from 'node:test';
import assert from 'node:assert/strict';
-import { createOAuthState, verifyOAuthState } from '../../lib/oauthState.ts';
+import { createOAuthState, readOAuthState, verifyOAuthState } from '../../lib/oauthState.ts';
test('a state verifies back to its user id', async () => {
const state = await createOAuthState('user-123', 'secret');
@@ -33,3 +33,9 @@ test('a state older than 10 minutes is rejected', async () => {
mock.timers.reset();
}
});
+
+test('a state carries its subject, and a state without one reads back as null', async () => {
+ assert.deepEqual(await readOAuthState(await createOAuthState('user-123', 'secret', 'account-9'), 'secret'), { userId: 'user-123', subject: 'account-9' });
+ assert.deepEqual(await readOAuthState(await createOAuthState('user-123', 'secret'), 'secret'), { userId: 'user-123', subject: null });
+ assert.equal(await verifyOAuthState(await createOAuthState('user-123', 'secret', 'account-9'), 'secret'), 'user-123');
+});
diff --git a/backend/tests/routes/youtubeRoutes.test.ts b/backend/tests/routes/youtubeRoutes.test.ts
index e3fc2e1..399d6a9 100644
--- a/backend/tests/routes/youtubeRoutes.test.ts
+++ b/backend/tests/routes/youtubeRoutes.test.ts
@@ -1,8 +1,8 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { handleYouTubeCallback } from '../../controllers/youtubeController.ts';
-import { createOAuthState } from '../../lib/oauthState.ts';
-import { fakeSupabase } from '../fixtures/fakeSupabase.ts';
+import { getYouTubeAuthUrl, handleYouTubeCallback } from '../../controllers/youtubeController.ts';
+import { createOAuthState, readOAuthState } from '../../lib/oauthState.ts';
+import { accountRow, fakeSupabase } from '../fixtures/fakeSupabase.ts';
import { mountWithContext } from '../fixtures/routeHarness.ts';
import type { Env } from '../../types/env.ts';
@@ -31,3 +31,19 @@ test('a changed state, a cancelled sign-in or an unconfigured server never reach
const unconfigured = await app().request('/auth/youtube/callback?code=CODE&state=x', {}, {});
assert.equal(unconfigured.status, 503);
});
+
+test('a verify link is only made for one of the person\'s own YouTube channels, and names it in the signed state', async () => {
+ const supabase = fakeSupabase([
+ accountRow({ id: 'yt1', platform: 'youtube', channelId: 'UC123' }),
+ accountRow({ id: 'ig1', platform: 'instagram', igUserId: '1789' }),
+ accountRow({ id: 'theirs', platform: 'youtube', channelId: 'UC999' }, 'user-2'),
+ ]);
+ const server = mountWithContext(app => app.get('/auth/youtube/url', ...getYouTubeAuthUrl), { supabase, redis: null, rateLimitRedis: null, userId: 'user-1' });
+ assert.equal((await server.request('/auth/youtube/url', {}, ENV)).status, 400);
+ assert.equal((await server.request('/auth/youtube/url?accountId=ig1', {}, ENV)).status, 404);
+ assert.equal((await server.request('/auth/youtube/url?accountId=theirs', {}, ENV)).status, 404);
+ const made = await server.request('/auth/youtube/url?accountId=yt1', {}, ENV);
+ assert.equal(made.status, 200);
+ const state = new URL(((await made.json()) as { url: string }).url).searchParams.get('state') ?? '';
+ assert.deepEqual(await readOAuthState(state, 'google-secret'), { userId: 'user-1', subject: 'yt1' });
+});
diff --git a/backend/tests/services/accountService.test.ts b/backend/tests/services/accountService.test.ts
index 1c20f5c..df28636 100644
--- a/backend/tests/services/accountService.test.ts
+++ b/backend/tests/services/accountService.test.ts
@@ -51,3 +51,23 @@ test('any other failed insert stays a database error', async t => {
const accounts = accountsFailingWith({ code: '08006', message: 'connection failure' });
await assert.rejects(service(accounts).addYouTube('user-1', CHANNEL_ID), DatabaseError);
});
+
+test('removing a YouTube account turns off its publishing first; removing an Instagram account does not touch YouTube', async () => {
+ const owned = [{ id: 'yt1', platform: 'youtube', channelId: CHANNEL_ID }, { id: 'ig1', platform: 'instagram' }];
+ const steps: string[] = [];
+ const accounts = {
+ findForUser: async (id: string) => owned.find(account => account.id === id) ?? null,
+ deleteForUser: async (id: string) => { steps.push(`deleted ${id}`); },
+ } as unknown as AccountRepository;
+ const removing = createAccountService({
+ accounts,
+ cache: { deleteAllForAccount: async () => undefined } as unknown as AnalyticsCacheRepository,
+ audit: { recordForUser: async () => undefined } as unknown as AuditRepository,
+ config: readConfig({ YOUTUBE_API_KEY: 'KEY' } as Env),
+ context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },
+ youtubePublishing: { disconnectChannel: async (_userId, channelId) => { steps.push(`publishing off ${channelId}`); } },
+ });
+ await removing.remove('user-1', 'yt1');
+ await removing.remove('user-1', 'ig1');
+ assert.deepEqual(steps, [`publishing off ${CHANNEL_ID}`, 'deleted yt1', 'deleted ig1']);
+});
diff --git a/backend/tests/services/youtubeConnectService.test.ts b/backend/tests/services/youtubeConnectService.test.ts
index 30972c0..631c085 100644
--- a/backend/tests/services/youtubeConnectService.test.ts
+++ b/backend/tests/services/youtubeConnectService.test.ts
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import { createYouTubeConnectService } from '../../services/youtubeConnectService.ts';
import { createOAuthState } from '../../lib/oauthState.ts';
import { decryptToken, encryptToken } from '../../lib/tokenCrypto.ts';
-import { ForbiddenError, NotConfiguredError, ValidationError } from '../../lib/errors.ts';
+import { ForbiddenError, NotConfiguredError, NotFoundError, ValidationError } from '../../lib/errors.ts';
import { readConfig } from '../../lib/config.ts';
import { createLogger } from '../../lib/logger.ts';
import type { NewYouTubeConnection, StoredYouTubeConnection, YouTubeConnectionRepository, YouTubeConnectionTokens } from '../../repositories/youtubeConnectionRepository.ts';
@@ -42,7 +42,12 @@ function memory() {
parkForConnection: async (id: string) => { parked.push(id); },
resumeParkedForUser: async (id: string) => { resumed.push(id); },
} as unknown as YouTubeUploadRepository;
- const accounts = { listForUser: async () => [{ id: 'acc-1', platform: 'youtube', channelId: 'UC123' }] } as unknown as AccountRepository;
+ const owned = [
+ { id: 'acc-1', userId: 'user-1', platform: 'youtube', channelId: 'UC123', title: 'Cooking' },
+ { id: 'acc-2', userId: 'user-1', platform: 'youtube', channelId: 'UC999', title: 'Travel' },
+ { id: 'ig-1', userId: 'user-1', platform: 'instagram' },
+ ];
+ const accounts = { findForUser: async (id: string, userId: string) => owned.find(item => item.id === id && item.userId === userId) ?? null } as unknown as AccountRepository;
const audit = { recordForUser: async () => undefined } as unknown as AuditRepository;
return { rows, parked, resumed, service: createYouTubeConnectService({ connections, uploads, accounts, audit, config: readConfig(ENV), context: CONTEXT }) };
}
@@ -57,22 +62,22 @@ function google(t: { after(fn: () => void): void }, token: Record<string, unknow
test('a sign-in started by one person cannot be finished by another, and a changed state is refused', async () => {
const { service } = memory();
- const state = await createOAuthState('user-1', 'google-secret');
+ const state = await createOAuthState('user-1', 'google-secret', 'acc-1');
await assert.rejects(service.completeForUser('user-2', 'code', state), ForbiddenError);
await assert.rejects(service.completeForUser('user-1', 'code', `${state}x`), ValidationError);
});
-test('finishing a sign-in seals both tokens, links the analytics account, and a second sign-in renews in place and resumes parked uploads', async t => {
+test('verifying a channel seals both tokens, links its account, and a second sign-in renews in place and resumes parked uploads', async t => {
google(t, { access_token: 'ACCESS', refresh_token: 'REFRESH', expires_in: 3600, scope: 'https://www.googleapis.com/auth/youtube.upload' });
const { rows, resumed, service } = memory();
- const state = await createOAuthState('user-1', 'google-secret');
+ const state = await createOAuthState('user-1', 'google-secret', 'acc-1');
const first = await service.completeForUser('user-1', 'code', state);
assert.equal(first.outcome, 'connected');
assert.equal(first.connection.accountId, 'acc-1');
assert.equal(JSON.stringify(first).includes('REFRESH'), false);
assert.equal(await decryptToken(rows[0].refreshTokenEnc, SECRET), 'REFRESH');
assert.ok(!rows[0].refreshTokenEnc.includes('REFRESH'));
- const again = await service.completeForUser('user-1', 'code', await createOAuthState('user-1', 'google-secret'));
+ const again = await service.completeForUser('user-1', 'code', await createOAuthState('user-1', 'google-secret', 'acc-1'));
assert.equal(again.outcome, 'reconnected');
assert.equal(rows.length, 1);
assert.deepEqual(resumed, [rows[0].id]);
@@ -98,5 +103,44 @@ test('without the Google client settings, connecting says what the owner must se
audit: {} as AuditRepository, config: readConfig({} as Env), context: CONTEXT,
});
assert.equal(service.configured(), false);
- await assert.rejects(service.authorizationUrl('user-1'), (err: Error) => err instanceof NotConfiguredError && /GOOGLE_CLIENT_ID/.test(err.message));
+ await assert.rejects(service.authorizationUrl('user-1', 'acc-1'), (err: Error) => err instanceof NotConfiguredError && /GOOGLE_CLIENT_ID/.test(err.message));
+});
+
+test('a sign-in that returns another channel verifies nothing and gives back the access Google granted', async t => {
+ const fetchMock = google(t, { access_token: 'ACCESS', refresh_token: 'REFRESH', expires_in: 3600, scope: '' });
+ const { rows, service } = memory();
+ await assert.rejects(
+ service.completeForUser('user-1', 'code', await createOAuthState('user-1', 'google-secret', 'acc-2')),
+ (err: Error) => err instanceof ValidationError && /signed you in to Cooking, not Travel/.test(err.message) && /pick Travel/.test(err.message),
+ );
+ assert.equal(rows.length, 0);
+ assert.ok(fetchMock.mock.calls.some(call => String(call.arguments[0]).includes('oauth2.googleapis.com/revoke')));
+});
+
+test('a sign-in must name one of the person\'s own YouTube channels, both when it starts and when it finishes', async () => {
+ const { service } = memory();
+ await assert.rejects(service.authorizationUrl('user-1', 'ig-1'), NotFoundError);
+ await assert.rejects(service.authorizationUrl('user-2', 'acc-1'), NotFoundError);
+ assert.ok((await service.authorizationUrl('user-1', 'acc-1')).startsWith('https://accounts.google.com/'));
+ await assert.rejects(service.completeForUser('user-1', 'code', await createOAuthState('user-1', 'google-secret')), ValidationError);
+ await assert.rejects(service.completeForUser('user-1', 'code', await createOAuthState('user-1', 'google-secret', 'missing')), NotFoundError);
+});
+
+test('removing a channel\'s account turns its publishing off, and an unverified channel is left alone', async () => {
+ const { rows } = memory();
+ rows.push({
+ id: 'c1', userId: 'user-1', channelId: 'UC123', channelTitle: 'Cooking', accountId: 'acc-1', status: 'active', scopes: [], createdAt: '',
+ refreshTokenEnc: 'sealed', accessTokenEnc: null, accessTokenExpiresAt: null,
+ });
+ const removed: string[] = [];
+ const tracked = createYouTubeConnectService({
+ connections: { findByChannelForUser: async (channelId: string, userId: string) => rows.find(row => row.channelId === channelId && row.userId === userId) ?? null, deleteForUser: async (id: string) => { removed.push(id); return true; } } as unknown as YouTubeConnectionRepository,
+ uploads: {} as YouTubeUploadRepository, accounts: {} as AccountRepository,
+ audit: { recordForUser: async () => undefined } as unknown as AuditRepository, config: readConfig(ENV), context: CONTEXT,
+ });
+ await tracked.disconnectChannel('user-1', 'UC999');
+ await tracked.disconnectChannel('user-2', 'UC123');
+ assert.deepEqual(removed, []);
+ await tracked.disconnectChannel('user-1', 'UC123');
+ assert.deepEqual(removed, ['c1']);
});
diff --git a/backend/validators/youtubeValidators.ts b/backend/validators/youtubeValidators.ts
index 485e4fc..3ea94ff 100644
--- a/backend/validators/youtubeValidators.ts
+++ b/backend/validators/youtubeValidators.ts
@@ -2,7 +2,7 @@ import { ValidationError } from '../lib/errors.ts';
import { optionalBoolean, optionalString, requiredString } from './fields.ts';
import type { Fields } from './fields.ts';
import type {
- YouTubeConnectCompleteRequest, YouTubePrivacy, YouTubeUploadRequest, YouTubeUploadUpdateRequest,
+ YouTubeAuthUrlQuery, YouTubeConnectCompleteRequest, YouTubePrivacy, YouTubeUploadRequest, YouTubeUploadUpdateRequest,
} from '../../shared/types/youtubePublishing.ts';
const PRIVACY: YouTubePrivacy[] = ['private', 'unlisted', 'public'];
@@ -85,10 +85,16 @@ export function parseYouTubeUploadUpdate(body: Fields): YouTubeUploadUpdateReque
return edit;
}
+export function parseYouTubeAuthUrl(query: Fields): YouTubeAuthUrlQuery {
+ const accountId = requiredString(query, 'accountId', 'accountId is required: the YouTube channel to verify.').trim();
+ if (accountId.length > MAX_ID) throw new ValidationError(`accountId must be at most ${MAX_ID} characters`);
+ return { accountId };
+}
+
export function parseYouTubeComplete(body: Fields): YouTubeConnectCompleteRequest {
return {
- code: requiredString(body, 'code', 'The Google sign-in code is missing. Start connecting again.'),
- state: requiredString(body, 'state', 'The Google sign-in state is missing. Start connecting again.'),
+ code: requiredString(body, 'code', 'The Google sign-in code is missing. Choose Verify on the channel again.'),
+ state: requiredString(body, 'state', 'The Google sign-in state is missing. Choose Verify on the channel again.'),
};
}
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 23955e6..a732ba8 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -202,8 +202,8 @@ Controllers in `youtubeController.ts` call `YouTubeConnectService` and `YouTubeU
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/auth/youtube/url` | `youtubeRoutes.ts`, `youtubeController.getYouTubeAuthUrl` | Google's consent URL with a state signed for the caller; `503` when not set up |
-| POST | `/api/auth/youtube/complete` | `youtubeRoutes.ts`, `youtubeController.completeYouTubeConnection` | Body `{ code, state }`: connects the channel only when the state was started by the caller (403 otherwise); answers `{ connection, outcome: 'connected' \| 'reconnected' }` |
+| GET | `/api/auth/youtube/url` | `youtubeRoutes.ts`, `youtubeController.getYouTubeAuthUrl` | Query `accountId`: one of the caller's YouTube accounts (`400` without it, `404` for any other account). Answers Google's consent URL with a state signed for the caller that names that account; `503` when not set up |
+| POST | `/api/auth/youtube/complete` | `youtubeRoutes.ts`, `youtubeController.completeYouTubeConnection` | Body `{ code, state }`: verifies the channel for publishing only when the state was started by the caller (`403` otherwise) and Google returned the channel of the account the state names (`400` otherwise, after revoking the access Google granted); answers `{ connection, outcome: 'connected' \| 'reconnected' }` |
| GET | `/api/youtube/connections` | `youtubeRoutes.ts`, `youtubeController.listYouTubeConnections` | The caller's connected channels (never a token) and `configured` |
| DELETE | `/api/youtube/connections/:id` | `youtubeRoutes.ts`, `youtubeController.deleteYouTubeConnection` | Revokes the access at Google and removes the connection with its uploads |
| GET | `/api/youtube/uploads` | `youtubeRoutes.ts`, `youtubeController.listYouTubeUploads` | The caller's 200 newest upload jobs |
diff --git a/shared/types/youtubePublishing.ts b/shared/types/youtubePublishing.ts
index 8ce26d1..56e5c76 100644
--- a/shared/types/youtubePublishing.ts
+++ b/shared/types/youtubePublishing.ts
@@ -74,6 +74,11 @@ export interface YouTubeConnectionListResponse {
configured: boolean;
}
+// the YouTube account (analytics card) whose channel the Google sign-in must prove
+export interface YouTubeAuthUrlQuery {
+ accountId: string;
+}
+
export interface YouTubeAuthUrlResponse {
success: true;
url: string;