Files
HealthLog/src/lib/logging/redact.ts
T
Marc-André Bombeck 1a478d3028 feat(whoop): native-scheme connect redirect and Bearer connect ticket
Two connect-in-app enhancements for the native client.

return_scheme: GET /api/whoop/connect accepts an optional custom scheme,
threaded through the server-side OAuth-state row so it survives the round
trip without ever riding in the URL or cookie. When a valid scheme is
present, the callback's final redirect targets <scheme>://whoop?whoop=
connected|error&reason=... so an in-app web session auto-completes on its
custom-scheme match; absent or invalid, the web settings redirect is
unchanged. Schemes validate against a strict allowlist (custom app scheme
only, ^[a-z][a-z0-9.+-]*$, http/https/javascript/data/file/vbscript
rejected, pinned to dev.healthlog.app). A rejected scheme falls back to
the web redirect and never reflects an arbitrary value.

Bearer connect ticket: a purely Bearer-authenticated client holds no web
session cookie, so it cannot start the handshake through the cookie-gated
connect route. POST /api/whoop/connect/ticket (Bearer) mints a one-time,
~60s, opaque ticket bound to the user; only its HMAC-SHA256 hash is stored
(the raw value never persists). GET /api/whoop/connect?ticket=<opaque>
accepts the ticket in lieu of a cookie, consumes it atomically (single-use,
reuse rejected), sets the nonce cookie, and 302s to WHOOP exactly as the
cookie path. Expired, consumed, or invalid tickets return a typed 401. The
two combine. The daily WHOOP OAuth-state cleanup also sweeps expired ticket
rows.

The ticket query param is added to the egress redaction denylist so the
opaque value never reaches logs or error reports.

Migration 0124 adds whoop_connect_tickets (id, user_id FK cascade,
token_hash unique, expires_at, consumed_at, created_at) and a nullable
return_scheme column on whoop_oauth_states.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 221b362011d52dda314139e0be7cc195c47d016e)
2026-06-05 08:10:13 +02:00

110 lines
5.6 KiB
TypeScript

