diff --git a/apps/web/src/cloud/desktopAuth.test.ts b/apps/web/src/cloud/desktopAuth.test.ts index 171e5cb4f8..9a9b244517 100644 --- a/apps/web/src/cloud/desktopAuth.test.ts +++ b/apps/web/src/cloud/desktopAuth.test.ts @@ -19,6 +19,41 @@ describe("resolveDesktopCloudAuthOAuthOptions", () => { }, }, }), - ).toEqual([{ strategy: "oauth_google", label: "Google" }]); + ).toEqual([ + { + strategy: "oauth_google", + label: "Google", + providerId: "google", + iconUrl: null, + }, + ]); + }); + + it("preserves provider display metadata when Clerk exposes the strategy list", () => { + expect( + resolveDesktopCloudAuthOAuthOptions({ + environment: { + userSettings: { + authenticatableSocialStrategies: ["oauth_google"], + social: { + oauth_google: { + strategy: "oauth_google", + enabled: true, + authenticatable: true, + name: "Google", + logo_url: "https://img.clerk.com/static/google.png", + }, + }, + }, + }, + }), + ).toEqual([ + { + strategy: "oauth_google", + label: "Google", + providerId: "google", + iconUrl: "https://img.clerk.com/static/google.png", + }, + ]); }); }); diff --git a/apps/web/src/cloud/desktopAuth.ts b/apps/web/src/cloud/desktopAuth.ts index be7377be15..0e2a328c30 100644 --- a/apps/web/src/cloud/desktopAuth.ts +++ b/apps/web/src/cloud/desktopAuth.ts @@ -3,6 +3,8 @@ export type DesktopCloudAuthOAuthStrategy = `oauth_${string}`; export interface DesktopCloudAuthOAuthOption { readonly strategy: DesktopCloudAuthOAuthStrategy; readonly label: string; + readonly providerId: string; + readonly iconUrl: string | null; } interface ClerkOAuthProviderSetting { @@ -10,6 +12,7 @@ interface ClerkOAuthProviderSetting { readonly authenticatable?: unknown; readonly strategy?: unknown; readonly name?: unknown; + readonly logo_url?: unknown; } interface ClerkUserSettingsLike { @@ -41,6 +44,8 @@ const OAUTH_LABELS: Readonly> = { oauth_x: "X", }; +// Mirrors Clerk UI's enabled-provider projection for the local desktop replacement: +// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/hooks/useEnabledThirdPartyProviders.tsx export function isDesktopCloudAuthOAuthStrategy( value: unknown, ): value is DesktopCloudAuthOAuthStrategy { @@ -71,10 +76,11 @@ export function resolveDesktopCloudAuthOAuthOptions( const strategies = userSettings?.authenticatableSocialStrategies; if (Array.isArray(strategies)) { return uniqueOptions( - strategies.filter(isDesktopCloudAuthOAuthStrategy).map((strategy) => ({ - strategy, - label: getDesktopCloudAuthOAuthStrategyLabel(strategy), - })), + strategies + .filter(isDesktopCloudAuthOAuthStrategy) + .map((strategy) => + createOAuthOption(strategy, findProviderSetting(userSettings, strategy)), + ), ); } @@ -92,18 +98,40 @@ export function resolveDesktopCloudAuthOAuthOptions( ? provider.strategy : null; if (!strategy) return null; - return { - strategy, - label: - typeof provider.name === "string" && provider.name.trim() - ? provider.name - : getDesktopCloudAuthOAuthStrategyLabel(strategy), - }; + return createOAuthOption(strategy, provider); }) .filter((option): option is DesktopCloudAuthOAuthOption => option !== null), ); } +function findProviderSetting( + userSettings: ClerkUserSettingsLike | undefined, + strategy: DesktopCloudAuthOAuthStrategy, +): ClerkOAuthProviderSetting | undefined { + const social = userSettings?.social; + if (!social || typeof social !== "object") return undefined; + + return Object.values(social as Record) + .filter(isClerkOAuthProviderSetting) + .find((provider) => provider.strategy === strategy); +} + +function createOAuthOption( + strategy: DesktopCloudAuthOAuthStrategy, + provider?: ClerkOAuthProviderSetting, +): DesktopCloudAuthOAuthOption { + return { + strategy, + label: + typeof provider?.name === "string" && provider.name.trim() + ? provider.name + : getDesktopCloudAuthOAuthStrategyLabel(strategy), + providerId: strategy.replace(/^oauth_/, ""), + iconUrl: + typeof provider?.logo_url === "string" && provider.logo_url.trim() ? provider.logo_url : null, + }; +} + function uniqueOptions( options: readonly DesktopCloudAuthOAuthOption[], ): readonly DesktopCloudAuthOAuthOption[] { diff --git a/apps/web/src/cloud/desktopClerk.tsx b/apps/web/src/cloud/desktopClerk.tsx index 25ed936a18..cf023a3dda 100644 --- a/apps/web/src/cloud/desktopClerk.tsx +++ b/apps/web/src/cloud/desktopClerk.tsx @@ -210,6 +210,8 @@ function getDesktopClerkInstance(publishableKey: string): Clerk { const onAfterResponse = nextClerk.__internal_onAfterResponse ?? nextClerk.__unstable__onAfterResponse; + // Keep this aligned with Clerk Expo's native FAPI adapter: + // https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/expo/src/provider/singleton/createClerkInstance.ts onBeforeRequest(async (request) => { request.credentials = "omit"; request.url?.searchParams.append("_is_native", "1"); diff --git a/apps/web/src/components/clerk/DesktopClerkCard.tsx b/apps/web/src/components/clerk/DesktopClerkCard.tsx new file mode 100644 index 0000000000..e2e0c4f9aa --- /dev/null +++ b/apps/web/src/components/clerk/DesktopClerkCard.tsx @@ -0,0 +1,137 @@ +import type { ReactNode } from "react"; + +import { cn } from "../../lib/utils"; + +// Mirrors Clerk's raised card/footer/branding composition for the desktop-native flow: +// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/Card/CardRoot.tsx +// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/Card/CardFooter.tsx +// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/Card/CardClerkAndPagesTag.tsx +// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/DevModeNotice.tsx +export function DesktopClerkCard({ + children, + footerAction, +}: { + children: ReactNode; + footerAction?: ReactNode; +}) { + return ( +
+
+ {children} +
+
+ {footerAction ? ( +
{footerAction}
+ ) : null} + +
+
+ ); +} + +export function DesktopClerkHeader({ title, subtitle }: { title: string; subtitle: string }) { + return ( +
+

{title}

+

{subtitle}

+
+ ); +} + +export function DesktopClerkFooterAction({ + children, + actionLabel, + onAction, +}: { + children: ReactNode; + actionLabel: string; + onAction: () => void; +}) { + return ( +

+ {children} + +

+ ); +} + +export function DesktopClerkAlert({ children }: { children?: ReactNode }) { + if (!children) return null; + + return ( +
+ {children} +
+ ); +} + +export function DesktopClerkInput({ + className, + ...props +}: React.ComponentPropsWithoutRef<"input">) { + return ( + + ); +} + +export function DesktopClerkPrimaryButton({ + children, + disabled, +}: { + children: ReactNode; + disabled?: boolean; +}) { + return ( + + ); +} + +function DesktopClerkBranding() { + const isDevelopmentMode = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY?.startsWith("pk_test_"); + + return ( +
+ + Secured by{" "} + + clerk + + + {isDevelopmentMode ? ( + Development mode + ) : null} +
+ ); +} diff --git a/apps/web/src/components/clerk/DesktopClerkSignIn.browser.tsx b/apps/web/src/components/clerk/DesktopClerkSignIn.browser.tsx new file mode 100644 index 0000000000..b3b55c3c31 --- /dev/null +++ b/apps/web/src/components/clerk/DesktopClerkSignIn.browser.tsx @@ -0,0 +1,71 @@ +import "../../index.css"; + +import { page, userEvent } from "vitest/browser"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { render } from "vitest-browser-react"; + +import type { DesktopCloudAuthOAuthOption } from "../../cloud/desktopAuth"; +import { DesktopClerkSignInCard } from "./DesktopClerkSignIn"; + +const GOOGLE: DesktopCloudAuthOAuthOption = { + strategy: "oauth_google", + label: "Google", + providerId: "google", + iconUrl: null, +}; + +const PROVIDERS: readonly DesktopCloudAuthOAuthOption[] = [ + { + strategy: "oauth_apple", + label: "Apple", + providerId: "apple", + iconUrl: null, + }, + GOOGLE, + { + strategy: "oauth_microsoft", + label: "Microsoft", + providerId: "microsoft", + iconUrl: null, + }, +]; + +describe("DesktopClerkSignInCard", () => { + afterEach(() => { + document.body.innerHTML = ""; + }); + + it("uses Clerk's compact provider grid when more than two providers are enabled", async () => { + await render( + , + ); + + expect(document.querySelectorAll('button[aria-label^="Continue with "]')).toHaveLength(3); + expect(document.body.textContent).toContain("Want early access?"); + expect(document.body.textContent).not.toContain("Continue with Google"); + }); + + it("renders a full provider label and starts OAuth for a single provider", async () => { + const onStartOAuth = vi.fn(); + await render( + , + ); + + await userEvent.click(page.getByRole("button", { name: "Continue with Google" })); + + expect(document.body.textContent).toContain("Continue with Google"); + expect(onStartOAuth).toHaveBeenCalledWith("oauth_google"); + }); +}); diff --git a/apps/web/src/components/clerk/DesktopClerkSignIn.tsx b/apps/web/src/components/clerk/DesktopClerkSignIn.tsx new file mode 100644 index 0000000000..dc8b432e1c --- /dev/null +++ b/apps/web/src/components/clerk/DesktopClerkSignIn.tsx @@ -0,0 +1,150 @@ +import { LoaderCircleIcon } from "lucide-react"; + +import type { + DesktopCloudAuthOAuthOption, + DesktopCloudAuthOAuthStrategy, +} from "../../cloud/desktopAuth"; +import { cn } from "../../lib/utils"; +import { + DesktopClerkAlert, + DesktopClerkCard, + DesktopClerkFooterAction, + DesktopClerkHeader, +} from "./DesktopClerkCard"; +import { useDesktopClerkSignIn } from "./useDesktopClerkSignIn"; + +// Mirrors Clerk's compact social-button layout while delegating OAuth to the desktop bridge: +// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/elements/SocialButtons.tsx +export function DesktopClerkSignIn({ onJoinWaitlist }: { onJoinWaitlist: () => void }) { + const { isStarting, oauthOptions, startingStrategy, startOAuth } = useDesktopClerkSignIn(); + + return ( + void startOAuth(strategy)} + /> + ); +} + +export function DesktopClerkSignInCard({ + isStarting, + oauthOptions, + startingStrategy, + onJoinWaitlist, + onStartOAuth, +}: { + isStarting: boolean; + oauthOptions: readonly DesktopCloudAuthOAuthOption[]; + startingStrategy: DesktopCloudAuthOAuthStrategy | null; + onJoinWaitlist: () => void; + onStartOAuth: (strategy: DesktopCloudAuthOAuthStrategy) => void; +}) { + return ( + + Want early access? + + } + > + + {oauthOptions.length === 0 ? ( + No OAuth providers are enabled for desktop sign-in. + ) : ( + + )} + + ); +} + +function DesktopClerkSocialButtons({ + isStarting, + oauthOptions, + startingStrategy, + onStartOAuth, +}: { + isStarting: boolean; + oauthOptions: readonly DesktopCloudAuthOAuthOption[]; + startingStrategy: DesktopCloudAuthOAuthStrategy | null; + onStartOAuth: (strategy: DesktopCloudAuthOAuthStrategy) => void; +}) { + const useBlockButtons = oauthOptions.length <= 2; + + return ( +
+ {oauthOptions.map((option) => { + const isCurrent = option.strategy === startingStrategy; + return ( + + ); + })} +
+ ); +} + +function DesktopClerkProviderIcon({ option }: { option: DesktopCloudAuthOAuthOption }) { + if (!option.iconUrl) { + return ( + + {option.label.slice(0, 1).toUpperCase()} + + ); + } + + if (["apple", "github", "vercel"].includes(option.providerId)) { + return ( + + ); + } + + return ; +} diff --git a/apps/web/src/components/clerk/DesktopClerkWaitlist.tsx b/apps/web/src/components/clerk/DesktopClerkWaitlist.tsx new file mode 100644 index 0000000000..ec9198498d --- /dev/null +++ b/apps/web/src/components/clerk/DesktopClerkWaitlist.tsx @@ -0,0 +1,106 @@ +import { useClerk } from "@clerk/react"; +import { useState } from "react"; + +import { + DesktopClerkAlert, + DesktopClerkCard, + DesktopClerkFooterAction, + DesktopClerkHeader, + DesktopClerkInput, + DesktopClerkPrimaryButton, +} from "./DesktopClerkCard"; +import { DesktopClerkSignIn } from "./DesktopClerkSignIn"; + +type DesktopClerkScreen = "waitlist" | "sign-in"; + +// Mirrors Clerk's waitlist card and form, replacing its router transition with the desktop sign-in flow: +// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/Waitlist/index.tsx +// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/Waitlist/WaitlistForm.tsx +export function DesktopClerkWaitlist() { + const [screen, setScreen] = useState("waitlist"); + + if (screen === "sign-in") { + return setScreen("waitlist")} />; + } + + return setScreen("sign-in")} />; +} + +function DesktopClerkWaitlistForm({ onSignIn }: { onSignIn: () => void }) { + const clerk = useClerk(); + const [emailAddress, setEmailAddress] = useState(""); + const [error, setError] = useState(null); + const [isSubmitting, setIsSubmitting] = useState(false); + const [didJoin, setDidJoin] = useState(false); + + const submitWaitlist = async (event: React.FormEvent) => { + event.preventDefault(); + setError(null); + setIsSubmitting(true); + try { + await clerk.joinWaitlist({ emailAddress }); + setDidJoin(true); + } catch (cause) { + setError(getClerkErrorMessage(cause)); + } finally { + setIsSubmitting(false); + } + }; + + if (didJoin) { + return ( + + + + ); + } + + return ( + + Already have access? + + } + > + + {error} +
+ + + {isSubmitting ? "Joining the waitlist…" : "Join the waitlist"} + +
+
+ ); +} + +function getClerkErrorMessage(error: unknown): string { + if (typeof error === "object" && error !== null && "errors" in error) { + const errors = (error as { errors?: Array<{ longMessage?: unknown; message?: unknown }> }) + .errors; + const firstError = errors?.[0]; + if (typeof firstError?.longMessage === "string") return firstError.longMessage; + if (typeof firstError?.message === "string") return firstError.message; + } + if (error instanceof Error && error.message) return error.message; + return "Could not join the waitlist. Please try again."; +} diff --git a/apps/web/src/components/clerk/useDesktopClerkSignIn.ts b/apps/web/src/components/clerk/useDesktopClerkSignIn.ts new file mode 100644 index 0000000000..7b58c4f1ee --- /dev/null +++ b/apps/web/src/components/clerk/useDesktopClerkSignIn.ts @@ -0,0 +1,199 @@ +import { useClerk } from "@clerk/react"; +import { useSignIn, useSignUp } from "@clerk/react/legacy"; +import { useCallback, useEffect, useRef, useState } from "react"; + +import { + type DesktopCloudAuthOAuthStrategy, + resolveDesktopCloudAuthOAuthOptions, +} from "../../cloud/desktopAuth"; +import { toastManager } from "../ui/toast"; + +// Mirrors Clerk Expo's browser-based native SSO flow, with Electron handling the external browser +// and callback transport: +// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/expo/src/hooks/useSSO.ts +class DesktopClerkOperationError extends Error { + override readonly cause?: unknown; + + constructor(message: string, cause?: unknown) { + super(message); + this.name = "DesktopClerkOperationError"; + this.cause = cause; + } +} + +async function runDesktopClerkOperation( + operation: () => Promise, + message: string, +): Promise { + try { + return await operation(); + } catch (cause) { + throw new DesktopClerkOperationError(message, cause); + } +} + +function desktopClerkErrorMessage(error: unknown, fallback: string): string { + if (error instanceof DesktopClerkOperationError) { + const cause = error.cause; + if (cause instanceof Error && cause.message && cause.message !== error.message) { + return `${error.message}: ${cause.message}`; + } + return error.message; + } + return error instanceof Error ? error.message : fallback; +} + +export function useDesktopClerkSignIn() { + const clerk = useClerk(); + const { setActive } = clerk; + const { isLoaded: signInLoaded, signIn } = useSignIn(); + const { isLoaded: signUpLoaded, signUp } = useSignUp(); + const [startingStrategy, setStartingStrategy] = useState( + null, + ); + const oauthOptions = resolveDesktopCloudAuthOAuthOptions(clerk); + const callbackCleanupRef = useRef<(() => void) | null>(null); + + const clearCallbackListener = useCallback(() => { + callbackCleanupRef.current?.(); + callbackCleanupRef.current = null; + }, []); + + const completeOAuthCallback = useCallback( + async (rawUrl: string) => { + if (!signInLoaded || !signIn || !signUpLoaded || !signUp) { + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: "Clerk is still loading. Try signing in again.", + }); + return; + } + + let rotatingTokenNonce: string | null = null; + let sessionId: string | null = null; + try { + const callbackUrl = new URL(rawUrl); + rotatingTokenNonce = callbackUrl.searchParams.get("rotating_token_nonce"); + sessionId = callbackUrl.searchParams.get("created_session_id"); + } catch { + // Handled by the explicit nonce check below. + } + if (!rotatingTokenNonce) { + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: + "Clerk did not return a native session nonce. Verify this redirect URL is allowlisted for native SSO redirects.", + }); + return; + } + + try { + await runDesktopClerkOperation( + () => signIn.reload({ rotatingTokenNonce }), + "Could not reload the desktop sign-in session.", + ); + sessionId = sessionId || signIn.createdSessionId; + + if (!sessionId && signIn.firstFactorVerification.status === "transferable") { + const signUpAttempt = await runDesktopClerkOperation( + () => signUp.create({ transfer: true }), + "Could not transfer the desktop sign-up session.", + ); + sessionId = signUpAttempt.createdSessionId; + } + + if (!sessionId) { + throw new DesktopClerkOperationError("Clerk did not create a desktop session."); + } + + await runDesktopClerkOperation( + () => setActive({ session: sessionId! }), + "Could not activate the desktop cloud session.", + ); + } catch (error) { + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: desktopClerkErrorMessage(error, "Could not complete cloud sign-in."), + }); + } + }, + [setActive, signIn, signInLoaded, signUp, signUpLoaded], + ); + + useEffect(() => { + return () => { + clearCallbackListener(); + }; + }, [clearCallbackListener]); + + const startOAuth = useCallback( + async (strategy: DesktopCloudAuthOAuthStrategy) => { + if (!signInLoaded || !signIn) { + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: "Clerk is still loading. Try signing in again.", + }); + return; + } + + setStartingStrategy(strategy); + clearCallbackListener(); + try { + const redirectUrl = await runDesktopClerkOperation( + () => window.desktopBridge?.createCloudAuthRequest() ?? Promise.resolve(undefined), + "Desktop auth callback is unavailable.", + ); + if (!redirectUrl) { + throw new DesktopClerkOperationError("Desktop auth callback is unavailable."); + } + + callbackCleanupRef.current = + window.desktopBridge?.onCloudAuthCallback((rawUrl) => { + clearCallbackListener(); + void completeOAuthCallback(rawUrl); + }) ?? null; + + await runDesktopClerkOperation( + () => signIn.create({ strategy, redirectUrl } as never), + "Could not create the desktop OAuth request.", + ); + const externalUrl = + signIn.firstFactorVerification.externalVerificationRedirectURL?.toString(); + if (!externalUrl) { + throw new DesktopClerkOperationError( + "Clerk did not return an external OAuth redirect URL.", + ); + } + + const opened = await runDesktopClerkOperation( + () => window.desktopBridge?.openExternal(externalUrl) ?? Promise.resolve(false), + "Could not open the system browser.", + ); + if (!opened) { + throw new DesktopClerkOperationError("Could not open the system browser."); + } + } catch (error) { + clearCallbackListener(); + toastManager.add({ + type: "error", + title: "Cloud sign-in failed", + description: desktopClerkErrorMessage(error, "Could not start cloud sign-in."), + }); + } finally { + setStartingStrategy(null); + } + }, + [clearCallbackListener, completeOAuthCallback, signIn, signInLoaded], + ); + + return { + isStarting: startingStrategy !== null, + oauthOptions, + startingStrategy, + startOAuth, + }; +} diff --git a/apps/web/src/components/settings/CloudSettings.tsx b/apps/web/src/components/settings/CloudSettings.tsx index d44032d1e2..40e0e73acc 100644 --- a/apps/web/src/components/settings/CloudSettings.tsx +++ b/apps/web/src/components/settings/CloudSettings.tsx @@ -1,13 +1,8 @@ -import { UserButton, Waitlist, useAuth, useClerk } from "@clerk/react"; -import { useSignIn, useSignUp } from "@clerk/react/legacy"; +import { UserButton, Waitlist, useAuth } from "@clerk/react"; import { AuthRelayWriteScope } from "@t3tools/contracts"; import { CloudIcon, RefreshCwIcon, SmartphoneIcon } from "lucide-react"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useEffect, useState } from "react"; -import { - type DesktopCloudAuthOAuthStrategy, - resolveDesktopCloudAuthOAuthOptions, -} from "../../cloud/desktopAuth"; import { updatePrimaryCloudPreferences } from "../../cloud/linkEnvironment"; import { useManagedRelayDevices } from "../../cloud/managedRelayState"; import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState"; @@ -15,6 +10,7 @@ import { isElectron } from "../../env"; import { usePrimarySessionState } from "../../environments/primary"; import { webRuntime } from "../../lib/runtime"; import { cn } from "../../lib/utils"; +import { DesktopClerkWaitlist } from "../clerk/DesktopClerkWaitlist"; import { Button } from "../ui/button"; import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; import { Skeleton } from "../ui/skeleton"; @@ -57,32 +53,7 @@ function hasClerkConfig(): boolean { return Boolean(import.meta.env.VITE_CLERK_PUBLISHABLE_KEY); } -class CloudSettingsOperationError extends Error { - override readonly cause?: unknown; - - constructor(message: string, cause?: unknown) { - super(message); - this.name = "CloudSettingsOperationError"; - this.cause = cause; - } -} - -async function runCloudOperation(operation: () => Promise, message: string): Promise { - try { - return await operation(); - } catch (cause) { - throw new CloudSettingsOperationError(message, cause); - } -} - function cloudErrorMessage(error: unknown, fallback: string): string { - if (error instanceof CloudSettingsOperationError) { - const cause = error.cause; - if (cause instanceof Error && cause.message && cause.message !== error.message) { - return `${error.message}: ${cause.message}`; - } - return error.message; - } return error instanceof Error ? error.message : fallback; } @@ -116,13 +87,7 @@ function ConfiguredCloudSettingsPanel() { function CloudWaitlistPanel() { return ( - - {isElectron ? ( -
-

