Skip to content

fix(relay): harden self-hosted relay and OIDC sign-in - #2

Open
flvvius wants to merge 20 commits into
TuroYT:t3/self-hosted-connect-servicefrom
flvvius:relay-oidc-hardening
Open

flvvius wants to merge 20 commits into
TuroYT:t3/self-hosted-connect-servicefrom
flvvius:relay-oidc-hardening

Conversation

@flvvius

@flvvius flvvius commented Nov 19, 2026

Copy link
Copy Markdown

Problem

A source review of the self-hosted relay and OIDC sign-in in pingdotgg#34302 found no auth bypass, but found several ways a relay, a look-alike relay or a client could get more than it should:

  • A session obtained through one relay was reused after switching to another relay with the same issuer and client id. That relay received the user's ID token. The CLI did the same when T3CODE_RELAY_URL changed.
  • Web and desktop kept the OIDC refresh token in localStorage.
  • The relay accepted access tokens where it expected ID tokens. OIDC discovery followed redirects and accepted any scheme.
  • Manual endpoints were on (public) in the compose file, and checked by hostname only, so a name that resolves to an internal address reached the relay's network.
  • The relay had no body, frame, queue or per-user link limits. The compose stack ran the relay as the Postgres superuser.
  • An operator could not cut one account off. Revoked credentials kept their relay channel open until the next recheck.
  • --publish-only still gave a host a relay channel, which means remote control.
  • The self-host README said thread data never reaches the relay.

Change

Clients

  • Sessions name the relay, issuer and client they were obtained for. Any other session is dropped, so switching relays always signs in again. The CLI credential is bound to T3CODE_RELAY_URL the same way, and the CLI prints the relay and sign-in host before showing a code.
  • A build can set T3CODE_RELAY_PINNED=true or T3CODE_RELAY_ALLOWLIST (web, desktop, mobile) to stop users from choosing another relay. Unset keeps today's behavior.
  • Web keeps the session in the tab's sessionStorage. Desktop keeps it in the main process, encrypted with safeStorage, and posts token requests from there. This also fixes Entra refusing to redeem a code from the t3code:// origin (AADSTS9002326).
  • Mobile unregisters the phone from the relay before clearing the session on sign-out.
  • t3 connect link --activity-only and T3CODE_RELAY_REMOTE_CONTROL=false refuse relay channels. link, --publish-only and status say whether remote control is on.

Relay

  • Accepts only ID tokens (no at+jwt, no scp, azp must match when present). Discovery is https only (http for loopback), refuses redirects, caps the document size, and refuses a bad issuer at startup.
  • Resolves manual endpoint names itself and refuses internal addresses, connecting to the address it checked. Callers get a generic error.
  • Limits: RELAY_API_MAX_BODY_BYTES (1 MiB), RELAY_CHANNEL_* and RELAY_WS_MAX_FRAME_BYTES, and RELAY_MAX_ENVIRONMENTS_PER_USER (25). Slow socket readers get closed.
  • Drops client-sent forwarding and hop-by-hop headers. Redirects must stay under the environment's /env/<key>/ path.
  • node src/node.mjs offboard --subject <sub> [--issuer <iss>] revokes an account's links and credentials and deletes its devices in one transaction. Revocations notify all relays, which close those channels at once.
  • <NAME>_FILE reads any secret from a file.

Self-host stack

  • Manual endpoints are off by default. The relay connects as a relay role that owns only its database.
  • Secrets are files from gen-keys.sh. Containers are read-only, drop all capabilities and run with no-new-privileges.
  • Caddy caps bodies (2 MiB API, 64 MiB /env/) and adds security headers. Base images are pinned by digest.
  • The README now says what the relay stores and sees, and covers encrypted backups and moving an older deployment to the relay role. OPERATING.md covers running the relay: host, identity provider settings, offboarding and known limitations.

Scope

This targets the pingdotgg#34302 branch. It changes the self-hosted relay, OIDC sign-in, and the client code that picks a relay. The hosted (Clerk) sign-in flow is unchanged, except that its stored CLI credential is now also bound to the relay URL.

What users will notice:

