feat(web): add desktop Clerk-compatible cloud auth UI
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
fd3fff7f19
commit
2b5213d920
9 files changed
+744
-221
No files matched your search
@@ -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",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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<Record<string, string>> = {
|
||||
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<string, ClerkOAuthProviderSetting>)
|
||||
.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[] {
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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 (
|
||||
<div className="isolate w-full max-w-[25rem] overflow-hidden rounded-xl border border-border/80 bg-card text-card-foreground shadow-[0_12px_28px_rgba(0,0,0,0.12)]">
|
||||
<div className="relative -m-px flex flex-col gap-8 rounded-lg border border-border/80 bg-card px-10 py-8 text-center">
|
||||
{children}
|
||||
</div>
|
||||
<div className="-mt-2 flex flex-col bg-muted/45 pt-2">
|
||||
{footerAction ? (
|
||||
<div className="border-t border-border/70 px-8 py-4">{footerAction}</div>
|
||||
) : null}
|
||||
<DesktopClerkBranding />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkHeader({ title, subtitle }: { title: string; subtitle: string }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-xl font-bold tracking-[-0.025em] text-foreground">{title}</h2>
|
||||
<p className="text-sm leading-5 text-muted-foreground">{subtitle}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkFooterAction({
|
||||
children,
|
||||
actionLabel,
|
||||
onAction,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
actionLabel: string;
|
||||
onAction: () => void;
|
||||
}) {
|
||||
return (
|
||||
<p className="flex items-center justify-center gap-1 text-sm text-muted-foreground">
|
||||
<span>{children}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="cursor-pointer font-semibold text-foreground outline-none hover:underline focus-visible:underline"
|
||||
onClick={onAction}
|
||||
>
|
||||
{actionLabel}
|
||||
</button>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkAlert({ children }: { children?: ReactNode }) {
|
||||
if (!children) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-md border border-destructive/20 bg-destructive/8 px-3 py-2 text-left text-xs leading-5 text-destructive-foreground"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentPropsWithoutRef<"input">) {
|
||||
return (
|
||||
<input
|
||||
{...props}
|
||||
className={cn(
|
||||
"h-10 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground shadow-xs outline-none placeholder:text-muted-foreground/80 focus:border-ring focus:ring-2 focus:ring-ring/15 disabled:opacity-64",
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function DesktopClerkPrimaryButton({
|
||||
children,
|
||||
disabled,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="submit"
|
||||
disabled={disabled}
|
||||
className="h-10 w-full cursor-pointer rounded-md border border-neutral-950 bg-neutral-900 px-4 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-neutral-800 disabled:pointer-events-none disabled:opacity-64 dark:border-neutral-200 dark:bg-neutral-100 dark:text-neutral-900 dark:hover:bg-white"
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopClerkBranding() {
|
||||
const isDevelopmentMode = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY?.startsWith("pk_test_");
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-center justify-center gap-2 border-t border-border/70 px-8 py-4 text-xs text-muted-foreground",
|
||||
isDevelopmentMode &&
|
||||
"bg-[repeating-linear-gradient(-45deg,rgba(249,115,22,0.035),rgba(249,115,22,0.035)_8px,transparent_8px,transparent_16px)]",
|
||||
)}
|
||||
>
|
||||
<span>
|
||||
Secured by{" "}
|
||||
<a
|
||||
className="font-bold text-muted-foreground hover:text-foreground"
|
||||
href="https://go.clerk.com/components"
|
||||
rel="noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
clerk
|
||||
</a>
|
||||
</span>
|
||||
{isDevelopmentMode ? (
|
||||
<strong className="font-semibold text-orange-500">Development mode</strong>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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(
|
||||
<DesktopClerkSignInCard
|
||||
isStarting={false}
|
||||
oauthOptions={PROVIDERS}
|
||||
startingStrategy={null}
|
||||
onJoinWaitlist={vi.fn()}
|
||||
onStartOAuth={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
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(
|
||||
<DesktopClerkSignInCard
|
||||
isStarting={false}
|
||||
oauthOptions={[GOOGLE]}
|
||||
startingStrategy={null}
|
||||
onJoinWaitlist={vi.fn()}
|
||||
onStartOAuth={onStartOAuth}
|
||||
/>,
|
||||
);
|
||||
|
||||
await userEvent.click(page.getByRole("button", { name: "Continue with Google" }));
|
||||
|
||||
expect(document.body.textContent).toContain("Continue with Google");
|
||||
expect(onStartOAuth).toHaveBeenCalledWith("oauth_google");
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<DesktopClerkSignInCard
|
||||
isStarting={isStarting}
|
||||
oauthOptions={oauthOptions}
|
||||
startingStrategy={startingStrategy}
|
||||
onJoinWaitlist={onJoinWaitlist}
|
||||
onStartOAuth={(strategy) => 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 (
|
||||
<DesktopClerkCard
|
||||
footerAction={
|
||||
<DesktopClerkFooterAction actionLabel="Join waitlist" onAction={onJoinWaitlist}>
|
||||
Want early access?
|
||||
</DesktopClerkFooterAction>
|
||||
}
|
||||
>
|
||||
<DesktopClerkHeader
|
||||
title="Sign in to T3 Code"
|
||||
subtitle="Welcome back! Please sign in to continue"
|
||||
/>
|
||||
{oauthOptions.length === 0 ? (
|
||||
<DesktopClerkAlert>No OAuth providers are enabled for desktop sign-in.</DesktopClerkAlert>
|
||||
) : (
|
||||
<DesktopClerkSocialButtons
|
||||
isStarting={isStarting}
|
||||
oauthOptions={oauthOptions}
|
||||
startingStrategy={startingStrategy}
|
||||
onStartOAuth={onStartOAuth}
|
||||
/>
|
||||
)}
|
||||
</DesktopClerkCard>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopClerkSocialButtons({
|
||||
isStarting,
|
||||
oauthOptions,
|
||||
startingStrategy,
|
||||
onStartOAuth,
|
||||
}: {
|
||||
isStarting: boolean;
|
||||
oauthOptions: readonly DesktopCloudAuthOAuthOption[];
|
||||
startingStrategy: DesktopCloudAuthOAuthStrategy | null;
|
||||
onStartOAuth: (strategy: DesktopCloudAuthOAuthStrategy) => void;
|
||||
}) {
|
||||
const useBlockButtons = oauthOptions.length <= 2;
|
||||
|
||||
return (
|
||||
<div className={cn("grid gap-2", useBlockButtons ? "grid-cols-1" : "grid-cols-3")}>
|
||||
{oauthOptions.map((option) => {
|
||||
const isCurrent = option.strategy === startingStrategy;
|
||||
return (
|
||||
<button
|
||||
key={option.strategy}
|
||||
type="button"
|
||||
aria-label={`Continue with ${option.label}`}
|
||||
className={cn(
|
||||
"flex h-10 cursor-pointer items-center justify-center rounded-md border border-input bg-popover px-3 text-sm font-semibold text-foreground shadow-xs outline-none transition-colors hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring/20 disabled:pointer-events-none disabled:opacity-64",
|
||||
useBlockButtons && "w-full",
|
||||
)}
|
||||
disabled={isStarting}
|
||||
onClick={() => onStartOAuth(option.strategy)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"flex min-w-0 items-center justify-center gap-3",
|
||||
useBlockButtons && "w-full",
|
||||
)}
|
||||
>
|
||||
{isCurrent ? (
|
||||
<LoaderCircleIcon className="size-4 animate-spin opacity-70" />
|
||||
) : (
|
||||
<DesktopClerkProviderIcon option={option} />
|
||||
)}
|
||||
{useBlockButtons ? (
|
||||
<span className="truncate">
|
||||
{oauthOptions.length === 1 ? `Continue with ${option.label}` : option.label}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopClerkProviderIcon({ option }: { option: DesktopCloudAuthOAuthOption }) {
|
||||
if (!option.iconUrl) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className="flex size-4 shrink-0 items-center justify-center rounded bg-muted text-[9px] font-bold text-muted-foreground"
|
||||
>
|
||||
{option.label.slice(0, 1).toUpperCase()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (["apple", "github", "vercel"].includes(option.providerId)) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className="size-4 shrink-0 bg-foreground"
|
||||
style={{
|
||||
WebkitMask: `url(${option.iconUrl}) center / cover no-repeat`,
|
||||
mask: `url(${option.iconUrl}) center / cover no-repeat`,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <img alt="" aria-hidden className="size-4 shrink-0" src={option.iconUrl} />;
|
||||
}
|
||||
@@ -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<DesktopClerkScreen>("waitlist");
|
||||
|
||||
if (screen === "sign-in") {
|
||||
return <DesktopClerkSignIn onJoinWaitlist={() => setScreen("waitlist")} />;
|
||||
}
|
||||
|
||||
return <DesktopClerkWaitlistForm onSignIn={() => setScreen("sign-in")} />;
|
||||
}
|
||||
|
||||
function DesktopClerkWaitlistForm({ onSignIn }: { onSignIn: () => void }) {
|
||||
const clerk = useClerk();
|
||||
const [emailAddress, setEmailAddress] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [didJoin, setDidJoin] = useState(false);
|
||||
|
||||
const submitWaitlist = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await clerk.joinWaitlist({ emailAddress });
|
||||
setDidJoin(true);
|
||||
} catch (cause) {
|
||||
setError(getClerkErrorMessage(cause));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (didJoin) {
|
||||
return (
|
||||
<DesktopClerkCard>
|
||||
<DesktopClerkHeader
|
||||
title="Thanks for joining the waitlist!"
|
||||
subtitle="We’ll be in touch when your spot is ready"
|
||||
/>
|
||||
</DesktopClerkCard>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DesktopClerkCard
|
||||
footerAction={
|
||||
<DesktopClerkFooterAction actionLabel="Sign in" onAction={onSignIn}>
|
||||
Already have access?
|
||||
</DesktopClerkFooterAction>
|
||||
}
|
||||
>
|
||||
<DesktopClerkHeader
|
||||
title="Join the waitlist"
|
||||
subtitle="Enter your email address and we’ll let you know when your spot is ready"
|
||||
/>
|
||||
<DesktopClerkAlert>{error}</DesktopClerkAlert>
|
||||
<form className="space-y-8 text-left" onSubmit={submitWaitlist}>
|
||||
<label className="block space-y-2" htmlFor="desktop-clerk-waitlist-email">
|
||||
<span className="text-sm font-semibold text-foreground">Email address</span>
|
||||
<DesktopClerkInput
|
||||
required
|
||||
autoComplete="email"
|
||||
id="desktop-clerk-waitlist-email"
|
||||
name="emailAddress"
|
||||
placeholder="Enter your email address"
|
||||
type="email"
|
||||
value={emailAddress}
|
||||
onChange={(event) => setEmailAddress(event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
<DesktopClerkPrimaryButton disabled={isSubmitting}>
|
||||
{isSubmitting ? "Joining the waitlist…" : "Join the waitlist"}
|
||||
</DesktopClerkPrimaryButton>
|
||||
</form>
|
||||
</DesktopClerkCard>
|
||||
);
|
||||
}
|
||||
|
||||
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.";
|
||||
}
|
||||
@@ -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<T>(
|
||||
operation: () => Promise<T>,
|
||||
message: string,
|
||||
): Promise<T> {
|
||||
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<DesktopCloudAuthOAuthStrategy | null>(
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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<T>(operation: () => Promise<T>, message: string): Promise<T> {
|
||||
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 (
|
||||
<SettingsPageContainer className="min-h-full items-center justify-center">
|
||||
<Waitlist />
|
||||
{isElectron ? (
|
||||
<div className="flex flex-col items-center gap-3 text-xs text-muted-foreground">
|
||||
<p>Already approved? Sign in through the desktop app.</p>
|
||||
<DesktopCloudSignInButton />
|
||||
</div>
|
||||
) : null}
|
||||
{isElectron ? <DesktopClerkWaitlist /> : <Waitlist />}
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
@@ -244,173 +209,3 @@ function CloudSettingsPanelInner() {
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopCloudSignInButton() {
|
||||
const clerk = useClerk();
|
||||
const { setActive } = clerk;
|
||||
const { isLoaded: signInLoaded, signIn } = useSignIn();
|
||||
const { isLoaded: signUpLoaded, signUp } = useSignUp();
|
||||
const [startingStrategy, setStartingStrategy] = useState<DesktopCloudAuthOAuthStrategy | null>(
|
||||
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 (
|
||||
<Button disabled size="sm">
|
||||
No OAuth providers enabled
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap justify-end gap-2">
|
||||
{oauthOptions.map((option) => (
|
||||
<Button
|
||||
key={option.strategy}
|
||||
disabled={isStarting}
|
||||
onClick={() => void startOAuth(option.strategy)}
|
||||
size="sm"
|
||||
>
|
||||
{startingStrategy === option.strategy ? "Opening..." : `Continue with ${option.label}`}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user