Repository navigation
feat(auth): native-app sign-in handoff via one-time code #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rigwig
wants to merge
3
commits into
jetkvm:dev
Choose a base branch
from
rigwig:feat/native-app-auth
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| import express from "express"; | ||
| import * as crypto from "crypto"; | ||
| import { LRUCache } from "lru-cache"; | ||
| import { | ||
| BadRequestError, | ||
| ForbiddenError, | ||
| UnauthorizedError, | ||
| UnprocessableEntityError, | ||
| } from "./errors"; | ||
|
|
||
| /** | ||
| * Native-app sign-in handoff. | ||
| * | ||
| * The normal flow leaves the signed-in session as a cookie in whichever | ||
| * browser ran the OIDC dance. A native app can't read cookies out of the | ||
| * system browser, so today it has to embed a web view and scrape the cookie — | ||
| * which also rules out passkeys (WebKit doesn't expose WebAuthn to embedded | ||
| * views for third-party origins) and is the kind of embedded OAuth Google | ||
| * discourages. | ||
| * | ||
| * With this handoff a native app opens the regular login page in the system | ||
| * browser with a `returnTo` on one of its registered URL schemes | ||
| * (NATIVE_APP_SCHEMES). After sign-in, /oidc/callback redirects there with a | ||
| * short-lived, single-use `code`, and the app exchanges it at | ||
| * POST /auth/exchange for an ordinary session cookie. | ||
| * | ||
| * A URL scheme identifies a redirect target, not an app: another app on the | ||
| * device can register the same scheme and receive the redirect. So the code | ||
| * is bound to the app that started sign-in, as in PKCE (RFC 7636): the app | ||
| * puts `code_challenge` (the base64url SHA-256 of a random verifier it keeps) | ||
| * in its `returnTo`, and must present the verifier to redeem the code. | ||
| */ | ||
|
|
||
| const NATIVE_APP_SCHEMES = new Set( | ||
| (process.env.NATIVE_APP_SCHEMES ?? "") | ||
| .split(",") | ||
| .map(scheme => scheme.trim().toLowerCase().replace(/:$/, "")) | ||
| .filter(Boolean), | ||
| ); | ||
|
|
||
| export const NATIVE_AUTH_CODE_TTL_MS = 5 * 60 * 1000; | ||
|
|
||
| export interface PendingNativeSession { | ||
| id_token: string; | ||
| /** base64url(SHA-256(verifier)), from the app's `returnTo`. */ | ||
| code_challenge: string; | ||
| } | ||
|
|
||
| // A SHA-256 digest in unpadded base64url is always 43 characters. | ||
| const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/; | ||
| // RFC 7636 section 4.1: 43 to 128 unreserved characters. | ||
| const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]{43,128}$/; | ||
|
|
||
| /** | ||
| * The `code_challenge` query parameter of a native `returnTo`; throws when it | ||
| * is missing or not a base64url SHA-256 digest. | ||
| */ | ||
| export function nativeCodeChallenge(returnTo: string): string { | ||
| const challenge = new URL(returnTo).searchParams.get("code_challenge"); | ||
| if (!challenge || !CODE_CHALLENGE_PATTERN.test(challenge)) { | ||
| throw new BadRequestError( | ||
| "returnTo needs a code_challenge (base64url SHA-256 of the code verifier)", | ||
| "missing_code_challenge", | ||
| ); | ||
| } | ||
| return challenge; | ||
| } | ||
|
|
||
| function matchesChallenge(verifier: string, challenge: string): boolean { | ||
| const expected = Buffer.from(challenge, "base64url"); | ||
| const actual = crypto.createHash("sha256").update(verifier).digest(); | ||
| return expected.length === actual.length && crypto.timingSafeEqual(expected, actual); | ||
| } | ||
|
|
||
| // In-memory like `activeConnections`: codes are only meaningful for the | ||
| // instance that issued them, and they live for five minutes at most. | ||
| const pendingSessions = new LRUCache<string, PendingNativeSession>({ | ||
| max: 10_000, | ||
| ttl: NATIVE_AUTH_CODE_TTL_MS, | ||
| }); | ||
|
|
||
| /** True when `returnTo` is a URL on one of the registered native-app schemes. */ | ||
| export function isNativeReturnTo(returnTo: unknown): returnTo is string { | ||
| if (typeof returnTo !== "string" || NATIVE_APP_SCHEMES.size === 0) return false; | ||
| let url: URL; | ||
| try { | ||
| url = new URL(returnTo); | ||
| } catch { | ||
| return false; | ||
| } | ||
| const scheme = url.protocol.replace(/:$/, "").toLowerCase(); | ||
| if (scheme === "http" || scheme === "https") return false; | ||
| return NATIVE_APP_SCHEMES.has(scheme); | ||
| } | ||
|
|
||
| export function issueNativeAuthCode(session: PendingNativeSession): string { | ||
| const code = crypto.randomBytes(32).toString("base64url"); | ||
| pendingSessions.set(code, session); | ||
| return code; | ||
| } | ||
|
|
||
| /** | ||
| * Returns the session for a code and invalidates the code, provided the | ||
| * verifier matches the challenge the code was issued for. A wrong verifier | ||
| * leaves the code in place, so whoever intercepted a code cannot burn it | ||
| * before the app that owns it redeems it. | ||
| */ | ||
| export function redeemNativeAuthCode( | ||
| code: string, | ||
| verifier: string, | ||
| ): PendingNativeSession | undefined { | ||
| const session = pendingSessions.get(code); | ||
| if (!session || !matchesChallenge(verifier, session.code_challenge)) return undefined; | ||
| pendingSessions.delete(code); | ||
| return session; | ||
| } | ||
|
|
||
| export function nativeRedirectUrl(returnTo: string, code: string): string { | ||
| const url = new URL(returnTo); | ||
| // The app already knows its challenge; only the code goes back. | ||
| url.searchParams.delete("code_challenge"); | ||
| url.searchParams.set("code", code); | ||
| return url.toString(); | ||
| } | ||
|
|
||
| /** | ||
| * POST /auth/exchange { code, code_verifier } → session cookie for the native app. | ||
| * | ||
| * Only for native clients: the body must be JSON (which a cross-site form | ||
| * cannot send) and the request must not come from a browser page (which | ||
| * always sends Origin on a POST), so a web page cannot sign a visitor's | ||
| * browser in to somebody else's session. Both are checked before the code is | ||
| * looked at. | ||
| */ | ||
| export const Exchange = async (req: express.Request, res: express.Response) => { | ||
| if (!req.is("application/json")) { | ||
| throw new BadRequestError("Body must be application/json", "invalid_content_type"); | ||
| } | ||
| if (req.headers.origin) { | ||
| throw new ForbiddenError("This endpoint is for native apps"); | ||
| } | ||
|
|
||
| const { code, code_verifier } = (req.body ?? {}) as { | ||
| code?: unknown; | ||
| code_verifier?: unknown; | ||
| }; | ||
| if (typeof code !== "string" || !code) { | ||
| throw new UnprocessableEntityError("Missing code in body"); | ||
| } | ||
| if (typeof code_verifier !== "string" || !CODE_VERIFIER_PATTERN.test(code_verifier)) { | ||
| throw new UnprocessableEntityError("Missing or malformed code_verifier in body"); | ||
| } | ||
|
|
||
| const pending = redeemNativeAuthCode(code, code_verifier); | ||
| if (!pending) | ||
| throw new UnauthorizedError("Invalid or expired code", "invalid_auth_code"); | ||
|
|
||
| req.session = { id_token: pending.id_token }; | ||
| return res.json({ ok: true }); | ||
| }; |
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CSRF
Reachability: External
Exploitability: Moderate
CWE: CWE-352 — Cross-Site Request Forgery (CSRF)
View Security blast radius
Reject cross-site form submissions to the exchange route.
An attacker with an unused code for their own account can submit that code through a top-level HTML form in the victim's browser. The global URL-encoded parser accepts the form.
Exchangethen sets the attacker's session in that browser. CORS does not reject this request. (raw.githubusercontent.com)SameSite=Strictdoes not prevent this login CSRF. It withholds the old cookie, but a top-level POST response can still set replacement cookies. The victim subsequently uses the attacker's account until logout. (datatracker.ietf.org)Require
application/jsonbefore callingExchange, and reject untrusted browser origins. Keep origin-less native JSON requests supported. Reject these requests before consuming the code.