Already approved? Sign in through the desktop app.

- -
- ) : null} + {isElectron ? : }
); } @@ -244,173 +209,3 @@ function CloudSettingsPanelInner() { ); } - -function DesktopCloudSignInButton() { - const clerk = useClerk(); - const { setActive } = clerk; - const { isLoaded: signInLoaded, signIn } = useSignIn(); - const { isLoaded: signUpLoaded, signUp } = useSignUp(); - const [startingStrategy, setStartingStrategy] = useState( - null, - ); - const oauthOptions = resolveDesktopCloudAuthOAuthOptions(clerk); - const callbackCleanupRef = useRef<(() => void) | null>(null); - - const clearCallbackListener = useCallback(() => { - callbackCleanupRef.current?.(); - callbackCleanupRef.current = null; - }, []); - - const completeOAuthCallback = useCallback( - async (rawUrl: string) => { - if (!signInLoaded || !signIn || !signUpLoaded || !signUp) { - toastManager.add({ - type: "error", - title: "Cloud sign-in failed", - description: "Clerk is still loading. Try signing in again.", - }); - return; - } - - let rotatingTokenNonce: string | null = null; - let sessionId: string | null = null; - try { - const callbackUrl = new URL(rawUrl); - rotatingTokenNonce = callbackUrl.searchParams.get("rotating_token_nonce"); - sessionId = callbackUrl.searchParams.get("created_session_id"); - } catch { - // Handled by the explicit nonce check below. - } - if (!rotatingTokenNonce) { - toastManager.add({ - type: "error", - title: "Cloud sign-in failed", - description: - "Clerk did not return a native session nonce. Verify this redirect URL is allowlisted for native SSO redirects.", - }); - return; - } - - try { - await runCloudOperation( - () => signIn.reload({ rotatingTokenNonce }), - "Could not reload the desktop sign-in session.", - ); - sessionId = sessionId || signIn.createdSessionId; - - if (!sessionId && signIn.firstFactorVerification.status === "transferable") { - const signUpAttempt = await runCloudOperation( - () => signUp.create({ transfer: true }), - "Could not transfer the desktop sign-up session.", - ); - sessionId = signUpAttempt.createdSessionId; - } - - if (!sessionId) { - throw new CloudSettingsOperationError("Clerk did not create a desktop session."); - } - - await runCloudOperation( - () => setActive({ session: sessionId! }), - "Could not activate the desktop cloud session.", - ); - } catch (error) { - toastManager.add({ - type: "error", - title: "Cloud sign-in failed", - description: cloudErrorMessage(error, "Could not complete cloud sign-in."), - }); - } - }, - [setActive, signIn, signInLoaded, signUp, signUpLoaded], - ); - - useEffect(() => { - return () => { - clearCallbackListener(); - }; - }, [clearCallbackListener]); - - const startOAuth = async (strategy: DesktopCloudAuthOAuthStrategy) => { - if (!signInLoaded || !signIn) { - toastManager.add({ - type: "error", - title: "Cloud sign-in failed", - description: "Clerk is still loading. Try signing in again.", - }); - return; - } - - setStartingStrategy(strategy); - clearCallbackListener(); - try { - const redirectUrl = await runCloudOperation( - () => window.desktopBridge?.createCloudAuthRequest() ?? Promise.resolve(undefined), - "Desktop auth callback is unavailable.", - ); - if (!redirectUrl) { - throw new CloudSettingsOperationError("Desktop auth callback is unavailable."); - } - - callbackCleanupRef.current = - window.desktopBridge?.onCloudAuthCallback((rawUrl) => { - clearCallbackListener(); - void completeOAuthCallback(rawUrl); - }) ?? null; - - const signInAttempt = await runCloudOperation( - () => signIn.create({ strategy, redirectUrl } as never), - "Could not create the desktop OAuth request.", - ); - const externalUrl = - signInAttempt.firstFactorVerification.externalVerificationRedirectURL?.toString(); - if (!externalUrl) { - throw new CloudSettingsOperationError( - "Clerk did not return an external OAuth redirect URL.", - ); - } - - const opened = await runCloudOperation( - () => window.desktopBridge?.openExternal(externalUrl) ?? Promise.resolve(false), - "Could not open the system browser.", - ); - if (!opened) { - throw new CloudSettingsOperationError("Could not open the system browser."); - } - } catch (error) { - clearCallbackListener(); - toastManager.add({ - type: "error", - title: "Cloud sign-in failed", - description: cloudErrorMessage(error, "Could not start cloud sign-in."), - }); - } finally { - setStartingStrategy(null); - } - }; - - const isStarting = startingStrategy !== null; - - if (oauthOptions.length === 0) { - return ( - - ); - } - - return ( -
- {oauthOptions.map((option) => ( - - ))} -
- ); -}