Skip to content

fix(auth)!: harden OAuth, JWT auth, avatar uploads, and chat sanitization - #44

Merged
kixelated merged 6 commits into
mainfrom
quest/m0/security-auth
Nov 26, 2026
Merged

kixelated merged 6 commits into
mainfrom
quest/m0/security-auth

Conversation

@kixelated

@kixelated kixelated commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

The 2026-11-25 audit found that the API's auth surface could be abused:

  • OAuth redirects were prefix-matched (startsWith(APP_URL), startsWith("http://localhost:")), so https://hang.live.evil.com and http://localhost:80@evil.com received a 1-year session JWT in the query string.
  • Any provider email, verified or not, linked to or created an account, so anyone could take over (or pre-claim) an account by typing a victim's address into Discord. Apple's unsigned user POST field renamed whichever account had the email it named.
  • Uploads were typed by filename, allowing SVG; string avatars were unchecked; /public/* proxied any R2 key; /avatar/:key served SVG from the API origin.
  • jwtVerify threw on expired or malformed tokens, so Auth.required and Auth.optional returned 500, which broke guest room joins for returning browsers holding a stale token.
  • Peer chat Markdown could embed <img>, style="url()", media and so on, revealing every reader's IP address.

Approach

  • Login codes (PKCE-style, RFC 7636). The client generates a 32-byte crypto.getRandomValues verifier and sends only its SHA-256 challenge through the provider. The callback validates the redirect by parsed origin (web app origin, http://localhost:* for the native loopback server, hang://oauth) before contacting the provider, then redirects with a 5-minute code JWT (typed header, so it can never pass as a session). POST /auth/token {code, verifier} returns the session token. A leaked URL is useless without the verifier, which also stops login CSRF. This replaces the client-side random check and the dead URL cleanup.
  • Verified email only. On a login with no existing provider link, the API requires the provider's verified flag (Discord verified, Google verified_email, Apple email_verified) before matching or creating by email, and returns 403 otherwise. Each link now records whether it verified the account's own address (migration 0004, additive; every legacy link starts unverified). Linking by email is refused (409, "sign in once with the method you used before") while the account has an unverified link, so a pre-fix attacker-created account cannot absorb its address's real owner. A legacy link vouches again after its next verified sign-in with the account's address, which a legitimate user's normal sign-in provides. Existing provider links log in as before. Apple's name is used only when creating a new account, and first and last names are both optional.
  • Avatars. The leading bytes decide the type (PNG/JPEG/GIF/WebP only), and the upload is stored with its R2 contentType. String avatars must be a bundled /avatar/N.svg. Validation and upload run before the old object is deleted. PUT /account/info checks auth before parsing the form, and the form has a body limit. /public serves only avatar/<uuid>.<raster> with nosniff and CSP: default-src 'none'; sandbox. The account page's picker offers and names only those four types (avatarTypes in @hang/api/client). The /avatar/:key route is removed (nothing used it).
  • JWT failures. Auth.Context.verify returns undefined for any verification failure. The app clears its token when account/info returns 401.
  • Chat. app/src/room/sanitize.ts uses a private DOMPurify instance with a tag allowlist (no img/media/svg/iframe), href/title only, https?:/mailto: URIs only, and a hook that forces target="_blank" rel="noopener noreferrer". It throws if DOMPurify reports an unsupported DOM, because DOMPurify otherwise returns its input untouched. The worker's custom link renderer is removed.
  • Also fixed along the way: Discord users with no custom avatar or display name (null) failed the login schema; malformed callbacks now return 400 instead of 500.

Impact

  • Wire (breaking, hence !): GET /auth/:provider/login takes challenge instead of random. The callback redirects with ?code= instead of ?token=&random=. New POST /auth/token. Removed GET /avatar/:key, and /public serves only avatar keys. Migration: the web app updates on deploy. Native builds bundling the old frontend still send random. /login answers those with the download page as their url, which they open in the browser instead of a dead login. Existing sessions keep working. Installed desktop builds are being retired anyway (chore!: remove the Tauri native app #47), so no native release accompanies this change.
  • Behavior: logins with an unverified provider email that are not already linked are refused (403). String avatars other than bundled defaults are refused (400). Non-raster uploads return 415 and oversized ones 413.
  • Schema: migration 0004_link_email_verified.sql adds accounts_linked.email_verified (default 0, no backfill). It is additive, and an older Worker ignores the column (its new links default to unverified, the safe side). Numbering collision: fix: SolidJS UI, account, and favorites API reliability #45 (queued to land first) also adds a 0004 (0004_random_avatar_type.sql, an independent UPDATE on accounts). Whichever lands second renumbers its file to 0005; this PR rechecks before its final push and updates the 0004 cutoff in api/test/oauth.test.ts with it. The two migrations touch different tables, so either order is correct.
  • Public TS API: @hang/api/client adds oauthVerifier, oauthChallenge, oauthTokenSchema, avatarTypes; oauthStateSchema changes shape; OAuth.callbackResponseSchema, Callback, CallbackResponse, Provider.updateAppleUser, Storage.validateAvatar, Storage.extension removed. No schema migration.
  • Overlap: ui-api-fixes (in progress in parallel) lists "validate and upload the new R2 avatar before deleting the old object". That ordering lands here, because enforced validation needs it. Its other account.ts items (the avatarType: "r2" default-avatar bug, updatedAt) are left to it.

Decisions

Maintainer, 2026-11-25 (#44 (comment)), recorded with quest review --accept:

  • Stale Google verified_email (api/src/oauth.ts:312): ✅ accept, it is the standard provider bar (rejected: first-party email verification, Gmail/Workspace-only Google linking).
  • No recovery for a pre-fix account whose original login is lost (api/src/oauth.ts:568): ✅ accept, handled through support until the API can send email (rejected: a verified recovery path now, restoring trust in legacy links).
  • Native release at the cutover: ✅ moot, Hang is retiring its installed desktop builds (chore!: remove the Tauri native app #47) (rejected: cutting signed native builds with this deploy). As currently written, chore!: remove the Tauri native app #47 keeps native/ as a minimal MoQ canary rather than deleting it. Either way, this PR needs no release, and stale builds still get the /download answer.
  • Peer avatars follow-up: ✅ keep, and copy provider avatars into R2 at signup (rejected: allowlist provider CDNs).

Made without asking, for review:

  • Break legacy login starts rather than keep a token-in-URL path. Keeping the old random flow for stale native builds would keep the hole open. Existing sessions are unaffected.
  • Require verified email on every new link or account, including account creation. Otherwise an unverified address can pre-claim an account that a later verified login lands in.
  • No legacy link is trusted on its provider's name. Apple Managed Accounts can carry email_verified: false, and nothing recorded what each legacy login saw. Cost: a legacy user's first sign-in with a new provider gets a 409 asking them to sign in once with their usual one.
  • Stale native builds get an upgrade prompt. /login answers the old random shape with {url: APP_URL/download} rather than a 400. These are a few lines to delete once no supported build sends random.
  • String avatars limited to the bundled defaults (the only strings the app sends), rather than a scheme blocklist.
  • Already-uploaded SVGs in R2 stay as they are. public.hang.live is a separate origin holding no credentials, and new uploads can no longer be SVG.
  • jsdom added as an app devDependency for the sanitizer test. happy-dom 21's NodeIterator stops at the first removed node ([BODY, I] instead of [BODY, I, B, U]), so DOMPurify under happy-dom silently keeps everything after the first stripped element.

Alternatives

  • A stateful single-use exchange code (D1/KV row) instead of the stateless verifier-bound JWT. Rejected: it adds storage and cleanup, and the verifier binding already makes a leaked code worthless.
  • A URL fragment instead of a code. Rejected: fragments never reach the native app's loopback HTTP server.

Follow-ups

  • peer-avatars: peers can still point their broadcast avatar URL at a tracking host (app/src/room/video.ts loads it unchecked). Decided: copy provider avatars into R2 at signup (rejected: allowlist provider CDNs). No open decisions.

Caused by

No single PR. The prefix checks, email linking, avatar handling, and chat sanitizer date from the initial import of the API and app.

Validation

  • After merging main at b98b9aa: quest gate just check passes (API 26, app 31, browser media 2).
  • quest gate just check: Quest, TypeScript, Biome, API tests (26), app tests (12), native fmt. All pass.
  • New API tests run the real Hono routers over in-memory SQLite with every migration applied, with provider HTTP mocked, Apple included (real ES256 ID tokens checked against a mocked JWKS). They cover redirect bypasses, forged callback state (provider never contacted), code redemption with a wrong or missing verifier, code/session confusion, expired codes, unverified-email takeover and pre-hijack, forged Apple user fields, legacy unverified links (refused, then re-vouched) and the 0004 migration over legacy rows, the stale-client download redirect, null Discord fields, byte-sniffed uploads, URL avatars, old-avatar retention, body limit, and the /public restrictions. Before the fix, the old auth.ts fails 3 of the 4 middleware tests (500s), and the old DOMPurify config fails 3 of the 4 sanitizer tests.
  • Real surfaces: ran the Worker in workerd (wrangler dev, local D1/R2) and hit each changed route: evil redirects 400, legit web/loopback/deep-link 200, legacy random 400, forged callback 400, bogus code 401, garbage bearer on /account/info 401, room join with garbage bearer 200 as guest, SVG labelled PNG 415, javascript: avatar 400, PNG upload served with image/png + nosniff + sandbox CSP and deleted when replaced, non-avatar /public keys 404, /avatar/* 404. Ran the bundled sanitizer in Chrome 157: every remote-loading vector stripped, javascript: href dropped, links forced to _blank + noopener noreferrer.
  • Migration 0004 applied by wrangler d1 migrations apply --local over D1 state holding legacy links (round-1 version; the final version only drops its backfill UPDATE).
  • Not run: a live provider login (needs real OAuth credentials and registered redirect URIs), and native compilation (native/src/lib.rs changes are comments only).

Models

  • Size: M
  • Implementer: Claude Code, claude-opus-5-5, high
  • Implementer: Claude Code, claude-opus-5-5, unknown (iterate, M)

🤖 Generated with Claude Code

(Written by Claude Opus 5.5 with high)

Review

Rewritten by quest review after each round.

  • Head: d1d12e1

  • Base: origin/main at b98b9aa

  • Risk: medium, the base has no RISK.md to name what is always high or customer-facing, so every change is medium

  • Classified: medium by default

  • Reviewer: Codex, gpt-6.2-sol, high effort

  • Session: 01a215ed-4c43-7461-9b3c-da52f871f3e2, round 4

  • Score: 10/10, The only new branch change records the peer-avatar follow-up decision, and the supplied maintainer record settles all three prior findings.

  • Rounds: 4; first round 3 (high 2, medium 1); findings 4 (high 1, medium 3): fixed 1, refuted 3, open 0

  • Findings: none

  • The last round's findings, at f16e88f:

    • Refuted: medium, api/src/oauth.ts:312: Require current email ownership before trusting a legacy Google link; The supplied maintainer record accepts Google's `verified_email` as the provider standard, and the code supporting that decision is unchanged at this head (direct GitHub verification was unavailable). [Maintainer decision](https://github.com/moq-dev/hang.live/pull/44#issuecomment-7182575734)
    • Refuted: high, api/src/oauth.ts:500: Make compatible native installers available at the OAuth cutover; The supplied maintainer record removes the native release requirement because Hang is retiring its installed desktop builds. [Maintainer decision](https://github.com/moq-dev/hang.live/pull/44#issuecomment-7182575734) · [Desktop retirement PR](https://github.com/moq-dev/hang.live/pull/47)
    • Refuted: medium, api/src/oauth.ts:568: Provide recovery when a legacy sign-in method is unavailable; The supplied maintainer record assigns legacy account recovery to support until the API can send email, and the recovery behavior is unchanged at this head. [Maintainer decision](https://github.com/moq-dev/hang.live/pull/44#issuecomment-7182575734)

Quest-Claim: fd92861f44a20095
…tion

- OAuth redirects are checked by parsed origin; the redirect carries a
  5-minute PKCE-bound code instead of the session JWT, redeemed at
  POST /auth/token with a crypto-random verifier only the client holds.
- New logins link or create accounts by email only when the provider
  verified it; Apple's unsigned user field only names a new account.
- Malformed or expired JWTs return 401 (guest on optional routes), and
  the app drops a token the API rejects.
- Avatar uploads are typed by magic bytes (PNG/JPEG/GIF/WebP), string
  avatars are limited to bundled defaults, /public serves only avatar
  keys with nosniff and a sandbox CSP, and the SVG-serving /avatar route
  is removed.
- Chat HTML is sanitized with a tag/attribute/scheme allowlist that
  loads no remote resources and forces safe link targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kixelated kixelated changed the title Harden OAuth, JWT auth, avatar uploads, and chat sanitization fix(auth)!: harden OAuth, JWT auth, avatar uploads, and chat sanitization Nov 26, 2026
kixelated and others added 2 commits November 25, 2026 19:41
…avatar picker

Links now record whether the provider verified the account's own address
(migration 0004 backfills Google and Apple as verified, Discord as not).
Linking a new provider by email is refused while the account has an
unverified link; a legacy link vouches again after its next verified
sign-in with the account's address. The avatar picker offers only the
raster types the API accepts and names them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…download

Migration 0004 no longer backfills Google and Apple links as verified,
since nothing recorded which addresses were. Every legacy link vouches
again on its next verified sign-in with the account's address.

Native builds older than the code exchange send `random` and open the
returned `url`, so /login now points them at the download page instead
of a dead 400.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kixelated

Copy link
Copy Markdown
Collaborator Author

Maintainer decision (2026-11-25, /quest-run):

  • Accept the stale Google "verified" flag. It's the standard provider bar.
  • Accept no recovery path for pre-fix accounts whose original login is lost. Handle them through support until the API can send email.
  • The native release step is moot: Hang is dropping Tauri (see chore!: remove the Tauri native app #47).
  • Keep follow-up quest/m1/peer-avatars.md. Decided: copy provider avatars into R2 at signup, rejecting a CDN allowlist.
  • Pick: /quest-merge once the new head is reviewed and checks pass.

(Written by Claude Opus 5.5 with high)

@kixelated
kixelated marked this pull request as ready for review November 26, 2026 04:29
@coderabbitai

coderabbitai Bot commented Nov 26, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 7 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6b69e857-54a1-4a35-b2cf-9f4891669ffd
Commits

Reviewing files that changed from the base of the PR and between b98b9aa and d1d12e1.

Files ignored due to path filters: 1

  • bun.lock is excluded by !**/*.lock