Who Change
Web, desktop and self-hosted CLI users Sign in once more after upgrading. Every relay switch signs in again.
Hosted CLI users Sign in once more after upgrading (the credential's stamp now names the relay).
Web users Each new tab or browser session signs in again, usually a quick redirect.
Operators with an existing stack Manual endpoints become off. Moving to the relay role is a README step.
Hosts on a channels relay --activity-only or T3CODE_RELAY_REMOTE_CONTROL=false opts out of remote control.

Left out on purpose, since these are product or policy decisions or need their own design:

  • Making device approval the default.
  • Analytics and telemetry defaults.
  • Desktop CSP.
  • Android cleartext and user-CA settings.
  • Revoking environment credentials on unlink from the host.
  • An expected-host check on local cookie auth.
  • End-to-end encryption between client and environment.
  • Android App Links for the sign-in redirect.

Verification

  • vp run check:changed c417cb8eb3 passes: format, lint, knip, graphql, typecheck (38 packages), tests (23 files, 302 tests) and react compiler. New and extended tests cover session binding, relay policy, ID-token checks, endpoint vetting, channel limits, link caps, offboarding and the CLI binding.
  • Live run of infra/relay/selfhost built from this branch:
    • All three containers healthy, read-only, with all capabilities dropped. The relay runs as uid 1000.
    • Migrations are applied by the relay role, which is not a superuser.
    • /.well-known/t3-relay answers.
    • A 3 MiB API body gets 413 from Caddy, and a 1.5 MiB one gets 413 from the relay. A 65 MiB /env/ body gets 413.
    • Manual endpoints are off when unset.
    • An http:// issuer refuses startup.
    • offboard --subject <sub> prints its counts.
    • This run also found that offboard with bad arguments tried to bind port 8080. That is fixed in the last commit.

Not verified:

  • Live Entra sign-in on desktop, web, CLI and Android.
  • Android sign-out on a real device.
  • Browser tests, which were not run locally.
  • An offboard against real links.

Model and harness: Claude Opus 5.5 in Claude Code (T3 Code).

🤖 Generated with Claude Code

flvvius and others added 20 commits November 19, 2026 15:28
A session obtained through one relay was reused after switching to another
whenever the new relay advertised the same issuer and client id, handing the
user's ID token to that relay. Sessions now live under one key and name the
relay, issuer and client they were obtained for; any other session is dropped
on read, and the old provider-keyed entry is removed.

Adds RelayPolicy (pinned / allowlisted origins) that the apps read from build
config to hide or restrict the self-hosted relay choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Manual endpoints default to off. Postgres keeps its superuser for setup and the relay connects as a role that owns only the relay database, created by an init script. Database passwords and the URL are secret files from gen-keys.sh, read through POSTGRES_PASSWORD_FILE and DATABASE_URL_FILE. Every container drops all capabilities, runs with no-new-privileges, a read-only root, memory, process and log limits; Postgres runs as its own user on an internal network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
API requests are capped at 2 MiB and relay channel requests at the relay's 64 MiB limit. Every response gets HSTS; API responses also get nosniff, no framing and no referrer. Carried environments keep the relay's sandbox policy without framing limits, since the apps frame their file previews. Slow request headers time out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Node, Postgres and Caddy images are pinned by digest so a rebuild from unchanged source uses the same inputs. The runtime image also drops npm, which the bundled relay never uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Manual endpoints were validated by hostname only, so a name resolving to a
private or link-local address turned the relay into an internal scanner.
The Node relay now resolves the name itself, refuses the whole answer when
any address is internal or (in public mode) private, and connects to the
address it checked. IP literals are checked before connecting. Callers get a
generic failure for these endpoints; the reason stays in the relay's logs.
Push delivery queues are bounded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The README no longer claims thread data never reaches the relay: it lists what the database holds and that relay channels carry live traffic in clear. Backups are encrypted with age and come with retention and restore steps, plus a migration for deployments that ran the relay as the Postgres superuser. A new operator guide covers the relay host, identity provider settings, device approval, offboarding and known limitations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Any user could type any relay address under T3 Connect service, and a
look-alike relay then received the user's ID token. A build can now set
T3CODE_RELAY_PINNED=true to use only its own T3CODE_RELAY_URL (the
self-hosted choice and its search entry are hidden, a stored choice is
ignored), or T3CODE_RELAY_ALLOWLIST to accept only listed origins. Unset
keeps today's behavior. Desktop renders the same bundle, so it follows.

The OIDC config now carries the relay URL so the session is bound to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The refresh and ID tokens sat in localStorage, readable by any script on
the origin and kept on disk for the refresh token's lifetime (90 days for
the desktop's public client).

Web now keeps the session in this tab's sessionStorage. Memory alone would
lose it on every reload, and the redirect sign-in and the relay switch both
reload the page; sessionStorage survives those but ends with the tab, is
not shared with other tabs and is not kept across browser restarts. The
cost: each new tab or browser session signs in again (usually a quick
bounce through the identity provider's own session).

Desktop keeps the session in the main process, encrypted with Electron
safeStorage (oidc-session.bin in the state directory); without a keychain
it stays in memory and ends with the app. Token requests also move to the
main process: Entra refuses to redeem a code sent from the renderer's
t3code:// origin (AADSTS9002326), because only SPA redirect URIs may
redeem cross-origin and a custom scheme cannot be one. The main process
discovers the issuer itself and only posts authorization-code or
refresh-token grants to that issuer's token endpoint.

Existing localStorage sessions are deleted on upgrade, so users sign in
once more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Discovery followed redirects, accepted any scheme and any size, so whoever
answered it could choose the keys every token is checked against. It now
requires https (http only for loopback), refuses redirects, caps the
document and refuses a bad issuer at startup. JWKS fetches use the same
no-redirect client.

Tokens carrying the at+jwt type or an scp claim are access tokens and are
refused where an ID token is expected, and azp, when present, must name the
relay's client. Entra v2 ID tokens carry neither, so they keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The mobile app reads T3CODE_RELAY_PINNED / T3CODE_RELAY_ALLOWLIST from its
Expo config like web and desktop: a pinned build hides the T3 Connect
service row and ignores a stored relay; an allowlist limits which relay
can be chosen. The OIDC session is bound to the relay URL.

Sign-out used to clear the session first, so the cleanup that unregisters
the phone from the relay found no token and the relay kept pushing agent
activity (thread titles) to a signed-out phone. Sign-out now unregisters
the device while the token is still valid (bounded to 5 s), then clears
the session; switching relays signs out first for the same reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stored CLI credential was stamped with the identity provider only, so a
changed T3CODE_RELAY_URL (a stray dotenv, a malicious env var) received the
existing ID and refresh tokens without a new sign-in. The stamp now also
names the relay URL; a credential for any other relay is not used and the
CLI asks to sign in again. Existing credentials carry no relay, so every
CLI host signs in once more after upgrading.

Before showing a device code or sign-in link, the CLI now prints the relay
and the sign-in provider's host it is about to use, so a swapped relay or
provider is visible before the user approves anything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`t3 connect link --publish-only` skipped the managed tunnel, but a
self-hosted relay with channels still handed the host a relay channel,
which gives approved devices remote control. The CLI only said "start
T3 to publish agent activity".

- `t3 connect link --activity-only` (and a link that `t3 connect publish`
  creates) records that this link refuses relay channels.
- `T3CODE_RELAY_REMOTE_CONTROL=false` refuses them for every link; a bad
  value fails closed.
- The host drops a relay channel config it is refused, and never starts
  one stored earlier.
- `--publish-only`, `link` and `status` state whether remote control is on.
- A reachable relay channel reads "Relay channel connected", and the
  startup log says remote control is on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Channels could make the relay buffer 64 MiB request bodies and unbounded
socket frames, any client could claim any X-Forwarded-For, and absolute
redirects from an environment sent visitors anywhere from the relay origin.

- Per-channel caps on pending requests and carried sockets, a shared
  memory budget for bodies and frames, and a 50 MiB body limit; slow
  socket readers are closed with 1013 instead of buffered without end.
- Writers wait for the peer to drain before sending more.
- Forwarding and hop-by-hop headers are dropped; the relay sets
  X-Forwarded-For from its own peer, or the front proxy's last entry.
- Redirects must resolve under the environment's own /env/<key>/ path.
- Credential rechecks can be woken early, and four failed lookups in a
  row end the channel instead of keeping it open forever.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An operator had no way to cut one account off, and a revoked
credential kept its channel open until the next 25 second recheck.

- offboardOidcSubject revokes the account's links and the credentials
  behind them in one transaction, and deletes its devices and live
  activities (push tokens).
- Revoking credentials sends pg_notify on t3_relay_credentials_revoked
  after commit, so relays recheck their channels at once.
- pruneRevoked forgets credentials revoked long ago.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The self-hosted relay read request bodies without a limit, accepted
100 MiB WebSocket frames, let one account link any number of
environments, and could only read its database URL from the
environment.

- RELAY_API_MAX_BODY_BYTES (1 MiB) bounds every relay API body,
  including the unauthenticated DPoP token route.
- Channel limits and the WebSocket frame limit come from RELAY_CHANNEL_*
  and RELAY_WS_MAX_FRAME_BYTES; the frame default follows the body limit.
- RELAY_MAX_ENVIRONMENTS_PER_USER (25) caps active links. The link and
  its credential are written in one transaction, so a refused or failed
  link leaves nothing behind.
- <NAME>_FILE reads secrets such as DATABASE_URL_FILE from files.
- The relay listens for credential revocations to close channels.
- `node src/node.mjs offboard --subject <sub> [--issuer <iss>]`.
- The cron drops activity rows abandoned for 7 days and credentials
  revoked 30 days ago.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Drop build-policy guidance that belongs to individual forks, use the
real offboard command, and remove the Android transport section whose
code is not part of this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The server layer was built whenever the arguments did not parse as an
offboard command, so a mistyped offboard inside the running container
failed with EADDRINUSE before it could print usage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added vouch:unvouched PR author is not yet trusted in the VOUCHED list. size:XXL labels Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XXL vouch:unvouched PR author is not yet trusted in the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant