diff --git a/docs/design/stage-bridge.md b/docs/design/stage-bridge.md index ec50b77..c05aa44 100644 --- a/docs/design/stage-bridge.md +++ b/docs/design/stage-bridge.md @@ -193,7 +193,7 @@ Two identities, both registered on the provider: the **bot account** (chat send) | `channel:manage:broadcast` | broadcaster | stream markers | | `channel:manage:predictions` | broadcaster | predictions (later, Affiliate-gated) | -Startup asserts the actual granted scopes via `getTokenInfo` and refuses to start with a named missing scope rather than failing at the first subscription. `channel.raid` needs no scope but does need a user token and a `to_broadcaster_user_id` condition. +Startup asserts the actual granted scopes via `getTokenInfo` and refuses to start with a named missing scope rather than failing at the first subscription. Before that assertion, each role's stored token is made usable (added 2026-09-28): an access token expired by `obtainmentTimestamp + expiresIn`, or one `validate` rejects with 401, is refreshed once through that role's `RefreshingAuthProvider`, and every refresh is persisted under the role whose provider made it (serialized atomic writes), so both roles survive a restart even when they are one account. Only a refresh Twitch refuses (4xx) is fatal, with one line naming the role and the runbook's re-authorize step; tokens, the client secret and request URLs never reach the log. `channel.raid` needs no scope but does need a user token and a `to_broadcaster_user_id` condition. ## B2. Day one (pre-channel-setup) diff --git a/docs/stream-mvp-plan.md b/docs/stream-mvp-plan.md index 39c189f..a4c733a 100644 --- a/docs/stream-mvp-plan.md +++ b/docs/stream-mvp-plan.md @@ -891,3 +891,10 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m recovery splash counts down over the stuck loop, covers the game while it acts, and reports the result (`apps/stage/mockups/`). Independent review: BLOCK, then fixed; round 2 approved with the watchdog wait fixed. +- 2026-09-28 (bridge, unreleased): chat died for hours after an unrelated bridge outage outlived + both access tokens (~4 h) and the next start failed `validate` with 401 in a crash loop, with + both refresh tokens still good. Closes the v0.2.3 debt: on load, a stored token expired by its + timestamps or rejected with 401 is refreshed once through its role's provider before giving up, + and every refresh is persisted under its own role (serialized atomic 0600 writes), so both roles + survive when they are one account. Only a refresh Twitch refuses is fatal, one line pointing at + the runbook's re-authorize step; Twitch errors are logged without URLs, tokens or the secret. diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index 81b7073..a8748a2 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -193,6 +193,8 @@ ssh the host pct exec -- curl -s 127.0.0.1:7410/metrics | grep fl | Repeating `FATAL:` + `transport_limit` for more than ~10 min | Something else is holding this account's websocket transports (a second bridge, a dev box, a stale `tools/mock-twitch.sh`) | Find and stop the other client. `GET https://api.twitch.tv/helix/eventsub/subscriptions` with the broadcaster token lists them; delete the strays. | | Repeating `FATAL:` + `create failure ... missing scope` | The token lost a scope (re-authorized with the wrong `--role`, or Twitch revoked it) | Re-run `tools/authorize.mts` — see "Rotate the bot token" below. The bridge will NOT recover from this on its own; restarting cannot add a scope. | | Repeating `FATAL:` + `revoked (authorization_revoked)` | The channel or the user revoked the app | Re-authorize. Same as above. | +| Repeating `FATAL: Twitch refused to refresh the token ... (HTTP 400 "Invalid refresh token")` at startup | That role's refresh token is revoked or invalid (password change, app disconnected, re-authorized elsewhere) | Re-authorize that `--role` — "Rotate the bot token" below. Restarting cannot help; systemd keeps retrying every 15 s with one refresh request per role until the file is fixed. | +| `the stored access token has expired; refreshing it` or `rejected the stored access token (401); refreshing it once`, then a normal start | The bridge was down longer than an access token lives (~4 h), or Twitch invalidated it early | Nothing: it refreshed and persisted the new token itself. | | One `FATAL:` then a quiet, `chatSubscriptionHealthy: true` bridge | It healed. | Nothing. Note it in the status log if it was during a stream. | | `active (running)`, `chatSubscriptionHealthy: false`, and NO `FATAL:` line after more than 2 min | The watchdog itself is not running — an old bundle | Check `/opt/fly/current/bridge/index.js` is from a release that has it, then `systemctl restart flybridge`. | @@ -203,13 +205,30 @@ unit, so chat can never take the fly down. ## Rotate the bot token (flybridge) -Not yet applicable until flybridge exists and is wired up (P3, `docs/design/infra.md` -section 7). Once it is: re-run `tools/authorize.mts` (`docs/design/stage-bridge.md` -section B1) on the operator box to get a fresh refresh token, which -`RefreshingAuthProvider`'s `onRefresh` persists to `/var/lib/fly/bridge/tokens.json` -automatically from then on — a one-time manual step, not a recurring one. The -`twitch-app` credential (client id/secret) only needs rotating if the app itself is -compromised; follow the same `06-secrets.sh` pattern as the stream key. +Access tokens live about 4 h; refresh tokens until revoked. The bridge refreshes on its own: +at runtime through `RefreshingAuthProvider`, and ON LOAD (`prepareStartupTokens` in +`services/bridge/src/auth.ts`) — a stored access token that has expired, or that Twitch's +validate endpoint rejects with 401, is refreshed with its refresh token before the bridge gives +up, for both roles, and each refreshed token is written back to `/var/lib/flybridge/tokens.json` +under its own role (tmp file + rename, mode 0600), also when the bot and the broadcaster are one +account. So an outage longer than an access token's life no longer needs a hand refresh +(2026-09-28: it used to crash-loop on 401 at `validate`). + +Re-authorizing is needed only when the journal says +`flybridge: FATAL: Twitch refused to refresh the token for user (HTTP 400 "Invalid refresh token")`, +or a scope is missing (the table in "Chat dead" above). Then, on the operator box: + +1. `npx tsx tools/authorize.mts --role --tokens-file ` + (`services/bridge`, `docs/design/stage-bridge.md` section B1). It rewrites only that role's + entry and keeps the other. +2. Push the file to the release container as `/var/lib/flybridge/tokens.json`, owned by the + service user, mode 0600 (it is a secret; never in a release artifact or in git). +3. `systemctl restart flybridge` and read the journal for the startup notice line. + +Never paste a token or the client secret into a log, a ticket or chat: the bridge itself prints +neither (Twitch errors are logged by status and message only, URLs redacted). The `twitch-app` +credential (client id/secret) only needs rotating if the app itself is compromised; follow the +same `06-secrets.sh` pattern as the stream key. ## Restore a checkpoint locally diff --git a/services/bridge/src/auth.ts b/services/bridge/src/auth.ts index 0a483d4..bd9246f 100644 --- a/services/bridge/src/auth.ts +++ b/services/bridge/src/auth.ts @@ -2,14 +2,18 @@ * Loads `tokens.json` (written by `tools/authorize.mts`) and builds the `RefreshingAuthProvider` * with both identities registered (`docs/design/stage-bridge.md` B1): the bot account (chat) and * the broadcaster account (redemptions, predictions, follows). Persists refreshed tokens back to - * the same file, atomically, 0600. + * the same file, atomically, 0600 — for BOTH roles, including when they are one account. + * + * On load, a stored access token that has expired, or that Twitch's validate endpoint rejects with + * 401, is refreshed with its refresh token before anything gives up (`prepareStartupTokens`). Only + * a refresh that Twitch itself refuses is fatal, with one line pointing at the runbook. */ import { readFile } from 'node:fs/promises'; -import type { AccessTokenMaybeWithUserId, AccessTokenWithUserId, AuthProvider } from '@twurple/auth'; -import { RefreshingAuthProvider } from '@twurple/auth'; -import { getTokenInfo } from '@twurple/auth'; +import type { AccessToken, AccessTokenMaybeWithUserId, AccessTokenWithUserId, AuthProvider } from '@twurple/auth'; +import { accessTokenIsExpired, getTokenInfo, InvalidTokenError, RefreshingAuthProvider } from '@twurple/auth'; import { atomicWriteJson } from './atomic-file'; import type { BridgeConfig } from './config'; +import { safeErrorMessage } from './redact'; import { assertRequiredScopes, type GrantedScopes } from './scopes'; /** One stored OAuth token, shaped like `@twurple/auth`'s `AccessToken` plus the user id. */ @@ -27,6 +31,9 @@ export interface TokensFile { broadcaster: StoredToken; } +export type TokenRole = keyof TokensFile; +const ROLES: readonly TokenRole[] = ['bot', 'broadcaster']; + export async function loadTokensFile(path: string): Promise { let raw: string; try { @@ -48,6 +55,8 @@ export interface AuthSetup { botAuthProvider: RefreshingAuthProvider; /** Carries the broadcaster token only: follows, raids, Channel Points. */ broadcasterAuthProvider: RefreshingAuthProvider; + /** Where every refresh, by either role, is persisted; `flush()` waits for the writes. */ + tokenStore: TokenStore; botUserId: string; broadcasterUserId: string; /** True when one Twitch account holds both roles — see the comment on `buildAuthProvider`. */ @@ -73,7 +82,7 @@ export interface AuthSetup { * second call silently REPLACED the first. The surviving token was the broadcaster's, which holds * `channel:bot`/`moderator:read:followers`/`channel:*:redemptions` and none of * `user:read:chat`/`user:write:chat`/`user:bot`. The startup scope assertion still passed, because - * `assertStartupScopes` calls `getTokenInfo` on each stored token separately and never asks the + * the startup scope assertion called `getTokenInfo` on each stored token separately and never asked the * provider what it would actually hand out; the failure landed later, on the first chat send and * on the `channel.chat.message` subscription, as a missing-scope error. * @@ -83,23 +92,29 @@ export interface AuthSetup { * is authorized by the token of the user it names. */ export function buildAuthProvider(config: Pick, tokens: TokensFile): AuthSetup { - const newProvider = (): RefreshingAuthProvider => { + const tokenStore = new TokenStore(config.tokensFile, tokens); + + // The ROLE is fixed per provider, so a refresh is persisted under the role whose provider did + // it. This replaced guessing the role from the refreshed token's scope set, which is all a + // single shared callback could go on when both roles are one account. + const newProvider = (role: TokenRole): RefreshingAuthProvider => { const provider = new RefreshingAuthProvider({ clientId: config.twitchClientId, clientSecret: config.twitchClientSecret, }); provider.onRefresh((userId, newTokenData) => { - void persistRefreshedToken(config.tokensFile, tokens, userId, newTokenData).catch((cause: unknown) => { - console.error(`flybridge: failed to persist refreshed token for ${userId}: ${String(cause)}`); - }); + tokenStore.update(role, userId, newTokenData); + }); + provider.onRefreshFailure((userId, error) => { + console.error(runtimeRefreshFailureLine(role, userId, error)); }); return provider; }; - const botAuthProvider = newProvider(); + const botAuthProvider = newProvider('bot'); botAuthProvider.addUser(tokens.bot.userId, toAccessToken(tokens.bot), ['chat']); - const broadcasterAuthProvider = newProvider(); + const broadcasterAuthProvider = newProvider('broadcaster'); broadcasterAuthProvider.addUser(tokens.broadcaster.userId, toAccessToken(tokens.broadcaster), ['broadcaster']); const sameAccount = tokens.bot.userId === tokens.broadcaster.userId; @@ -107,6 +122,7 @@ export function buildAuthProvider(config: Pick` case) the id says nothing, and writing the refreshed - * broadcaster token over the `bot` entry would destroy the chat scopes on disk — a corruption that - * survives a restart, unlike the in-memory collision `buildAuthProvider` describes. Scopes are - * preserved exactly across a refresh, so they are a reliable discriminator. + * Every refresh, by either role, lands here keyed by ROLE (never by user id — when both roles are + * one account the id says nothing, and writing the broadcaster token over the `bot` entry would + * destroy the chat scopes on disk). Writes are serialized, and each writes the WHOLE current + * state, so two refreshes that land together (both roles refreshed on load) cannot race each + * other's renames and leave one role's new token unpersisted — the v0.2.3 incident, where only the + * bot role's fresher token reached disk and the next start failed on the broadcaster's. */ -async function persistRefreshedToken( - tokensFilePath: string, - tokens: TokensFile, - userId: string, - newToken: { accessToken: string; refreshToken: string | null; scope: string[]; expiresIn: number | null; obtainmentTimestamp: number }, -): Promise { - const key = roleForRefreshedToken(tokens, userId, newToken.scope); - if (!key) { - console.error( - `flybridge: refreshed token for ${userId} matches neither stored role by scope set; not persisting`, - ); - return; +export class TokenStore { + private chain: Promise = Promise.resolve(); + private lastError: unknown = null; + + constructor( + private readonly path: string, + private readonly tokens: TokensFile, + ) {} + + /** The current (possibly refreshed) token for a role. */ + get(role: TokenRole): StoredToken { + return this.tokens[role]; + } + + update(role: TokenRole, userId: string, token: AccessToken): void { + this.tokens[role] = { + userId, + accessToken: token.accessToken, + refreshToken: token.refreshToken ?? this.tokens[role].refreshToken, + // twurple turns a refresh response without `scope` into []; never let that wipe the scopes + // the role routing and the startup assertion read from disk. + scope: token.scope.length > 0 ? token.scope : this.tokens[role].scope, + expiresIn: token.expiresIn, + obtainmentTimestamp: token.obtainmentTimestamp, + }; + this.chain = this.chain.then(async () => { + try { + await atomicWriteJson(this.path, this.tokens); + } catch (cause) { + this.lastError = cause; + console.error(`flybridge: failed to persist the refreshed ${role} token to ${this.path}: ${safeErrorMessage(cause)}`); + } + }); + } + + /** Resolves once every queued write has finished; rejects if any of them failed. */ + async flush(): Promise { + await this.chain; + if (this.lastError !== null) { + const cause = this.lastError; + this.lastError = null; + throw new Error(`could not persist refreshed tokens to ${this.path}: ${safeErrorMessage(cause)}`); + } } - tokens[key] = { userId, ...newToken }; - await atomicWriteJson(tokensFilePath, tokens); } -function roleForRefreshedToken( - tokens: TokensFile, - userId: string, - scope: readonly string[], -): keyof TokensFile | null { - const sameSet = (a: readonly string[], b: readonly string[]): boolean => - a.length === b.length && [...a].sort().join(' ') === [...b].sort().join(' '); - if (sameSet(tokens.bot.scope, scope)) return 'bot'; - if (sameSet(tokens.broadcaster.scope, scope)) return 'broadcaster'; - // Different accounts: the id is unambiguous, so fall back to it. - if (tokens.bot.userId !== tokens.broadcaster.userId) { - return tokens.bot.userId === userId ? 'bot' : 'broadcaster'; +const REAUTHORIZE_HINT = + 'Restarting will not fix this: re-authorize that role with tools/authorize.mts, see ' + + 'infra/docs/runbook.md "Rotate the bot token".'; + +/** + * `@twurple/api-call`'s `HttpStatusCodeError`, recognised by shape: that package is only a + * transitive dependency here, and the esbuild bundle would inline a second copy of it, against + * which `instanceof` never matches the one `@twurple/auth` (external) throws. + */ +interface TwitchHttpError extends Error { + statusCode: number; + body: string; +} + +function isTwitchHttpError(error: unknown): error is TwitchHttpError { + return ( + error instanceof Error && + error.name === 'HttpStatusCodeError' && + typeof (error as Partial).statusCode === 'number' + ); +} + +/** Status code and Twitch's own message, never the URL (which carries the secret and the token). */ +function describeTwitchError(error: unknown): string { + if (isTwitchHttpError(error)) { + let message = ''; + try { + const body = JSON.parse(String(error.body)) as { message?: unknown }; + if (typeof body.message === 'string') message = body.message; + } catch { + // not JSON: say nothing more than the status + } + return `HTTP ${String(error.statusCode)}${message ? ` "${message}"` : ''}`; } - return null; + return safeErrorMessage(error); +} + +/** Twitch answered the refresh grant itself with a 4xx: the refresh token is dead. */ +function isRefreshRefusal(error: unknown): boolean { + return isTwitchHttpError(error) && error.statusCode >= 400 && error.statusCode < 500; +} + +function refreshFailureLine(role: TokenRole, userId: string, error: unknown): string { + return ( + `flybridge: FATAL: Twitch refused to refresh the ${role} token for user ${userId} ` + + `(${describeTwitchError(error)}): the refresh token is revoked or invalid. ${REAUTHORIZE_HINT}` + ); +} + +/** What `onRefreshFailure` logs, at startup (before the FATAL line) and at runtime alike. */ +function runtimeRefreshFailureLine(role: TokenRole, userId: string, error: unknown): string { + const base = `flybridge: refreshing the ${role} token for user ${userId} failed (${describeTwitchError(error)})`; + return isRefreshRefusal(error) + ? `${base}; Twitch calls as ${role} will fail until it is re-authorized (infra/docs/runbook.md "Rotate the bot token")` + : base; } /** - * Startup scope assertion via `getTokenInfo` (`docs/design/stage-bridge.md` B1): refuses to - * start with a named missing scope rather than failing at the first subscription. + * A stored token that could not be brought back to life on load. Its message is the whole log line + * and carries no token, secret or URL, so the entrypoint prints it as-is. `reauthorize` is true + * when Twitch refused the refresh (restarting cannot help); false for a transient failure (network, + * 5xx), which the next start retries. + */ +export class StartupTokenError extends Error { + constructor( + message: string, + readonly reauthorize: boolean, + ) { + super(message); + this.name = 'StartupTokenError'; + } +} + +export interface PrepareStartupTokensOptions { + /** Informational lines; defaults to `console.log`. */ + log?: (line: string) => void; +} + +/** + * Make both stored tokens usable before the bridge does anything else, and return the scopes + * Twitch reports for each (for `assertRequiredScopes`). + * + * Per role, at most ONE refresh request: + * - expired on disk (obtainmentTimestamp + expiresIn, twurple's one-minute grace) → the role's + * `RefreshingAuthProvider` refreshes it inside `getAccessTokenForUser`, before any validate; + * - otherwise validate it; a 401 → `refreshAccessTokenForUser` once, then validate the new token. + * Every refresh goes through the role's provider, so `onRefresh` persists it under that role, and + * the writes are flushed before this returns. A refresh Twitch refuses (4xx: revoked or invalid + * refresh token) is fatal with a pointer to the runbook; twurple then also caches the failure, so + * nothing in this process asks again. Both roles are attempted before failing, so one start names + * every dead role. + * + * This replaces validating the stored access tokens first, which crash-looped the bridge on 401 + * whenever it had been down longer than an access token lives (~4 h), even though both refresh + * tokens were still good (v0.2.3 and 2026-09-28). + */ +export async function prepareStartupTokens( + config: Pick, + setup: Pick, + options: PrepareStartupTokensOptions = {}, +): Promise { + const log = options.log ?? ((line: string) => console.log(line)); + const roles = { + bot: { provider: setup.botAuthProvider, userId: setup.botUserId }, + broadcaster: { provider: setup.broadcasterAuthProvider, userId: setup.broadcasterUserId }, + }; + + const granted: Partial = {}; + const failures: StartupTokenError[] = []; + + for (const role of ROLES) { + const { provider, userId } = roles[role]; + const fail = (error: unknown, what: string): StartupTokenError => + isRefreshRefusal(error) + ? new StartupTokenError(refreshFailureLine(role, userId, error), true) + : new StartupTokenError( + `flybridge: FATAL: ${what} for the ${role} token (user ${userId}) failed: ${describeTwitchError(error)}`, + false, + ); + + try { + const expiredOnDisk = accessTokenIsExpired(setup.tokenStore.get(role)); + if (expiredOnDisk) log(`flybridge: the stored ${role} access token has expired; refreshing it before validating`); + const stored = await provider.getAccessTokenForUser(userId).catch((error: unknown) => { + throw fail(error, 'refreshing the expired stored token'); + }); + if (stored === null) throw new StartupTokenError(`flybridge: FATAL: no ${role} token was registered`, false); + // Nothing was spent on validate yet: twurple refreshed an expired token before returning it. + let token: AccessToken = stored; + + let info; + try { + info = await getTokenInfo(token.accessToken, config.twitchClientId); + } catch (error) { + if (!(error instanceof InvalidTokenError)) throw fail(error, 'validating'); + if (expiredOnDisk) { + // It was refreshed a moment ago and Twitch still says 401: a second refresh would only + // repeat the first. + throw new StartupTokenError( + `flybridge: FATAL: the freshly refreshed ${role} token for user ${userId} was rejected (401). ${REAUTHORIZE_HINT}`, + true, + ); + } + log(`flybridge: Twitch rejected the stored ${role} access token (401); refreshing it once`); + token = await provider.refreshAccessTokenForUser(userId).catch((refreshError: unknown) => { + throw fail(refreshError, 'refreshing the rejected token'); + }); + info = await getTokenInfo(token.accessToken, config.twitchClientId).catch((again: unknown) => { + throw again instanceof InvalidTokenError + ? new StartupTokenError( + `flybridge: FATAL: the freshly refreshed ${role} token for user ${userId} was also rejected (401). ${REAUTHORIZE_HINT}`, + true, + ) + : fail(again, 'validating the refreshed token'); + }); + } + granted[role] = info.scopes; + } catch (error) { + if (error instanceof StartupTokenError) failures.push(error); + else throw error; + } + } + + // Persist what did refresh even if the other role is dead: its new token is still good. + await setup.tokenStore.flush(); + + if (failures.length > 0) { + throw new StartupTokenError( + failures.map((f) => f.message).join('\n'), + failures.some((f) => f.reauthorize), + ); + } + return granted as GrantedScopes; +} + +/** + * Startup token check (`docs/design/stage-bridge.md` B1): refresh-before-give-up on both stored + * tokens (`prepareStartupTokens`), then refuse to start with a named missing scope rather than + * failing at the first subscription. */ export async function assertStartupScopes( config: Pick, - tokens: TokensFile, + setup: Parameters[1], + options: PrepareStartupTokensOptions = {}, ): Promise { - const [botInfo, broadcasterInfo] = await Promise.all([ - getTokenInfo(tokens.bot.accessToken, config.twitchClientId), - getTokenInfo(tokens.broadcaster.accessToken, config.twitchClientId), - ]); - const granted: GrantedScopes = { bot: botInfo.scopes, broadcaster: broadcasterInfo.scopes }; + const granted = await prepareStartupTokens(config, setup, options); assertRequiredScopes(config, granted); } diff --git a/services/bridge/src/eventsub.ts b/services/bridge/src/eventsub.ts index 20bc426..3573ba9 100644 --- a/services/bridge/src/eventsub.ts +++ b/services/bridge/src/eventsub.ts @@ -40,6 +40,7 @@ import { HealthState, Metrics } from './health'; import type { ExplainerPoster } from './explainer'; import type { OnscreenChat } from './onscreen-chat'; import type { ChatSubscriptionHealth } from './subscription-health'; +import { safeErrorMessage } from './redact'; import { isWebsocketTransportLimitError } from './subscription-health'; /** What one created subscription looks like from here: an id, which is all this module uses. */ @@ -244,7 +245,7 @@ export function startEventSub(deps: EventSubDeps): EventSubListeners { connected.set(listener, false); publishConnected(); deps.metrics.increment('flybridge_eventsub_reconnects_total'); - if (error) console.error(`flybridge: EventSub ${which} socket for ${userId} disconnected: ${error.message}`); + if (error) console.error(`flybridge: EventSub ${which} socket for ${userId} disconnected: ${safeErrorMessage(error)}`); if (carriesChat) { // twurple marks every subscription for this user dropped and re-creates them on the next // `session_welcome`. Arm the grace timer here: if the re-create never lands (the 429 @@ -280,7 +281,7 @@ export function startEventSub(deps: EventSubDeps): EventSubListeners { }); listener.onSubscriptionCreateFailure((subscription, error) => { - console.error(`flybridge: EventSub subscription create failure for ${subscription.id}: ${error.message}`); + console.error(`flybridge: EventSub subscription create failure for ${subscription.id}: ${safeErrorMessage(error)}`); deps.metrics.increment('flybridge_eventsub_subscription_create_failures_total'); if (isWebsocketTransportLimitError(error)) { deps.metrics.increment('flybridge_eventsub_transport_limit_total'); diff --git a/services/bridge/src/index.ts b/services/bridge/src/index.ts index 1adb8ae..393949e 100644 --- a/services/bridge/src/index.ts +++ b/services/bridge/src/index.ts @@ -5,7 +5,7 @@ import { realpathSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { ApiClient } from '@twurple/api'; -import { assertStartupScopes, buildAuthProvider, loadTokensFile } from './auth'; +import { assertStartupScopes, buildAuthProvider, loadTokensFile, StartupTokenError } from './auth'; import { createSend, TwurpleChatSender } from './chat'; import { loadConfig } from './config'; import { startEventSub } from './eventsub'; @@ -23,6 +23,7 @@ import { RedemptionManager, TwurpleRedemptionApi, } from './redemptions'; +import { safeErrorText } from './redact'; import { HttpSimClient } from './sim'; const EXPLAINER_TICK_MS = 60_000; @@ -31,7 +32,11 @@ const SUGAR_REWARD_TITLE = 'Sugar'; async function main(): Promise { const config = loadConfig(); const tokens = await loadTokensFile(config.tokensFile); - await assertStartupScopes(config, tokens); + const auth = buildAuthProvider(config, tokens); + // Refreshes an expired or 401-rejected stored token (either role) BEFORE giving up, persists + // it, then asserts scopes. Validating first crash-looped the bridge after any outage longer + // than an access token's ~4 h life (src/auth.ts, `prepareStartupTokens`). + await assertStartupScopes(config, auth); const { botAuthProvider, @@ -40,7 +45,7 @@ async function main(): Promise { broadcasterUserId, sameAccount, sharedEventSubAuthProvider, - } = buildAuthProvider(config, tokens); + } = auth; // One client per identity. See `buildAuthProvider` in src/auth.ts: a single provider holding both // tokens loses one of them whenever the two roles are the same Twitch account. const botApiClient = new ApiClient({ authProvider: botAuthProvider }); @@ -250,7 +255,10 @@ const isMainModule = (() => { if (isMainModule) { main().catch((error: unknown) => { - console.error(error); + // A StartupTokenError's message is the whole, secret-free line (and names the runbook step). + // Anything else may be a twurple HttpStatusCodeError, whose message carries the request URL — + // for the refresh grant that is the client secret and refresh token — so it is redacted. + console.error(error instanceof StartupTokenError ? error.message : safeErrorText(error)); process.exit(1); }); } diff --git a/services/bridge/src/redact.ts b/services/bridge/src/redact.ts new file mode 100644 index 0000000..1bf5651 --- /dev/null +++ b/services/bridge/src/redact.ts @@ -0,0 +1,27 @@ +/** + * Keeps OAuth secrets out of the journal. + * + * `@twurple/api-call`'s `HttpStatusCodeError` puts the FULL request URL, query string included, in + * its message — and twurple sends the refresh grant as a query string, so a failed refresh throws + * an error whose message carries `client_secret=` and `refresh_token=` in clear. Anything that + * prints a Twitch error (the entrypoint's last-resort handler, the EventSub failure lines, a failed + * token persist) goes through here first. + */ +import { inspect } from 'node:util'; + +const SECRET_PARAMS = /\b(client_secret|refresh_token|access_token|code|token)=([^&\s"']+)/g; +const AUTH_HEADER = /\b(OAuth|Bearer)\s+[A-Za-z0-9._~+/-]{8,}/g; + +export function redactSecrets(text: string): string { + return text.replace(SECRET_PARAMS, '$1=').replace(AUTH_HEADER, '$1 '); +} + +/** One printable, secret-free description of anything thrown (stack and `cause` chain included). */ +export function safeErrorText(error: unknown): string { + return redactSecrets(error instanceof Error ? inspect(error) : String(error)); +} + +/** Like `safeErrorText`, but only the message: for one-line log entries. */ +export function safeErrorMessage(error: unknown): string { + return redactSecrets(error instanceof Error ? error.message : String(error)); +} diff --git a/services/bridge/tests/auth-refresh.test.ts b/services/bridge/tests/auth-refresh.test.ts new file mode 100644 index 0000000..df1ceba --- /dev/null +++ b/services/bridge/tests/auth-refresh.test.ts @@ -0,0 +1,339 @@ +/** + * Refresh-before-give-up on load (`prepareStartupTokens` / `assertStartupScopes` in + * `src/auth.ts`), against a mock of Twitch's two OAuth endpoints (`/oauth2/validate`, + * `/oauth2/token` refresh grant) installed as `globalThis.fetch`, which is what + * `@twurple/api-call` calls. + * + * The incident: the bridge was down longer than an access token lives (~4 h), both stored access + * tokens expired, and the next start validated them first, got 401 and crash-looped under + * Restart=always — with both refresh tokens still good. + */ +import assert from 'node:assert/strict'; +import { mkdtemp, readdir, readFile, stat, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { + assertStartupScopes, + buildAuthProvider, + loadTokensFile, + prepareStartupTokens, + StartupTokenError, + type StoredToken, + type TokensFile, +} from '../src/auth'; + +const CLIENT_ID = 'test-client-id'; +const CLIENT_SECRET = 'test-client-secret-DO-NOT-LOG'; +const BOT_SCOPES = ['user:read:chat', 'user:write:chat', 'user:bot']; +const BROADCASTER_SCOPES = ['channel:bot', 'moderator:read:followers']; +const FOUR_HOURS_S = 14_400; + +interface MockTwitch { + validateCalls: string[]; + refreshCalls: string[]; + restore: () => void; +} + +/** + * Twitch's id endpoints. `valid` maps a live access token to its owner and scopes; `refreshable` + * maps a live refresh token to the same. A refresh mints `-fresh-` and makes it + * valid; an unknown refresh token gets Twitch's real answer, 400 "Invalid refresh token". + */ +function mockTwitch( + valid: Map, + refreshable: Map, +): MockTwitch { + const original = globalThis.fetch; + const validateCalls: string[] = []; + const refreshCalls: string[] = []; + let minted = 0; + const json = (status: number, body: unknown): Response => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit): Promise => { + const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url); + assert.equal(url.host, 'id.twitch.tv', `unexpected request to ${url.host}`); + if (url.pathname === '/oauth2/validate') { + const auth = new Headers(init?.headers).get('Authorization') ?? ''; + const token = auth.replace(/^OAuth /, ''); + validateCalls.push(token); + const owner = valid.get(token); + if (!owner) return json(401, { status: 401, message: 'invalid access token' }); + return json(200, { + client_id: CLIENT_ID, + login: 'someone', + user_id: owner.userId, + scopes: owner.scopes, + expires_in: FOUR_HOURS_S, + }); + } + if (url.pathname === '/oauth2/token' && url.searchParams.get('grant_type') === 'refresh_token') { + assert.equal(url.searchParams.get('client_secret'), CLIENT_SECRET); + const refreshToken = url.searchParams.get('refresh_token') ?? ''; + refreshCalls.push(refreshToken); + const owner = refreshable.get(refreshToken); + if (!owner) return json(400, { status: 400, message: 'Invalid refresh token' }); + minted += 1; + const accessToken = `${refreshToken}-fresh-${String(minted)}`; + valid.set(accessToken, owner); + return json(200, { + access_token: accessToken, + refresh_token: refreshToken, + scope: owner.scopes, + expires_in: FOUR_HOURS_S, + token_type: 'bearer', + }); + } + throw new Error(`mock Twitch: unhandled ${url.pathname}`); + }) as typeof fetch; + + return { validateCalls, refreshCalls, restore: () => (globalThis.fetch = original) }; +} + +function stored(userId: string, name: string, scope: string[], obtainedMsAgo: number): StoredToken { + return { + userId, + accessToken: `access-${name}`, + refreshToken: `refresh-${name}`, + scope, + expiresIn: FOUR_HOURS_S, + obtainmentTimestamp: Date.now() - obtainedMsAgo, + }; +} + +const EXPIRED = 6 * 3600_000; // down for six hours +const FRESH = 60_000; + +async function writeTokens(tokens: TokensFile): Promise { + const dir = await mkdtemp(join(tmpdir(), 'flybridge-refresh-')); + const path = join(dir, 'tokens.json'); + await writeFile(path, JSON.stringify(tokens), { mode: 0o600 }); + return path; +} + +const CONFIG_BASE = { + twitchClientId: CLIENT_ID, + twitchClientSecret: CLIENT_SECRET, + featureRedemptions: false, + featurePredictions: false, +}; + +async function start(path: string, lines: string[] = []) { + const config = { ...CONFIG_BASE, tokensFile: path }; + const setup = buildAuthProvider(config, await loadTokensFile(path)); + await assertStartupScopes(config, setup, { log: (line) => lines.push(line) }); + return setup; +} + +void test('expired-on-disk tokens for both roles are refreshed (not validated first) and the bridge starts', async () => { + const path = await writeTokens({ + bot: stored('111', 'bot', BOT_SCOPES, EXPIRED), + broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, EXPIRED), + }); + const twitch = mockTwitch( + new Map(), // neither stored access token is valid any more + new Map([ + ['refresh-bot', { userId: '111', scopes: BOT_SCOPES }], + ['refresh-caster', { userId: '222', scopes: BROADCASTER_SCOPES }], + ]), + ); + try { + const lines: string[] = []; + await start(path, lines); + assert.deepEqual(twitch.refreshCalls, ['refresh-bot', 'refresh-caster']); + // Only the refreshed tokens were ever sent to validate: no 401 was spent on the stale ones. + assert.deepEqual(twitch.validateCalls, ['refresh-bot-fresh-1', 'refresh-caster-fresh-2']); + assert.ok(lines.some((l) => l.includes('stored bot access token has expired'))); + + const onDisk = JSON.parse(await readFile(path, 'utf8')) as TokensFile; + assert.equal(onDisk.bot.accessToken, 'refresh-bot-fresh-1'); + assert.equal(onDisk.broadcaster.accessToken, 'refresh-caster-fresh-2'); + assert.ok(Date.now() - onDisk.bot.obtainmentTimestamp < 60_000); + } finally { + twitch.restore(); + } +}); + +void test('a 401 on validate of an unexpired token triggers exactly one refresh, then succeeds', async () => { + const path = await writeTokens({ + bot: stored('111', 'bot', BOT_SCOPES, FRESH), + broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, FRESH), + }); + const twitch = mockTwitch( + // The broadcaster's access token is fine; the bot's was invalidated early (e.g. superseded). + new Map([['access-caster', { userId: '222', scopes: BROADCASTER_SCOPES }]]), + new Map([ + ['refresh-bot', { userId: '111', scopes: BOT_SCOPES }], + ['refresh-caster', { userId: '222', scopes: BROADCASTER_SCOPES }], + ]), + ); + try { + const lines: string[] = []; + await start(path, lines); + assert.deepEqual(twitch.refreshCalls, ['refresh-bot'], 'one refresh, for the rejected role only'); + assert.deepEqual(twitch.validateCalls, ['access-bot', 'refresh-bot-fresh-1', 'access-caster']); + assert.ok(lines.some((l) => l.includes('rejected the stored bot access token (401)'))); + const onDisk = JSON.parse(await readFile(path, 'utf8')) as TokensFile; + assert.equal(onDisk.bot.accessToken, 'refresh-bot-fresh-1'); + assert.equal(onDisk.broadcaster.accessToken, 'access-caster', 'untouched role is left as it was'); + } finally { + twitch.restore(); + } +}); + +void test('a revoked refresh token is fatal with the runbook pointer, one attempt, and no secret in the message', async () => { + const path = await writeTokens({ + bot: stored('111', 'bot', BOT_SCOPES, EXPIRED), + broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, EXPIRED), + }); + const twitch = mockTwitch( + new Map(), + // Broadcaster's refresh token still works; the bot's was revoked. + new Map([['refresh-caster', { userId: '222', scopes: BROADCASTER_SCOPES }]]), + ); + const errors: string[] = []; + const originalError = console.error; + console.error = (...args: unknown[]) => errors.push(args.map(String).join(' ')); + try { + const error = await start(path).then( + () => assert.fail('startup should have failed'), + (e: unknown) => e, + ); + assert.ok(error instanceof StartupTokenError); + assert.equal(error.reauthorize, true); + assert.match(error.message, /FATAL: Twitch refused to refresh the bot token for user 111 \(HTTP 400 "Invalid refresh token"\)/); + assert.match(error.message, /tools\/authorize\.mts/); + assert.match(error.message, /infra\/docs\/runbook\.md "Rotate the bot token"/); + assert.doesNotMatch(error.message, /broadcaster token/, 'the healthy role is not blamed'); + + // No retry storm: one refresh request per role, and nothing validated with the dead bot token. + assert.deepEqual(twitch.refreshCalls, ['refresh-bot', 'refresh-caster']); + assert.deepEqual(twitch.validateCalls, ['refresh-caster-fresh-1']); + + // Nothing printed may carry a token or the client secret. + for (const text of [error.message, ...errors]) { + assert.doesNotMatch(text, /DO-NOT-LOG|refresh-bot|refresh-caster|client_secret=(?!)/, text); + } + // The role that did refresh is still persisted. + const onDisk = JSON.parse(await readFile(path, 'utf8')) as TokensFile; + assert.equal(onDisk.broadcaster.accessToken, 'refresh-caster-fresh-1'); + assert.equal(onDisk.bot.accessToken, 'access-bot'); + } finally { + console.error = originalError; + twitch.restore(); + } +}); + +void test('a refreshed token that validate still rejects is fatal without a second refresh', async () => { + const path = await writeTokens({ + bot: stored('111', 'bot', BOT_SCOPES, FRESH), + broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, FRESH), + }); + const valid = new Map([['access-caster', { userId: '222', scopes: BROADCASTER_SCOPES }]]); + const twitch = mockTwitch(valid, new Map([['refresh-bot', { userId: '111', scopes: BOT_SCOPES }]])); + // Make every freshly minted bot token invalid as soon as it is minted. + const mintingFetch = globalThis.fetch; + globalThis.fetch = (async (...args: Parameters) => { + const response = await mintingFetch(...args); + for (const key of [...valid.keys()]) if (key.startsWith('refresh-bot-fresh')) valid.delete(key); + return response; + }) as typeof fetch; + try { + const error = await start(path).then( + () => assert.fail('startup should have failed'), + (e: unknown) => e, + ); + assert.ok(error instanceof StartupTokenError); + assert.match(error.message, /freshly refreshed bot token .* rejected \(401\)/); + assert.deepEqual(twitch.refreshCalls, ['refresh-bot']); + } finally { + twitch.restore(); + } +}); + +void test('both roles on ONE account: each refresh is persisted under its own role, scopes intact', async () => { + const path = await writeTokens({ + bot: stored('333', 'bot', BOT_SCOPES, EXPIRED), + broadcaster: stored('333', 'caster', BROADCASTER_SCOPES, EXPIRED), + }); + const twitch = mockTwitch( + new Map(), + new Map([ + ['refresh-bot', { userId: '333', scopes: BOT_SCOPES }], + ['refresh-caster', { userId: '333', scopes: BROADCASTER_SCOPES }], + ]), + ); + try { + const setup = await start(path); + assert.equal(setup.sameAccount, true); + const onDisk = JSON.parse(await readFile(path, 'utf8')) as TokensFile; + assert.equal(onDisk.bot.userId, '333'); + assert.equal(onDisk.broadcaster.userId, '333'); + assert.equal(onDisk.bot.accessToken, 'refresh-bot-fresh-1'); + assert.deepEqual(onDisk.bot.scope, BOT_SCOPES); + assert.equal(onDisk.broadcaster.accessToken, 'refresh-caster-fresh-2'); + assert.deepEqual(onDisk.broadcaster.scope, BROADCASTER_SCOPES); + + // A later runtime refresh of one role must not + // clobber the other role's entry. + twitch.refreshCalls.length = 0; + await setup.broadcasterAuthProvider.refreshAccessTokenForUser('333'); + await setup.tokenStore.flush(); + const after = JSON.parse(await readFile(path, 'utf8')) as TokensFile; + assert.equal(after.bot.accessToken, 'refresh-bot-fresh-1'); + assert.equal(after.broadcaster.accessToken, 'refresh-caster-fresh-3'); + } finally { + twitch.restore(); + } +}); + +void test('tokens.json is rewritten atomically at mode 0600 with no temp file left behind', async () => { + const path = await writeTokens({ + bot: stored('111', 'bot', BOT_SCOPES, EXPIRED), + broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, EXPIRED), + }); + const before = await stat(path); + const twitch = mockTwitch( + new Map(), + new Map([ + ['refresh-bot', { userId: '111', scopes: BOT_SCOPES }], + ['refresh-caster', { userId: '222', scopes: BROADCASTER_SCOPES }], + ]), + ); + try { + await start(path); + const after = await stat(path); + assert.equal(after.mode & 0o777, 0o600); + // A rename puts a new inode in place; an in-place rewrite would keep the old one. + assert.notEqual(after.ino, before.ino); + const dir = join(path, '..'); + assert.deepEqual(await readdir(dir), ['tokens.json']); + } finally { + twitch.restore(); + } +}); + +void test('a transient failure (Twitch 5xx on refresh) is fatal for this start but not a re-authorize', async () => { + const path = await writeTokens({ + bot: stored('111', 'bot', BOT_SCOPES, EXPIRED), + broadcaster: stored('222', 'caster', BROADCASTER_SCOPES, FRESH), + }); + const original = globalThis.fetch; + globalThis.fetch = (async () => + new Response('upstream sad', { status: 503, headers: { 'Content-Type': 'text/plain' } })) as typeof fetch; + try { + const config = { ...CONFIG_BASE, tokensFile: path }; + const setup = buildAuthProvider(config, await loadTokensFile(path)); + const error = await prepareStartupTokens(config, setup, { log: () => undefined }).then( + () => assert.fail('should fail'), + (e: unknown) => e, + ); + assert.ok(error instanceof StartupTokenError); + assert.equal(error.reauthorize, false); + assert.match(error.message, /HTTP 503/); + assert.doesNotMatch(error.message, /DO-NOT-LOG|refresh-bot/); + } finally { + globalThis.fetch = original; + } +}); diff --git a/services/bridge/tests/redact.test.ts b/services/bridge/tests/redact.test.ts new file mode 100644 index 0000000..f9b1031 --- /dev/null +++ b/services/bridge/tests/redact.test.ts @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { redactSecrets, safeErrorText } from '../src/redact'; + +void test('redactSecrets strips OAuth secrets from a twurple HttpStatusCodeError-shaped message', () => { + const message = + 'Encountered HTTP status code 400: Bad Request\n\nURL: token?grant_type=refresh_token&client_id=abc' + + '&client_secret=s3cr3t&refresh_token=r3fr3sh\nMethod: POST'; + const out = redactSecrets(message); + assert.doesNotMatch(out, /s3cr3t|r3fr3sh/); + assert.match(out, /client_secret=&refresh_token=/); + assert.match(out, /client_id=abc/, 'the client id is not a secret and stays readable'); +}); + +void test('redactSecrets strips Authorization header values', () => { + assert.equal(redactSecrets('Authorization: OAuth abcdef0123456789'), 'Authorization: OAuth '); +}); + +void test('safeErrorText redacts the cause chain too', () => { + const error = new Error('outer', { cause: new Error('URL: token?client_secret=s3cr3t') }); + assert.doesNotMatch(safeErrorText(error), /s3cr3t/); +});