flybrain/services/bridge/src/redact.ts
acamilo d06e1cf809 bridge: refresh stored tokens on load before giving up, persist both roles
A stored access token that has expired (obtainmentTimestamp + expiresIn) or
that validate rejects with 401 is now refreshed once through its role's
RefreshingAuthProvider before startup fails, for the bot and broadcaster
roles alike. Refreshes are persisted under the role whose provider made
them (no more scope-set guessing), through one serialized writer, so both
roles reach tokens.json even when they are one account; writes stay
tmp + rename, 0600.

Only a refresh Twitch refuses (4xx, e.g. 400 Invalid refresh token) is
fatal, with one line naming the role and the runbook's re-authorize step.
Twitch errors are logged by status and message only: twurple's
HttpStatusCodeError message carries the refresh grant URL, client secret
and refresh token included, so the entrypoint and EventSub log lines now
redact it.

Tests mock Twitch's validate and token endpoints. Runbook and B1 updated.
2026-09-28 23:47:48 +00:00

27 lines
1.3 KiB
TypeScript

/**
* 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=<redacted>').replace(AUTH_HEADER, '$1 <redacted>');
}
/** 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));
}