Files selected for processing: 26

  • api/migrations/0004_link_email_verified.sql
  • api/package.json
  • api/src/account.ts
  • api/src/auth.ts
  • api/src/avatar.ts
  • api/src/client.ts
  • api/src/index.ts
  • api/src/oauth.ts
  • api/src/storage.ts
  • api/test/auth.test.ts
  • api/test/avatar.test.ts
  • api/test/harness.ts
  • api/test/oauth.test.ts
  • app/package.json
  • app/src/account.tsx
  • app/src/api.test.ts
  • app/src/api.ts
  • app/src/oauth.tsx
  • app/src/room/chat-worker.ts
  • app/src/room/chat.ts
  • app/src/room/sanitize.test.ts
  • app/src/room/sanitize.ts
  • app/src/settings.tsx
  • native/src/lib.rs
  • quest/m0/security-auth.md
  • quest/m1/peer-avatars.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@kixelated
kixelated merged commit 048c95a into main Nov 26, 2026
4 checks passed
@kixelated
kixelated deleted the quest/m0/security-auth branch November 26, 2026 04:36
kixelated added a commit that referenced this pull request Nov 26, 2026
Keep #44's OAuth hardening and drop the redirect allowances and legacy
login shim it kept for the native app, which this branch deletes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kixelated added a commit that referenced this pull request Nov 26, 2026
Keep #44's avatar validation and default-only URL avatars in account.update(),
renumber the random-avatar repair migration to 0005 after #44's 0004, take
#33's camera picker condition, and drop the download.tsx change that #47
makes moot.

Also settle the two CodeRabbit findings on account.ts: a failed delete of the
replaced upload is logged instead of failing a committed save, and
account.delete() deletes the R2 avatar before the rows again so a failed R2
delete stays retryable. The account tests now share #44's harness, which
enforces foreign keys as D1 does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant