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(accounts): verify YouTube channels for publishing from their own cards
spacesdrive5372acdb29da
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.mdindex fe3ca94..1d452f1 100644--- a/docs/architecture/frontend/API_LAYER.md+++ b/docs/architecture/frontend/API_LAYER.md@@ -162,7 +162,7 @@ The types are in `shared/types/mcp.ts`. Settings, Claude (`features/settings/use## YouTube Publishing and Media Methods-`getMedia`, `registerMedia` and `uploadWithDetails` (a browser upload to Cloudinary that also returns the id, size and dimensions) feed the media library. `getYouTubeConnections`, `getYouTubeAuthUrl`, `completeYouTubeConnection` and `deleteYouTubeConnection` serve the Accounts page panel; `getYouTubeUploads`, `createYouTubeUpload`, `updateYouTubeUpload`, `cancelYouTubeUpload` and `retryYouTubeUpload` serve the YouTube uploads page. Types are in `shared/types/youtubePublishing.ts` and `shared/types/media.ts`.+`getMedia`, `registerMedia` and `uploadWithDetails` (a browser upload to Cloudinary that also returns the id, size and dimensions) feed the media library. `getYouTubeConnections`, `getYouTubeAuthUrl(accountId)` (Verify on a YouTube card), `completeYouTubeConnection` and `deleteYouTubeConnection` (Turn off) serve the publishing row on the Accounts page YouTube cards; `getYouTubeUploads`, `createYouTubeUpload`, `updateYouTubeUpload`, `cancelYouTubeUpload` and `retryYouTubeUpload` serve the YouTube uploads page. Types are in `shared/types/youtubePublishing.ts` and `shared/types/media.ts`.## Tracked Content Methodsdiff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdindex 1ceec1d..12a13f7 100644--- a/docs/architecture/frontend/FEATURES.md+++ b/docs/architecture/frontend/FEATURES.md@@ -56,6 +56,9 @@ frontend/src/│ │ ├── useAccountRefresh.ts, useAccountDelete.ts│ │ ├── useInstagramOAuthReturn.ts <- Finishes a sign-in from #ig_code and #ig_state, reads ?ig_error and ?add, then clears them│ │ ├── platformChoices.ts <- Platform choice titles, descriptions and icons+│ │ ├── YouTubePublishingRow.tsx <- A YouTube card's publishing row: Verify, Verify again, or Verified with Turn off+│ │ ├── useYouTubeConnections.ts <- Which channels can publish; starts Verify, finishes it from #yt_code, turns publishing off+│ │ ├── youtubePublishingState.ts <- Pure card publishing state and Google return errors (youtubePublishingState.test.ts)│ │ └── accountManagerData.ts <- Pure OAuth return, error text, card metrics (accountManagerData.test.ts)│ ├── publishing/│ │ ├── UploadContent.tsx <- Page: tabs, Cloudinary alert, scheduled posts (default export)diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.mdindex 07c2676..fafe959 100644--- a/docs/architecture/frontend/ROUTING.md+++ b/docs/architecture/frontend/ROUTING.md@@ -10,7 +10,7 @@ The app uses React Router 7 in `frontend/src/App.tsx`: a data router from `creat|---|---|---|| `/login` | `Login.tsx` | Public - redirects to `/` if already authenticated. Opens on the start view: Continue with Google, an email field that sends a sign-in code, and a Use password link. `?mode=signup` keeps the same view with the headline "Create your Twiligent account" and Google's "Sign up with Google"; the emailed code creates the account the first time an address is used (the public site's Get started buttons link to `https://app.twiligent.ujjwal.fyi/login?mode=signup`) || `/oauth/consent` | `pages/OAuthConsent.tsx` | Protected, outside the app shell: Supabase Auth's OAuth server sends a person here to approve a Claude app (`?authorization_id=`). Signed out, it signs in through `/login?next=...` and comes back. See `docs/architecture/data-flows/AUTHENTICATION.md` |-| `/youtube-uploads` | `features/youtube/YouTubeUploads.tsx` | Protected. Queue a video for a connected YouTube channel and follow every upload (Publishing group in the sidebar) |+| `/youtube-uploads` | `features/youtube/YouTubeUploads.tsx` | Protected. Queue a video for a YouTube channel verified for publishing and follow every upload (Publishing group in the sidebar) || `/docs/*` | `components/DocsRedirect.tsx` | Public. The docs live on the public site; this route replaces the location with the same path and hash under `https://twiligent.ujjwal.fyi/docs` (`docsUrl()` in `lib/docs.ts`), so old links keep working || `/` (layout) | `AppLayout` (inline) | Protected - redirects to `/login?next=<path>` if unauthenticated, and back after sign-in || `/` (index) | `Overview.tsx` | Default page after login |diff --git a/docs/platform-v2/YOUTUBE_INTEGRATION.md b/docs/platform-v2/YOUTUBE_INTEGRATION.mdindex caf11b3..1b628fa 100644--- a/docs/platform-v2/YOUTUBE_INTEGRATION.md+++ b/docs/platform-v2/YOUTUBE_INTEGRATION.md@@ -4,7 +4,7 @@ How Twiligent uploads videos and Shorts to a person's YouTube channel (#147): th## What it does-- A person connects a channel on the Accounts page (YouTube publishing) by signing in with Google once.+- A person verifies a YouTube channel they already added on the Accounts page: **Verify** on its card signs in with Google once, and Twiligent checks the Google account manages that channel. There is no separate list of publishing channels (#166).- On the YouTube uploads page (`/youtube-uploads`) they queue a video with:- title, description and tags;- category;@@ -20,23 +20,23 @@ How Twiligent uploads videos and Shorts to a person's YouTube channel (#147): th- A vertical or square video of at most three minutes becomes a Short. YouTube decides this from the file itself; there is no separate Shorts upload.- Playlists are not part of this release. Adding a video to a playlist needs Google's full `youtube` scope; Twiligent asks only to upload and to read, so a leaked token can never change or delete what is already on a channel.-## Connecting a channel+## Verifying a channel-1. `GET /api/auth/youtube/url` (signed in) returns Google's consent URL:+1. `GET /api/auth/youtube/url?accountId=<id>` (signed in, for one of the person's own YouTube accounts) returns Google's consent URL:- scopes `youtube.upload` and `youtube.readonly`;- `access_type=offline` and `prompt=consent`, so a refresh token comes back every time;- - a state signed with the Google client secret that names the person.+ - a state signed with the Google client secret that names the person and the account (`createOAuthState` with a subject).2. Google sends the browser to the public `GET /api/auth/youtube/callback`.- It checks the state's signature and redirects to the Accounts page with `#yt_code=...&yt_state=...` in the fragment, which never reaches a server or a referrer.- A cancelled or changed sign-in goes back with `?yt_error=...`.3. The signed-in app posts the code to `POST /api/auth/youtube/complete`. The service:- - refuses a state started by anyone else (403);+ - refuses a state started by anyone else (403), or one that names no account or an account that is gone;- exchanges the code;- - reads the channel with `channels.list?mine=true`;- - links the analytics account for the same channel, if there is one;- - stores both tokens sealed with AES-GCM under a key derived from `TOKEN_ENCRYPTION_KEY` (`backend/lib/tokenCrypto.ts`).-4. Signing in again for the same channel renews its tokens in place and puts any parked uploads back in the queue.-5. Disconnecting asks Google to revoke the refresh token, then deletes the connection with its upload queue and history. Videos already on YouTube stay.+ - reads the channel with `channels.list?mine=true`, which answers for the channel the person picked in Google's channel chooser;+ - refuses any channel but the account's own (400, naming both channels), after revoking the access Google just granted. This is the proof of ownership: only a Google account that manages the channel can return it;+ - stores both tokens sealed with AES-GCM under a key derived from `TOKEN_ENCRYPTION_KEY` (`backend/lib/tokenCrypto.ts`), linked to the account.+4. Verifying the same channel again renews its tokens in place and puts any parked uploads back in the queue.+5. **Turn off** on the card asks Google to revoke the refresh token, then deletes the connection with its upload queue and history. Removing the YouTube account does the same first (`accountService.remove` calls `disconnectChannel`). Videos already on YouTube stay.Tokens never appear in a response, a log or an MCP result. A refresh Google refuses (`invalid_grant`), or a token that no longer unseals because the key changed, marks the connection `needs_reconnect` and parks its uploads without spending their attempts.@@ -99,7 +99,7 @@ The Google Cloud project's daily allowance is shared by every channel on the ins- **Video size:** Cloudinary's plan sets the largest video, 100 MB on the free plan. Larger videos need a paid plan.- **Throughput:** four YouTube runs an hour move about 400 MB an hour. Each run handles one job at a time.- **Worker CPU:** each chunk copies 8 MiB through the Worker. Whether that stays within the Workers Free plan's 10 ms of CPU per invocation has not been measured; if it does not, the run fails as a passing error and the paid plan is the fix.-- **Unverified Google projects:** uploads from a project still in testing are locked private by YouTube, and testing-mode refresh tokens expire after 7 days. Publish the OAuth consent screen to production.+- **The Google app's publishing status:** while the OAuth consent screen is in testing, only its listed test users can sign in and their refresh tokens expire after 7 days; publish it to production. An app not verified by Google shows people an unverified-app screen at sign-in and is limited to 100 users. Google's `videos.insert` reference (checked 5 Nov 2026) no longer locks uploads from unaudited API projects as private; Google confirmed the change on its issue tracker in October 2026, though its revision history still has the 2020 rule.## Security@@ -129,7 +129,7 @@ The Google Cloud project's daily allowance is shared by every channel on the ins- `npx wrangler secret put GOOGLE_CLIENT_SECRET`- `npx wrangler secret put TOKEN_ENCRYPTION_KEY`: 32 or more random characters, for example from `openssl rand -base64 48`. Changing it later makes every stored token unreadable, and people must connect again.3. Apply the migrations: `npm run db:push`, then `npm run db:schema`.-4. Deploy the Worker. Open Accounts, then YouTube publishing, then Connect a channel.+4. Deploy the Worker. On the Accounts page, add the channel if it is not there, then choose **Verify** on its card.The public guide is at `https://twiligent.ujjwal.fyi/docs/self-host/youtube-publishing` (source: `site/content/docs/self-host/youtube-publishing.mdx`).diff --git a/frontend/src/features/accounts/AccountCard.tsx b/frontend/src/features/accounts/AccountCard.tsxindex ca9279e..a1c7d43 100644--- a/frontend/src/features/accounts/AccountCard.tsx+++ b/frontend/src/features/accounts/AccountCard.tsx@@ -18,9 +18,11 @@ export interface AccountCardProps {refreshing: boolean;onRefresh: () => void;onDelete: () => void;+ // a platform's extra row above the actions, such as YouTube publishing+ extra?: React.ReactNode;}-export default function AccountCard({ acct, platform, refreshing, onRefresh, onDelete }: AccountCardProps) {+export default function AccountCard({ acct, platform, refreshing, onRefresh, onDelete, extra }: AccountCardProps) {const metrics = accountMetrics(platform, acct);return (<article className="flex flex-col gap-4 rounded-card border border-line bg-surface-raised p-4">@@ -51,6 +53,8 @@ export default function AccountCard({ acct, platform, refreshing, onRefresh, onD{acct.lastUpdated && <span>Updated <RelativeTime date={acct.lastUpdated} /></span>}</div>+ {extra}+<div className="mt-auto flex gap-2"><Button variant="outline" size="sm" className="flex-1" onClick={onRefresh} disabled={refreshing}><RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />diff --git a/frontend/src/features/accounts/AccountManager.tsx b/frontend/src/features/accounts/AccountManager.tsxindex 6594a34..0b72a08 100644--- a/frontend/src/features/accounts/AccountManager.tsx+++ b/frontend/src/features/accounts/AccountManager.tsx@@ -1,9 +1,11 @@-import React from 'react';+import React, { useState } from 'react';import { Plus, RefreshCw } from 'lucide-react';+import { Alert, AlertAction, AlertDescription } from '@/components/ui/alert';import { Button } from '@/components/ui/button';import PageHeader from '@/components/PageHeader';import ConfirmDialog from '@/components/ConfirmDialog';import { accountName, groupByPlatform, platformSummary } from '@/lib/accounts';+import { docsUrl } from '@/lib/docs';import { cn } from '@/lib/utils';import { useAppContext } from '../../context/AppContext';import { visibleSections } from './accountManagerData';@@ -11,10 +13,16 @@ import { useAddAccount } from './useAddAccount';import { useAccountRefresh } from './useAccountRefresh';import { useAccountDelete } from './useAccountDelete';import { useInstagramOAuthReturn } from './useInstagramOAuthReturn';+import { useYouTubeConnections } from './useYouTubeConnections';+import { cardPublishing } from './youtubePublishingState';import AccountsEmptyState from './AccountsEmptyState';import AccountSection from './AccountSection';import AddAccountDialog from './AddAccountDialog';-import YouTubePublishingSection from './YouTubePublishingSection';+import YouTubePublishingRow from './YouTubePublishingRow';+import type { AppAccount } from '../../utils/formatters';+import type { YouTubeConnectionSummary } from '@shared/types/youtubePublishing.ts';++const REMOVE_DESCRIPTION = 'Its cached analytics are deleted. Scheduled posts for this account are removed with it. You can add the account again later.';export default function AccountManager() {const { accounts, showToast, loadAccounts } = useAppContext();@@ -22,10 +30,43 @@ export default function AccountManager() {const { refreshingId, refreshOne, refreshAll } = useAccountRefresh({ showToast, loadAccounts });const { pendingDelete, setPendingDelete, deleting, handleDelete } = useAccountDelete({ showToast, loadAccounts });useInstagramOAuthReturn({ showToast, loadAccounts, setDialogOpen: addFlow.setDialogOpen });+ const youtube = useYouTubeConnections(showToast);+ const [pendingTurnOff, setPendingTurnOff] = useState<YouTubeConnectionSummary | null>(null);const groups = groupByPlatform(accounts);const sections = visibleSections(groups);const refreshingAll = refreshingId === 'all';+ const publishingStatus = { loading: youtube.loading, failed: youtube.error !== null, configured: youtube.configured, connections: youtube.connections };+ const publishingOf = (acct: AppAccount) => cardPublishing(acct, publishingStatus);+ const pendingPublishing = pendingDelete ? publishingOf(pendingDelete).kind : 'hidden';+ const deletingVerified = pendingPublishing === 'verified' || pendingPublishing === 'needs_sign_in';++ const youtubeNotice = youtube.error ? (+ <Alert variant="destructive" role="alert">+ <AlertDescription>Couldn't load which channels can publish. {youtube.error}</AlertDescription>+ <AlertAction><Button size="xs" variant="outline" onClick={() => { void youtube.reload(); }}>Try again</Button></AlertAction>+ </Alert>+ ) : !youtube.loading && !youtube.configured ? (+ <p className="max-w-prose text-sm text-ink-muted">+ Publishing to YouTube is not set up on this server, so channels can't be verified yet. Analytics work without it.{' '}+ <a href={docsUrl('/self-host/youtube-publishing')} target="_blank" rel="noopener noreferrer" className="font-medium text-brand-text underline underline-offset-4">+ How to set it up<span className="sr-only"> (opens in a new tab)</span>+ </a>+ </p>+ ) : null;++ const youtubeExtra = (acct: AppAccount) => {+ const publishing = publishingOf(acct);+ return (+ <YouTubePublishingRow+ publishing={publishing}+ channelName={accountName(acct)}+ verifying={youtube.verifyingId === acct.id}+ onVerify={() => { void youtube.verify(acct.id); }}+ onTurnOff={() => { if (publishing.kind === 'verified') setPendingTurnOff(publishing.connection); }}+ />+ );+ };return (<div className="flex flex-col gap-8">@@ -59,25 +100,41 @@ export default function AccountManager() {refreshingId={refreshingId}onRefresh={refreshOne}onDelete={setPendingDelete}+ notice={section.key === 'youtube' ? youtubeNotice : undefined}+ extraFor={section.key === 'youtube' ? youtubeExtra : undefined}/>)))}- <YouTubePublishingSection />-<AddAccountDialog flow={addFlow} /><ConfirmDialogopen={Boolean(pendingDelete)}onOpenChange={open => { if (!open) setPendingDelete(null); }}title={pendingDelete ? `Remove ${accountName(pendingDelete)}?` : 'Remove account?'}- description="Its cached analytics are deleted. Scheduled posts for this account are removed with it. You can add the account again later."+ description={deletingVerified+ ? `${REMOVE_DESCRIPTION} Its publishing is turned off too: Google is told to drop Twiligent's access, and its upload queue is removed. Videos already on YouTube stay there.`+ : REMOVE_DESCRIPTION}confirmLabel="Remove account"busyLabel="Removing"- onConfirm={handleDelete}+ onConfirm={() => { void handleDelete().then(youtube.reload); }}busy={deleting}hold/>++ <ConfirmDialog+ open={pendingTurnOff !== null}+ onOpenChange={open => { if (!open) setPendingTurnOff(null); }}+ title={`Turn off publishing for ${pendingTurnOff?.channelTitle || 'this channel'}?`}+ description="Google is told to drop Twiligent's access, and this channel's upload queue and history are removed. Videos already on YouTube stay there, and its analytics are not affected. You can verify it again later."+ confirmLabel="Turn off publishing"+ busyLabel="Turning off"+ busy={pendingTurnOff !== null && youtube.removingId === pendingTurnOff.id}+ onConfirm={() => {+ if (pendingTurnOff) void youtube.turnOff(pendingTurnOff).then(done => { if (done) setPendingTurnOff(null); });+ }}+ hold+ /></div>);}diff --git a/frontend/src/features/accounts/AccountSection.tsx b/frontend/src/features/accounts/AccountSection.tsxindex 6a36e3e..58f85cf 100644--- a/frontend/src/features/accounts/AccountSection.tsx+++ b/frontend/src/features/accounts/AccountSection.tsx@@ -12,20 +12,24 @@ export interface AccountSectionProps {refreshingId: string | null;onRefresh: (acct: AppAccount) => void;onDelete: (acct: AppAccount) => void;+ // one message for the whole section, so it is not repeated on every card+ notice?: React.ReactNode;+ extraFor?: (acct: AppAccount) => React.ReactNode;}-export default function AccountSection({ section, accounts, refreshingId, onRefresh, onDelete }: AccountSectionProps) {+export default function AccountSection({ section, accounts, refreshingId, onRefresh, onDelete, notice, extraFor }: AccountSectionProps) {return (- <section className="flex flex-col gap-3">+ <section id={section.key} aria-labelledby={`${section.key}-accounts-title`} className="flex scroll-mt-20 flex-col gap-3"><SectionHeadertitle={- <span className="flex items-center gap-2">+ <span id={`${section.key}-accounts-title`} className="flex items-center gap-2"><PlatformIcon platform={section.key} className="size-4 text-ink-muted" />{section.title}<Badge variant="secondary">{accounts.length}</Badge></span>}/>+ {notice}<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">{accounts.map(acct => (<AccountCard@@ -35,6 +39,7 @@ export default function AccountSection({ section, accounts, refreshingId, onRefrrefreshing={refreshingId === acct.id}onRefresh={() => onRefresh(acct)}onDelete={() => onDelete(acct)}+ extra={extraFor?.(acct)}/>))}</div>diff --git a/frontend/src/features/accounts/YouTubePublishingRow.tsx b/frontend/src/features/accounts/YouTubePublishingRow.tsxnew file mode 100644index 0000000..30128f4--- /dev/null+++ b/frontend/src/features/accounts/YouTubePublishingRow.tsx@@ -0,0 +1,56 @@+import React from 'react';+import { CheckCircle2, CircleDashed, ShieldCheck, TriangleAlert } from 'lucide-react';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import { Spinner } from '@/components/ui/spinner';+import type { CardPublishing } from './youtubePublishingState';++export interface YouTubePublishingRowProps {+ publishing: CardPublishing;+ channelName: string;+ verifying: boolean;+ onVerify: () => void;+ onTurnOff: () => void;+}++// publishing status for one YouTube card: whether Google confirmed the channel is the person's, and the one action that fits+export default function YouTubePublishingRow({ publishing, channelName, verifying, onVerify, onTurnOff }: YouTubePublishingRowProps) {+ if (publishing.kind === 'hidden') return null;+ if (publishing.kind === 'loading') return <Skeleton className="h-8 rounded-control" />;++ const verifyButton = (label: string) => (+ <Button variant="outline" size="sm" onClick={onVerify} disabled={verifying} aria-label={verifying ? undefined : `${label} for publishing: ${channelName}`}>+ {verifying ? <Spinner className="size-4" /> : <ShieldCheck data-icon="inline-start" />}+ {verifying ? 'Opening Google' : label}+ </Button>+ );++ return (+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-divider pt-3">+ {publishing.kind === 'verified' && (+ <>+ <Badge variant="success"><CheckCircle2 />Verified for publishing</Badge>+ <Button variant="ghost" size="sm" className="text-ink-muted" onClick={onTurnOff} aria-label={`Turn off publishing for ${channelName}`}>+ Turn off+ </Button>+ </>+ )}+ {publishing.kind === 'needs_sign_in' && (+ <>+ <Badge variant="warning"><TriangleAlert />Needs a new sign-in</Badge>+ {verifyButton('Verify again')}+ </>+ )}+ {publishing.kind === 'unverified' && (+ <>+ <span className="flex items-center gap-1.5 text-sm text-ink-muted">+ <CircleDashed className="size-4" aria-hidden="true" />+ Not verified for publishing+ </span>+ {verifyButton('Verify')}+ </>+ )}+ </div>+ );+}diff --git a/frontend/src/features/accounts/YouTubePublishingSection.tsx b/frontend/src/features/accounts/YouTubePublishingSection.tsxdeleted file mode 100644index 43f224a..0000000--- a/frontend/src/features/accounts/YouTubePublishingSection.tsx+++ /dev/null@@ -1,97 +0,0 @@-import React, { useState } from 'react';-import { CheckCircle2, Link2, Trash2, TriangleAlert } from 'lucide-react';-import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';-import { Skeleton } from '@/components/ui/skeleton';-import { Spinner } from '@/components/ui/spinner';-import ConfirmDialog from '@/components/ConfirmDialog';-import RelativeTime from '@/components/RelativeTime';-import RowAction from '@/components/RowAction';-import SurfaceBox from '@/components/SurfaceBox';-import { EmptyState, ErrorState } from '@/components/StateViews';-import { useAppContext } from '../../context/AppContext';-import { useYouTubeConnections } from './useYouTubeConnections';-import type { YouTubeConnectionSummary } from '@shared/types/youtubePublishing.ts';--export default function YouTubePublishingSection() {- const { showToast } = useAppContext();- const youtube = useYouTubeConnections(showToast);- const [pending, setPending] = useState<YouTubeConnectionSummary | null>(null);-- const connectButton = (- <Button variant="outline" onClick={() => { void youtube.connect(); }} disabled={youtube.connecting || !youtube.configured}>- {youtube.connecting ? <Spinner className="size-4" /> : <Link2 data-icon="inline-start" />}- {youtube.connecting ? 'Opening Google' : 'Connect a channel'}- </Button>- );-- return (- <section id="youtube-publishing" aria-labelledby="youtube-publishing-title" className="flex scroll-mt-20 flex-col gap-3">- <div className="flex flex-wrap items-end justify-between gap-3">- <div className="flex flex-col gap-1">- <h2 id="youtube-publishing-title" className="font-heading text-section font-semibold text-ink">YouTube publishing</h2>- <p className="max-w-prose text-body text-ink-muted">- Connect a channel with Google to upload videos to it. Twiligent asks only to upload and to read the channel, never to change or delete what is there.- </p>- </div>- {youtube.connections.length > 0 && connectButton}- </div>-- {youtube.loading ? (- <Skeleton className="h-24 rounded-card" />- ) : youtube.error ? (- <SurfaceBox><ErrorState title="YouTube connections could not load" description={youtube.error} onRetry={() => { void youtube.reload(); }} /></SurfaceBox>- ) : !youtube.configured ? (- <SurfaceBox>- <EmptyState compact icon={<TriangleAlert />} title="Not set up on this server" description="The owner needs to add a Google OAuth client and TOKEN_ENCRYPTION_KEY before channels can be connected." />- </SurfaceBox>- ) : youtube.connections.length === 0 ? (- <SurfaceBox>- <EmptyState compact icon={<Link2 />} title="No channel connected for publishing" description="Analytics work without this; publishing needs the channel owner to sign in once." action={connectButton} />- </SurfaceBox>- ) : (- <SurfaceBox content={false}>- <ul className="divide-y divide-divider">- {youtube.connections.map(connection => (- <li key={connection.id} className="flex items-center justify-between gap-4 px-4 py-3">- <div className="flex min-w-0 flex-col gap-1">- <div className="flex flex-wrap items-center gap-2">- <p className="truncate text-sm font-medium text-ink">{connection.channelTitle || connection.channelId}</p>- {connection.status === 'active'- ? <Badge variant="success"><CheckCircle2 />Connected</Badge>- : <Badge variant="warning"><TriangleAlert />Needs a new sign-in</Badge>}- </div>- <p className="text-caption text-ink-muted"><RelativeTime date={connection.createdAt} prefix="Connected " /></p>- </div>- <div className="flex items-center gap-2">- {connection.status !== 'active' && (- <Button variant="outline" size="sm" onClick={() => { void youtube.connect(); }} disabled={youtube.connecting} aria-label={`Sign in again: ${connection.channelTitle}`}>- Sign in again- </Button>- )}- <RowAction label="Disconnect" target={connection.channelTitle || connection.channelId} onClick={() => setPending(connection)} danger>- <Trash2 />- </RowAction>- </div>- </li>- ))}- </ul>- </SurfaceBox>- )}-- <ConfirmDialog- open={pending !== null}- onOpenChange={open => { if (!open) setPending(null); }}- title={`Disconnect ${pending?.channelTitle || 'this channel'}?`}- description="Google is told to drop Twiligent's access, and this channel's upload queue and history are removed. Videos already on YouTube stay there. Its analytics are not affected."- confirmLabel="Disconnect"- busyLabel="Disconnecting"- busy={pending !== null && youtube.removingId === pending.id}- onConfirm={() => {- if (pending) void youtube.disconnect(pending).then(done => { if (done) setPending(null); });- }}- hold- />- </section>- );-}diff --git a/frontend/src/features/accounts/useYouTubeConnections.ts b/frontend/src/features/accounts/useYouTubeConnections.tsindex e5a4917..a373a84 100644--- a/frontend/src/features/accounts/useYouTubeConnections.ts+++ b/frontend/src/features/accounts/useYouTubeConnections.ts@@ -1,18 +1,20 @@import { useCallback, useEffect, useRef, useState } from 'react';import { useSearchParams } from 'react-router-dom';import { api } from '../../services/api';-import { readYouTubeReturn, youtubeReturnError } from '../youtube/youtubeUploadData';+import { readYouTubeReturn } from '../youtube/youtubeUploadData';+import { verifyReturnError } from './youtubePublishingState';import type { AppContextValue } from '../../context/AppContext';import type { YouTubeConnectionSummary } from '@shared/types/youtubePublishing.ts';type ShowToast = AppContextValue['showToast'];+// publishing status for the YouTube cards on the Accounts page: verifying a channel and turning its publishing offexport function useYouTubeConnections(showToast: ShowToast) {const [connections, setConnections] = useState<YouTubeConnectionSummary[]>([]);const [configured, setConfigured] = useState(true);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);- const [connecting, setConnecting] = useState(false);+ const [verifyingId, setVerifyingId] = useState<string | null>(null);const [removingId, setRemovingId] = useState<string | null>(null);const [searchParams, setSearchParams] = useSearchParams();// the code works once, so a second run of the effect must not send it again@@ -33,7 +35,7 @@ export function useYouTubeConnections(showToast: ShowToast) {useEffect(() => { void load(); }, [load]);- // a finished Google sign-in: the server connects the channel only if this person started it+ // a finished Google sign-in: the server verifies the channel only if this person started it from that channel's carduseEffect(() => {const returned = readYouTubeReturn(window.location.hash);if (!returned || completing.current) return;@@ -42,14 +44,15 @@ export function useYouTubeConnections(showToast: ShowToast) {window.history.replaceState(window.history.state, '', window.location.pathname + window.location.search);api.completeYouTubeConnection(returned.code, returned.state).then(({ outcome, connection }) => {- showToast(`${connection.channelTitle || 'YouTube channel'} ${outcome === 'reconnected' ? 'reconnected' : 'connected'} for publishing`);+ const name = connection.channelTitle || 'The channel';+ showToast(outcome === 'reconnected' ? `${name} verified again` : `${name} verified for publishing`);void load();})- .catch((err: unknown) => showToast(`Couldn't connect YouTube. ${(err as Error).message}`, 'error'));+ .catch((err: unknown) => showToast(`Couldn't verify the channel. ${(err as Error).message}`, 'error'));}, [showToast, load]);useEffect(() => {- const message = youtubeReturnError(searchParams);+ const message = verifyReturnError(searchParams);if (!message) return;showToast(message, 'error');const next = new URLSearchParams(searchParams);@@ -57,31 +60,31 @@ export function useYouTubeConnections(showToast: ShowToast) {setSearchParams(next, { replace: true });}, [searchParams, setSearchParams, showToast]);- const connect = async () => {- setConnecting(true);+ const verify = async (accountId: string) => {+ setVerifyingId(accountId);try {- const { url } = await api.getYouTubeAuthUrl();+ const { url } = await api.getYouTubeAuthUrl(accountId);window.location.assign(url);} catch (err) {- showToast(`Couldn't start connecting YouTube. ${(err as Error).message}`, 'error');- setConnecting(false);+ showToast(`Couldn't start verifying the channel. ${(err as Error).message}`, 'error');+ setVerifyingId(null);}};- const disconnect = async (connection: YouTubeConnectionSummary): Promise<boolean> => {+ const turnOff = async (connection: YouTubeConnectionSummary): Promise<boolean> => {setRemovingId(connection.id);try {await api.deleteYouTubeConnection(connection.id);setConnections(current => current.filter(item => item.id !== connection.id));- showToast(`${connection.channelTitle || 'YouTube channel'} disconnected`);+ showToast(`Publishing turned off for ${connection.channelTitle || 'the channel'}`);return true;} catch (err) {- showToast(`Couldn't disconnect the channel. ${(err as Error).message}`, 'error');+ showToast(`Couldn't turn off publishing. ${(err as Error).message}`, 'error');return false;} finally {setRemovingId(null);}};- return { connections, configured, loading, error, reload: load, connecting, connect, removingId, disconnect };+ return { connections, configured, loading, error, reload: load, verifyingId, verify, removingId, turnOff };}diff --git a/frontend/src/features/accounts/youtubePublishingState.ts b/frontend/src/features/accounts/youtubePublishingState.tsnew file mode 100644index 0000000..c3a787e--- /dev/null+++ b/frontend/src/features/accounts/youtubePublishingState.ts@@ -0,0 +1,48 @@+import type { YouTubeConnectionSummary } from '../../../../shared/types/youtubePublishing.ts';++export interface PublishingAccount {+ id: string;+ platform: string;+ channelId?: string;+}++export interface PublishingStatus {+ loading: boolean;+ failed: boolean;+ configured: boolean;+ connections: YouTubeConnectionSummary[];+}++// hidden: not a YouTube card, or the section already says why publishing is unavailable+export type CardPublishing =+ | { kind: 'hidden' }+ | { kind: 'loading' }+ | { kind: 'unverified' }+ | { kind: 'verified'; connection: YouTubeConnectionSummary }+ | { kind: 'needs_sign_in'; connection: YouTubeConnectionSummary };++export function connectionFor(account: PublishingAccount, connections: YouTubeConnectionSummary[]): YouTubeConnectionSummary | null {+ return connections.find(connection => connection.accountId === account.id || (account.channelId !== undefined && connection.channelId === account.channelId)) ?? null;+}++export function cardPublishing(account: PublishingAccount, status: PublishingStatus): CardPublishing {+ if (account.platform !== 'youtube' || !account.channelId) return { kind: 'hidden' };+ if (status.loading) return { kind: 'loading' };+ if (status.failed || !status.configured) return { kind: 'hidden' };+ const connection = connectionFor(account, status.connections);+ if (!connection) return { kind: 'unverified' };+ return connection.status === 'active' ? { kind: 'verified', connection } : { kind: 'needs_sign_in', connection };+}++// a failed return from Google, as a toast that says what failed and what to do+const RETURN_ERRORS: Record<string, string> = {+ access_denied: 'Couldn\'t verify the channel. The Google sign-in was cancelled.',+ cancelled: 'Couldn\'t verify the channel. The Google sign-in was cancelled.',+ invalid_state: 'Couldn\'t verify the channel. The sign-in link expired or was changed. Choose Verify again.',+};++export function verifyReturnError(search: URLSearchParams): string | null {+ const error = search.get('yt_error');+ if (!error) return null;+ return RETURN_ERRORS[error] ?? `Couldn't verify the channel. Google answered "${error}". Choose Verify again.`;+}diff --git a/frontend/src/features/youtube/YouTubeUploads.tsx b/frontend/src/features/youtube/YouTubeUploads.tsxindex f6aed0b..216012c 100644--- a/frontend/src/features/youtube/YouTubeUploads.tsx+++ b/frontend/src/features/youtube/YouTubeUploads.tsx@@ -1,6 +1,6 @@import React from 'react';import { Link } from 'react-router-dom';-import { AlertCircle, Link2 } from 'lucide-react';+import { AlertCircle, ShieldCheck } from 'lucide-react';import { Alert, AlertDescription } from '@/components/ui/alert';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';@@ -14,7 +14,7 @@ import YouTubeComposer from './YouTubeComposer';import YouTubeUploadList from './YouTubeUploadList';import { useYouTubePublishing } from './useYouTubePublishing';-const DESCRIPTION = 'Upload videos and Shorts to your connected YouTube channels.';+const DESCRIPTION = 'Upload videos and Shorts to your YouTube channels verified for publishing.';export default function YouTubeUploads() {const { accounts, showToast } = useAppContext();@@ -50,10 +50,10 @@ export default function YouTubeUploads() {) : active.length === 0 ? (<SurfaceBox><EmptyState- icon={<Link2 />}- title={youtube.connections.length > 0 ? 'Your channel needs a new sign-in' : 'Connect a YouTube channel first'}- description="Connecting signs in with Google and lets Twiligent upload videos to the channel. It cannot change or delete videos already there."- action={<Button render={<Link to="/accounts#youtube-publishing" />}>Go to Accounts</Button>}+ icon={<ShieldCheck />}+ title={youtube.connections.length > 0 ? 'Your channel needs a new sign-in' : 'Verify a YouTube channel first'}+ description="On the Accounts page, choose Verify on the channel's card and sign in with the Google account that manages it. Twiligent can then upload to it, never change or delete videos already there."+ action={<Button render={<Link to="/accounts#youtube" />}>Go to Accounts</Button>}/></SurfaceBox>) : (diff --git a/frontend/src/features/youtube/youtubeUploadData.ts b/frontend/src/features/youtube/youtubeUploadData.tsindex c6ce18c..33689d1 100644--- a/frontend/src/features/youtube/youtubeUploadData.ts+++ b/frontend/src/features/youtube/youtubeUploadData.ts@@ -108,15 +108,3 @@ export function readYouTubeReturn(hash: string): YouTubeOAuthReturn | null {const state = params.get('yt_state');return code && state ? { code, state } : null;}--const RETURN_ERRORS: Record<string, string> = {- access_denied: 'YouTube was not connected: the sign-in was cancelled.',- invalid_state: 'YouTube was not connected: the sign-in link expired or was changed. Try again.',- cancelled: 'YouTube was not connected: the sign-in was cancelled.',-};--export function youtubeReturnError(search: URLSearchParams): string | null {- const error = search.get('yt_error');- if (!error) return null;- return RETURN_ERRORS[error] ?? `YouTube was not connected (${error}). Try again.`;-}diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.tsindex e0f9f29..76ff5c3 100644--- a/frontend/src/services/api.ts+++ b/frontend/src/services/api.ts@@ -232,9 +232,10 @@ export const api = {registerMedia: (data: MediaRegistrationRequest) => request<MediaResponse>('/media', { method: 'POST', body: JSON.stringify(data) }),uploadWithDetails,- // YouTube publishing: connecting a channel with Google, then upload jobs the scheduled runs move+ // YouTube publishing: verifying a channel with Google, then upload jobs the scheduled runs movegetYouTubeConnections: () => request<YouTubeConnectionListResponse>('/youtube/connections'),- getYouTubeAuthUrl: () => request<YouTubeAuthUrlResponse>('/auth/youtube/url'),+ // the sign-in proves the Google account manages this YouTube account's channel+ getYouTubeAuthUrl: (accountId: string) => request<YouTubeAuthUrlResponse>(`/auth/youtube/url?accountId=${encodeURIComponent(accountId)}`),completeYouTubeConnection: (code: string, state: string) => request<YouTubeConnectCompleteResponse>('/auth/youtube/complete', { method: 'POST', body: JSON.stringify({ code, state }) }),deleteYouTubeConnection: (id: string) => request<SuccessResponse>(`/youtube/connections/${id}`, { method: 'DELETE' }),getYouTubeUploads: () => request<YouTubeUploadListResponse>('/youtube/uploads'),diff --git a/frontend/tests/features/accounts/youtubePublishingState.test.ts b/frontend/tests/features/accounts/youtubePublishingState.test.tsnew file mode 100644index 0000000..f24e35f--- /dev/null+++ b/frontend/tests/features/accounts/youtubePublishingState.test.ts@@ -0,0 +1,32 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { cardPublishing, verifyReturnError } from '../../../src/features/accounts/youtubePublishingState.ts';+import type { YouTubeConnectionSummary } from '../../../../shared/types/youtubePublishing.ts';++const CHANNEL = { id: 'yt1', platform: 'youtube', channelId: 'UC1' };+const READY = { loading: false, failed: false, configured: true, connections: [] };++function connection(status: YouTubeConnectionSummary['status'], accountId: string | null = 'yt1'): YouTubeConnectionSummary {+ return { id: 'c1', channelId: 'UC1', channelTitle: 'Cooking', accountId, status, scopes: [], createdAt: '2026-11-05T00:00:00Z' };+}++test('a YouTube card shows whether its channel can publish, matched by account or by channel', () => {+ assert.deepEqual(cardPublishing(CHANNEL, READY), { kind: 'unverified' });+ assert.equal(cardPublishing(CHANNEL, { ...READY, connections: [connection('active')] }).kind, 'verified');+ assert.equal(cardPublishing(CHANNEL, { ...READY, connections: [connection('active', null)] }).kind, 'verified');+ assert.equal(cardPublishing(CHANNEL, { ...READY, connections: [connection('needs_reconnect')] }).kind, 'needs_sign_in');+ assert.equal(cardPublishing({ ...CHANNEL, channelId: 'UC2' }, { ...READY, connections: [connection('active', 'other')] }).kind, 'unverified');+});++test('cards stay quiet while the section explains why publishing is unavailable, and wait while it loads', () => {+ assert.deepEqual(cardPublishing(CHANNEL, { ...READY, loading: true }), { kind: 'loading' });+ assert.deepEqual(cardPublishing(CHANNEL, { ...READY, failed: true }), { kind: 'hidden' });+ assert.deepEqual(cardPublishing(CHANNEL, { ...READY, configured: false }), { kind: 'hidden' });+ assert.deepEqual(cardPublishing({ id: 'ig1', platform: 'instagram' }, READY), { kind: 'hidden' });+});++test('a failed return from Google says what failed and what to do', () => {+ assert.match(verifyReturnError(new URLSearchParams('yt_error=access_denied')) ?? '', /^Couldn't verify the channel\. .*cancelled/);+ assert.match(verifyReturnError(new URLSearchParams('yt_error=weird')) ?? '', /weird.*Choose Verify again/);+ assert.equal(verifyReturnError(new URLSearchParams('')), null);+});diff --git a/frontend/tests/features/youtube/youtubeUploadData.test.ts b/frontend/tests/features/youtube/youtubeUploadData.test.tsindex 52ce94d..4343cdb 100644--- a/frontend/tests/features/youtube/youtubeUploadData.test.ts+++ b/frontend/tests/features/youtube/youtubeUploadData.test.ts@@ -1,7 +1,7 @@import { test } from 'node:test';import assert from 'node:assert/strict';import {- STATE_DISPLAY, anyActive, composerProblem, parseTags, readYouTubeReturn, uploadPercent, youtubeReturnError,+ STATE_DISPLAY, anyActive, composerProblem, parseTags, readYouTubeReturn, uploadPercent,} from '../../../src/features/youtube/youtubeUploadData.ts';import type { ComposerValues } from '../../../src/features/youtube/youtubeUploadData.ts';@@ -38,10 +38,7 @@ test('the composer names the first missing field, including YouTube\'s requiredassert.equal(composerProblem({ ...READY, scheduled: true, publishAt: '2026-11-06T11:00' }, NOW), null);});-test('the sign-in return is read from the fragment, and errors from the query', () => {+test('the sign-in return is read from the fragment', () => {assert.deepEqual(readYouTubeReturn('#yt_code=abc&yt_state=s1'), { code: 'abc', state: 's1' });assert.equal(readYouTubeReturn('#ig_code=abc'), null);- assert.match(youtubeReturnError(new URLSearchParams('yt_error=access_denied')) ?? '', /cancelled/);- assert.match(youtubeReturnError(new URLSearchParams('yt_error=weird')) ?? '', /weird/);- assert.equal(youtubeReturnError(new URLSearchParams('')), null);});diff --git a/site/content/docs/reference/environment.mdx b/site/content/docs/reference/environment.mdxindex c4563aa..90ee41b 100644--- a/site/content/docs/reference/environment.mdx+++ b/site/content/docs/reference/environment.mdx@@ -32,7 +32,7 @@ The backend only answers browsers on `FRONTEND_URL` and the addresses in `ALLOWE| `EMAIL_FROM` | <Badge tone="optional">Optional</Badge> | A sender on a domain verified in Resend, for example {'Twiligent <[email protected]>'} | The sender of those emails. || `EMAIL_DAILY_LIMIT` | <Badge tone="optional">Optional</Badge> | A whole number; 100 when not set | Emails a day before the sign-in page pauses email codes and points people to Google or a password. || `CLOUDINARY_API_KEY`, `CLOUDINARY_API_SECRET` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">For Claude</Badge> | Cloudinary, Settings, API Keys | Lets Claude delete media files it imported from a link. Without them, and for files uploaded from the browser, a delete only removes Twiligent's record. |-| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">For YouTube publishing</Badge> | Google Cloud, Clients, your Web application client | Lets members connect their YouTube channels to upload videos. See [YouTube publishing](/docs/self-host/youtube-publishing). |+| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">For YouTube publishing</Badge> | Google Cloud, Clients, your Web application client | Lets members verify their YouTube channels to upload videos to them. See [YouTube publishing](/docs/self-host/youtube-publishing). || `TOKEN_ENCRYPTION_KEY` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">For Claude and YouTube</Badge> | 32 or more random characters, for example from {'openssl rand -base64 48'} | Signs the confirmations Claude needs before it schedules or cancels a post, and seals the stored Google tokens. If it changes, members connect YouTube again. || `MCP_OAUTH_ENABLED` | <Badge tone="optional">For Claude</Badge> | `true` | Lets Claude on the web, desktop and mobile connect, after you turn on Supabase's OAuth server. |diff --git a/site/content/docs/self-host/youtube-publishing.mdx b/site/content/docs/self-host/youtube-publishing.mdxindex b29bed8..757b62f 100644--- a/site/content/docs/self-host/youtube-publishing.mdx+++ b/site/content/docs/self-host/youtube-publishing.mdx@@ -12,9 +12,9 @@ In [Google Cloud](https://console.cloud.google.com/), choose the project you useOpen **Google Auth Platform** (OAuth consent screen). Give the app a name and support email, and add the scopes `.../auth/youtube.upload` and `.../auth/youtube.readonly`. Then publish the app to **In production**.-<Callout type="warning" title="Publish it, or uploads stay private">+<Callout type="warning" title="Publish it, or sign-ins expire">-While the app is in testing, YouTube locks every uploaded video as private and members must sign in again every 7 days. Google may ask to verify the app because the scopes are sensitive; until it does, members see a warning screen they can pass.+While the app is in testing, only the test users you list can sign in, and they must sign in again every 7 days. The scopes are sensitive, so until Google verifies the app, members see an unverified-app screen they can pass (choose **Advanced**, then go to the app), and at most 100 people can use it.</Callout>@@ -46,7 +46,7 @@ npx wrangler secret put TOKEN_ENCRYPTION_KEY</Step><Step title="Update the database and deploy">-Run `npm run db:push`, then deploy the backend. In the app, open **Accounts**, then **YouTube publishing**, then **Connect a channel**. Queue a video on the **YouTube uploads** page.+Run `npm run db:push`, then deploy the backend. In the app, open **Accounts**, add the channel if it is not there yet, and choose **Verify** on its card. Sign in with the Google account that manages the channel and pick that channel if Google asks; Twiligent refuses any other. Then queue a video on the **YouTube uploads** page.</Step></Steps>diff --git a/site/content/docs/use/claude.mdx b/site/content/docs/use/claude.mdxindex 9510b4f..99a38cb 100644--- a/site/content/docs/use/claude.mdx+++ b/site/content/docs/use/claude.mdx@@ -8,7 +8,7 @@ Each connection signs in as you and sees only your accounts. You decide whether| With | Claude can || --- | --- |-| Read only | List your accounts; read YouTube channel and Instagram account analytics; list videos and posts; compare your YouTube channels; list your imported media, your connected YouTube channels and your YouTube uploads; read your scheduled posts, your settings (never keys or tokens) and an account's Instagram publishing limit |+| Read only | List your accounts; read YouTube channel and Instagram account analytics; list videos and posts; compare your YouTube channels; list your imported media, your YouTube channels verified for publishing and your YouTube uploads; read your scheduled posts, your settings (never keys or tokens) and an account's Instagram publishing limit || Read and make changes | Everything above, plus import images and videos from a public link, rename or delete them, schedule, edit and cancel Instagram posts, queue, change, retry and cancel YouTube uploads, and change the GitHub scheduling setting |Before Claude schedules or cancels a post, or deletes media, it must ask you. Twiligent gives it a one-time confirmation for exactly that post, and it can only go ahead after you agree.