-
Notifications
You must be signed in to change notification settings - Fork 435
feat(react-router): Add support for keyless mode #7794
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
a659eaf
feat(react-router): Keyless support
wobsoriano e08192c
chore: clean up
wobsoriano 140ba30
chore: clean up var name
wobsoriano 6bc3243
chore: remove any assertion
wobsoriano 15d5fc0
Merge branch 'main' into rob/react-router-keyless
wobsoriano 6638d89
chore: throw only if not keyless mode
wobsoriano fe7577e
add integraiton test
wobsoriano 4a6b959
chore: extract shared test utils
wobsoriano f79def9
chore: add changeset
wobsoriano 9354709
chore: share main keyless fallback function
wobsoriano ae6c168
chore: delete md file
wobsoriano 9e962c2
Merge branch 'main' into rob/react-router-keyless
wobsoriano 818352a
chore: extract reusable file storage create function
wobsoriano 57a8049
Add Keyless quickstart and refactor createFileStorage
wobsoriano 834c6eb
chore: revert
wobsoriano 069aaef
Merge branch 'main' into rob/react-router-keyless
wobsoriano 32bec51
chore: Make resolveKeysWithKeylessFallback function a method on the k…
wobsoriano 9fee85e
Merge branch 'main' into rob/react-router-keyless
wobsoriano a70b8a2
Merge branch 'main' into rob/react-router-keyless
wobsoriano 1c39d21
fix(repo): Handle framework query param in keyless claim URLs integra…
wobsoriano 6b04f9f
chore: share main keyless fallback function
wobsoriano 567b5a5
refactor: use shared helper for Next.js keyless test
wobsoriano 7183175
Merge branch 'main' into rob/react-router-keyless
wobsoriano 0049b7f
delete doc
wobsoriano 2e71569
chore: add missing framework requirement
wobsoriano ab36fa8
chore: remove redundant export
wobsoriano cda1649
fix type errors
wobsoriano File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { createNodeFileStorage, type KeylessStorage } from '@clerk/shared/keyless'; | ||
|
|
||
| export type { KeylessStorage }; | ||
|
|
||
| export interface FileStorageOptions { | ||
| cwd?: () => string; | ||
| } | ||
|
|
||
| /** | ||
| * Creates a file-based storage adapter for keyless mode. | ||
| * Uses dynamic imports to avoid breaking Cloudflare Workers. | ||
| * | ||
| * @throws {Error} If called in a non-Node.js environment | ||
| */ | ||
| export async function createFileStorage(options: FileStorageOptions = {}): Promise<KeylessStorage> { | ||
| const { cwd = () => process.cwd() } = options; | ||
|
|
||
| try { | ||
| // Dynamic import to avoid bundler issues with edge runtimes | ||
| const [fs, path] = await Promise.all([import('node:fs'), import('node:path')]); | ||
|
|
||
| return createNodeFileStorage(fs, path, { | ||
| cwd, | ||
| frameworkPackageName: '@clerk/react-router', | ||
| }); | ||
| } catch (error) { | ||
| throw new Error( | ||
| 'Keyless mode requires a Node.js runtime with file system access. ' + | ||
| 'Set VITE_CLERK_KEYLESS_DISABLED=1 to disable keyless mode.', | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| import { createKeylessService } from '@clerk/shared/keyless'; | ||
|
|
||
| import { clerkClient } from '../clerkClient'; | ||
| import type { DataFunctionArgs } from '../loadOptions'; | ||
| import type { ClerkMiddlewareOptions } from '../types'; | ||
| import { createFileStorage } from './fileStorage'; | ||
|
|
||
| // Singleton with lazy initialization | ||
| let keylessServiceInstance: ReturnType<typeof createKeylessService> | null = null; | ||
| let keylessInitPromise: Promise<ReturnType<typeof createKeylessService> | null> | null = null; | ||
|
|
||
| /** | ||
| * Detects if the current runtime supports file system operations. | ||
| */ | ||
| function canUseFileSystem(): boolean { | ||
| try { | ||
| return typeof process !== 'undefined' && typeof process.cwd === 'function'; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Gets or creates the keyless service instance. | ||
| * | ||
| * Returns null for non-Node.js runtimes (Cloudflare Workers). | ||
| * This function is async because storage creation may involve dynamic imports. | ||
| */ | ||
| export async function keyless( | ||
| args?: DataFunctionArgs, | ||
| options?: ClerkMiddlewareOptions, | ||
| ): Promise<ReturnType<typeof createKeylessService> | null> { | ||
| // Guard: Return null for non-Node.js runtimes | ||
| if (!canUseFileSystem()) { | ||
| return null; | ||
| } | ||
|
|
||
| // Return existing instance | ||
| if (keylessServiceInstance) { | ||
| return keylessServiceInstance; | ||
| } | ||
|
|
||
| // Return in-flight initialization | ||
| if (keylessInitPromise) { | ||
| return keylessInitPromise; | ||
| } | ||
|
|
||
| // Initialize service | ||
| keylessInitPromise = (async () => { | ||
| try { | ||
| const storage = await createFileStorage(); | ||
|
|
||
| const service = createKeylessService({ | ||
| storage, | ||
| api: { | ||
| async createAccountlessApplication(requestHeaders?: Headers) { | ||
| try { | ||
| // Create a default args object if not provided | ||
| const client = args ? clerkClient(args, options) : clerkClient({} as any, options); | ||
| return await client.__experimental_accountlessApplications.createAccountlessApplication({ | ||
| requestHeaders, | ||
| }); | ||
| } catch { | ||
| return null; | ||
| } | ||
| }, | ||
| async completeOnboarding(requestHeaders?: Headers) { | ||
| try { | ||
| const client = args ? clerkClient(args, options) : clerkClient({} as any, options); | ||
| return await client.__experimental_accountlessApplications.completeAccountlessApplicationOnboarding({ | ||
| requestHeaders, | ||
| }); | ||
| } catch { | ||
| return null; | ||
| } | ||
| }, | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }, | ||
| framework: 'react-router', | ||
| frameworkVersion: PACKAGE_VERSION, | ||
| }); | ||
|
|
||
| keylessServiceInstance = service; | ||
| return service; | ||
| } catch (error) { | ||
| console.warn('[Clerk] Failed to initialize keyless service:', error); | ||
| return null; | ||
| } finally { | ||
| keylessInitPromise = null; | ||
| } | ||
| })(); | ||
|
|
||
| return keylessInitPromise; | ||
| } | ||
|
|
||
| /** | ||
| * Resets the keyless service instance (for testing). | ||
| * @internal | ||
| */ | ||
| export function resetKeylessService(): void { | ||
| keylessServiceInstance = null; | ||
| keylessInitPromise = null; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import type { AccountlessApplication } from '@clerk/shared/keyless'; | ||
| import { clerkDevelopmentCache, createConfirmationMessage, createKeylessModeMessage } from '@clerk/shared/keyless'; | ||
|
|
||
| import { canUseKeyless } from '../../utils/feature-flags'; | ||
| import type { DataFunctionArgs } from '../loadOptions'; | ||
| import type { ClerkMiddlewareOptions } from '../types'; | ||
| import { keyless } from './index'; | ||
|
|
||
| export interface KeylessResult { | ||
| publishableKey: string | undefined; | ||
| secretKey: string | undefined; | ||
| claimUrl: string | undefined; | ||
| apiKeysUrl: string | undefined; | ||
| } | ||
|
|
||
| /** | ||
| * Resolves Clerk keys, falling back to keyless mode in development if configured keys are missing. | ||
| * | ||
| * Implements the TanStack keyless pattern: | ||
| * 1. Check if keyless mode is enabled (dev + not disabled) | ||
| * 2. If running with claimed keys (configured === stored), complete onboarding | ||
| * 3. If no keys configured, create/read keyless keys from storage | ||
| * 4. Return resolved keys + keyless URLs | ||
| * | ||
| * @returns The resolved keys + keyless URLs to inject into state | ||
| */ | ||
| export async function resolveKeysWithKeylessFallback( | ||
| configuredPublishableKey: string | undefined, | ||
| configuredSecretKey: string | undefined, | ||
| args?: DataFunctionArgs, | ||
| options?: ClerkMiddlewareOptions, | ||
| ): Promise<KeylessResult> { | ||
| let publishableKey = configuredPublishableKey; | ||
| let secretKey = configuredSecretKey; | ||
| let claimUrl: string | undefined; | ||
| let apiKeysUrl: string | undefined; | ||
|
|
||
| // Early return if keyless is disabled | ||
| if (!canUseKeyless) { | ||
| return { publishableKey, secretKey, claimUrl, apiKeysUrl }; | ||
| } | ||
|
|
||
| try { | ||
| const keylessService = await keyless(args, options); | ||
|
|
||
| // Early return if keyless service unavailable (e.g., Cloudflare) | ||
| if (!keylessService) { | ||
| return { publishableKey, secretKey, claimUrl, apiKeysUrl }; | ||
| } | ||
|
|
||
| const locallyStoredKeys = keylessService.readKeys(); | ||
|
|
||
| // Scenario 1: Running with claimed keys | ||
| const runningWithClaimedKeys = | ||
| Boolean(configuredPublishableKey) && configuredPublishableKey === locallyStoredKeys?.publishableKey; | ||
|
|
||
| if (runningWithClaimedKeys && locallyStoredKeys) { | ||
| // Complete onboarding (throttled by dev cache) | ||
| try { | ||
| await clerkDevelopmentCache?.run(() => keylessService.completeOnboarding(), { | ||
| cacheKey: `${locallyStoredKeys.publishableKey}_complete`, | ||
| onSuccessStale: 24 * 60 * 60 * 1000, // 24 hours | ||
| }); | ||
| } catch { | ||
| // noop - non-critical | ||
| } | ||
|
|
||
| clerkDevelopmentCache?.log({ | ||
| cacheKey: `${locallyStoredKeys.publishableKey}_claimed`, | ||
| msg: createConfirmationMessage(), | ||
| }); | ||
|
|
||
| return { publishableKey, secretKey, claimUrl, apiKeysUrl }; | ||
| } | ||
|
|
||
| // Scenario 2: Keyless mode (no keys configured) | ||
| if (!publishableKey || !secretKey) { | ||
| const keylessApp: AccountlessApplication | null = await keylessService.getOrCreateKeys(); | ||
|
|
||
| if (keylessApp) { | ||
| publishableKey = publishableKey || keylessApp.publishableKey; | ||
| secretKey = secretKey || keylessApp.secretKey; | ||
| claimUrl = keylessApp.claimUrl; | ||
| apiKeysUrl = keylessApp.apiKeysUrl; | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| clerkDevelopmentCache?.log({ | ||
| cacheKey: keylessApp.publishableKey, | ||
| msg: createKeylessModeMessage(keylessApp), | ||
| }); | ||
| } | ||
| } | ||
| } catch (error) { | ||
| // Graceful fallback - never break the app | ||
| console.warn('[Clerk] Keyless resolution failed:', error); | ||
| } | ||
|
|
||
| return { publishableKey, secretKey, claimUrl, apiKeysUrl }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This can be extracted as well, but will plan to do so while implementing keyless for other SDKs.
Having these node imports in the shared
@clerk/shared/keylessbarrel export would break Next.js at edge runtime, sincepackages/nextjs/src/server/keyless-node.tsimports from that barrel (correct me if Im wrong!)