/**
* Redact secrets from strings before they leave the process boundary
* (Loki, Glitchtip, console). Applied in `WideEventBuilder.setError()`,
* `WideEventBuilder.setHttp()`, and `reportToGlitchtip()` so every
* value reaching observability is scrubbed once, centrally.
*
* Patterns:
* - `Bearer <token>` — generic API tokens incl. our `hlk_` /
* `hlr_` formats and external OAuth bearers (Withings, AI providers).
* - `bot<digits>:<token>` — Telegram bot URLs embed the token in the
* path: `https://api.telegram.org/bot1234567:ABC-…/sendMessage`.
* If `fetch()` rejects with a `cause` that surfaces the URL (some
* Node runtimes), the token would land in error reports.
* - `?secret=…` and `?code=…` — query-string leaks for legacy
* Withings webhooks and OAuth callbacks (already scrubbed at the
* URL level in `reportToGlitchtip`, but error.message can carry
* the URL too).
* - `sk-…` and `sk-ant-…` — OpenAI / Anthropic API keys. We never
* log them on purpose, but a misconfigured client error or a
* dump of the request body could carry one. Scrub before egress.
* - path-segment secrets — routes like `/api/withings/webhook/<secret>`
* and the clinician share view `/c/<hls_…>` carry a bearer secret as
* a positional path segment. The Wide Event `http.path` and
* `http.route` fields would otherwise leak the secret into stdout,
* the in-memory ring buffer, and Loki. See `PATH_SECRET_PATHS`.
*
* The substitution is intentionally generic ([REDACTED]) — we don't
* want partial revelation of token entropy.
*/
/**
* Registry of path prefixes where the trailing segment is a shared
* secret. Each entry's `prefix` must end with `/`; any non-empty
* segment after it is rewritten to `[REDACTED]`. Subsequent path
* segments are preserved (so `/foo/<secret>/bar` becomes
* `/foo/[REDACTED]/bar`).
*
* Add a new entry whenever a route exposes a secret in its URL path
* (rather than headers, body, or query). Tested in `redact.test.ts`.
*/
export const PATH_SECRET_PATHS: ReadonlyArray<{ prefix: string }> = [
// Withings webhook entrypoint: `WITHINGS_WEBHOOK_SECRET` travels as
// the trailing path segment (v1.4.25 W17a). Without this rule the
// secret lands in every Wide Event's `http.path` / `http.route`.
{ prefix: "/api/withings/webhook/" },
// v1.11.0 — clinician share view (Epic C). The raw `hls_` share token
// rides as the trailing path segment of `/c/<token>`; it is a bearer
// credential for the share surface, so scrub it from `http.path` /
// `http.route` the same way the Withings webhook secret is scrubbed.
{ prefix: "/c/" },
// v1.11.0 — WHOOP webhook entrypoint: `WHOOP_WEBHOOK_SECRET` travels as
// the trailing path segment (mirrors Withings). Without this rule the
// secret lands in every Wide Event's `http.path` / `http.route`.
{ prefix: "/api/whoop/webhook/" },
];
function redactPathSegments(input: string): string {
let out = input;
for (const { prefix } of PATH_SECRET_PATHS) {
// Match `<prefix><segment>` where `<segment>` is one or more
// non-`/` non-`?` chars, then preserve anything after (next path
// segment, query string, hash). Capture group 1 is the optional
// trailing context starting with `/`, `?`, or `#`.
const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(`${escaped}[^/?#\\s]+([/?#][^\\s]*)?`, "g");
out = out.replace(re, (_match, tail: string | undefined) => {
return `${prefix}[REDACTED]${tail ?? ""}`;
});
}
return out;
}
export function redactSecrets(input: string): string {
return (
redactPathSegments(input)
.replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]")
.replace(/bot\d+:[A-Za-z0-9_-]+/g, "bot[REDACTED]")
// `sk-` is a common English-prefix substring (task-force, risk-
// management, disk-io). Without a word-boundary, the original
// `/sk-(?:ant-)?[A-Za-z0-9_-]+/g` over-matched and made server logs
// unreadable. Require the `sk-` token to be at the start of the
// string OR preceded by a non-alphanumeric character (whitespace,
// `=`, `{`, `,`, `:`, etc.). The minimum length-8 tail keeps a
// tiny safety margin against `sk-1`-style false-positives in code
// identifiers. Capture group 1 = the leading separator (preserved).
.replace(/(^|[^A-Za-z0-9])sk-(?:ant-)?[A-Za-z0-9_-]{8,}/g, "$1[REDACTED]")
// HealthLog native API tokens (`hlk_<64hex>` access, `hlr_<64hex>`
// refresh). Same boundary-aware shape as the `sk-` rule. The
// idempotency replay-cache already rejects bodies containing
// these prefixes (CLAUDE.md headless-client-API patterns); this
// is the matching egress guard for log/error surfaces.
.replace(/(^|[^A-Za-z0-9])hl[kr]_[A-Fa-f0-9]{32,}/g, "$1[REDACTED]")
// v1.7.0 — `insurance`/`insuranceNumber`/`kvnr` (German statutory-
// insurance number) added as defence-in-depth: the value is
// encrypted at rest and never deliberately logged, but a stray
// query-string leak (`?kvnr=…`) is scrubbed at the egress boundary.
// v1.12.2 — `ticket` (the one-time WHOOP connect ticket rides in the
// `GET /api/whoop/connect?ticket=…` URL): scrub it so the opaque value
// never lands in `http.path`/error strings reaching Loki/Glitchtip.
.replace(
/([?&])(secret|code|token|ticket|api[_-]?key|insurance(?:number)?|kvnr)=[^&\s]+/gi,
"$1$2=[REDACTED]",
)
);
}
/** Apply `redactSecrets` to a possibly-undefined string. */
export function redactOptional(s: string | undefined): string | undefined {
return s === undefined ? undefined : redactSecrets(s);
}