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.

docs(youtube): document YouTube publishing, its setup, routes, tables and tools

spacesdrive0a5a5c66b353
diff --git a/DECISIONS.md b/DECISIONS.md
index db3e276..e4bebbc 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -1139,3 +1139,26 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts
**Trade-offs:**
- A video larger than Cloudinary's plan limit, or slower than a tool call, cannot be imported this way.
- Without the API secret, files deleted in Twiligent stay on Cloudinary until the owner removes them.
+
+---
+
+## ADR-053: YouTube uploads run as leased jobs that stream Cloudinary byte ranges into resumable sessions
+
+**Date:** 2026-11-05
+**Status:** Accepted
+
+**Decision:** YouTube publishing (#147) stores one `youtube_uploads` row per video. The five minute cron gives four runs an hour to `youtubeRunner`, which leases one job (`claim_youtube_upload`, `FOR UPDATE SKIP LOCKED`), saves the resumable session before sending any byte, resumes from Google's own count, and moves 8 MiB chunks read from Cloudinary by byte range until its 50 subrequests or 12 minutes run out; processing and the thumbnail are separate later steps. Each channel is connected by its owner through Google OAuth with only the `youtube.upload` and `youtube.readonly` scopes, finished by the person who started it, and its tokens are sealed with AES-GCM under a key derived from `TOKEN_ENCRYPTION_KEY`. A Postgres ledger counts the Google project's daily units and inserts per Pacific day before each call. New Worker secrets: `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`.
+
+**Context:** The Worker runs on the Free plan (10 ms CPU, 50 subrequests, 15 minute cron limit), so a video cannot be uploaded in one request, and a run that dies must never start a second copy of the same video on a public channel.
+
+**Alternatives considered:**
+- Uploading at publish time, as with Instagram. Errors would surface at the last moment; YouTube schedules publication itself with `publishAt`, so the upload can happen early.
+- Queues or workflow engines (Cloudflare Queues, Temporal). They add paid or external infrastructure for a job a leased row already describes.
+- Sending the browser's file straight to YouTube. The person would have to keep the page open for the whole upload, and the token would reach the browser.
+- The full `youtube` scope for playlists. It would let a leaked token change or delete existing videos; playlists wait.
+
+**Trade-offs:**
+- Throughput is about 400 MB an hour, and a video is limited by the Cloudinary plan (100 MB on free).
+- The CPU cost of copying 8 MiB per chunk on the Free plan is unmeasured; the paid plan is the fallback.
+- A session lost after the last byte goes to a person (`needs_review`) instead of a retry, trading automation for never publishing twice.
+- Changing `TOKEN_ENCRYPTION_KEY` signs everyone out of YouTube.
diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.md
index f18c69c..de26ab1 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -16,6 +16,7 @@ The Workers Free plan allows five cron triggers per Cloudflare account. This Wor
| `* * * * *` | `dispatch` | `automationProcessor.run()`, then `automationFollowups.run()`, then `automationPublicReplies.run()` | Queue dispatch and recovery: due private replies, follow-ups and public replies, jobs whose run stopped |
| `*/5 * * * *` at minutes 0, 15, 30, 45 | `publish` | `scheduledPublisher.publishDue()` | Scheduled processing: due Instagram posts |
| `*/5 * * * *` at the other minutes | `reconcile` | `automationReconciler.run()` | Reconciliation: overdue jobs, replies whose answer was lost, queue health |
+| `*/5 * * * *` at minutes 5, 20, 35, 50 | `youtube` | `youtubeRunner.run()` | Moves one YouTube upload: session, chunks, processing check or thumbnail (`docs/platform-v2/YOUTUBE_INTEGRATION.md`); the reconcile plan keeps minutes 10, 25, 40 and 55 |
| `0 0 * * *` | `daily` | `tokenRefresh.refreshExpiringInstagramTokens()`, then `retention.purge()` | Maintenance: tokens and retention |
Cron jobs coordinate and recover; they are not a second delivery pipeline. The dispatch sends through the same claim, reservation and finish as the webhook, so its runs, the webhook's runs and a retry can overlap without sending anything twice, and the reconciler only reads from Instagram.
diff --git a/docs/architecture/backend/RATE_LIMITING.md b/docs/architecture/backend/RATE_LIMITING.md
index 1551858..3e0c381 100644
--- a/docs/architecture/backend/RATE_LIMITING.md
+++ b/docs/architecture/backend/RATE_LIMITING.md
@@ -36,7 +36,7 @@ Defined in `backend/lib/rateLimit/rules.ts`.
| `quota` | `POST /accounts`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `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 |
+| `oauth` | `GET /auth/instagram/callback`, `GET /auth/youtube/callback` | Client IP | Fixed window counter | 10 per 10 minutes |
The Instagram webhook (`POST /api/webhooks/instagram`) has only the `ip` rule. Meta sends from its own servers, so a burst past 300 a minute from one of them gets 429, and Meta delivers those notifications again later; nothing is lost. Private replies have their own limits, which are not rate limit rules: hourly counts per instance, user, account and rule and a daily count per person, kept in the database by `reserve_automation_send` so every Worker sees them (`docs/architecture/data-flows/AUTOMATION.md`).
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index cef6599..23955e6 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -38,6 +38,7 @@ Registered on `publicRoutes` in `routes/index.ts`.
|---|---|---|---|
| GET | `/api/health` | `healthController.getHealth` | Liveness: returns `{ status: 'ok', timestamp }` without touching the database |
| GET | `/api/health/ready` | `healthController.getReadiness` | Readiness: the Supabase secrets are set and one database read succeeds; returns `{ status: 'ready', databaseMs, timestamp }`, or `503 NOT_CONFIGURED` naming a missing secret, or `500 DATABASE_ERROR` |
+| GET | `/api/auth/youtube/callback` | `youtubeController.handleYouTubeCallback` | Checks the signed state and redirects to the accounts page with `#yt_code=<code>&yt_state=<state>` for the app to complete, or `?yt_error=<reason>`; `503` when YouTube publishing is not set up. Rate limited by `oauth` |
| GET | `/api/auth/instagram/callback` | `instagramAuthController.handleInstagramCallback` | Checks the signed state and redirects the browser to the accounts page with `#ig_code=<code>&ig_state=<state>` for the app to complete, or `?ig_error=<reason>`; never exchanges the code itself and never answers JSON |
| POST | `/api/auth/email-hook` | `authHookController.sendAuthEmail` (`routes/authHookRoutes.ts`) | Supabase Auth's Send Email hook: sends sign-up, password reset and other auth emails through Resend. Answers `{}` |
| GET | `/api/webhooks/instagram` | `instagramWebhookController.verifyInstagramWebhook` (`routes/instagramWebhookRoutes.ts`) | Meta's webhook check: answers the bare `hub.challenge` as text when `hub.mode=subscribe` and `hub.verify_token` matches `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`; 403 otherwise, 503 when the token is not set |
@@ -195,6 +196,24 @@ Controllers in `mcpAccessController.ts` call `McpAccessService` (`services/mcpAc
| POST | `/api/mcp/clients` | `mcpRoutes.ts`, `mcpAccessController.approveClient` | Body `{ clientId, clientName, permission }`: saves the consent page's choice for the caller before the page approves the request with Supabase |
| DELETE | `/api/mcp/clients/:id` | `mcpRoutes.ts`, `mcpAccessController.revokeClient` | Removes an approval; the client is refused at its next call |
+### YouTube publishing
+
+Controllers in `youtubeController.ts` call `YouTubeConnectService` and `YouTubeUploadService`; `mediaController.ts` calls `MediaService`. See `docs/platform-v2/YOUTUBE_INTEGRATION.md`.
+
+| 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/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 |
+| POST | `/api/youtube/uploads` | `youtubeRoutes.ts`, `youtubeController.createYouTubeUpload` | Queues a video from the caller's media; `201`, or `200` with the first job when `clientRequestId` was seen |
+| PUT | `/api/youtube/uploads/:id` | `youtubeRoutes.ts`, `youtubeController.updateYouTubeUpload` | Changes the details of a job that has not started |
+| POST | `/api/youtube/uploads/:id/cancel` | `youtubeRoutes.ts`, `youtubeController.cancelYouTubeUpload` | Stops a job YouTube has not finished |
+| POST | `/api/youtube/uploads/:id/retry` | `youtubeRoutes.ts`, `youtubeController.retryYouTubeUpload` | Queues a failed or needs-review job again from byte 0 |
+| GET | `/api/media` | `mediaRoutes.ts`, `mediaController.listMedia` | The caller's media library |
+| POST | `/api/media` | `mediaRoutes.ts`, `mediaController.registerMedia` | Adds a file the browser uploaded to this instance's Cloudinary cloud; the size is measured by the server; `201` |
+
## Adding a New Route
See `docs/features/NEW_API_ENDPOINT.md` for the complete workflow.
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 6224d6a..9617403 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -52,6 +52,9 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from
| `mcpFor(principal)` | `mcpService.ts` | (the other services, through the tools in `backend/mcp/`) | `handle(body, headers)`: one JSON-RPC message for one verified caller; lists only the tools the permission allows, asks for confirmation before publishing or deleting, stops a tool after 25 seconds, refuses a result over 40,000 characters, and audits write tools |
| `youtubeQuota` (internal, not on `Services`) | `youtubeQuotaService.ts` | YouTube quota counters (Redis) | `run(userId, apiKey, work)`: refuses a member who spent `USER_DAILY_UNITS` (2,500, a quarter of the default 10,000) on the current Pacific day with `RateLimitedError` (429), hands the work a metered key that `ytFetch` charges per call, and records the units once at the end, even when the work failed. `accounts`, `youtubeAnalytics`, `trackedContent` and `overview` run every YouTube call through it; refresh-all uses one run for all of a member's channels. Without Redis nothing is metered (audit lead L6) |
| `media` | `mediaService.ts`, `cloudinary/cloudinaryApi.ts` | media assets, audit | `list`, `importFromUrl` (Cloudinary fetches the public https address with the unsigned preset, then a `media_assets` row for the caller), `updateLabel`, `remove` (deletes the file from Cloudinary first when `CLOUDINARY_API_KEY` and `CLOUDINARY_API_SECRET` are set, otherwise only the record, and says which), `canDeleteFiles`. Used by the MCP media tools |
+| `youtubeConnect` | `youtubeConnectService.ts`, `youtube/googleApi.ts` | YouTube connections, YouTube uploads, accounts, audit | `configured`, `authorizationUrl`, `stateIsValid`, `completeForUser` (403 for a state another person started), `list`, `disconnect` (revokes at Google), `accessTokenFor` (refreshes; a refused refresh marks the connection `needs_reconnect` and parks its jobs) |
+| `youtubeUploads` | `youtubeUploadService.ts` | YouTube uploads, YouTube connections, media assets, audit | `list`, `get`, `create` (from the caller's own connection and media, YouTube's metadata limits, idempotent by `clientRequestId`), `update` (before the upload starts), `cancel`, `retry` |
+| `youtubeRunner` | `youtubeUploadRunner.ts` | YouTube uploads, YouTube connections, quota ledger | `run({ subrequests, timeBudgetMs })`: one job per run on the YouTube cron plan; session saved before bytes, resume from Google's count, 8 MiB chunks from Cloudinary, processing check, thumbnail, and an end state for every error class. Cross-user: `claim`, `saveLeased`, `releaseLeased`, `findById`, `updateTokensById`, `markNeedsReconnectById`, `parkForConnection` |
| `health` | `healthService.ts` | health | `readiness()` (`GET /api/health/ready`: one database read, timed; returns no data) |
Every user-scoped method takes the verified `userId` as its first argument. Methods that need one of the user's records load it with a `...ForUser` repository method and throw `NotFoundError` when it is missing or on the wrong platform, so another user's record is never found. `scheduledPublisher`, `tokenRefresh`, `automationWebhook`, `automationProcessor`, `automationFollowups`, `automationPublicReplies`, `automationReconciler` and `retention` are the only services that use the cross-user repository methods (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and the automation queue, follow-up, review, intake and retention methods).
diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.md
index a59ed99..8b5395b 100644
--- a/docs/architecture/cloudflare/CI_CD.md
+++ b/docs/architecture/cloudflare/CI_CD.md
@@ -52,7 +52,7 @@ A type error or failing test stops the run before the deploy step.
- `CLOUDFLARE_API_TOKEN` - API token with Worker deploy permission
- `CLOUDFLARE_ACCOUNT_ID` - your Cloudflare account ID
-The workflow does not set the Worker's own secrets (`SUPABASE_*`, `FRONTEND_URL`, the optional `ALLOWED_ORIGINS`, the optional email secrets `SEND_EMAIL_HOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` and `EMAIL_DAILY_LIMIT`, the optional automation settings `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, `META_APP_SECRET` and `AUTOMATION_*`, the optional Claude settings `TOKEN_ENCRYPTION_KEY`, `MCP_OAUTH_ENABLED`, `CLOUDINARY_API_KEY` and `CLOUDINARY_API_SECRET`, and the rest). They are set once with `npx wrangler secret put` and kept across deploys; see `WORKERS.md`.
+The workflow does not set the Worker's own secrets (`SUPABASE_*`, `FRONTEND_URL`, the optional `ALLOWED_ORIGINS`, the optional email secrets `SEND_EMAIL_HOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` and `EMAIL_DAILY_LIMIT`, the optional automation settings `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, `META_APP_SECRET` and `AUTOMATION_*`, the optional Claude settings `TOKEN_ENCRYPTION_KEY`, `MCP_OAUTH_ENABLED`, `CLOUDINARY_API_KEY` and `CLOUDINARY_API_SECRET`, the optional YouTube publishing settings `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`, and the rest). They are set once with `npx wrangler secret put` and kept across deploys; see `WORKERS.md`.
**Does not** redeploy on frontend-only changes, documentation changes, or script changes.
diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.md
index b2f3222..6211db0 100644
--- a/docs/architecture/cloudflare/WORKERS.md
+++ b/docs/architecture/cloudflare/WORKERS.md
@@ -58,7 +58,8 @@ All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. T
| `EMAIL_DAILY_LIMIT` | Optional | Auth emails a day across all users (each code sign-in is one) before the sign-in page pauses email codes and points to Google or a password; defaults to `100`, Resend's free daily quota |
| `INSTAGRAM_WEBHOOK_VERIFY_TOKEN` | Optional | The Verify Token typed into the Meta dashboard's Instagram webhook settings; `GET /api/webhooks/instagram` answers Meta's check only with it. Without it, and `INSTAGRAM_APP_SECRET`, no comment reaches the Worker and the Automations page says so |
| `CLOUDINARY_API_KEY`, `CLOUDINARY_API_SECRET` | Optional | The Cloudinary account's API key and secret (Settings, API Keys). Only for deleting files through the Claude `delete_media` tool; without them a delete removes Twiligent's record and says the file stays on Cloudinary. Never sent to the browser |
-| `TOKEN_ENCRYPTION_KEY` | Optional | At least 32 random characters (`openssl rand -base64 48`). Keys derived from it sign the MCP confirmation tokens, so without it the Claude tools that publish or delete refuse to run; YouTube publishing will also encrypt stored tokens with it. Changing it voids confirmations in flight |
+| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | Optional | The Google Cloud Web application OAuth client for YouTube publishing (redirect URI `<BACKEND_URL>/api/auth/youtube/callback`). With `TOKEN_ENCRYPTION_KEY` they turn YouTube publishing on; see `docs/platform-v2/YOUTUBE_INTEGRATION.md` |
+| `TOKEN_ENCRYPTION_KEY` | Optional | At least 32 random characters (`openssl rand -base64 48`). Keys derived from it sign the MCP confirmation tokens and seal the stored Google tokens (AES-GCM). Without it the Claude tools that publish or delete refuse to run and YouTube publishing stays off. Changing it voids confirmations in flight and makes every stored Google token unreadable, so people connect YouTube again |
| `MCP_OAUTH_ENABLED` | Optional | `true` once Supabase Auth's OAuth server is turned on with the authorization path `/oauth/consent`; the MCP endpoint then publishes its protected resource metadata, so Claude on the web, desktop and mobile can connect. Access tokens work without it |
| `META_APP_SECRET` | Optional | The Meta app's own secret (App settings, Basic). Webhook signatures are checked against `INSTAGRAM_APP_SECRET` and, when this is set, against it too |
| `AUTOMATION_PAUSED` | Optional | `true` holds every comment-to-DM reply on the instance; comments are still stored and matched |
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index e32d3ed..b24d299 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -470,6 +470,51 @@ Index `media_assets_user_created_idx` on `(user_id, created_at desc)` serves the
---
+## YouTube Publishing Tables
+
+See `docs/platform-v2/YOUTUBE_INTEGRATION.md` for the flow. All three are reached only by the Worker with the service key.
+
+### Table: `youtube_connections`
+
+| Column | Type | Constraints | Description |
+|---|---|---|---|
+| `id` | text | primary key | `newRowId()` |
+| `user_id` | uuid | not null, references `auth.users` on delete cascade | |
+| `account_id` | text | references `accounts (id, user_id)` on delete set null (account_id) | The analytics account for the same channel, if any |
+| `channel_id`, `channel_title` | text | unique `(user_id, channel_id)` | |
+| `scopes` | text[] | not null | As Google granted them |
+| `status` | text | `active` or `needs_reconnect` | |
+| `refresh_token_enc`, `access_token_enc` | text | refresh not null | AES-GCM sealed under a key derived from `TOKEN_ENCRYPTION_KEY`; never leave the Worker |
+| `access_token_expires_at` | timestamptz | | |
+| `created_at`, `updated_at` | timestamptz | not null, default now() | |
+
+### Table: `youtube_uploads`
+
+| Column | Type | Constraints | Description |
+|---|---|---|---|
+| `id`, `user_id` | text, uuid | primary key; references `auth.users` on delete cascade | |
+| `connection_id` | text | references `youtube_connections` on delete cascade | |
+| `source_url`, `source_bytes`, `content_type` | text, bigint, text | https; bytes above 0 | The Cloudinary source, read in byte ranges |
+| `thumbnail_url`, `is_short` | text, boolean | | |
+| `title`, `description`, `tags`, `category_id` | text, text, text[], text | title 1 to 100 characters | The metadata snapshot |
+| `privacy`, `publish_at` | text, timestamptz | `private`, `unlisted` or `public`; a publish time only with `private` | |
+| `made_for_kids`, `synthetic_media`, `notify_subscribers` | boolean | not null | |
+| `state` | text | `queued`, `uploading`, `processing`, `finalizing`, `done`, `waiting_quota`, `needs_reconnect`, `needs_review`, `failed`, `cancelled` | |
+| `session_uri`, `bytes_confirmed`, `video_id` | text, bigint, text | bytes between 0 and the source size | Saved before any byte is sent |
+| `attempts`, `next_attempt_at`, `lease_owner`, `lease_until`, `last_error` | integer, timestamptz, text, timestamptz, text | | The runner's bookkeeping |
+| `client_request_id` | text | unique `(user_id, client_request_id)` | The same request twice queues once |
+| `created_at`, `updated_at` | timestamptz | not null, default now() | |
+
+Indexes: `youtube_uploads_due_idx` on `(next_attempt_at)` for the runnable states; `youtube_uploads_user_created_idx` on `(user_id, created_at desc)`.
+
+### Table: `youtube_quota_usage`
+
+The Google project's units per Pacific `day` and `bucket` (`uploads`: 100 inserts; `default`: 10,000 units), primary key `(day, bucket)`.
+
+Functions: `claim_youtube_upload(p_owner, p_lease_seconds)` leases one due job with `for update skip locked`; `reserve_youtube_quota(p_day, p_bucket, p_units, p_limit)` adds units only while they fit and answers whether it did. Both are granted to `service_role` only.
+
+---
+
## Table: `audit_events`
Who connected, reconnected or removed an account, changed a rule, paused or subscribed an account, or retried a reply. Rows reference only the user, so they outlive the account they describe.
@@ -478,7 +523,7 @@ Who connected, reconnected or removed an account, changed a rule, paused or subs
|---|---|---|---|
| `id` | text | primary key | `newRowId()` |
| `user_id` | uuid | not null, references `auth.users` on delete cascade | |
-| `action` | text | `^[a-z_]+\.[a-z_]+$` | `account.connected`, `account.reconnected`, `account.removed`, `automation_rule.created`, `.updated`, `.duplicated`, `.deleted`, `automation_account.paused`, `.resumed`, `.subscribed`, `automation_comment.retried`, `automation_public_reply.retried`, `mcp_access_token.created`, `.revoked`, `mcp_client.approved`, `.revoked`, `media_asset.imported`, `.deleted`, and `mcp_access_token.called_tool` or `mcp_client.called_tool` for each write tool a Claude client ran (with the tool name and outcome) |
+| `action` | text | `^[a-z_]+\.[a-z_]+$` | `account.connected`, `account.reconnected`, `account.removed`, `automation_rule.created`, `.updated`, `.duplicated`, `.deleted`, `automation_account.paused`, `.resumed`, `.subscribed`, `automation_comment.retried`, `automation_public_reply.retried`, `mcp_access_token.created`, `.revoked`, `mcp_client.approved`, `.revoked`, `media_asset.imported`, `.deleted`, `youtube_connection.connected`, `.reconnected`, `.removed`, `youtube_upload.created`, `.cancelled`, and `mcp_access_token.called_tool` or `mcp_client.called_tool` for each write tool a Claude client ran (with the tool name and outcome) |
| `subject_type` | text | `account`, `automation_rule`, `automation_account`, `automation_comment`, `mcp_access_token`, `mcp_client`, `scheduled_post`, `tracked_post`, `media_asset`, `youtube_connection`, `youtube_upload`, `settings` | The last six are for changes made through Claude clients, publishing, media and YouTube |
| `subject_id` | text | | |
| `details` | jsonb | not null, default `{}`, an object | Small facts such as the platform or the changed field names; never tokens or comment text |
diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.md
index 1b2da48..80f943e 100644
--- a/docs/architecture/database/SECURITY.md
+++ b/docs/architecture/database/SECURITY.md
@@ -53,7 +53,7 @@ The migrations in `supabase/migrations/` enforce this on every instance:
The service-role key used by the Worker and the GitHub Actions scheduler bypasses row level security and keeps its grants. The frontend never queries tables directly (it uses Supabase only for Auth). `backend/tests/database/migrations.test.ts` fails if a migration creates a function without the revoke.
-To check a live instance, call the Data API with the anon key (`GET <SUPABASE_URL>/rest/v1/accounts` with the `apikey` header): it must answer 401 for all fourteen tables and for `POST /rest/v1/rpc/merge_account_data`, `POST /rest/v1/rpc/claim_automation_comments`, `POST /rest/v1/rpc/claim_automation_followups` and `POST /rest/v1/rpc/claim_automation_public_replies`. The manual check is in `docs/workflows/TESTING.md`.
+To check a live instance, call the Data API with the anon key (`GET <SUPABASE_URL>/rest/v1/accounts` with the `apikey` header): it must answer 401 for all seventeen tables and for `POST /rest/v1/rpc/merge_account_data`, `POST /rest/v1/rpc/claim_automation_comments`, `POST /rest/v1/rpc/claim_automation_followups` and `POST /rest/v1/rpc/claim_automation_public_replies`. The manual check is in `docs/workflows/TESTING.md`.
### What was wrong before
@@ -101,6 +101,10 @@ The MCP endpoint (`POST /mcp`) does not take the app's session token. `requireMc
Each credential carries `read` or `write`. A read credential never sees the write tools in `tools/list` and is refused if it calls one. Publishing and deleting also need a confirmation token: an HMAC over the user, the tool and the exact arguments, keyed from `TOKEN_ENCRYPTION_KEY`, valid for five minutes. Every write tool call is recorded in `audit_events`.
+## YouTube Publishing
+
+`youtube_connections` holds each channel's Google tokens sealed with AES-GCM under a key derived from `TOKEN_ENCRYPTION_KEY`; they are unsealed only in the Worker, to call Google, and never returned or logged. The connection is finished only by the person who started the Google sign-in. The runner's repository methods `claim`, `saveLeased`, `releaseLeased`, `parkForConnection`, `findById`, `updateTokensById` and `markNeedsReconnectById` are not user-scoped and serve only `youtubeUploadRunner` and `youtubeConnectService.accessTokenFor`; every runner write is conditioned on its lease. The runner reads only Cloudinary addresses.
+
## Audit Events
`audit_events` records connecting, reconnecting and removing accounts, rule changes, pausing and subscribing an account, and retries, with the user, the subject and small details (never tokens or comment text). Rows reference the user only, so they stay after the account is removed, and are deleted after a year or with the user.
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index 65692db..fe3ca94 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -160,6 +160,10 @@ revokeMcpClient: (id: string) => request<SuccessResponse>(`/mcp/clients/${id}`,
The types are in `shared/types/mcp.ts`. Settings, Claude (`features/settings/useClaudeAccess.ts`) uses all but `approveMcpClient`, which the consent page (`pages/useOAuthConsent.ts`) calls before it approves the request with `supabase.auth.oauth.approveAuthorization`. The token from `createMcpToken` is kept only in component state until the person dismisses it. These calls manage access; the MCP endpoint itself (`/mcp`) is never called from the app.
+## 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`.
+
## Tracked Content Methods
Added to the `api` object in `api.ts`. Tracked content is YouTube videos only:
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index de6c889..1ceec1d 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -85,6 +85,11 @@ frontend/src/
│ │ ├── useAutomationActivity.ts <- Filters, counts, activity pages and retry
│ │ ├── useRuleForm.ts <- Rule editor state, draft, field problems, the account's posts, the test call
│ │ └── automationData.ts <- Pure status labels, filters, summary, form conversion and checks (automationData.test.ts)
+│ ├── youtube/
+│ │ ├── YouTubeUploads.tsx <- Page: composer and upload list, with loading, error, not-set-up and no-channel states
+│ │ ├── YouTubeComposer.tsx, YouTubeUploadList.tsx
+│ │ ├── useYouTubePublishing.ts <- Loads channels and uploads, reloads every 30 s while one moves, queue, cancel, retry
+│ │ └── youtubeUploadData.ts <- Pure state labels, progress, tags, composer checks, sign-in return (youtubeUploadData.test.ts)
│ ├── settings/
│ │ ├── Settings.tsx <- Page: loads server settings, then renders each section; keeps the #hash scroll
│ │ ├── SettingsSection.tsx, AppearanceSection.tsx, PasswordSection.tsx, ServerKeysSection.tsx, SchedulingSection.tsx
diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.md
index 4fdb946..07c2676 100644
--- a/docs/architecture/frontend/ROUTING.md
+++ b/docs/architecture/frontend/ROUTING.md
@@ -10,6 +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) |
| `/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/MCP_DOCUMENTATION.md b/docs/platform-v2/MCP_DOCUMENTATION.md
index 162e3a4..5df90d6 100644
--- a/docs/platform-v2/MCP_DOCUMENTATION.md
+++ b/docs/platform-v2/MCP_DOCUMENTATION.md
@@ -130,6 +130,12 @@ Every tool works only on the caller's own data. Read tools need no confirmation.
| `import_media_from_url` | write | `url` (public https), `resourceType` (`image` or `video`), `label` | `media`. Cloudinary downloads the file, not the Worker; private and non-https addresses are refused |
| `update_media` | write | `mediaId`, `label` | `media` |
| `delete_media` | write, confirm | `mediaId` | `deleted`, `removedFromCloudinary`, and a `note` when the file stays on Cloudinary because the instance has no API secret |
+| `list_youtube_channels` | read | none | `channels` (no tokens), `configured` |
+| `list_youtube_uploads`, `get_youtube_upload` | read | `limit`, `cursor`; or `uploadId` | Upload jobs with state, progress, video id and error |
+| `create_youtube_upload` | write, confirm when public, unlisted or scheduled | `connectionId`, `mediaId`, `title`, `privacy`, `madeForKids`, and optional `description`, `tags`, `categoryId`, `publishAt`, `syntheticMedia`, `notifySubscribers`, `thumbnailMediaId`, `clientRequestId` | `upload`, `alreadyQueued` |
+| `update_youtube_upload` | write, confirm when it makes the video public, unlisted or scheduled | `uploadId` and the details to change | `upload` |
+| `retry_youtube_upload` | write | `uploadId` | `upload` |
+| `cancel_youtube_upload` | write, confirm | `uploadId` | `upload` |
| `list_scheduled_posts` | read | `status`, `limit` (1 to 50, default 20), `cursor` | `posts`, `nextCursor`, `total` |
| `get_scheduled_post` | read | `postId` | `post` |
| `schedule_instagram_post` | write, confirm | `accountId`, `mediaUrl` (public https), `scheduledAt` (future ISO 8601), `mediaType` (IMAGE, VIDEO, REELS, STORIES), `caption`, `shareToFeed`, `collaborators`, `altText`, `locationId` | `post`, `alreadyScheduled` (true when the same media was already scheduled for that account and time) |
diff --git a/docs/platform-v2/YOUTUBE_INTEGRATION.md b/docs/platform-v2/YOUTUBE_INTEGRATION.md
new file mode 100644
index 0000000..caf11b3
--- /dev/null
+++ b/docs/platform-v2/YOUTUBE_INTEGRATION.md
@@ -0,0 +1,149 @@
+# YouTube publishing
+
+How Twiligent uploads videos and Shorts to a person's YouTube channel (#147): the Google connection, the upload pipeline, its states, quota, limits and security, and how an instance owner sets it up. The design and its trade-offs are in `ARCHITECTURE.md` (section 3) and ADR-053 in `DECISIONS.md`.
+
+## What it does
+
+- A person connects a channel on the Accounts page (YouTube publishing) by signing in with Google once.
+- On the YouTube uploads page (`/youtube-uploads`) they queue a video with:
+ - title, description and tags;
+ - category;
+ - visibility, or a publish time;
+ - the made-for-kids answer YouTube requires;
+ - the AI disclosure;
+ - whether to notify subscribers;
+ - an optional thumbnail.
+- The video goes to the instance's Cloudinary account from the browser first.
+- Scheduled runs then move it to YouTube in resumable 8 MiB chunks, wait for YouTube to process it, and set the thumbnail.
+- The page shows each upload's state in words, its progress, any reason it stopped, and retry or cancel where they apply.
+- Claude can do the same through the MCP tools (`MCP_DOCUMENTATION.md`).
+- 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
+
+1. `GET /api/auth/youtube/url` (signed in) 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.
+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);
+ - 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.
+
+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.
+
+## The upload pipeline
+
+**Where the work happens:**
+- One row per video in `youtube_uploads`, holding:
+ - a snapshot of the metadata;
+ - the Cloudinary source (address, size, content type);
+ - the resumable session, the bytes Google confirmed and the video id;
+ - the state, attempts, next attempt and a lease.
+- The five minute cron gives the second run of each quarter hour, at minutes 5, 20, 35 and 50, to `youtubeRunner.run()` (`backend/services/youtubeUploadRunner.ts`).
+- Each run claims one due job with `claim_youtube_upload` (`FOR UPDATE SKIP LOCKED`, a 10 minute lease) and moves it as far as its 50 subrequests and 12 minutes allow. Every write checks the run still holds the lease.
+
+**What one run does:**
+1. **Queued:**
+ - It reserves one call from the day's `uploads` bucket (`reserve_youtube_quota`).
+ - It opens a resumable session (`videos.insert`, `uploadType=resumable`, `part=snippet,status`).
+ - It saves the session address before any byte goes out, so a run that dies resumes it instead of starting a second video.
+2. **Uploading:**
+ - It asks Google how many bytes it holds (`Content-Range: bytes */total`) and resumes from there.
+ - Each chunk is read from Cloudinary with a `Range` request, sent with an exact `Content-Range` and saved.
+ - Chunks are 8 MiB, a multiple of 256 KiB, the same size except the last. Each costs three subrequests (the read, the write and the save), so a run moves about 13 chunks, roughly 100 MB.
+3. **Processing:**
+ - The next runs check `videos.list` (`part=status,processingDetails`, 1 unit) every 3 minutes until YouTube reports the video processed, failed or rejected.
+4. **Finalizing:**
+ - When there is a thumbnail, it is read from Cloudinary and set with `thumbnails.set` (50 units).
+ - A thumbnail YouTube refuses, such as on an unverified channel, never undoes the upload: the job ends `done` with a note.
+
+## States
+
+| State | Meaning | What happens next |
+|---|---|---|
+| `queued` | Waiting for a run | The next YouTube run opens the session |
+| `uploading` | Chunks are being sent | Each run continues from Google's own count |
+| `processing` | YouTube has the whole file | Checked every 3 minutes |
+| `finalizing` | Processed; the thumbnail is being set | One more step |
+| `done` | On the channel | Nothing; the page links to the video |
+| `waiting_quota` | The day's allowance is used up | Continues after midnight Pacific time |
+| `needs_reconnect` | Google stopped accepting the sign-in | Signing in again puts it back in the queue |
+| `needs_review` | Every byte was sent but the answer and the session were lost | A person checks the channel; retry would start a second upload |
+| `failed` | A lasting error, or 8 passing errors in a row | Retry starts again from byte 0 |
+| `cancelled` | Stopped before YouTube had the video | Nothing |
+
+**How errors are handled:**
+- Passing errors back off exponentially with jitter, from a minute to about four hours. They are network failures, timeouts, 5xx, 429, database errors and Cloudinary hiccups.
+- An upload address that expired before the last byte (404 or 410) starts again from byte 0.
+- `quotaExceeded` and its kin wait until midnight Pacific time.
+
+## Quota
+
+The Google Cloud project's daily allowance is shared by every channel on the instance:
+- 100 `videos.insert` calls a day;
+- 10,000 units for everything else.
+
+`youtube_quota_usage` counts both per Pacific day, and `reserve_youtube_quota` takes units atomically before each call, so Twiligent stops before Google refuses. The analytics features use the instance's API key and their own per-member meter (`youtubeQuotaService`, audit lead L6).
+
+## Limits
+
+- **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.
+
+## Security
+
+**Who can reach what:**
+- Every request method is scoped to the verified user.
+- An upload is built only from the caller's own connection and media.
+- The runner reads only Cloudinary addresses (`fetchFileRange` and `fetchWholeFile` refuse any other host), so a changed row cannot point the Worker elsewhere.
+- A browser upload is added to the library only from this instance's own cloud (`res.cloudinary.com/<cloud>/<type>/upload/`), with its size measured by the server.
+
+**Google sign-in and tokens:**
+- The Google sign-in is finished by the person who started it, through the authenticated complete step (ADR-050).
+- Tokens are sealed at rest and revoked at Google on disconnect.
+
+**Claude tools:**
+- Queuing or changing a public, unlisted or scheduled video asks for a confirmation that shows the title, visibility, publish time and description.
+- Cancelling always asks.
+
+## Setting it up (instance owner)
+
+1. In Google Cloud:
+ - create or choose a project;
+ - enable **YouTube Data API v3**;
+ - configure the OAuth consent screen, add the scopes `youtube.upload` and `youtube.readonly`, and publish it to production (see Limits);
+ - create an OAuth client of type **Web application** with the redirect URI `https://<worker>/api/auth/youtube/callback`.
+2. Set the Worker secrets:
+ - `npx wrangler secret put GOOGLE_CLIENT_ID`
+ - `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.
+
+The public guide is at `https://twiligent.ujjwal.fyi/docs/self-host/youtube-publishing` (source: `site/content/docs/self-host/youtube-publishing.mdx`).
+
+## Verified and not verified
+
+**Verified:** unit and service tests cover every runner transition:
+- session-before-bytes;
+- resume from Google's count;
+- the run budget;
+- quota, reconnect, expired session, lost answer;
+- passing and lasting errors;
+- processing and thumbnail;
+- a lost lease.
+
+They also cover the sign-in binding and token sealing, the upload service's ownership and limits, the callback, the tools and the page helpers.
+
+**Not verified:** a live upload to a real channel, Google's exact answers against this code, and the Worker's CPU use per chunk. These need the owner's Google client. The Google API calls follow the documentation recorded in `research/youtube.md`.
diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.md
index ff37dad..39bf98e 100644
--- a/docs/workflows/DEPLOYMENT.md
+++ b/docs/workflows/DEPLOYMENT.md
@@ -146,7 +146,9 @@ npx wrangler secret put META_APP_SECRET # optional; a second key for
npx wrangler secret put AUTOMATION_PAUSED # optional; "true" holds every automated reply
npx wrangler secret put CLOUDINARY_API_KEY # optional; with the secret below, lets Claude delete media files
npx wrangler secret put CLOUDINARY_API_SECRET # optional
-npx wrangler secret put TOKEN_ENCRYPTION_KEY # optional; signs MCP confirmations (openssl rand -base64 48)
+npx wrangler secret put GOOGLE_CLIENT_ID # optional; YouTube publishing (with the two below)
+npx wrangler secret put GOOGLE_CLIENT_SECRET # optional
+npx wrangler secret put TOKEN_ENCRYPTION_KEY # optional; signs MCP confirmations and seals Google tokens (openssl rand -base64 48)
npx wrangler secret put MCP_OAUTH_ENABLED # optional; "true" after turning on Supabase's OAuth server
```
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 33510fd..eb86d9e 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -100,6 +100,8 @@ Comment automation has its own tests. `tests/lib/automationMatching.test.ts` cov
The MCP server has its own tests. `tests/lib/mcp/protocol.test.ts` covers parsing JSON-RPC, the two protocol eras, the header checks and the error replies; `tests/lib/mcp/accessToken.test.ts` and `confirmation.test.ts` the token format and hash, and that a confirmation fails for other arguments, another tool, another person or after five minutes. `tests/services/mcpAccessService.test.ts` covers creating, listing, revoking and authenticating tokens and approving clients; `tests/services/mcpService.test.ts` the dispatch, that read-only callers never see or run write tools, the confirmation flow, the timeout, the result size cap and the audit lines. `tests/mcp/scheduledPostTools.test.ts`, `tests/mcp/analyticsTools.test.ts` and `tests/mcp/mediaTools.test.ts` check each tool's input checks, paging and that another person's records are not found and tokens never appear; `tests/routes/mcpRoutes.test.ts` runs `/mcp` and `/api/mcp/*` in the full app (401 with the challenge, the Origin check, 405 for GET, revoked tokens). The media tools also have `tests/services/mediaService.test.ts` (records per person, no Cloudinary id in results, deletes with and without the API secret), `tests/validators/mediaValidators.test.ts` (only public https addresses) and `tests/services/cloudinary/cloudinaryApi.test.ts` (the request Cloudinary gets, and the signature checked against Cloudinary's documented example). On the frontend, `tests/features/settings/claudeAccessData.test.ts` covers the Settings section's helpers, `tests/lib/oauthConsent.test.ts` which return addresses the consent page accepts, and `tests/lib/signInPage.test.ts` that signing in returns only to a path on this site.
+YouTube publishing has its own tests: `tests/lib/youtubeUpload.test.ts` (chunk math, the Range header, Shorts, metadata limits, backoff, failure classes, the Pacific midnight), `tests/lib/tokenCrypto.test.ts` (sealing, wrong key, tampering), `tests/services/youtubeUploadRunner.test.ts` (every runner transition, the budget and a lost lease), `tests/services/youtubeConnectService.test.ts` (the sign-in bound to its starter, sealed tokens, reconnect, a refused refresh), `tests/services/youtubeUploadService.test.ts`, `tests/routes/youtubeRoutes.test.ts` (the callback) and `tests/mcp/youtubeTools.test.ts`; on the frontend `tests/features/youtube/youtubeUploadData.test.ts`.
+
The Send Email hook has its own tests: `tests/lib/webhookSignature.test.ts` (valid, tampered, wrong-key, multi-signature and replayed requests), `tests/validators/authHookValidators.test.ts`, `tests/services/email/authEmails.test.ts` (the email for each action, the verify links, HTML escaping and the two Secure Email Change emails), `tests/repositories/emailQuotaRepository.test.ts` (daily and per-address caps, hashed keys, Redis failures), `tests/services/authEmailService.test.ts` (Resend requests, idempotency keys, the caps and Resend's own quota errors, skipped notices) and `tests/routes/authHookRoutes.test.ts` (the hook error shape, and the route answering unsigned calls with 401 in the full app). `tests/fixtures/authHook.ts` signs requests the way Supabase Auth does. The Lua claim script cannot run in Node; the repository test runs the same rules in memory. On the frontend, `tests/lib/authErrors.test.ts` covers when the sign-in page shows the daily cap warning and whether it offers Google, `tests/lib/emailAddress.test.ts` when an address looks complete enough to enable the Continue arrow, `tests/lib/googleIdentity.test.ts` the label drawn on the Google button for each text option, and `tests/lib/signInPage.test.ts` when the sign-in page opens the dashboard for a stored session and when it leaves a sign-in on the page to finish.
The testing workflow documented here describes what should run before shipping any change.
diff --git a/site/content/docs/reference/environment.mdx b/site/content/docs/reference/environment.mdx
index cda7bd2..64b5b46 100644
--- a/site/content/docs/reference/environment.mdx
+++ b/site/content/docs/reference/environment.mdx
@@ -32,7 +32,8 @@ 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. Without them, a delete only removes Twiligent's record. |
-| `TOKEN_ENCRYPTION_KEY` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">For Claude</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. |
+| `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). |
+| `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. |
Platform keys are shared by every member of the instance. Missing ones only switch off that platform: Settings shows which are set, and members see a clear message instead of an error.
diff --git a/site/content/docs/self-host/youtube-publishing.mdx b/site/content/docs/self-host/youtube-publishing.mdx
new file mode 100644
index 0000000..b29bed8
--- /dev/null
+++ b/site/content/docs/self-host/youtube-publishing.mdx
@@ -0,0 +1,60 @@
+export const meta = { title: 'YouTube publishing', description: 'Let members upload videos and Shorts to their YouTube channels from Twiligent.' }
+
+YouTube analytics only need an API key. Publishing also needs a Google OAuth client, so each member can connect their own channel and Twiligent can upload to it. Twiligent asks only to upload videos and to read the channel. It can never change or delete what is already there.
+
+<Steps level={3}>
+<Step title="Enable the API">
+
+In [Google Cloud](https://console.cloud.google.com/), choose the project you use for Twiligent (or create one). Open **APIs and services**, **Library**, and enable **YouTube Data API v3**.
+
+</Step>
+<Step title="Set up the consent screen">
+
+Open **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">
+
+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.
+
+</Callout>
+
+</Step>
+<Step title="Create the OAuth client">
+
+Open **Clients**, **Create client**, type **Web application**. Under **Authorized redirect URIs** add your backend address followed by `/api/auth/youtube/callback`, for example:
+
+```text
+https://twiligent.you.workers.dev/api/auth/youtube/callback
+```
+
+Copy the client ID and client secret.
+
+</Step>
+<Step title="Set the backend secrets">
+
+In the top folder of the project, run each command and paste the value when asked:
+
+```bash
+cd backend
+npx wrangler secret put GOOGLE_CLIENT_ID
+npx wrangler secret put GOOGLE_CLIENT_SECRET
+npx wrangler secret put TOKEN_ENCRYPTION_KEY
+```
+
+`TOKEN_ENCRYPTION_KEY` is 32 or more random characters, for example from `openssl rand -base64 48`. It seals the stored Google tokens. Keep it safe: if it changes, every member has to connect YouTube again.
+
+</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.
+
+</Step>
+</Steps>
+
+## How uploads run
+
+The video goes to your Cloudinary account from the browser first. Every 15 minutes a backend run sends up to about 100 MB of it to YouTube, then checks until YouTube has processed it and sets the thumbnail. A vertical or square video of up to three minutes becomes a Short.
+
+- **Size:** your Cloudinary plan sets the largest video (100 MB on the free plan).
+- **Daily limits:** Google allows 100 uploads a day per project, shared by every channel on your instance. When they run out, uploads continue after midnight Pacific time.
+- **Thumbnails:** YouTube only accepts custom thumbnails from verified channels. Without one, the video is still published and the page says the thumbnail was not set.
diff --git a/site/content/docs/use/claude.mdx b/site/content/docs/use/claude.mdx
index 345aa7c..9510b4f 100644
--- a/site/content/docs/use/claude.mdx
+++ b/site/content/docs/use/claude.mdx
@@ -8,8 +8,8 @@ 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; 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, and change the GitHub scheduling setting |
+| 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 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.
diff --git a/site/src/docs/nav.ts b/site/src/docs/nav.ts
index 44a5f1e..1933eb2 100644
--- a/site/src/docs/nav.ts
+++ b/site/src/docs/nav.ts
@@ -103,6 +103,7 @@ export const DOC_TABS: DocTab[] = [
{ slug: 'self-host/cloudinary', title: 'Cloudinary', icon: Gallery },
{ slug: 'self-host/redis', title: 'Upstash Redis (optional)', icon: ServerSquare },
{ slug: 'self-host/comment-automation', title: 'Comment automation (optional)', icon: Plug },
+ { slug: 'self-host/youtube-publishing', title: 'YouTube publishing (optional)', icon: YouTubeIcon },
],
},
{