Skip to content

feat(expo): add hosted auth flow - #8960

Merged
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in
Jul 27, 2026
Merged

feat(expo): add hosted auth flow#8960
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in

Conversation

@mikepitre

@mikepitremikepitre commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds the Expo client SDK surface for hosted auth through Account Portal.

Expo apps can now start a hosted sign-in or sign-up flow in the system browser, return through a native callback, and activate the single Clerk session that ClerkGo attaches to the native client.

What Changed

  • Adds useHostedAuth() through the opt-in @clerk/expo/hosted-auth subpath.
  • Opens Account Portal with expo-web-browser / expo-auth-session.
  • Registers the canonical clerk://<android.package>.callback intent filter through the Expo config plugin.
  • Generates and validates state for callback correlation.
  • Generates a PKCE verifier/challenge pair and sends only the challenge when creating the hosted-auth attempt.
  • Redeems the returned rotating token nonce from the Expo hosted-auth helper.
  • Applies the returned /client payload to the existing Clerk client and activates the created native session. The payload is applied before the created session is validated, so local client state stays in sync with the rotated server state even when validation fails.
  • If an abandoned handoff leaves the native client stale, retries hosted-auth creation once after the response hook stores ClerkGo's replacement device token.
  • Rejects overlapping startHostedAuth calls while a flow is in progress.
  • Warns once in development builds when the default Android callback is used, since it only works after the Clerk config plugin registers the intent filter and the native project is rebuilt. The hook docs spell out the same prerequisite.

Developer Experience

import{useHostedAuth}from'@clerk/expo/hosted-auth';const{ startHostedAuth }=useHostedAuth();awaitstartHostedAuth();awaitstartHostedAuth({mode: 'sign-up'});

Apps may pass mode: 'sign-in' | 'sign-up', a custom non-HTTP redirectUrl, or authSessionOptions. By default, the hook uses the canonical callback registered for a native build and AuthSession.makeRedirectUri() in Expo Go.

Flow

  1. The hook creates a redirect URL, random state, and PKCE verifier/challenge.
  2. It asks ClerkGo to create a hosted-auth Account Portal URL.
  3. It opens that URL with openAuthSessionAsync.
  4. On callback, it validates the redirect URL and state.
  5. It redeems the returned rotating_token_nonce with the original PKCE verifier.
  6. It updates the current Clerk client instance and calls setActive with the created native session.

Security

  • Uses a random state and verifies it on callback so the app only accepts the browser result for the auth attempt it initiated.
  • Uses PKCE so ClerkGo stores the challenge at creation time and requires the matching verifier at redemption time.
  • Sends the PKCE verifier in the FAPI request body, not in the URL.
  • Validates callback protocol, host, and path against the initiated redirect URL before redeeming anything.
  • Does not create or keep a web session in the SDK; the browser only drives Account Portal and the completed session is attached to the native client.
  • Leaves production redirect-url allowlisting enforced by ClerkGo.

Implementation Notes

Hosted auth is exposed from @clerk/expo/hosted-auth so apps that import the default @clerk/expo package do not need to resolve optional Expo auth/browser/crypto peer dependencies unless they opt into this flow.

The completion request is a physical POST /v1/client with _method=GET in the form body. That lets the backend route to the existing /client read/rotation path while keeping the PKCE verifier out of query strings and logs.

The verifier-bound completion stays scoped to packages/expo/src/utils/hostedAuth.ts. Generic Client.reload() remains the normal GET reload path, so ClerkJS core does not gain hosted-auth-specific branches.

Screen Recording

Simulator.Screen.Recording.-.iPhone.Air.+.Watch.-.2026-07-09.at.17.20.58.mov

Related PRs

@vercel

vercelBot commented Jun 23, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentActionsUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentJul 27, 2026 6:30pm
swingsetReadyReadyPreview, CommentJul 27, 2026 6:30pm

Request Review

@changeset-bot

changeset-botBot commented Jun 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1ab2f63

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
@clerk/expoMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitaiBot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds hosted auth support for native Expo apps, with new hook and utility APIs, shared PKCE/codeVerifier plumbing, public re-exports, and tests.

Changes

Hosted Auth Flow for Expo

Layer / File(s)Summary
Shared reload and FAPI params
packages/shared/src/types/resource.ts, packages/clerk-js/src/core/resources/Client.ts, packages/clerk-js/src/core/__tests__/fapiClient.test.ts, packages/clerk-js/src/core/resources/__tests__/Client.test.ts
ClerkResourceReloadParams gains codeVerifier, Client.reload redeems hosted-auth callbacks with nonce and verifier, and the related FAPI/client tests cover the new request shape and query parameter.
Hosted auth utility
packages/expo/src/utils/hostedAuth.ts
createHostedAuth resolves an FAPI client, POSTs /client/hosted_auth, validates the response payload, and surfaces API errors with retry-after data.
Hosted auth hook and exports
packages/expo/src/hooks/useHostedAuth.ts, packages/expo/src/hooks/index.ts, packages/expo/src/types/index.ts, .changeset/hosted-auth-expo.md
useHostedAuth adds PKCE/state generation, callback validation, client reload and session activation, and the Expo hook/type re-exports and changeset entry expose the new API.
Hosted auth tests
packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
Vitest coverage exercises the hook’s success path, state and session fallback behavior, callback validation, and hosted-auth error cases with mocked Expo and Clerk modules.

Sequence Diagram(s)

sequenceDiagram
participant useHostedAuth
participant createHostedAuth
participant expoWebBrowser
participant Client
participant clerk
useHostedAuth->>createHostedAuth: create hosted-auth URL
createHostedAuth->>clerk: POST /client/hosted_auth
createHostedAuth-->>useHostedAuth: hosted-auth URL
useHostedAuth->>expoWebBrowser: openAuthSessionAsync(hosted-auth URL, redirectUrl)
expoWebBrowser-->>useHostedAuth: callback URL
useHostedAuth->>Client: reload({ rotatingTokenNonce, codeVerifier })
Client-->>useHostedAuth: updated client
useHostedAuth->>clerk: setActive(created_session_id)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • wobsoriano

Poem

A bunny hopped through PKCE light,
With hosted auth all snug and right.
A nonce, a state, a code verifier too,
Then sessions clicked in, bright and new.
🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 5.56% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly summarizes the main change: adding the Expo hosted auth flow.

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-newBot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@8960

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@8960

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@8960

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@8960

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@8960

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@8960

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@8960

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@8960

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@8960

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@8960

@clerk/express

npm i https://pkg.pr.new/@clerk/express@8960

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@8960

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8960

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@8960

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@8960

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@8960

@clerk/react

npm i https://pkg.pr.new/@clerk/react@8960

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@8960

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@8960

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@8960

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@8960

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8960

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@8960

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@8960

commit: 1ab2f63

@github-actions

github-actionsBot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-07-27T18:34:59.745Z

Summary

MetricCount
Packages analyzed19
Packages with changes1
🔴 Breaking changes0
🟡 Non-breaking changes0
🟢 Additions1

@clerk/expo

Current version: 4.0.4
Recommended bump: MINOR → 4.1.0

Subpath ./hosted-auth

🟢 Additions (1)

Added: ./hosted-auth

New subpath export ./hosted-auth (4 exported members)


Report generated by Break Check

Last ran on 1ab2f63.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/core/resources/Base.ts (1)

204-210: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Don't send the PKCE verifier through _baseGet.

Line 209 forwards codeVerifier on a hard-coded GET, and packages/clerk-js/src/core/fapiClient.ts serializes that field into the URL as code_verifier. That puts the PKCE secret in request URLs, which are routinely captured by logs, proxies, and request instrumentation. This redemption should go through a body-bearing request instead of the _baseGet path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Base.ts` around lines 204 - 210, The
_baseGet method in BaseResource is forwarding codeVerifier into a hard-coded GET
request, which causes fapiClient serialization to place the PKCE secret in the
URL. Update BaseResource._baseGet so it no longer passes codeVerifier through
the GET path; instead, route this redemption through a body-bearing request flow
or another non-URL transport, and keep the existing path/rotatingTokenNonce
behavior intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/expo/src/hooks/useHostedAuth.ts`:
- Around line 10-30: Add customer-facing JSDoc for the new public hosted-auth
exports so generated docs are populated and reviewable. Document HostedAuthMode,
StartHostedAuthParams, and StartHostedAuthReturnType with concise descriptions
of their purpose and fields, and add JSDoc on useHostedAuth explaining what the
hook provides. Also give useHostedAuth an explicit return type instead of
relying on inference, matching the repo’s public API guidelines and keeping the
exported surface in line with other SDK APIs.
- Around line 12-23: The public types in useHostedAuth are leaking optional Expo
browser dependencies into the `@clerk/expo` API surface. Update
StartHostedAuthParams and StartHostedAuthReturnType so they no longer reference
WebBrowser.AuthSessionOpenOptions, WebBrowser.WebBrowserAuthSessionResult, or
ClientResource directly in the exported declarations; instead, hide those behind
local/internal interfaces or move the hosted-auth-specific types into a separate
entrypoint. Ensure the exposed .d.ts for useHostedAuth only contains
dependency-agnostic types so consumers who do not install expo-auth-session or
expo-web-browser are not forced to resolve them.
- Around line 189-205: The callback URL validation in
callbackUrlMatchesRedirectUrl currently skips authority checking when the
redirect URL has an empty host, which allows unexpected authorities like
attacker-controlled hosts to pass for triple-slashed deep links. Update the
matching logic in useHostedAuth.ts to compare the callbackUrl host/authority and
pathname exactly against the parsed redirectUrl for hosted-auth callbacks,
instead of treating an empty expected host as a wildcard. Add a regression test
covering a redirectUrl such as myapp:///hosted-auth-callback and a mismatched
callbackUrl like myapp://attacker/hosted-auth-callback to ensure the authority
is rejected.
---
Outside diff comments:
In `@packages/clerk-js/src/core/resources/Base.ts`:
- Around line 204-210: The _baseGet method in BaseResource is forwarding
codeVerifier into a hard-coded GET request, which causes fapiClient
serialization to place the PKCE secret in the URL. Update BaseResource._baseGet
so it no longer passes codeVerifier through the GET path; instead, route this
redemption through a body-bearing request flow or another non-URL transport, and
keep the existing path/rotatingTokenNonce behavior intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 9713ccce-5bc5-4f09-bb0b-c9275074bbd5

📥 Commits

Reviewing files that changed from the base of the PR and between 52d310c and 4d734f0.

📒 Files selected for processing (10)
  • .changeset/hosted-auth-expo.md
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/fapiClient.ts
  • packages/clerk-js/src/core/resources/Base.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/index.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/types/index.ts
  • packages/expo/src/utils/hostedAuth.ts
  • packages/shared/src/types/resource.ts

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:4d734f0d8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread.changeset/hosted-auth-expo.md Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:5dfea68732

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/Client.ts (1)

81-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clarify docs for the new reload hosted-auth path.

