Repository navigation
fix(auth)!: harden OAuth, JWT auth, avatar uploads, and chat sanitization - #44
Merged
Merged
Conversation
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>
…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>
Collaborator
Author
|
Maintainer decision (2026-11-25, /quest-run):
(Written by Claude Opus 5.5 with high) |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Warning Review limit reachedYou'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. View limit details
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. |
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>
This was referenced Nov 26, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The 2026-11-25 audit found that the API's auth surface could be abused:
startsWith(APP_URL),startsWith("http://localhost:")), sohttps://hang.live.evil.comandhttp://localhost:80@evil.comreceived a 1-year session JWT in the query string.userPOST field renamed whichever account had the email it named./public/*proxied any R2 key;/avatar/:keyserved SVG from the API origin.jwtVerifythrew on expired or malformed tokens, soAuth.requiredandAuth.optionalreturned 500, which broke guest room joins for returning browsers holding a stale token.<img>,style="url()", media and so on, revealing every reader's IP address.Approach
crypto.getRandomValuesverifier and sends only its SHA-256challengethrough 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-minutecodeJWT (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-siderandomcheck and the dead URL cleanup.verified, Googleverified_email, Appleemail_verified) before matching or creating by email, and returns 403 otherwise. Each link now records whether it verified the account's own address (migration0004, 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.contentType. String avatars must be a bundled/avatar/N.svg. Validation and upload run before the old object is deleted.PUT /account/infochecks auth before parsing the form, and the form has a body limit./publicserves onlyavatar/<uuid>.<raster>withnosniffandCSP: default-src 'none'; sandbox. The account page's picker offers and names only those four types (avatarTypesin@hang/api/client). The/avatar/:keyroute is removed (nothing used it).Auth.Context.verifyreturnsundefinedfor any verification failure. The app clears its token whenaccount/inforeturns 401.app/src/room/sanitize.tsuses a private DOMPurify instance with a tag allowlist (noimg/media/svg/iframe),href/titleonly,https?:/mailto:URIs only, and a hook that forcestarget="_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.null) failed the login schema; malformed callbacks now return 400 instead of 500.Impact
!):GET /auth/:provider/logintakeschallengeinstead ofrandom. The callback redirects with?code=instead of?token=&random=. NewPOST /auth/token. RemovedGET /avatar/:key, and/publicserves only avatar keys. Migration: the web app updates on deploy. Native builds bundling the old frontend still sendrandom./loginanswers those with the download page as theirurl, 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.0004_link_email_verified.sqladdsaccounts_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 a0004(0004_random_avatar_type.sql, an independentUPDATEonaccounts). Whichever lands second renumbers its file to0005; this PR rechecks before its final push and updates the0004cutoff inapi/test/oauth.test.tswith it. The two migrations touch different tables, so either order is correct.@hang/api/clientaddsoauthVerifier,oauthChallenge,oauthTokenSchema,avatarTypes;oauthStateSchemachanges shape;OAuth.callbackResponseSchema,Callback,CallbackResponse,Provider.updateAppleUser,Storage.validateAvatar,Storage.extensionremoved. No schema migration.account.tsitems (theavatarType: "r2"default-avatar bug,updatedAt) are left to it.Decisions
Maintainer, 2026-11-25 (#44 (comment)), recorded with
quest review --accept:verified_email(api/src/oauth.ts:312): ✅ accept, it is the standard provider bar (rejected: first-party email verification, Gmail/Workspace-only Google linking).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/as a minimal MoQ canary rather than deleting it. Either way, this PR needs no release, and stale builds still get the/downloadanswer.Made without asking, for review:
randomflow for stale native builds would keep the hole open. Existing sessions are unaffected.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./loginanswers the oldrandomshape with{url: APP_URL/download}rather than a 400. These are a few lines to delete once no supported build sendsrandom.public.hang.liveis a separate origin holding no credentials, and new uploads can no longer be SVG.jsdomadded as an app devDependency for the sanitizer test. happy-dom 21'sNodeIteratorstops 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
Follow-ups
app/src/room/video.tsloads 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
mainat b98b9aa:quest gate just checkpasses (API 26, app 31, browser media 2).quest gate just check: Quest, TypeScript, Biome, API tests (26), app tests (12), native fmt. All pass.userfields, legacy unverified links (refused, then re-vouched) and the0004migration over legacy rows, the stale-client download redirect, null Discord fields, byte-sniffed uploads, URL avatars, old-avatar retention, body limit, and the/publicrestrictions. Before the fix, the oldauth.tsfails 3 of the 4 middleware tests (500s), and the old DOMPurify config fails 3 of the 4 sanitizer tests.wrangler dev, local D1/R2) and hit each changed route: evil redirects 400, legit web/loopback/deep-link 200, legacyrandom400, forged callback 400, bogus code 401, garbage bearer on/account/info401, room join with garbage bearer 200 as guest, SVG labelled PNG 415,javascript:avatar 400, PNG upload served withimage/png+nosniff+ sandbox CSP and deleted when replaced, non-avatar/publickeys 404,/avatar/*404. Ran the bundled sanitizer in Chrome 157: every remote-loading vector stripped,javascript:href dropped, links forced to_blank+noopener noreferrer.0004applied bywrangler d1 migrations apply --localover D1 state holding legacy links (round-1 version; the final version only drops its backfillUPDATE).native/src/lib.rschanges are comments only).Models
🤖 Generated with Claude Code
(Written by Claude Opus 5.5 with high)
Review
Rewritten by
quest reviewafter 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 mediumClassified: medium by default
Reviewer: Codex, gpt-6.2-sol, high effort
Session:
01a215ed-4c43-7461-9b3c-da52f871f3e2, round 4Score: 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:
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)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)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)