This changes a public method’s behavior when rotatingTokenNonce and codeVerifier are paired, but there’s still no method-level JSDoc explaining when callers should use that path or that the verifier is redeemed from the request body. If Client.reload is reference-facing, please document it and loop in Docs. As per path instructions, "If a PR adds or changes public/reference-facing API surface area, check whether the corresponding JSDoc is present, accurate, and aligned with the implementation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Client.ts` around lines 81 - 100,
`Client.reload` now has a hosted-auth branch when `rotatingTokenNonce` and
`codeVerifier` are present, but the public API lacks JSDoc describing when to
use it and that the verifier is sent in the request body. Add method-level
documentation on `Client.reload` explaining the two reload paths, the required
pairing of `rotatingTokenNonce` with `codeVerifier`, and that this path redeems
the verifier via the POST body; keep the docs aligned with the implementation
and note that Docs should be looped in for this reference-facing change.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/clerk-js/src/core/__tests__/fapiClient.test.ts`:
- Line 154: The test in fapiClient should cover both rotating token nonce
behavior and the security edge case that codeVerifier is never included in the
generated URL. Update the existing `adds rotating token nonce when provided`
test around `buildUrl()` to assert the nonce is present while also verifying
`code_verifier` is not emitted, using the same `FapiClient` URL-building path so
the regression is caught if PKCE data ever leaks.
---
Nitpick comments:
In `@packages/clerk-js/src/core/resources/Client.ts`:
- Around line 81-100: `Client.reload` now has a hosted-auth branch when
`rotatingTokenNonce` and `codeVerifier` are present, but the public API lacks
JSDoc describing when to use it and that the verifier is sent in the request
body. Add method-level documentation on `Client.reload` explaining the two
reload paths, the required pairing of `rotatingTokenNonce` with `codeVerifier`,
and that this path redeems the verifier via the POST body; keep the docs aligned
with the implementation and note that Docs should be looped in for this
reference-facing change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 745841d4-8924-4910-bab0-04c9e597e775

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfea68 and 9b96d7f.

📒 Files selected for processing (6)
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/resources/Client.ts
  • packages/clerk-js/src/core/resources/__tests__/Client.test.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/utils/hostedAuth.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/expo/src/utils/hostedAuth.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/hooks/tests/useHostedAuth.test.ts

Comment threadpackages/clerk-js/src/core/__tests__/fapiClient.test.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
- Require created_session_id on the callback before redeeming, matching
iOS and Android; drop the last_active_session_id fallback.
- Align error strings with the native SDKs so the same condition reads
identically across platforms.
- Allow preferEphemeralSession in authSessionOptions for parity with the
iOS SDK's prefersEphemeralWebBrowserSession.
- Fold createCodeChallenge into createPKCE and drop its test-only export;
return the Account Portal URL from createHostedAuth directly.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a q!

Everything looks good here, great job! Thanks for following existing conventions

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
… filter
clerk-android registers SSOReceiverActivity for clerk://<package>.callback,
so the Expo-registered filter for the same URI triggered an ambiguous
"Open with" chooser on callback, and picking the native handler consumed
the nonce and dropped the sign-in. Use clerk://<package>.hosted-callback
for the Expo hosted auth default instead.
Refreshing the JS client mutates the resource in place and resolves with
that same object, so the foreign-client guard was comparing a reference
that had already become the refreshed client. It could never reject, and
a native client change resolving to a different signed-out client was
applied over the active session, signing the user out.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-tested and the collision issue is fixed 👍🏼

@mikepitre
mikepitre merged commit 23a25cd into mainJul 27, 2026
60 checks passed
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@mikepitre@wobsoriano
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(expo): add hosted auth flow by mikepitre · Pull Request #8960 · clerk/javascript · GitHub
Skip to content

feat(expo): add hosted auth flow - #8960

Merged
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in
Jul 27, 2026
Merged

feat(expo): add hosted auth flow#8960
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in

Conversation

@mikepitre

@mikepitremikepitre commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds the Expo client SDK surface for hosted auth through Account Portal.

Expo apps can now start a hosted sign-in or sign-up flow in the system browser, return through a native callback, and activate the single Clerk session that ClerkGo attaches to the native client.

What Changed

  • Adds useHostedAuth() through the opt-in @clerk/expo/hosted-auth subpath.
  • Opens Account Portal with expo-web-browser / expo-auth-session.
  • Registers the canonical clerk://<android.package>.callback intent filter through the Expo config plugin.
  • Generates and validates state for callback correlation.
  • Generates a PKCE verifier/challenge pair and sends only the challenge when creating the hosted-auth attempt.
  • Redeems the returned rotating token nonce from the Expo hosted-auth helper.
  • Applies the returned /client payload to the existing Clerk client and activates the created native session. The payload is applied before the created session is validated, so local client state stays in sync with the rotated server state even when validation fails.
  • If an abandoned handoff leaves the native client stale, retries hosted-auth creation once after the response hook stores ClerkGo's replacement device token.
  • Rejects overlapping startHostedAuth calls while a flow is in progress.
  • Warns once in development builds when the default Android callback is used, since it only works after the Clerk config plugin registers the intent filter and the native project is rebuilt. The hook docs spell out the same prerequisite.

Developer Experience

import{useHostedAuth}from'@clerk/expo/hosted-auth';const{ startHostedAuth }=useHostedAuth();awaitstartHostedAuth();awaitstartHostedAuth({mode: 'sign-up'});

Apps may pass mode: 'sign-in' | 'sign-up', a custom non-HTTP redirectUrl, or authSessionOptions. By default, the hook uses the canonical callback registered for a native build and AuthSession.makeRedirectUri() in Expo Go.

Flow

  1. The hook creates a redirect URL, random state, and PKCE verifier/challenge.
  2. It asks ClerkGo to create a hosted-auth Account Portal URL.
  3. It opens that URL with openAuthSessionAsync.
  4. On callback, it validates the redirect URL and state.
  5. It redeems the returned rotating_token_nonce with the original PKCE verifier.
  6. It updates the current Clerk client instance and calls setActive with the created native session.

Security

  • Uses a random state and verifies it on callback so the app only accepts the browser result for the auth attempt it initiated.
  • Uses PKCE so ClerkGo stores the challenge at creation time and requires the matching verifier at redemption time.
  • Sends the PKCE verifier in the FAPI request body, not in the URL.
  • Validates callback protocol, host, and path against the initiated redirect URL before redeeming anything.
  • Does not create or keep a web session in the SDK; the browser only drives Account Portal and the completed session is attached to the native client.
  • Leaves production redirect-url allowlisting enforced by ClerkGo.

Implementation Notes

Hosted auth is exposed from @clerk/expo/hosted-auth so apps that import the default @clerk/expo package do not need to resolve optional Expo auth/browser/crypto peer dependencies unless they opt into this flow.

The completion request is a physical POST /v1/client with _method=GET in the form body. That lets the backend route to the existing /client read/rotation path while keeping the PKCE verifier out of query strings and logs.

The verifier-bound completion stays scoped to packages/expo/src/utils/hostedAuth.ts. Generic Client.reload() remains the normal GET reload path, so ClerkJS core does not gain hosted-auth-specific branches.

Screen Recording

Simulator.Screen.Recording.-.iPhone.Air.+.Watch.-.2026-07-09.at.17.20.58.mov

Related PRs

@vercel

vercelBot commented Jun 23, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentActionsUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentJul 27, 2026 6:30pm
swingsetReadyReadyPreview, CommentJul 27, 2026 6:30pm

Request Review

@changeset-bot

changeset-botBot commented Jun 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1ab2f63

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
@clerk/expoMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitaiBot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds hosted auth support for native Expo apps, with new hook and utility APIs, shared PKCE/codeVerifier plumbing, public re-exports, and tests.

Changes

Hosted Auth Flow for Expo

Layer / File(s)Summary
Shared reload and FAPI params
packages/shared/src/types/resource.ts, packages/clerk-js/src/core/resources/Client.ts, packages/clerk-js/src/core/__tests__/fapiClient.test.ts, packages/clerk-js/src/core/resources/__tests__/Client.test.ts
ClerkResourceReloadParams gains codeVerifier, Client.reload redeems hosted-auth callbacks with nonce and verifier, and the related FAPI/client tests cover the new request shape and query parameter.
Hosted auth utility
packages/expo/src/utils/hostedAuth.ts
createHostedAuth resolves an FAPI client, POSTs /client/hosted_auth, validates the response payload, and surfaces API errors with retry-after data.
Hosted auth hook and exports
packages/expo/src/hooks/useHostedAuth.ts, packages/expo/src/hooks/index.ts, packages/expo/src/types/index.ts, .changeset/hosted-auth-expo.md
useHostedAuth adds PKCE/state generation, callback validation, client reload and session activation, and the Expo hook/type re-exports and changeset entry expose the new API.
Hosted auth tests
packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
Vitest coverage exercises the hook’s success path, state and session fallback behavior, callback validation, and hosted-auth error cases with mocked Expo and Clerk modules.

Sequence Diagram(s)

sequenceDiagram
participant useHostedAuth
participant createHostedAuth
participant expoWebBrowser
participant Client
participant clerk
useHostedAuth->>createHostedAuth: create hosted-auth URL
createHostedAuth->>clerk: POST /client/hosted_auth
createHostedAuth-->>useHostedAuth: hosted-auth URL
useHostedAuth->>expoWebBrowser: openAuthSessionAsync(hosted-auth URL, redirectUrl)
expoWebBrowser-->>useHostedAuth: callback URL
useHostedAuth->>Client: reload({ rotatingTokenNonce, codeVerifier })
Client-->>useHostedAuth: updated client
useHostedAuth->>clerk: setActive(created_session_id)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • wobsoriano

Poem

A bunny hopped through PKCE light,
With hosted auth all snug and right.
A nonce, a state, a code verifier too,
Then sessions clicked in, bright and new.
🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 5.56% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly summarizes the main change: adding the Expo hosted auth flow.

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-newBot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@8960

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@8960

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@8960

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@8960

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@8960

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@8960

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@8960

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@8960

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@8960

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@8960

@clerk/express

npm i https://pkg.pr.new/@clerk/express@8960

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@8960

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8960

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@8960

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@8960

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@8960

@clerk/react

npm i https://pkg.pr.new/@clerk/react@8960

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@8960

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@8960

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@8960

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@8960

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8960

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@8960

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@8960

commit: 1ab2f63

@github-actions

github-actionsBot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-07-27T18:34:59.745Z

Summary

MetricCount
Packages analyzed19
Packages with changes1
🔴 Breaking changes0
🟡 Non-breaking changes0
🟢 Additions1

@clerk/expo

Current version: 4.0.4
Recommended bump: MINOR → 4.1.0

Subpath ./hosted-auth

🟢 Additions (1)

Added: ./hosted-auth

New subpath export ./hosted-auth (4 exported members)


Report generated by Break Check

Last ran on 1ab2f63.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/core/resources/Base.ts (1)

204-210: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Don't send the PKCE verifier through _baseGet.

Line 209 forwards codeVerifier on a hard-coded GET, and packages/clerk-js/src/core/fapiClient.ts serializes that field into the URL as code_verifier. That puts the PKCE secret in request URLs, which are routinely captured by logs, proxies, and request instrumentation. This redemption should go through a body-bearing request instead of the _baseGet path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Base.ts` around lines 204 - 210, The
_baseGet method in BaseResource is forwarding codeVerifier into a hard-coded GET
request, which causes fapiClient serialization to place the PKCE secret in the
URL. Update BaseResource._baseGet so it no longer passes codeVerifier through
the GET path; instead, route this redemption through a body-bearing request flow
or another non-URL transport, and keep the existing path/rotatingTokenNonce
behavior intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/expo/src/hooks/useHostedAuth.ts`:
- Around line 10-30: Add customer-facing JSDoc for the new public hosted-auth
exports so generated docs are populated and reviewable. Document HostedAuthMode,
StartHostedAuthParams, and StartHostedAuthReturnType with concise descriptions
of their purpose and fields, and add JSDoc on useHostedAuth explaining what the
hook provides. Also give useHostedAuth an explicit return type instead of
relying on inference, matching the repo’s public API guidelines and keeping the
exported surface in line with other SDK APIs.
- Around line 12-23: The public types in useHostedAuth are leaking optional Expo
browser dependencies into the `@clerk/expo` API surface. Update
StartHostedAuthParams and StartHostedAuthReturnType so they no longer reference
WebBrowser.AuthSessionOpenOptions, WebBrowser.WebBrowserAuthSessionResult, or
ClientResource directly in the exported declarations; instead, hide those behind
local/internal interfaces or move the hosted-auth-specific types into a separate
entrypoint. Ensure the exposed .d.ts for useHostedAuth only contains
dependency-agnostic types so consumers who do not install expo-auth-session or
expo-web-browser are not forced to resolve them.
- Around line 189-205: The callback URL validation in
callbackUrlMatchesRedirectUrl currently skips authority checking when the
redirect URL has an empty host, which allows unexpected authorities like
attacker-controlled hosts to pass for triple-slashed deep links. Update the
matching logic in useHostedAuth.ts to compare the callbackUrl host/authority and
pathname exactly against the parsed redirectUrl for hosted-auth callbacks,
instead of treating an empty expected host as a wildcard. Add a regression test
covering a redirectUrl such as myapp:///hosted-auth-callback and a mismatched
callbackUrl like myapp://attacker/hosted-auth-callback to ensure the authority
is rejected.
---
Outside diff comments:
In `@packages/clerk-js/src/core/resources/Base.ts`:
- Around line 204-210: The _baseGet method in BaseResource is forwarding
codeVerifier into a hard-coded GET request, which causes fapiClient
serialization to place the PKCE secret in the URL. Update BaseResource._baseGet
so it no longer passes codeVerifier through the GET path; instead, route this
redemption through a body-bearing request flow or another non-URL transport, and
keep the existing path/rotatingTokenNonce behavior intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 9713ccce-5bc5-4f09-bb0b-c9275074bbd5

📥 Commits

Reviewing files that changed from the base of the PR and between 52d310c and 4d734f0.

📒 Files selected for processing (10)
  • .changeset/hosted-auth-expo.md
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/fapiClient.ts
  • packages/clerk-js/src/core/resources/Base.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/index.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/types/index.ts
  • packages/expo/src/utils/hostedAuth.ts
  • packages/shared/src/types/resource.ts

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:4d734f0d8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread.changeset/hosted-auth-expo.md Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:5dfea68732

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/Client.ts (1)

81-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clarify docs for the new reload hosted-auth path.

This changes a public method’s behavior when rotatingTokenNonce and codeVerifier are paired, but there’s still no method-level JSDoc explaining when callers should use that path or that the verifier is redeemed from the request body. If Client.reload is reference-facing, please document it and loop in Docs. As per path instructions, "If a PR adds or changes public/reference-facing API surface area, check whether the corresponding JSDoc is present, accurate, and aligned with the implementation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Client.ts` around lines 81 - 100,
`Client.reload` now has a hosted-auth branch when `rotatingTokenNonce` and
`codeVerifier` are present, but the public API lacks JSDoc describing when to
use it and that the verifier is sent in the request body. Add method-level
documentation on `Client.reload` explaining the two reload paths, the required
pairing of `rotatingTokenNonce` with `codeVerifier`, and that this path redeems
the verifier via the POST body; keep the docs aligned with the implementation
and note that Docs should be looped in for this reference-facing change.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/clerk-js/src/core/__tests__/fapiClient.test.ts`:
- Line 154: The test in fapiClient should cover both rotating token nonce
behavior and the security edge case that codeVerifier is never included in the
generated URL. Update the existing `adds rotating token nonce when provided`
test around `buildUrl()` to assert the nonce is present while also verifying
`code_verifier` is not emitted, using the same `FapiClient` URL-building path so
the regression is caught if PKCE data ever leaks.
---
Nitpick comments:
In `@packages/clerk-js/src/core/resources/Client.ts`:
- Around line 81-100: `Client.reload` now has a hosted-auth branch when
`rotatingTokenNonce` and `codeVerifier` are present, but the public API lacks
JSDoc describing when to use it and that the verifier is sent in the request
body. Add method-level documentation on `Client.reload` explaining the two
reload paths, the required pairing of `rotatingTokenNonce` with `codeVerifier`,
and that this path redeems the verifier via the POST body; keep the docs aligned
with the implementation and note that Docs should be looped in for this
reference-facing change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 745841d4-8924-4910-bab0-04c9e597e775

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfea68 and 9b96d7f.

📒 Files selected for processing (6)
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/resources/Client.ts
  • packages/clerk-js/src/core/resources/__tests__/Client.test.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/utils/hostedAuth.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/expo/src/utils/hostedAuth.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/hooks/tests/useHostedAuth.test.ts

Comment threadpackages/clerk-js/src/core/__tests__/fapiClient.test.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
- Require created_session_id on the callback before redeeming, matching
iOS and Android; drop the last_active_session_id fallback.
- Align error strings with the native SDKs so the same condition reads
identically across platforms.
- Allow preferEphemeralSession in authSessionOptions for parity with the
iOS SDK's prefersEphemeralWebBrowserSession.
- Fold createCodeChallenge into createPKCE and drop its test-only export;
return the Account Portal URL from createHostedAuth directly.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a q!

Everything looks good here, great job! Thanks for following existing conventions

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
… filter
clerk-android registers SSOReceiverActivity for clerk://<package>.callback,
so the Expo-registered filter for the same URI triggered an ambiguous
"Open with" chooser on callback, and picking the native handler consumed
the nonce and dropped the sign-in. Use clerk://<package>.hosted-callback
for the Expo hosted auth default instead.
Refreshing the JS client mutates the resource in place and resolves with
that same object, so the foreign-client guard was comparing a reference
that had already become the refreshed client. It could never reject, and
a native client change resolving to a different signed-out client was
applied over the active session, signing the user out.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-tested and the collision issue is fixed 👍🏼

@mikepitre
mikepitre merged commit 23a25cd into mainJul 27, 2026
60 checks passed
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@mikepitre@wobsoriano
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(expo): add hosted auth flow by mikepitre · Pull Request #8960 · clerk/javascript · GitHub
Skip to content

feat(expo): add hosted auth flow - #8960

Merged
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in
Jul 27, 2026
Merged

feat(expo): add hosted auth flow#8960
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in

Conversation

@mikepitre

@mikepitremikepitre commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds the Expo client SDK surface for hosted auth through Account Portal.

Expo apps can now start a hosted sign-in or sign-up flow in the system browser, return through a native callback, and activate the single Clerk session that ClerkGo attaches to the native client.

What Changed

  • Adds useHostedAuth() through the opt-in @clerk/expo/hosted-auth subpath.
  • Opens Account Portal with expo-web-browser / expo-auth-session.
  • Registers the canonical clerk://<android.package>.callback intent filter through the Expo config plugin.
  • Generates and validates state for callback correlation.
  • Generates a PKCE verifier/challenge pair and sends only the challenge when creating the hosted-auth attempt.
  • Redeems the returned rotating token nonce from the Expo hosted-auth helper.
  • Applies the returned /client payload to the existing Clerk client and activates the created native session. The payload is applied before the created session is validated, so local client state stays in sync with the rotated server state even when validation fails.
  • If an abandoned handoff leaves the native client stale, retries hosted-auth creation once after the response hook stores ClerkGo's replacement device token.
  • Rejects overlapping startHostedAuth calls while a flow is in progress.
  • Warns once in development builds when the default Android callback is used, since it only works after the Clerk config plugin registers the intent filter and the native project is rebuilt. The hook docs spell out the same prerequisite.

Developer Experience

import{useHostedAuth}from'@clerk/expo/hosted-auth';const{ startHostedAuth }=useHostedAuth();awaitstartHostedAuth();awaitstartHostedAuth({mode: 'sign-up'});

Apps may pass mode: 'sign-in' | 'sign-up', a custom non-HTTP redirectUrl, or authSessionOptions. By default, the hook uses the canonical callback registered for a native build and AuthSession.makeRedirectUri() in Expo Go.

Flow

  1. The hook creates a redirect URL, random state, and PKCE verifier/challenge.
  2. It asks ClerkGo to create a hosted-auth Account Portal URL.
  3. It opens that URL with openAuthSessionAsync.
  4. On callback, it validates the redirect URL and state.
  5. It redeems the returned rotating_token_nonce with the original PKCE verifier.
  6. It updates the current Clerk client instance and calls setActive with the created native session.

Security

  • Uses a random state and verifies it on callback so the app only accepts the browser result for the auth attempt it initiated.
  • Uses PKCE so ClerkGo stores the challenge at creation time and requires the matching verifier at redemption time.
  • Sends the PKCE verifier in the FAPI request body, not in the URL.
  • Validates callback protocol, host, and path against the initiated redirect URL before redeeming anything.
  • Does not create or keep a web session in the SDK; the browser only drives Account Portal and the completed session is attached to the native client.
  • Leaves production redirect-url allowlisting enforced by ClerkGo.

Implementation Notes

Hosted auth is exposed from @clerk/expo/hosted-auth so apps that import the default @clerk/expo package do not need to resolve optional Expo auth/browser/crypto peer dependencies unless they opt into this flow.

The completion request is a physical POST /v1/client with _method=GET in the form body. That lets the backend route to the existing /client read/rotation path while keeping the PKCE verifier out of query strings and logs.

The verifier-bound completion stays scoped to packages/expo/src/utils/hostedAuth.ts. Generic Client.reload() remains the normal GET reload path, so ClerkJS core does not gain hosted-auth-specific branches.

Screen Recording

Simulator.Screen.Recording.-.iPhone.Air.+.Watch.-.2026-07-09.at.17.20.58.mov

Related PRs

@vercel

vercelBot commented Jun 23, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentActionsUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentJul 27, 2026 6:30pm
swingsetReadyReadyPreview, CommentJul 27, 2026 6:30pm

Request Review

@changeset-bot

changeset-botBot commented Jun 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1ab2f63

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
@clerk/expoMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitaiBot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds hosted auth support for native Expo apps, with new hook and utility APIs, shared PKCE/codeVerifier plumbing, public re-exports, and tests.

Changes

Hosted Auth Flow for Expo

Layer / File(s)Summary
Shared reload and FAPI params
packages/shared/src/types/resource.ts, packages/clerk-js/src/core/resources/Client.ts, packages/clerk-js/src/core/__tests__/fapiClient.test.ts, packages/clerk-js/src/core/resources/__tests__/Client.test.ts
ClerkResourceReloadParams gains codeVerifier, Client.reload redeems hosted-auth callbacks with nonce and verifier, and the related FAPI/client tests cover the new request shape and query parameter.
Hosted auth utility
packages/expo/src/utils/hostedAuth.ts
createHostedAuth resolves an FAPI client, POSTs /client/hosted_auth, validates the response payload, and surfaces API errors with retry-after data.
Hosted auth hook and exports
packages/expo/src/hooks/useHostedAuth.ts, packages/expo/src/hooks/index.ts, packages/expo/src/types/index.ts, .changeset/hosted-auth-expo.md
useHostedAuth adds PKCE/state generation, callback validation, client reload and session activation, and the Expo hook/type re-exports and changeset entry expose the new API.
Hosted auth tests
packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
Vitest coverage exercises the hook’s success path, state and session fallback behavior, callback validation, and hosted-auth error cases with mocked Expo and Clerk modules.

Sequence Diagram(s)

sequenceDiagram
participant useHostedAuth
participant createHostedAuth
participant expoWebBrowser
participant Client
participant clerk
useHostedAuth->>createHostedAuth: create hosted-auth URL
createHostedAuth->>clerk: POST /client/hosted_auth
createHostedAuth-->>useHostedAuth: hosted-auth URL
useHostedAuth->>expoWebBrowser: openAuthSessionAsync(hosted-auth URL, redirectUrl)
expoWebBrowser-->>useHostedAuth: callback URL
useHostedAuth->>Client: reload({ rotatingTokenNonce, codeVerifier })
Client-->>useHostedAuth: updated client
useHostedAuth->>clerk: setActive(created_session_id)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • wobsoriano

Poem

A bunny hopped through PKCE light,
With hosted auth all snug and right.
A nonce, a state, a code verifier too,
Then sessions clicked in, bright and new.
🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 5.56% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly summarizes the main change: adding the Expo hosted auth flow.

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-newBot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@8960

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@8960

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@8960

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@8960

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@8960

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@8960

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@8960

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@8960

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@8960

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@8960

@clerk/express

npm i https://pkg.pr.new/@clerk/express@8960

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@8960

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8960

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@8960

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@8960

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@8960

@clerk/react

npm i https://pkg.pr.new/@clerk/react@8960

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@8960

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@8960

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@8960

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@8960

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8960

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@8960

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@8960

commit: 1ab2f63

@github-actions

github-actionsBot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-07-27T18:34:59.745Z

Summary

MetricCount
Packages analyzed19
Packages with changes1
🔴 Breaking changes0
🟡 Non-breaking changes0
🟢 Additions1

@clerk/expo

Current version: 4.0.4
Recommended bump: MINOR → 4.1.0

Subpath ./hosted-auth

🟢 Additions (1)

Added: ./hosted-auth

New subpath export ./hosted-auth (4 exported members)


Report generated by Break Check

Last ran on 1ab2f63.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/core/resources/Base.ts (1)

204-210: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Don't send the PKCE verifier through _baseGet.

Line 209 forwards codeVerifier on a hard-coded GET, and packages/clerk-js/src/core/fapiClient.ts serializes that field into the URL as code_verifier. That puts the PKCE secret in request URLs, which are routinely captured by logs, proxies, and request instrumentation. This redemption should go through a body-bearing request instead of the _baseGet path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Base.ts` around lines 204 - 210, The
_baseGet method in BaseResource is forwarding codeVerifier into a hard-coded GET
request, which causes fapiClient serialization to place the PKCE secret in the
URL. Update BaseResource._baseGet so it no longer passes codeVerifier through
the GET path; instead, route this redemption through a body-bearing request flow
or another non-URL transport, and keep the existing path/rotatingTokenNonce
behavior intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/expo/src/hooks/useHostedAuth.ts`:
- Around line 10-30: Add customer-facing JSDoc for the new public hosted-auth
exports so generated docs are populated and reviewable. Document HostedAuthMode,
StartHostedAuthParams, and StartHostedAuthReturnType with concise descriptions
of their purpose and fields, and add JSDoc on useHostedAuth explaining what the
hook provides. Also give useHostedAuth an explicit return type instead of
relying on inference, matching the repo’s public API guidelines and keeping the
exported surface in line with other SDK APIs.
- Around line 12-23: The public types in useHostedAuth are leaking optional Expo
browser dependencies into the `@clerk/expo` API surface. Update
StartHostedAuthParams and StartHostedAuthReturnType so they no longer reference
WebBrowser.AuthSessionOpenOptions, WebBrowser.WebBrowserAuthSessionResult, or
ClientResource directly in the exported declarations; instead, hide those behind
local/internal interfaces or move the hosted-auth-specific types into a separate
entrypoint. Ensure the exposed .d.ts for useHostedAuth only contains
dependency-agnostic types so consumers who do not install expo-auth-session or
expo-web-browser are not forced to resolve them.
- Around line 189-205: The callback URL validation in
callbackUrlMatchesRedirectUrl currently skips authority checking when the
redirect URL has an empty host, which allows unexpected authorities like
attacker-controlled hosts to pass for triple-slashed deep links. Update the
matching logic in useHostedAuth.ts to compare the callbackUrl host/authority and
pathname exactly against the parsed redirectUrl for hosted-auth callbacks,
instead of treating an empty expected host as a wildcard. Add a regression test
covering a redirectUrl such as myapp:///hosted-auth-callback and a mismatched
callbackUrl like myapp://attacker/hosted-auth-callback to ensure the authority
is rejected.
---
Outside diff comments:
In `@packages/clerk-js/src/core/resources/Base.ts`:
- Around line 204-210: The _baseGet method in BaseResource is forwarding
codeVerifier into a hard-coded GET request, which causes fapiClient
serialization to place the PKCE secret in the URL. Update BaseResource._baseGet
so it no longer passes codeVerifier through the GET path; instead, route this
redemption through a body-bearing request flow or another non-URL transport, and
keep the existing path/rotatingTokenNonce behavior intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 9713ccce-5bc5-4f09-bb0b-c9275074bbd5

📥 Commits

Reviewing files that changed from the base of the PR and between 52d310c and 4d734f0.

📒 Files selected for processing (10)
  • .changeset/hosted-auth-expo.md
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/fapiClient.ts
  • packages/clerk-js/src/core/resources/Base.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/index.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/types/index.ts
  • packages/expo/src/utils/hostedAuth.ts
  • packages/shared/src/types/resource.ts

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:4d734f0d8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread.changeset/hosted-auth-expo.md Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:5dfea68732

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/Client.ts (1)

81-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clarify docs for the new reload hosted-auth path.

This changes a public method’s behavior when rotatingTokenNonce and codeVerifier are paired, but there’s still no method-level JSDoc explaining when callers should use that path or that the verifier is redeemed from the request body. If Client.reload is reference-facing, please document it and loop in Docs. As per path instructions, "If a PR adds or changes public/reference-facing API surface area, check whether the corresponding JSDoc is present, accurate, and aligned with the implementation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Client.ts` around lines 81 - 100,
`Client.reload` now has a hosted-auth branch when `rotatingTokenNonce` and
`codeVerifier` are present, but the public API lacks JSDoc describing when to
use it and that the verifier is sent in the request body. Add method-level
documentation on `Client.reload` explaining the two reload paths, the required
pairing of `rotatingTokenNonce` with `codeVerifier`, and that this path redeems
the verifier via the POST body; keep the docs aligned with the implementation
and note that Docs should be looped in for this reference-facing change.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/clerk-js/src/core/__tests__/fapiClient.test.ts`:
- Line 154: The test in fapiClient should cover both rotating token nonce
behavior and the security edge case that codeVerifier is never included in the
generated URL. Update the existing `adds rotating token nonce when provided`
test around `buildUrl()` to assert the nonce is present while also verifying
`code_verifier` is not emitted, using the same `FapiClient` URL-building path so
the regression is caught if PKCE data ever leaks.
---
Nitpick comments:
In `@packages/clerk-js/src/core/resources/Client.ts`:
- Around line 81-100: `Client.reload` now has a hosted-auth branch when
`rotatingTokenNonce` and `codeVerifier` are present, but the public API lacks
JSDoc describing when to use it and that the verifier is sent in the request
body. Add method-level documentation on `Client.reload` explaining the two
reload paths, the required pairing of `rotatingTokenNonce` with `codeVerifier`,
and that this path redeems the verifier via the POST body; keep the docs aligned
with the implementation and note that Docs should be looped in for this
reference-facing change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 745841d4-8924-4910-bab0-04c9e597e775

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfea68 and 9b96d7f.

📒 Files selected for processing (6)
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/resources/Client.ts
  • packages/clerk-js/src/core/resources/__tests__/Client.test.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/utils/hostedAuth.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/expo/src/utils/hostedAuth.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/hooks/tests/useHostedAuth.test.ts

Comment threadpackages/clerk-js/src/core/__tests__/fapiClient.test.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
- Require created_session_id on the callback before redeeming, matching
iOS and Android; drop the last_active_session_id fallback.
- Align error strings with the native SDKs so the same condition reads
identically across platforms.
- Allow preferEphemeralSession in authSessionOptions for parity with the
iOS SDK's prefersEphemeralWebBrowserSession.
- Fold createCodeChallenge into createPKCE and drop its test-only export;
return the Account Portal URL from createHostedAuth directly.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a q!

Everything looks good here, great job! Thanks for following existing conventions

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
… filter
clerk-android registers SSOReceiverActivity for clerk://<package>.callback,
so the Expo-registered filter for the same URI triggered an ambiguous
"Open with" chooser on callback, and picking the native handler consumed
the nonce and dropped the sign-in. Use clerk://<package>.hosted-callback
for the Expo hosted auth default instead.
Refreshing the JS client mutates the resource in place and resolves with
that same object, so the foreign-client guard was comparing a reference
that had already become the refreshed client. It could never reject, and
a native client change resolving to a different signed-out client was
applied over the active session, signing the user out.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-tested and the collision issue is fixed 👍🏼

@mikepitre
mikepitre merged commit 23a25cd into mainJul 27, 2026
60 checks passed
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@mikepitre@wobsoriano
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(expo): add hosted auth flow by mikepitre · Pull Request #8960 · clerk/javascript · GitHub
Skip to content

feat(expo): add hosted auth flow - #8960

Merged
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in
Jul 27, 2026
Merged

feat(expo): add hosted auth flow#8960
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in

Conversation

@mikepitre

@mikepitremikepitre commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds the Expo client SDK surface for hosted auth through Account Portal.

Expo apps can now start a hosted sign-in or sign-up flow in the system browser, return through a native callback, and activate the single Clerk session that ClerkGo attaches to the native client.

What Changed

  • Adds useHostedAuth() through the opt-in @clerk/expo/hosted-auth subpath.
  • Opens Account Portal with expo-web-browser / expo-auth-session.
  • Registers the canonical clerk://<android.package>.callback intent filter through the Expo config plugin.
  • Generates and validates state for callback correlation.
  • Generates a PKCE verifier/challenge pair and sends only the challenge when creating the hosted-auth attempt.
  • Redeems the returned rotating token nonce from the Expo hosted-auth helper.
  • Applies the returned /client payload to the existing Clerk client and activates the created native session. The payload is applied before the created session is validated, so local client state stays in sync with the rotated server state even when validation fails.
  • If an abandoned handoff leaves the native client stale, retries hosted-auth creation once after the response hook stores ClerkGo's replacement device token.
  • Rejects overlapping startHostedAuth calls while a flow is in progress.
  • Warns once in development builds when the default Android callback is used, since it only works after the Clerk config plugin registers the intent filter and the native project is rebuilt. The hook docs spell out the same prerequisite.

Developer Experience

import{useHostedAuth}from'@clerk/expo/hosted-auth';const{ startHostedAuth }=useHostedAuth();awaitstartHostedAuth();awaitstartHostedAuth({mode: 'sign-up'});

Apps may pass mode: 'sign-in' | 'sign-up', a custom non-HTTP redirectUrl, or authSessionOptions. By default, the hook uses the canonical callback registered for a native build and AuthSession.makeRedirectUri() in Expo Go.

Flow

  1. The hook creates a redirect URL, random state, and PKCE verifier/challenge.
  2. It asks ClerkGo to create a hosted-auth Account Portal URL.
  3. It opens that URL with openAuthSessionAsync.
  4. On callback, it validates the redirect URL and state.
  5. It redeems the returned rotating_token_nonce with the original PKCE verifier.
  6. It updates the current Clerk client instance and calls setActive with the created native session.

Security

  • Uses a random state and verifies it on callback so the app only accepts the browser result for the auth attempt it initiated.
  • Uses PKCE so ClerkGo stores the challenge at creation time and requires the matching verifier at redemption time.
  • Sends the PKCE verifier in the FAPI request body, not in the URL.
  • Validates callback protocol, host, and path against the initiated redirect URL before redeeming anything.
  • Does not create or keep a web session in the SDK; the browser only drives Account Portal and the completed session is attached to the native client.
  • Leaves production redirect-url allowlisting enforced by ClerkGo.

Implementation Notes

Hosted auth is exposed from @clerk/expo/hosted-auth so apps that import the default @clerk/expo package do not need to resolve optional Expo auth/browser/crypto peer dependencies unless they opt into this flow.

The completion request is a physical POST /v1/client with _method=GET in the form body. That lets the backend route to the existing /client read/rotation path while keeping the PKCE verifier out of query strings and logs.

The verifier-bound completion stays scoped to packages/expo/src/utils/hostedAuth.ts. Generic Client.reload() remains the normal GET reload path, so ClerkJS core does not gain hosted-auth-specific branches.

Screen Recording

Simulator.Screen.Recording.-.iPhone.Air.+.Watch.-.2026-07-09.at.17.20.58.mov

Related PRs

@vercel

vercelBot commented Jun 23, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentActionsUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentJul 27, 2026 6:30pm
swingsetReadyReadyPreview, CommentJul 27, 2026 6:30pm

Request Review

@changeset-bot

changeset-botBot commented Jun 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1ab2f63

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
@clerk/expoMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitaiBot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds hosted auth support for native Expo apps, with new hook and utility APIs, shared PKCE/codeVerifier plumbing, public re-exports, and tests.

Changes

Hosted Auth Flow for Expo

Layer / File(s)Summary
Shared reload and FAPI params
packages/shared/src/types/resource.ts, packages/clerk-js/src/core/resources/Client.ts, packages/clerk-js/src/core/__tests__/fapiClient.test.ts, packages/clerk-js/src/core/resources/__tests__/Client.test.ts
ClerkResourceReloadParams gains codeVerifier, Client.reload redeems hosted-auth callbacks with nonce and verifier, and the related FAPI/client tests cover the new request shape and query parameter.
Hosted auth utility
packages/expo/src/utils/hostedAuth.ts
createHostedAuth resolves an FAPI client, POSTs /client/hosted_auth, validates the response payload, and surfaces API errors with retry-after data.
Hosted auth hook and exports
packages/expo/src/hooks/useHostedAuth.ts, packages/expo/src/hooks/index.ts, packages/expo/src/types/index.ts, .changeset/hosted-auth-expo.md
useHostedAuth adds PKCE/state generation, callback validation, client reload and session activation, and the Expo hook/type re-exports and changeset entry expose the new API.
Hosted auth tests
packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
Vitest coverage exercises the hook’s success path, state and session fallback behavior, callback validation, and hosted-auth error cases with mocked Expo and Clerk modules.

Sequence Diagram(s)

sequenceDiagram
participant useHostedAuth
participant createHostedAuth
participant expoWebBrowser
participant Client
participant clerk
useHostedAuth->>createHostedAuth: create hosted-auth URL
createHostedAuth->>clerk: POST /client/hosted_auth
createHostedAuth-->>useHostedAuth: hosted-auth URL
useHostedAuth->>expoWebBrowser: openAuthSessionAsync(hosted-auth URL, redirectUrl)
expoWebBrowser-->>useHostedAuth: callback URL
useHostedAuth->>Client: reload({ rotatingTokenNonce, codeVerifier })
Client-->>useHostedAuth: updated client
useHostedAuth->>clerk: setActive(created_session_id)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • wobsoriano

Poem

A bunny hopped through PKCE light,
With hosted auth all snug and right.
A nonce, a state, a code verifier too,
Then sessions clicked in, bright and new.
🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 5.56% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly summarizes the main change: adding the Expo hosted auth flow.

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-newBot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@8960

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@8960

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@8960

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@8960

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@8960

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@8960

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@8960

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@8960

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@8960

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@8960

@clerk/express

npm i https://pkg.pr.new/@clerk/express@8960

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@8960

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8960

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@8960

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@8960

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@8960

@clerk/react

npm i https://pkg.pr.new/@clerk/react@8960

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@8960

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@8960

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@8960

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@8960

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8960

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@8960

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@8960

commit: 1ab2f63

@github-actions

github-actionsBot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-07-27T18:34:59.745Z

Summary

MetricCount
Packages analyzed19
Packages with changes1
🔴 Breaking changes0
🟡 Non-breaking changes0
🟢 Additions1

@clerk/expo

Current version: 4.0.4
Recommended bump: MINOR → 4.1.0

Subpath ./hosted-auth

🟢 Additions (1)

Added: ./hosted-auth

New subpath export ./hosted-auth (4 exported members)


Report generated by Break Check

Last ran on 1ab2f63.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/core/resources/Base.ts (1)

204-210: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Don't send the PKCE verifier through _baseGet.

Line 209 forwards codeVerifier on a hard-coded GET, and packages/clerk-js/src/core/fapiClient.ts serializes that field into the URL as code_verifier. That puts the PKCE secret in request URLs, which are routinely captured by logs, proxies, and request instrumentation. This redemption should go through a body-bearing request instead of the _baseGet path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Base.ts` around lines 204 - 210, The
_baseGet method in BaseResource is forwarding codeVerifier into a hard-coded GET
request, which causes fapiClient serialization to place the PKCE secret in the
URL. Update BaseResource._baseGet so it no longer passes codeVerifier through
the GET path; instead, route this redemption through a body-bearing request flow
or another non-URL transport, and keep the existing path/rotatingTokenNonce
behavior intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/expo/src/hooks/useHostedAuth.ts`:
- Around line 10-30: Add customer-facing JSDoc for the new public hosted-auth
exports so generated docs are populated and reviewable. Document HostedAuthMode,
StartHostedAuthParams, and StartHostedAuthReturnType with concise descriptions
of their purpose and fields, and add JSDoc on useHostedAuth explaining what the
hook provides. Also give useHostedAuth an explicit return type instead of
relying on inference, matching the repo’s public API guidelines and keeping the
exported surface in line with other SDK APIs.
- Around line 12-23: The public types in useHostedAuth are leaking optional Expo
browser dependencies into the `@clerk/expo` API surface. Update
StartHostedAuthParams and StartHostedAuthReturnType so they no longer reference
WebBrowser.AuthSessionOpenOptions, WebBrowser.WebBrowserAuthSessionResult, or
ClientResource directly in the exported declarations; instead, hide those behind
local/internal interfaces or move the hosted-auth-specific types into a separate
entrypoint. Ensure the exposed .d.ts for useHostedAuth only contains
dependency-agnostic types so consumers who do not install expo-auth-session or
expo-web-browser are not forced to resolve them.
- Around line 189-205: The callback URL validation in
callbackUrlMatchesRedirectUrl currently skips authority checking when the
redirect URL has an empty host, which allows unexpected authorities like
attacker-controlled hosts to pass for triple-slashed deep links. Update the
matching logic in useHostedAuth.ts to compare the callbackUrl host/authority and
pathname exactly against the parsed redirectUrl for hosted-auth callbacks,
instead of treating an empty expected host as a wildcard. Add a regression test
covering a redirectUrl such as myapp:///hosted-auth-callback and a mismatched
callbackUrl like myapp://attacker/hosted-auth-callback to ensure the authority
is rejected.
---
Outside diff comments:
In `@packages/clerk-js/src/core/resources/Base.ts`:
- Around line 204-210: The _baseGet method in BaseResource is forwarding
codeVerifier into a hard-coded GET request, which causes fapiClient
serialization to place the PKCE secret in the URL. Update BaseResource._baseGet
so it no longer passes codeVerifier through the GET path; instead, route this
redemption through a body-bearing request flow or another non-URL transport, and
keep the existing path/rotatingTokenNonce behavior intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 9713ccce-5bc5-4f09-bb0b-c9275074bbd5

📥 Commits

Reviewing files that changed from the base of the PR and between 52d310c and 4d734f0.

📒 Files selected for processing (10)
  • .changeset/hosted-auth-expo.md
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/fapiClient.ts
  • packages/clerk-js/src/core/resources/Base.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/index.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/types/index.ts
  • packages/expo/src/utils/hostedAuth.ts
  • packages/shared/src/types/resource.ts

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:4d734f0d8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread.changeset/hosted-auth-expo.md Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:5dfea68732

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/Client.ts (1)

81-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clarify docs for the new reload hosted-auth path.

This changes a public method’s behavior when rotatingTokenNonce and codeVerifier are paired, but there’s still no method-level JSDoc explaining when callers should use that path or that the verifier is redeemed from the request body. If Client.reload is reference-facing, please document it and loop in Docs. As per path instructions, "If a PR adds or changes public/reference-facing API surface area, check whether the corresponding JSDoc is present, accurate, and aligned with the implementation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Client.ts` around lines 81 - 100,
`Client.reload` now has a hosted-auth branch when `rotatingTokenNonce` and
`codeVerifier` are present, but the public API lacks JSDoc describing when to
use it and that the verifier is sent in the request body. Add method-level
documentation on `Client.reload` explaining the two reload paths, the required
pairing of `rotatingTokenNonce` with `codeVerifier`, and that this path redeems
the verifier via the POST body; keep the docs aligned with the implementation
and note that Docs should be looped in for this reference-facing change.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/clerk-js/src/core/__tests__/fapiClient.test.ts`:
- Line 154: The test in fapiClient should cover both rotating token nonce
behavior and the security edge case that codeVerifier is never included in the
generated URL. Update the existing `adds rotating token nonce when provided`
test around `buildUrl()` to assert the nonce is present while also verifying
`code_verifier` is not emitted, using the same `FapiClient` URL-building path so
the regression is caught if PKCE data ever leaks.
---
Nitpick comments:
In `@packages/clerk-js/src/core/resources/Client.ts`:
- Around line 81-100: `Client.reload` now has a hosted-auth branch when
`rotatingTokenNonce` and `codeVerifier` are present, but the public API lacks
JSDoc describing when to use it and that the verifier is sent in the request
body. Add method-level documentation on `Client.reload` explaining the two
reload paths, the required pairing of `rotatingTokenNonce` with `codeVerifier`,
and that this path redeems the verifier via the POST body; keep the docs aligned
with the implementation and note that Docs should be looped in for this
reference-facing change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 745841d4-8924-4910-bab0-04c9e597e775

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfea68 and 9b96d7f.

📒 Files selected for processing (6)
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/resources/Client.ts
  • packages/clerk-js/src/core/resources/__tests__/Client.test.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/utils/hostedAuth.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/expo/src/utils/hostedAuth.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/hooks/tests/useHostedAuth.test.ts

Comment threadpackages/clerk-js/src/core/__tests__/fapiClient.test.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
- Require created_session_id on the callback before redeeming, matching
iOS and Android; drop the last_active_session_id fallback.
- Align error strings with the native SDKs so the same condition reads
identically across platforms.
- Allow preferEphemeralSession in authSessionOptions for parity with the
iOS SDK's prefersEphemeralWebBrowserSession.
- Fold createCodeChallenge into createPKCE and drop its test-only export;
return the Account Portal URL from createHostedAuth directly.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a q!

Everything looks good here, great job! Thanks for following existing conventions

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
… filter
clerk-android registers SSOReceiverActivity for clerk://<package>.callback,
so the Expo-registered filter for the same URI triggered an ambiguous
"Open with" chooser on callback, and picking the native handler consumed
the nonce and dropped the sign-in. Use clerk://<package>.hosted-callback
for the Expo hosted auth default instead.
Refreshing the JS client mutates the resource in place and resolves with
that same object, so the foreign-client guard was comparing a reference
that had already become the refreshed client. It could never reject, and
a native client change resolving to a different signed-out client was
applied over the active session, signing the user out.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-tested and the collision issue is fixed 👍🏼

@mikepitre
mikepitre merged commit 23a25cd into mainJul 27, 2026
60 checks passed
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@mikepitre@wobsoriano
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(expo): add hosted auth flow by mikepitre · Pull Request #8960 · clerk/javascript · GitHub
Skip to content

feat(expo): add hosted auth flow - #8960

Merged
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in
Jul 27, 2026
Merged

feat(expo): add hosted auth flow#8960
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in

Conversation

@mikepitre

@mikepitremikepitre commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds the Expo client SDK surface for hosted auth through Account Portal.

Expo apps can now start a hosted sign-in or sign-up flow in the system browser, return through a native callback, and activate the single Clerk session that ClerkGo attaches to the native client.

What Changed

  • Adds useHostedAuth() through the opt-in @clerk/expo/hosted-auth subpath.
  • Opens Account Portal with expo-web-browser / expo-auth-session.
  • Registers the canonical clerk://<android.package>.callback intent filter through the Expo config plugin.
  • Generates and validates state for callback correlation.
  • Generates a PKCE verifier/challenge pair and sends only the challenge when creating the hosted-auth attempt.
  • Redeems the returned rotating token nonce from the Expo hosted-auth helper.
  • Applies the returned /client payload to the existing Clerk client and activates the created native session. The payload is applied before the created session is validated, so local client state stays in sync with the rotated server state even when validation fails.
  • If an abandoned handoff leaves the native client stale, retries hosted-auth creation once after the response hook stores ClerkGo's replacement device token.
  • Rejects overlapping startHostedAuth calls while a flow is in progress.
  • Warns once in development builds when the default Android callback is used, since it only works after the Clerk config plugin registers the intent filter and the native project is rebuilt. The hook docs spell out the same prerequisite.

Developer Experience

import{useHostedAuth}from'@clerk/expo/hosted-auth';const{ startHostedAuth }=useHostedAuth();awaitstartHostedAuth();awaitstartHostedAuth({mode: 'sign-up'});

Apps may pass mode: 'sign-in' | 'sign-up', a custom non-HTTP redirectUrl, or authSessionOptions. By default, the hook uses the canonical callback registered for a native build and AuthSession.makeRedirectUri() in Expo Go.

Flow

  1. The hook creates a redirect URL, random state, and PKCE verifier/challenge.
  2. It asks ClerkGo to create a hosted-auth Account Portal URL.
  3. It opens that URL with openAuthSessionAsync.
  4. On callback, it validates the redirect URL and state.
  5. It redeems the returned rotating_token_nonce with the original PKCE verifier.
  6. It updates the current Clerk client instance and calls setActive with the created native session.

Security

  • Uses a random state and verifies it on callback so the app only accepts the browser result for the auth attempt it initiated.
  • Uses PKCE so ClerkGo stores the challenge at creation time and requires the matching verifier at redemption time.
  • Sends the PKCE verifier in the FAPI request body, not in the URL.
  • Validates callback protocol, host, and path against the initiated redirect URL before redeeming anything.
  • Does not create or keep a web session in the SDK; the browser only drives Account Portal and the completed session is attached to the native client.
  • Leaves production redirect-url allowlisting enforced by ClerkGo.

Implementation Notes

Hosted auth is exposed from @clerk/expo/hosted-auth so apps that import the default @clerk/expo package do not need to resolve optional Expo auth/browser/crypto peer dependencies unless they opt into this flow.

The completion request is a physical POST /v1/client with _method=GET in the form body. That lets the backend route to the existing /client read/rotation path while keeping the PKCE verifier out of query strings and logs.

The verifier-bound completion stays scoped to packages/expo/src/utils/hostedAuth.ts. Generic Client.reload() remains the normal GET reload path, so ClerkJS core does not gain hosted-auth-specific branches.

Screen Recording

Simulator.Screen.Recording.-.iPhone.Air.+.Watch.-.2026-07-09.at.17.20.58.mov

Related PRs

@vercel

vercelBot commented Jun 23, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentActionsUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentJul 27, 2026 6:30pm
swingsetReadyReadyPreview, CommentJul 27, 2026 6:30pm

Request Review

@changeset-bot

changeset-botBot commented Jun 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1ab2f63

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
@clerk/expoMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitaiBot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds hosted auth support for native Expo apps, with new hook and utility APIs, shared PKCE/codeVerifier plumbing, public re-exports, and tests.

Changes

Hosted Auth Flow for Expo

Layer / File(s)Summary
Shared reload and FAPI params
packages/shared/src/types/resource.ts, packages/clerk-js/src/core/resources/Client.ts, packages/clerk-js/src/core/__tests__/fapiClient.test.ts, packages/clerk-js/src/core/resources/__tests__/Client.test.ts
ClerkResourceReloadParams gains codeVerifier, Client.reload redeems hosted-auth callbacks with nonce and verifier, and the related FAPI/client tests cover the new request shape and query parameter.
Hosted auth utility
packages/expo/src/utils/hostedAuth.ts
createHostedAuth resolves an FAPI client, POSTs /client/hosted_auth, validates the response payload, and surfaces API errors with retry-after data.
Hosted auth hook and exports
packages/expo/src/hooks/useHostedAuth.ts, packages/expo/src/hooks/index.ts, packages/expo/src/types/index.ts, .changeset/hosted-auth-expo.md
useHostedAuth adds PKCE/state generation, callback validation, client reload and session activation, and the Expo hook/type re-exports and changeset entry expose the new API.
Hosted auth tests
packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
Vitest coverage exercises the hook’s success path, state and session fallback behavior, callback validation, and hosted-auth error cases with mocked Expo and Clerk modules.

Sequence Diagram(s)

sequenceDiagram
participant useHostedAuth
participant createHostedAuth
participant expoWebBrowser
participant Client
participant clerk
useHostedAuth->>createHostedAuth: create hosted-auth URL
createHostedAuth->>clerk: POST /client/hosted_auth
createHostedAuth-->>useHostedAuth: hosted-auth URL
useHostedAuth->>expoWebBrowser: openAuthSessionAsync(hosted-auth URL, redirectUrl)
expoWebBrowser-->>useHostedAuth: callback URL
useHostedAuth->>Client: reload({ rotatingTokenNonce, codeVerifier })
Client-->>useHostedAuth: updated client
useHostedAuth->>clerk: setActive(created_session_id)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • wobsoriano

Poem

A bunny hopped through PKCE light,
With hosted auth all snug and right.
A nonce, a state, a code verifier too,
Then sessions clicked in, bright and new.
🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 5.56% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly summarizes the main change: adding the Expo hosted auth flow.

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-newBot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@8960

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@8960

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@8960

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@8960

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@8960

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@8960

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@8960

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@8960

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@8960

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@8960

@clerk/express

npm i https://pkg.pr.new/@clerk/express@8960

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@8960

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8960

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@8960

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@8960

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@8960

@clerk/react

npm i https://pkg.pr.new/@clerk/react@8960

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@8960

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@8960

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@8960

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@8960

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8960

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@8960

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@8960

commit: 1ab2f63

@github-actions

github-actionsBot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-07-27T18:34:59.745Z

Summary

MetricCount
Packages analyzed19
Packages with changes1
🔴 Breaking changes0
🟡 Non-breaking changes0
🟢 Additions1

@clerk/expo

Current version: 4.0.4
Recommended bump: MINOR → 4.1.0

Subpath ./hosted-auth

🟢 Additions (1)

Added: ./hosted-auth

New subpath export ./hosted-auth (4 exported members)


Report generated by Break Check

Last ran on 1ab2f63.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/core/resources/Base.ts (1)

204-210: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Don't send the PKCE verifier through _baseGet.

Line 209 forwards codeVerifier on a hard-coded GET, and packages/clerk-js/src/core/fapiClient.ts serializes that field into the URL as code_verifier. That puts the PKCE secret in request URLs, which are routinely captured by logs, proxies, and request instrumentation. This redemption should go through a body-bearing request instead of the _baseGet path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Base.ts` around lines 204 - 210, The
_baseGet method in BaseResource is forwarding codeVerifier into a hard-coded GET
request, which causes fapiClient serialization to place the PKCE secret in the
URL. Update BaseResource._baseGet so it no longer passes codeVerifier through
the GET path; instead, route this redemption through a body-bearing request flow
or another non-URL transport, and keep the existing path/rotatingTokenNonce
behavior intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/expo/src/hooks/useHostedAuth.ts`:
- Around line 10-30: Add customer-facing JSDoc for the new public hosted-auth
exports so generated docs are populated and reviewable. Document HostedAuthMode,
StartHostedAuthParams, and StartHostedAuthReturnType with concise descriptions
of their purpose and fields, and add JSDoc on useHostedAuth explaining what the
hook provides. Also give useHostedAuth an explicit return type instead of
relying on inference, matching the repo’s public API guidelines and keeping the
exported surface in line with other SDK APIs.
- Around line 12-23: The public types in useHostedAuth are leaking optional Expo
browser dependencies into the `@clerk/expo` API surface. Update
StartHostedAuthParams and StartHostedAuthReturnType so they no longer reference
WebBrowser.AuthSessionOpenOptions, WebBrowser.WebBrowserAuthSessionResult, or
ClientResource directly in the exported declarations; instead, hide those behind
local/internal interfaces or move the hosted-auth-specific types into a separate
entrypoint. Ensure the exposed .d.ts for useHostedAuth only contains
dependency-agnostic types so consumers who do not install expo-auth-session or
expo-web-browser are not forced to resolve them.
- Around line 189-205: The callback URL validation in
callbackUrlMatchesRedirectUrl currently skips authority checking when the
redirect URL has an empty host, which allows unexpected authorities like
attacker-controlled hosts to pass for triple-slashed deep links. Update the
matching logic in useHostedAuth.ts to compare the callbackUrl host/authority and
pathname exactly against the parsed redirectUrl for hosted-auth callbacks,
instead of treating an empty expected host as a wildcard. Add a regression test
covering a redirectUrl such as myapp:///hosted-auth-callback and a mismatched
callbackUrl like myapp://attacker/hosted-auth-callback to ensure the authority
is rejected.
---
Outside diff comments:
In `@packages/clerk-js/src/core/resources/Base.ts`:
- Around line 204-210: The _baseGet method in BaseResource is forwarding
codeVerifier into a hard-coded GET request, which causes fapiClient
serialization to place the PKCE secret in the URL. Update BaseResource._baseGet
so it no longer passes codeVerifier through the GET path; instead, route this
redemption through a body-bearing request flow or another non-URL transport, and
keep the existing path/rotatingTokenNonce behavior intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 9713ccce-5bc5-4f09-bb0b-c9275074bbd5

📥 Commits

Reviewing files that changed from the base of the PR and between 52d310c and 4d734f0.

📒 Files selected for processing (10)
  • .changeset/hosted-auth-expo.md
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/fapiClient.ts
  • packages/clerk-js/src/core/resources/Base.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/index.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/types/index.ts
  • packages/expo/src/utils/hostedAuth.ts
  • packages/shared/src/types/resource.ts

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:4d734f0d8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread.changeset/hosted-auth-expo.md Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:5dfea68732

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/Client.ts (1)

81-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clarify docs for the new reload hosted-auth path.

This changes a public method’s behavior when rotatingTokenNonce and codeVerifier are paired, but there’s still no method-level JSDoc explaining when callers should use that path or that the verifier is redeemed from the request body. If Client.reload is reference-facing, please document it and loop in Docs. As per path instructions, "If a PR adds or changes public/reference-facing API surface area, check whether the corresponding JSDoc is present, accurate, and aligned with the implementation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Client.ts` around lines 81 - 100,
`Client.reload` now has a hosted-auth branch when `rotatingTokenNonce` and
`codeVerifier` are present, but the public API lacks JSDoc describing when to
use it and that the verifier is sent in the request body. Add method-level
documentation on `Client.reload` explaining the two reload paths, the required
pairing of `rotatingTokenNonce` with `codeVerifier`, and that this path redeems
the verifier via the POST body; keep the docs aligned with the implementation
and note that Docs should be looped in for this reference-facing change.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/clerk-js/src/core/__tests__/fapiClient.test.ts`:
- Line 154: The test in fapiClient should cover both rotating token nonce
behavior and the security edge case that codeVerifier is never included in the
generated URL. Update the existing `adds rotating token nonce when provided`
test around `buildUrl()` to assert the nonce is present while also verifying
`code_verifier` is not emitted, using the same `FapiClient` URL-building path so
the regression is caught if PKCE data ever leaks.
---
Nitpick comments:
In `@packages/clerk-js/src/core/resources/Client.ts`:
- Around line 81-100: `Client.reload` now has a hosted-auth branch when
`rotatingTokenNonce` and `codeVerifier` are present, but the public API lacks
JSDoc describing when to use it and that the verifier is sent in the request
body. Add method-level documentation on `Client.reload` explaining the two
reload paths, the required pairing of `rotatingTokenNonce` with `codeVerifier`,
and that this path redeems the verifier via the POST body; keep the docs aligned
with the implementation and note that Docs should be looped in for this
reference-facing change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 745841d4-8924-4910-bab0-04c9e597e775

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfea68 and 9b96d7f.

📒 Files selected for processing (6)
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/resources/Client.ts
  • packages/clerk-js/src/core/resources/__tests__/Client.test.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/utils/hostedAuth.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/expo/src/utils/hostedAuth.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/hooks/tests/useHostedAuth.test.ts

Comment threadpackages/clerk-js/src/core/__tests__/fapiClient.test.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
- Require created_session_id on the callback before redeeming, matching
iOS and Android; drop the last_active_session_id fallback.
- Align error strings with the native SDKs so the same condition reads
identically across platforms.
- Allow preferEphemeralSession in authSessionOptions for parity with the
iOS SDK's prefersEphemeralWebBrowserSession.
- Fold createCodeChallenge into createPKCE and drop its test-only export;
return the Account Portal URL from createHostedAuth directly.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a q!

Everything looks good here, great job! Thanks for following existing conventions

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
… filter
clerk-android registers SSOReceiverActivity for clerk://<package>.callback,
so the Expo-registered filter for the same URI triggered an ambiguous
"Open with" chooser on callback, and picking the native handler consumed
the nonce and dropped the sign-in. Use clerk://<package>.hosted-callback
for the Expo hosted auth default instead.
Refreshing the JS client mutates the resource in place and resolves with
that same object, so the foreign-client guard was comparing a reference
that had already become the refreshed client. It could never reject, and
a native client change resolving to a different signed-out client was
applied over the active session, signing the user out.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-tested and the collision issue is fixed 👍🏼

@mikepitre
mikepitre merged commit 23a25cd into mainJul 27, 2026
60 checks passed
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@mikepitre@wobsoriano
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(expo): add hosted auth flow by mikepitre · Pull Request #8960 · clerk/javascript · GitHub
Skip to content

feat(expo): add hosted auth flow - #8960

Merged
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in
Jul 27, 2026
Merged

feat(expo): add hosted auth flow#8960
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in

Conversation

@mikepitre

@mikepitremikepitre commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds the Expo client SDK surface for hosted auth through Account Portal.

Expo apps can now start a hosted sign-in or sign-up flow in the system browser, return through a native callback, and activate the single Clerk session that ClerkGo attaches to the native client.

What Changed

  • Adds useHostedAuth() through the opt-in @clerk/expo/hosted-auth subpath.
  • Opens Account Portal with expo-web-browser / expo-auth-session.
  • Registers the canonical clerk://<android.package>.callback intent filter through the Expo config plugin.
  • Generates and validates state for callback correlation.
  • Generates a PKCE verifier/challenge pair and sends only the challenge when creating the hosted-auth attempt.
  • Redeems the returned rotating token nonce from the Expo hosted-auth helper.
  • Applies the returned /client payload to the existing Clerk client and activates the created native session. The payload is applied before the created session is validated, so local client state stays in sync with the rotated server state even when validation fails.
  • If an abandoned handoff leaves the native client stale, retries hosted-auth creation once after the response hook stores ClerkGo's replacement device token.
  • Rejects overlapping startHostedAuth calls while a flow is in progress.
  • Warns once in development builds when the default Android callback is used, since it only works after the Clerk config plugin registers the intent filter and the native project is rebuilt. The hook docs spell out the same prerequisite.

Developer Experience

import{useHostedAuth}from'@clerk/expo/hosted-auth';const{ startHostedAuth }=useHostedAuth();awaitstartHostedAuth();awaitstartHostedAuth({mode: 'sign-up'});

Apps may pass mode: 'sign-in' | 'sign-up', a custom non-HTTP redirectUrl, or authSessionOptions. By default, the hook uses the canonical callback registered for a native build and AuthSession.makeRedirectUri() in Expo Go.

Flow

  1. The hook creates a redirect URL, random state, and PKCE verifier/challenge.
  2. It asks ClerkGo to create a hosted-auth Account Portal URL.
  3. It opens that URL with openAuthSessionAsync.
  4. On callback, it validates the redirect URL and state.
  5. It redeems the returned rotating_token_nonce with the original PKCE verifier.
  6. It updates the current Clerk client instance and calls setActive with the created native session.

Security

  • Uses a random state and verifies it on callback so the app only accepts the browser result for the auth attempt it initiated.
  • Uses PKCE so ClerkGo stores the challenge at creation time and requires the matching verifier at redemption time.
  • Sends the PKCE verifier in the FAPI request body, not in the URL.
  • Validates callback protocol, host, and path against the initiated redirect URL before redeeming anything.
  • Does not create or keep a web session in the SDK; the browser only drives Account Portal and the completed session is attached to the native client.
  • Leaves production redirect-url allowlisting enforced by ClerkGo.

Implementation Notes

Hosted auth is exposed from @clerk/expo/hosted-auth so apps that import the default @clerk/expo package do not need to resolve optional Expo auth/browser/crypto peer dependencies unless they opt into this flow.

The completion request is a physical POST /v1/client with _method=GET in the form body. That lets the backend route to the existing /client read/rotation path while keeping the PKCE verifier out of query strings and logs.

The verifier-bound completion stays scoped to packages/expo/src/utils/hostedAuth.ts. Generic Client.reload() remains the normal GET reload path, so ClerkJS core does not gain hosted-auth-specific branches.

Screen Recording

Simulator.Screen.Recording.-.iPhone.Air.+.Watch.-.2026-07-09.at.17.20.58.mov

Related PRs

@vercel

vercelBot commented Jun 23, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentActionsUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentJul 27, 2026 6:30pm
swingsetReadyReadyPreview, CommentJul 27, 2026 6:30pm

Request Review

@changeset-bot

changeset-botBot commented Jun 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1ab2f63

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
@clerk/expoMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitaiBot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds hosted auth support for native Expo apps, with new hook and utility APIs, shared PKCE/codeVerifier plumbing, public re-exports, and tests.

Changes

Hosted Auth Flow for Expo

Layer / File(s)Summary
Shared reload and FAPI params
packages/shared/src/types/resource.ts, packages/clerk-js/src/core/resources/Client.ts, packages/clerk-js/src/core/__tests__/fapiClient.test.ts, packages/clerk-js/src/core/resources/__tests__/Client.test.ts
ClerkResourceReloadParams gains codeVerifier, Client.reload redeems hosted-auth callbacks with nonce and verifier, and the related FAPI/client tests cover the new request shape and query parameter.
Hosted auth utility
packages/expo/src/utils/hostedAuth.ts
createHostedAuth resolves an FAPI client, POSTs /client/hosted_auth, validates the response payload, and surfaces API errors with retry-after data.
Hosted auth hook and exports
packages/expo/src/hooks/useHostedAuth.ts, packages/expo/src/hooks/index.ts, packages/expo/src/types/index.ts, .changeset/hosted-auth-expo.md
useHostedAuth adds PKCE/state generation, callback validation, client reload and session activation, and the Expo hook/type re-exports and changeset entry expose the new API.
Hosted auth tests
packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
Vitest coverage exercises the hook’s success path, state and session fallback behavior, callback validation, and hosted-auth error cases with mocked Expo and Clerk modules.

Sequence Diagram(s)

sequenceDiagram
participant useHostedAuth
participant createHostedAuth
participant expoWebBrowser
participant Client
participant clerk
useHostedAuth->>createHostedAuth: create hosted-auth URL
createHostedAuth->>clerk: POST /client/hosted_auth
createHostedAuth-->>useHostedAuth: hosted-auth URL
useHostedAuth->>expoWebBrowser: openAuthSessionAsync(hosted-auth URL, redirectUrl)
expoWebBrowser-->>useHostedAuth: callback URL
useHostedAuth->>Client: reload({ rotatingTokenNonce, codeVerifier })
Client-->>useHostedAuth: updated client
useHostedAuth->>clerk: setActive(created_session_id)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • wobsoriano

Poem

A bunny hopped through PKCE light,
With hosted auth all snug and right.
A nonce, a state, a code verifier too,
Then sessions clicked in, bright and new.
🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 5.56% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly summarizes the main change: adding the Expo hosted auth flow.

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-newBot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@8960

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@8960

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@8960

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@8960

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@8960

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@8960

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@8960

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@8960

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@8960

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@8960

@clerk/express

npm i https://pkg.pr.new/@clerk/express@8960

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@8960

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8960

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@8960

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@8960

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@8960

@clerk/react

npm i https://pkg.pr.new/@clerk/react@8960

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@8960

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@8960

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@8960

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@8960

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8960

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@8960

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@8960

commit: 1ab2f63

@github-actions

github-actionsBot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-07-27T18:34:59.745Z

Summary

MetricCount
Packages analyzed19
Packages with changes1
🔴 Breaking changes0
🟡 Non-breaking changes0
🟢 Additions1

@clerk/expo

Current version: 4.0.4
Recommended bump: MINOR → 4.1.0

Subpath ./hosted-auth

🟢 Additions (1)

Added: ./hosted-auth

New subpath export ./hosted-auth (4 exported members)


Report generated by Break Check

Last ran on 1ab2f63.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/core/resources/Base.ts (1)

204-210: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Don't send the PKCE verifier through _baseGet.

Line 209 forwards codeVerifier on a hard-coded GET, and packages/clerk-js/src/core/fapiClient.ts serializes that field into the URL as code_verifier. That puts the PKCE secret in request URLs, which are routinely captured by logs, proxies, and request instrumentation. This redemption should go through a body-bearing request instead of the _baseGet path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Base.ts` around lines 204 - 210, The
_baseGet method in BaseResource is forwarding codeVerifier into a hard-coded GET
request, which causes fapiClient serialization to place the PKCE secret in the
URL. Update BaseResource._baseGet so it no longer passes codeVerifier through
the GET path; instead, route this redemption through a body-bearing request flow
or another non-URL transport, and keep the existing path/rotatingTokenNonce
behavior intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/expo/src/hooks/useHostedAuth.ts`:
- Around line 10-30: Add customer-facing JSDoc for the new public hosted-auth
exports so generated docs are populated and reviewable. Document HostedAuthMode,
StartHostedAuthParams, and StartHostedAuthReturnType with concise descriptions
of their purpose and fields, and add JSDoc on useHostedAuth explaining what the
hook provides. Also give useHostedAuth an explicit return type instead of
relying on inference, matching the repo’s public API guidelines and keeping the
exported surface in line with other SDK APIs.
- Around line 12-23: The public types in useHostedAuth are leaking optional Expo
browser dependencies into the `@clerk/expo` API surface. Update
StartHostedAuthParams and StartHostedAuthReturnType so they no longer reference
WebBrowser.AuthSessionOpenOptions, WebBrowser.WebBrowserAuthSessionResult, or
ClientResource directly in the exported declarations; instead, hide those behind
local/internal interfaces or move the hosted-auth-specific types into a separate
entrypoint. Ensure the exposed .d.ts for useHostedAuth only contains
dependency-agnostic types so consumers who do not install expo-auth-session or
expo-web-browser are not forced to resolve them.
- Around line 189-205: The callback URL validation in
callbackUrlMatchesRedirectUrl currently skips authority checking when the
redirect URL has an empty host, which allows unexpected authorities like
attacker-controlled hosts to pass for triple-slashed deep links. Update the
matching logic in useHostedAuth.ts to compare the callbackUrl host/authority and
pathname exactly against the parsed redirectUrl for hosted-auth callbacks,
instead of treating an empty expected host as a wildcard. Add a regression test
covering a redirectUrl such as myapp:///hosted-auth-callback and a mismatched
callbackUrl like myapp://attacker/hosted-auth-callback to ensure the authority
is rejected.
---
Outside diff comments:
In `@packages/clerk-js/src/core/resources/Base.ts`:
- Around line 204-210: The _baseGet method in BaseResource is forwarding
codeVerifier into a hard-coded GET request, which causes fapiClient
serialization to place the PKCE secret in the URL. Update BaseResource._baseGet
so it no longer passes codeVerifier through the GET path; instead, route this
redemption through a body-bearing request flow or another non-URL transport, and
keep the existing path/rotatingTokenNonce behavior intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 9713ccce-5bc5-4f09-bb0b-c9275074bbd5

📥 Commits

Reviewing files that changed from the base of the PR and between 52d310c and 4d734f0.

📒 Files selected for processing (10)
  • .changeset/hosted-auth-expo.md
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/fapiClient.ts
  • packages/clerk-js/src/core/resources/Base.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/index.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/types/index.ts
  • packages/expo/src/utils/hostedAuth.ts
  • packages/shared/src/types/resource.ts

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:4d734f0d8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread.changeset/hosted-auth-expo.md Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:5dfea68732

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/Client.ts (1)

81-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clarify docs for the new reload hosted-auth path.

This changes a public method’s behavior when rotatingTokenNonce and codeVerifier are paired, but there’s still no method-level JSDoc explaining when callers should use that path or that the verifier is redeemed from the request body. If Client.reload is reference-facing, please document it and loop in Docs. As per path instructions, "If a PR adds or changes public/reference-facing API surface area, check whether the corresponding JSDoc is present, accurate, and aligned with the implementation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Client.ts` around lines 81 - 100,
`Client.reload` now has a hosted-auth branch when `rotatingTokenNonce` and
`codeVerifier` are present, but the public API lacks JSDoc describing when to
use it and that the verifier is sent in the request body. Add method-level
documentation on `Client.reload` explaining the two reload paths, the required
pairing of `rotatingTokenNonce` with `codeVerifier`, and that this path redeems
the verifier via the POST body; keep the docs aligned with the implementation
and note that Docs should be looped in for this reference-facing change.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/clerk-js/src/core/__tests__/fapiClient.test.ts`:
- Line 154: The test in fapiClient should cover both rotating token nonce
behavior and the security edge case that codeVerifier is never included in the
generated URL. Update the existing `adds rotating token nonce when provided`
test around `buildUrl()` to assert the nonce is present while also verifying
`code_verifier` is not emitted, using the same `FapiClient` URL-building path so
the regression is caught if PKCE data ever leaks.
---
Nitpick comments:
In `@packages/clerk-js/src/core/resources/Client.ts`:
- Around line 81-100: `Client.reload` now has a hosted-auth branch when
`rotatingTokenNonce` and `codeVerifier` are present, but the public API lacks
JSDoc describing when to use it and that the verifier is sent in the request
body. Add method-level documentation on `Client.reload` explaining the two
reload paths, the required pairing of `rotatingTokenNonce` with `codeVerifier`,
and that this path redeems the verifier via the POST body; keep the docs aligned
with the implementation and note that Docs should be looped in for this
reference-facing change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 745841d4-8924-4910-bab0-04c9e597e775

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfea68 and 9b96d7f.

📒 Files selected for processing (6)
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/resources/Client.ts
  • packages/clerk-js/src/core/resources/__tests__/Client.test.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/utils/hostedAuth.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/expo/src/utils/hostedAuth.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/hooks/tests/useHostedAuth.test.ts

Comment threadpackages/clerk-js/src/core/__tests__/fapiClient.test.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
- Require created_session_id on the callback before redeeming, matching
iOS and Android; drop the last_active_session_id fallback.
- Align error strings with the native SDKs so the same condition reads
identically across platforms.
- Allow preferEphemeralSession in authSessionOptions for parity with the
iOS SDK's prefersEphemeralWebBrowserSession.
- Fold createCodeChallenge into createPKCE and drop its test-only export;
return the Account Portal URL from createHostedAuth directly.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a q!

Everything looks good here, great job! Thanks for following existing conventions

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
… filter
clerk-android registers SSOReceiverActivity for clerk://<package>.callback,
so the Expo-registered filter for the same URI triggered an ambiguous
"Open with" chooser on callback, and picking the native handler consumed
the nonce and dropped the sign-in. Use clerk://<package>.hosted-callback
for the Expo hosted auth default instead.
Refreshing the JS client mutates the resource in place and resolves with
that same object, so the foreign-client guard was comparing a reference
that had already become the refreshed client. It could never reject, and
a native client change resolving to a different signed-out client was
applied over the active session, signing the user out.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-tested and the collision issue is fixed 👍🏼

@mikepitre
mikepitre merged commit 23a25cd into mainJul 27, 2026
60 checks passed
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@mikepitre@wobsoriano
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(expo): add hosted auth flow by mikepitre · Pull Request #8960 · clerk/javascript · GitHub
Skip to content

feat(expo): add hosted auth flow - #8960

Merged
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in
Jul 27, 2026
Merged

feat(expo): add hosted auth flow#8960
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in

Conversation

@mikepitre

@mikepitremikepitre commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds the Expo client SDK surface for hosted auth through Account Portal.

Expo apps can now start a hosted sign-in or sign-up flow in the system browser, return through a native callback, and activate the single Clerk session that ClerkGo attaches to the native client.

What Changed

  • Adds useHostedAuth() through the opt-in @clerk/expo/hosted-auth subpath.
  • Opens Account Portal with expo-web-browser / expo-auth-session.
  • Registers the canonical clerk://<android.package>.callback intent filter through the Expo config plugin.
  • Generates and validates state for callback correlation.
  • Generates a PKCE verifier/challenge pair and sends only the challenge when creating the hosted-auth attempt.
  • Redeems the returned rotating token nonce from the Expo hosted-auth helper.
  • Applies the returned /client payload to the existing Clerk client and activates the created native session. The payload is applied before the created session is validated, so local client state stays in sync with the rotated server state even when validation fails.
  • If an abandoned handoff leaves the native client stale, retries hosted-auth creation once after the response hook stores ClerkGo's replacement device token.
  • Rejects overlapping startHostedAuth calls while a flow is in progress.
  • Warns once in development builds when the default Android callback is used, since it only works after the Clerk config plugin registers the intent filter and the native project is rebuilt. The hook docs spell out the same prerequisite.

Developer Experience

import{useHostedAuth}from'@clerk/expo/hosted-auth';const{ startHostedAuth }=useHostedAuth();awaitstartHostedAuth();awaitstartHostedAuth({mode: 'sign-up'});

Apps may pass mode: 'sign-in' | 'sign-up', a custom non-HTTP redirectUrl, or authSessionOptions. By default, the hook uses the canonical callback registered for a native build and AuthSession.makeRedirectUri() in Expo Go.

Flow

  1. The hook creates a redirect URL, random state, and PKCE verifier/challenge.
  2. It asks ClerkGo to create a hosted-auth Account Portal URL.
  3. It opens that URL with openAuthSessionAsync.
  4. On callback, it validates the redirect URL and state.
  5. It redeems the returned rotating_token_nonce with the original PKCE verifier.
  6. It updates the current Clerk client instance and calls setActive with the created native session.

Security

  • Uses a random state and verifies it on callback so the app only accepts the browser result for the auth attempt it initiated.
  • Uses PKCE so ClerkGo stores the challenge at creation time and requires the matching verifier at redemption time.
  • Sends the PKCE verifier in the FAPI request body, not in the URL.
  • Validates callback protocol, host, and path against the initiated redirect URL before redeeming anything.
  • Does not create or keep a web session in the SDK; the browser only drives Account Portal and the completed session is attached to the native client.
  • Leaves production redirect-url allowlisting enforced by ClerkGo.

Implementation Notes

Hosted auth is exposed from @clerk/expo/hosted-auth so apps that import the default @clerk/expo package do not need to resolve optional Expo auth/browser/crypto peer dependencies unless they opt into this flow.

The completion request is a physical POST /v1/client with _method=GET in the form body. That lets the backend route to the existing /client read/rotation path while keeping the PKCE verifier out of query strings and logs.

The verifier-bound completion stays scoped to packages/expo/src/utils/hostedAuth.ts. Generic Client.reload() remains the normal GET reload path, so ClerkJS core does not gain hosted-auth-specific branches.

Screen Recording

Simulator.Screen.Recording.-.iPhone.Air.+.Watch.-.2026-07-09.at.17.20.58.mov

Related PRs

@vercel

vercelBot commented Jun 23, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentActionsUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentJul 27, 2026 6:30pm
swingsetReadyReadyPreview, CommentJul 27, 2026 6:30pm

Request Review

@changeset-bot

changeset-botBot commented Jun 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1ab2f63

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
@clerk/expoMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitaiBot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds hosted auth support for native Expo apps, with new hook and utility APIs, shared PKCE/codeVerifier plumbing, public re-exports, and tests.

Changes

Hosted Auth Flow for Expo

Layer / File(s)Summary
Shared reload and FAPI params
packages/shared/src/types/resource.ts, packages/clerk-js/src/core/resources/Client.ts, packages/clerk-js/src/core/__tests__/fapiClient.test.ts, packages/clerk-js/src/core/resources/__tests__/Client.test.ts
ClerkResourceReloadParams gains codeVerifier, Client.reload redeems hosted-auth callbacks with nonce and verifier, and the related FAPI/client tests cover the new request shape and query parameter.
Hosted auth utility
packages/expo/src/utils/hostedAuth.ts
createHostedAuth resolves an FAPI client, POSTs /client/hosted_auth, validates the response payload, and surfaces API errors with retry-after data.
Hosted auth hook and exports
packages/expo/src/hooks/useHostedAuth.ts, packages/expo/src/hooks/index.ts, packages/expo/src/types/index.ts, .changeset/hosted-auth-expo.md
useHostedAuth adds PKCE/state generation, callback validation, client reload and session activation, and the Expo hook/type re-exports and changeset entry expose the new API.
Hosted auth tests
packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
Vitest coverage exercises the hook’s success path, state and session fallback behavior, callback validation, and hosted-auth error cases with mocked Expo and Clerk modules.

Sequence Diagram(s)

sequenceDiagram
participant useHostedAuth
participant createHostedAuth
participant expoWebBrowser
participant Client
participant clerk
useHostedAuth->>createHostedAuth: create hosted-auth URL
createHostedAuth->>clerk: POST /client/hosted_auth
createHostedAuth-->>useHostedAuth: hosted-auth URL
useHostedAuth->>expoWebBrowser: openAuthSessionAsync(hosted-auth URL, redirectUrl)
expoWebBrowser-->>useHostedAuth: callback URL
useHostedAuth->>Client: reload({ rotatingTokenNonce, codeVerifier })
Client-->>useHostedAuth: updated client
useHostedAuth->>clerk: setActive(created_session_id)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • wobsoriano

Poem

A bunny hopped through PKCE light,
With hosted auth all snug and right.
A nonce, a state, a code verifier too,
Then sessions clicked in, bright and new.
🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 5.56% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly summarizes the main change: adding the Expo hosted auth flow.

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-newBot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@8960

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@8960

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@8960

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@8960

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@8960

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@8960

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@8960

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@8960

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@8960

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@8960

@clerk/express

npm i https://pkg.pr.new/@clerk/express@8960

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@8960

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8960

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@8960

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@8960

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@8960

@clerk/react

npm i https://pkg.pr.new/@clerk/react@8960

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@8960

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@8960

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@8960

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@8960

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8960

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@8960

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@8960

commit: 1ab2f63

@github-actions

github-actionsBot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-07-27T18:34:59.745Z

Summary

MetricCount
Packages analyzed19
Packages with changes1
🔴 Breaking changes0
🟡 Non-breaking changes0
🟢 Additions1

@clerk/expo

Current version: 4.0.4
Recommended bump: MINOR → 4.1.0

Subpath ./hosted-auth

🟢 Additions (1)

Added: ./hosted-auth

New subpath export ./hosted-auth (4 exported members)


Report generated by Break Check

Last ran on 1ab2f63.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/core/resources/Base.ts (1)

204-210: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Don't send the PKCE verifier through _baseGet.

Line 209 forwards codeVerifier on a hard-coded GET, and packages/clerk-js/src/core/fapiClient.ts serializes that field into the URL as code_verifier. That puts the PKCE secret in request URLs, which are routinely captured by logs, proxies, and request instrumentation. This redemption should go through a body-bearing request instead of the _baseGet path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Base.ts` around lines 204 - 210, The
_baseGet method in BaseResource is forwarding codeVerifier into a hard-coded GET
request, which causes fapiClient serialization to place the PKCE secret in the
URL. Update BaseResource._baseGet so it no longer passes codeVerifier through
the GET path; instead, route this redemption through a body-bearing request flow
or another non-URL transport, and keep the existing path/rotatingTokenNonce
behavior intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/expo/src/hooks/useHostedAuth.ts`:
- Around line 10-30: Add customer-facing JSDoc for the new public hosted-auth
exports so generated docs are populated and reviewable. Document HostedAuthMode,
StartHostedAuthParams, and StartHostedAuthReturnType with concise descriptions
of their purpose and fields, and add JSDoc on useHostedAuth explaining what the
hook provides. Also give useHostedAuth an explicit return type instead of
relying on inference, matching the repo’s public API guidelines and keeping the
exported surface in line with other SDK APIs.
- Around line 12-23: The public types in useHostedAuth are leaking optional Expo
browser dependencies into the `@clerk/expo` API surface. Update
StartHostedAuthParams and StartHostedAuthReturnType so they no longer reference
WebBrowser.AuthSessionOpenOptions, WebBrowser.WebBrowserAuthSessionResult, or
ClientResource directly in the exported declarations; instead, hide those behind
local/internal interfaces or move the hosted-auth-specific types into a separate
entrypoint. Ensure the exposed .d.ts for useHostedAuth only contains
dependency-agnostic types so consumers who do not install expo-auth-session or
expo-web-browser are not forced to resolve them.
- Around line 189-205: The callback URL validation in
callbackUrlMatchesRedirectUrl currently skips authority checking when the
redirect URL has an empty host, which allows unexpected authorities like
attacker-controlled hosts to pass for triple-slashed deep links. Update the
matching logic in useHostedAuth.ts to compare the callbackUrl host/authority and
pathname exactly against the parsed redirectUrl for hosted-auth callbacks,
instead of treating an empty expected host as a wildcard. Add a regression test
covering a redirectUrl such as myapp:///hosted-auth-callback and a mismatched
callbackUrl like myapp://attacker/hosted-auth-callback to ensure the authority
is rejected.
---
Outside diff comments:
In `@packages/clerk-js/src/core/resources/Base.ts`:
- Around line 204-210: The _baseGet method in BaseResource is forwarding
codeVerifier into a hard-coded GET request, which causes fapiClient
serialization to place the PKCE secret in the URL. Update BaseResource._baseGet
so it no longer passes codeVerifier through the GET path; instead, route this
redemption through a body-bearing request flow or another non-URL transport, and
keep the existing path/rotatingTokenNonce behavior intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 9713ccce-5bc5-4f09-bb0b-c9275074bbd5

📥 Commits

Reviewing files that changed from the base of the PR and between 52d310c and 4d734f0.

📒 Files selected for processing (10)
  • .changeset/hosted-auth-expo.md
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/fapiClient.ts
  • packages/clerk-js/src/core/resources/Base.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/index.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/types/index.ts
  • packages/expo/src/utils/hostedAuth.ts
  • packages/shared/src/types/resource.ts

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:4d734f0d8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread.changeset/hosted-auth-expo.md Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:5dfea68732

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/Client.ts (1)

81-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clarify docs for the new reload hosted-auth path.

This changes a public method’s behavior when rotatingTokenNonce and codeVerifier are paired, but there’s still no method-level JSDoc explaining when callers should use that path or that the verifier is redeemed from the request body. If Client.reload is reference-facing, please document it and loop in Docs. As per path instructions, "If a PR adds or changes public/reference-facing API surface area, check whether the corresponding JSDoc is present, accurate, and aligned with the implementation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Client.ts` around lines 81 - 100,
`Client.reload` now has a hosted-auth branch when `rotatingTokenNonce` and
`codeVerifier` are present, but the public API lacks JSDoc describing when to
use it and that the verifier is sent in the request body. Add method-level
documentation on `Client.reload` explaining the two reload paths, the required
pairing of `rotatingTokenNonce` with `codeVerifier`, and that this path redeems
the verifier via the POST body; keep the docs aligned with the implementation
and note that Docs should be looped in for this reference-facing change.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/clerk-js/src/core/__tests__/fapiClient.test.ts`:
- Line 154: The test in fapiClient should cover both rotating token nonce
behavior and the security edge case that codeVerifier is never included in the
generated URL. Update the existing `adds rotating token nonce when provided`
test around `buildUrl()` to assert the nonce is present while also verifying
`code_verifier` is not emitted, using the same `FapiClient` URL-building path so
the regression is caught if PKCE data ever leaks.
---
Nitpick comments:
In `@packages/clerk-js/src/core/resources/Client.ts`:
- Around line 81-100: `Client.reload` now has a hosted-auth branch when
`rotatingTokenNonce` and `codeVerifier` are present, but the public API lacks
JSDoc describing when to use it and that the verifier is sent in the request
body. Add method-level documentation on `Client.reload` explaining the two
reload paths, the required pairing of `rotatingTokenNonce` with `codeVerifier`,
and that this path redeems the verifier via the POST body; keep the docs aligned
with the implementation and note that Docs should be looped in for this
reference-facing change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 745841d4-8924-4910-bab0-04c9e597e775

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfea68 and 9b96d7f.

📒 Files selected for processing (6)
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/resources/Client.ts
  • packages/clerk-js/src/core/resources/__tests__/Client.test.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/utils/hostedAuth.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/expo/src/utils/hostedAuth.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/hooks/tests/useHostedAuth.test.ts

Comment threadpackages/clerk-js/src/core/__tests__/fapiClient.test.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
- Require created_session_id on the callback before redeeming, matching
iOS and Android; drop the last_active_session_id fallback.
- Align error strings with the native SDKs so the same condition reads
identically across platforms.
- Allow preferEphemeralSession in authSessionOptions for parity with the
iOS SDK's prefersEphemeralWebBrowserSession.
- Fold createCodeChallenge into createPKCE and drop its test-only export;
return the Account Portal URL from createHostedAuth directly.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a q!

Everything looks good here, great job! Thanks for following existing conventions

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
… filter
clerk-android registers SSOReceiverActivity for clerk://<package>.callback,
so the Expo-registered filter for the same URI triggered an ambiguous
"Open with" chooser on callback, and picking the native handler consumed
the nonce and dropped the sign-in. Use clerk://<package>.hosted-callback
for the Expo hosted auth default instead.
Refreshing the JS client mutates the resource in place and resolves with
that same object, so the foreign-client guard was comparing a reference
that had already become the refreshed client. It could never reject, and
a native client change resolving to a different signed-out client was
applied over the active session, signing the user out.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-tested and the collision issue is fixed 👍🏼

@mikepitre
mikepitre merged commit 23a25cd into mainJul 27, 2026
60 checks passed
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@mikepitre@wobsoriano
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat(expo): add hosted auth flow by mikepitre · Pull Request #8960 · clerk/javascript · GitHub
Skip to content

feat(expo): add hosted auth flow - #8960

Merged
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in
Jul 27, 2026
Merged

feat(expo): add hosted auth flow#8960
mikepitre merged 33 commits into
mainfrom
mike/hosted-mobile-sign-in

Conversation

@mikepitre

@mikepitremikepitre commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds the Expo client SDK surface for hosted auth through Account Portal.

Expo apps can now start a hosted sign-in or sign-up flow in the system browser, return through a native callback, and activate the single Clerk session that ClerkGo attaches to the native client.

What Changed

  • Adds useHostedAuth() through the opt-in @clerk/expo/hosted-auth subpath.
  • Opens Account Portal with expo-web-browser / expo-auth-session.
  • Registers the canonical clerk://<android.package>.callback intent filter through the Expo config plugin.
  • Generates and validates state for callback correlation.
  • Generates a PKCE verifier/challenge pair and sends only the challenge when creating the hosted-auth attempt.
  • Redeems the returned rotating token nonce from the Expo hosted-auth helper.
  • Applies the returned /client payload to the existing Clerk client and activates the created native session. The payload is applied before the created session is validated, so local client state stays in sync with the rotated server state even when validation fails.
  • If an abandoned handoff leaves the native client stale, retries hosted-auth creation once after the response hook stores ClerkGo's replacement device token.
  • Rejects overlapping startHostedAuth calls while a flow is in progress.
  • Warns once in development builds when the default Android callback is used, since it only works after the Clerk config plugin registers the intent filter and the native project is rebuilt. The hook docs spell out the same prerequisite.

Developer Experience

import{useHostedAuth}from'@clerk/expo/hosted-auth';const{ startHostedAuth }=useHostedAuth();awaitstartHostedAuth();awaitstartHostedAuth({mode: 'sign-up'});

Apps may pass mode: 'sign-in' | 'sign-up', a custom non-HTTP redirectUrl, or authSessionOptions. By default, the hook uses the canonical callback registered for a native build and AuthSession.makeRedirectUri() in Expo Go.

Flow

  1. The hook creates a redirect URL, random state, and PKCE verifier/challenge.
  2. It asks ClerkGo to create a hosted-auth Account Portal URL.
  3. It opens that URL with openAuthSessionAsync.
  4. On callback, it validates the redirect URL and state.
  5. It redeems the returned rotating_token_nonce with the original PKCE verifier.
  6. It updates the current Clerk client instance and calls setActive with the created native session.

Security

  • Uses a random state and verifies it on callback so the app only accepts the browser result for the auth attempt it initiated.
  • Uses PKCE so ClerkGo stores the challenge at creation time and requires the matching verifier at redemption time.
  • Sends the PKCE verifier in the FAPI request body, not in the URL.
  • Validates callback protocol, host, and path against the initiated redirect URL before redeeming anything.
  • Does not create or keep a web session in the SDK; the browser only drives Account Portal and the completed session is attached to the native client.
  • Leaves production redirect-url allowlisting enforced by ClerkGo.

Implementation Notes

Hosted auth is exposed from @clerk/expo/hosted-auth so apps that import the default @clerk/expo package do not need to resolve optional Expo auth/browser/crypto peer dependencies unless they opt into this flow.

The completion request is a physical POST /v1/client with _method=GET in the form body. That lets the backend route to the existing /client read/rotation path while keeping the PKCE verifier out of query strings and logs.

The verifier-bound completion stays scoped to packages/expo/src/utils/hostedAuth.ts. Generic Client.reload() remains the normal GET reload path, so ClerkJS core does not gain hosted-auth-specific branches.

Screen Recording

Simulator.Screen.Recording.-.iPhone.Air.+.Watch.-.2026-07-09.at.17.20.58.mov

Related PRs

@vercel

vercelBot commented Jun 23, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentActionsUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentJul 27, 2026 6:30pm
swingsetReadyReadyPreview, CommentJul 27, 2026 6:30pm

Request Review

@changeset-bot

changeset-botBot commented Jun 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1ab2f63

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
@clerk/expoMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitaiBot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds hosted auth support for native Expo apps, with new hook and utility APIs, shared PKCE/codeVerifier plumbing, public re-exports, and tests.

Changes

Hosted Auth Flow for Expo

Layer / File(s)Summary
Shared reload and FAPI params
packages/shared/src/types/resource.ts, packages/clerk-js/src/core/resources/Client.ts, packages/clerk-js/src/core/__tests__/fapiClient.test.ts, packages/clerk-js/src/core/resources/__tests__/Client.test.ts
ClerkResourceReloadParams gains codeVerifier, Client.reload redeems hosted-auth callbacks with nonce and verifier, and the related FAPI/client tests cover the new request shape and query parameter.
Hosted auth utility
packages/expo/src/utils/hostedAuth.ts
createHostedAuth resolves an FAPI client, POSTs /client/hosted_auth, validates the response payload, and surfaces API errors with retry-after data.
Hosted auth hook and exports
packages/expo/src/hooks/useHostedAuth.ts, packages/expo/src/hooks/index.ts, packages/expo/src/types/index.ts, .changeset/hosted-auth-expo.md
useHostedAuth adds PKCE/state generation, callback validation, client reload and session activation, and the Expo hook/type re-exports and changeset entry expose the new API.
Hosted auth tests
packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
Vitest coverage exercises the hook’s success path, state and session fallback behavior, callback validation, and hosted-auth error cases with mocked Expo and Clerk modules.

Sequence Diagram(s)

sequenceDiagram
participant useHostedAuth
participant createHostedAuth
participant expoWebBrowser
participant Client
participant clerk
useHostedAuth->>createHostedAuth: create hosted-auth URL
createHostedAuth->>clerk: POST /client/hosted_auth
createHostedAuth-->>useHostedAuth: hosted-auth URL
useHostedAuth->>expoWebBrowser: openAuthSessionAsync(hosted-auth URL, redirectUrl)
expoWebBrowser-->>useHostedAuth: callback URL
useHostedAuth->>Client: reload({ rotatingTokenNonce, codeVerifier })
Client-->>useHostedAuth: updated client
useHostedAuth->>clerk: setActive(created_session_id)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • wobsoriano

Poem

A bunny hopped through PKCE light,
With hosted auth all snug and right.
A nonce, a state, a code verifier too,
Then sessions clicked in, bright and new.
🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 5.56% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly summarizes the main change: adding the Expo hosted auth flow.

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-newBot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@8960

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@8960

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@8960

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@8960

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@8960

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@8960

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@8960

@clerk/expo

npm i https://pkg.pr.new/@clerk/expo@8960

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@8960

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@8960

@clerk/express

npm i https://pkg.pr.new/@clerk/express@8960

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@8960

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@8960

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@8960

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@8960

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@8960

@clerk/react

npm i https://pkg.pr.new/@clerk/react@8960

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@8960

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@8960

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@8960

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@8960

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@8960

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@8960

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@8960

commit: 1ab2f63

@github-actions

github-actionsBot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-07-27T18:34:59.745Z

Summary

MetricCount
Packages analyzed19
Packages with changes1
🔴 Breaking changes0
🟡 Non-breaking changes0
🟢 Additions1

@clerk/expo

Current version: 4.0.4
Recommended bump: MINOR → 4.1.0

Subpath ./hosted-auth

🟢 Additions (1)

Added: ./hosted-auth

New subpath export ./hosted-auth (4 exported members)


Report generated by Break Check

Last ran on 1ab2f63.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/core/resources/Base.ts (1)

204-210: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Don't send the PKCE verifier through _baseGet.

Line 209 forwards codeVerifier on a hard-coded GET, and packages/clerk-js/src/core/fapiClient.ts serializes that field into the URL as code_verifier. That puts the PKCE secret in request URLs, which are routinely captured by logs, proxies, and request instrumentation. This redemption should go through a body-bearing request instead of the _baseGet path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Base.ts` around lines 204 - 210, The
_baseGet method in BaseResource is forwarding codeVerifier into a hard-coded GET
request, which causes fapiClient serialization to place the PKCE secret in the
URL. Update BaseResource._baseGet so it no longer passes codeVerifier through
the GET path; instead, route this redemption through a body-bearing request flow
or another non-URL transport, and keep the existing path/rotatingTokenNonce
behavior intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/expo/src/hooks/useHostedAuth.ts`:
- Around line 10-30: Add customer-facing JSDoc for the new public hosted-auth
exports so generated docs are populated and reviewable. Document HostedAuthMode,
StartHostedAuthParams, and StartHostedAuthReturnType with concise descriptions
of their purpose and fields, and add JSDoc on useHostedAuth explaining what the
hook provides. Also give useHostedAuth an explicit return type instead of
relying on inference, matching the repo’s public API guidelines and keeping the
exported surface in line with other SDK APIs.
- Around line 12-23: The public types in useHostedAuth are leaking optional Expo
browser dependencies into the `@clerk/expo` API surface. Update
StartHostedAuthParams and StartHostedAuthReturnType so they no longer reference
WebBrowser.AuthSessionOpenOptions, WebBrowser.WebBrowserAuthSessionResult, or
ClientResource directly in the exported declarations; instead, hide those behind
local/internal interfaces or move the hosted-auth-specific types into a separate
entrypoint. Ensure the exposed .d.ts for useHostedAuth only contains
dependency-agnostic types so consumers who do not install expo-auth-session or
expo-web-browser are not forced to resolve them.
- Around line 189-205: The callback URL validation in
callbackUrlMatchesRedirectUrl currently skips authority checking when the
redirect URL has an empty host, which allows unexpected authorities like
attacker-controlled hosts to pass for triple-slashed deep links. Update the
matching logic in useHostedAuth.ts to compare the callbackUrl host/authority and
pathname exactly against the parsed redirectUrl for hosted-auth callbacks,
instead of treating an empty expected host as a wildcard. Add a regression test
covering a redirectUrl such as myapp:///hosted-auth-callback and a mismatched
callbackUrl like myapp://attacker/hosted-auth-callback to ensure the authority
is rejected.
---
Outside diff comments:
In `@packages/clerk-js/src/core/resources/Base.ts`:
- Around line 204-210: The _baseGet method in BaseResource is forwarding
codeVerifier into a hard-coded GET request, which causes fapiClient
serialization to place the PKCE secret in the URL. Update BaseResource._baseGet
so it no longer passes codeVerifier through the GET path; instead, route this
redemption through a body-bearing request flow or another non-URL transport, and
keep the existing path/rotatingTokenNonce behavior intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 9713ccce-5bc5-4f09-bb0b-c9275074bbd5

📥 Commits

Reviewing files that changed from the base of the PR and between 52d310c and 4d734f0.

📒 Files selected for processing (10)
  • .changeset/hosted-auth-expo.md
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/fapiClient.ts
  • packages/clerk-js/src/core/resources/Base.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/index.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/types/index.ts
  • packages/expo/src/utils/hostedAuth.ts
  • packages/shared/src/types/resource.ts

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:4d734f0d8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread.changeset/hosted-auth-expo.md Outdated

@chatgpt-codex-connectorchatgpt-codex-connectorBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit:5dfea68732

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/Client.ts (1)

81-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clarify docs for the new reload hosted-auth path.

This changes a public method’s behavior when rotatingTokenNonce and codeVerifier are paired, but there’s still no method-level JSDoc explaining when callers should use that path or that the verifier is redeemed from the request body. If Client.reload is reference-facing, please document it and loop in Docs. As per path instructions, "If a PR adds or changes public/reference-facing API surface area, check whether the corresponding JSDoc is present, accurate, and aligned with the implementation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/clerk-js/src/core/resources/Client.ts` around lines 81 - 100,
`Client.reload` now has a hosted-auth branch when `rotatingTokenNonce` and
`codeVerifier` are present, but the public API lacks JSDoc describing when to
use it and that the verifier is sent in the request body. Add method-level
documentation on `Client.reload` explaining the two reload paths, the required
pairing of `rotatingTokenNonce` with `codeVerifier`, and that this path redeems
the verifier via the POST body; keep the docs aligned with the implementation
and note that Docs should be looped in for this reference-facing change.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/clerk-js/src/core/__tests__/fapiClient.test.ts`:
- Line 154: The test in fapiClient should cover both rotating token nonce
behavior and the security edge case that codeVerifier is never included in the
generated URL. Update the existing `adds rotating token nonce when provided`
test around `buildUrl()` to assert the nonce is present while also verifying
`code_verifier` is not emitted, using the same `FapiClient` URL-building path so
the regression is caught if PKCE data ever leaks.
---
Nitpick comments:
In `@packages/clerk-js/src/core/resources/Client.ts`:
- Around line 81-100: `Client.reload` now has a hosted-auth branch when
`rotatingTokenNonce` and `codeVerifier` are present, but the public API lacks
JSDoc describing when to use it and that the verifier is sent in the request
body. Add method-level documentation on `Client.reload` explaining the two
reload paths, the required pairing of `rotatingTokenNonce` with `codeVerifier`,
and that this path redeems the verifier via the POST body; keep the docs aligned
with the implementation and note that Docs should be looped in for this
reference-facing change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 745841d4-8924-4910-bab0-04c9e597e775

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfea68 and 9b96d7f.

📒 Files selected for processing (6)
  • packages/clerk-js/src/core/__tests__/fapiClient.test.ts
  • packages/clerk-js/src/core/resources/Client.ts
  • packages/clerk-js/src/core/resources/__tests__/Client.test.ts
  • packages/expo/src/hooks/__tests__/useHostedAuth.test.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/utils/hostedAuth.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/expo/src/utils/hostedAuth.ts
  • packages/expo/src/hooks/useHostedAuth.ts
  • packages/expo/src/hooks/tests/useHostedAuth.test.ts

Comment threadpackages/clerk-js/src/core/__tests__/fapiClient.test.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
- Require created_session_id on the callback before redeeming, matching
iOS and Android; drop the last_active_session_id fallback.
- Align error strings with the native SDKs so the same condition reads
identically across platforms.
- Allow preferEphemeralSession in authSessionOptions for parity with the
iOS SDK's prefersEphemeralWebBrowserSession.
- Fold createCodeChallenge into createPKCE and drop its test-only export;
return the Account Portal URL from createHostedAuth directly.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a q!

Everything looks good here, great job! Thanks for following existing conventions

Comment threadpackages/expo/src/hooks/useHostedAuth.ts Outdated
Comment threadpackages/expo/src/hooks/useHostedAuth.ts
… filter
clerk-android registers SSOReceiverActivity for clerk://<package>.callback,
so the Expo-registered filter for the same URI triggered an ambiguous
"Open with" chooser on callback, and picking the native handler consumed
the nonce and dropped the sign-in. Use clerk://<package>.hosted-callback
for the Expo hosted auth default instead.
Refreshing the JS client mutates the resource in place and resolves with
that same object, so the foreign-client guard was comparing a reference
that had already become the refreshed client. It could never reject, and
a native client change resolving to a different signed-out client was
applied over the active session, signing the user out.

@wobsorianowobsoriano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-tested and the collision issue is fixed 👍🏼

@mikepitre
mikepitre merged commit 23a25cd into mainJul 27, 2026
60 checks passed
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@mikepitre@wobsoriano