1import { createEffect, createResource, createSignal, For, onCleanup, onMount, Show } from "solid-js";
2import { authReason, authRequest } from "../auth.ts";
3import ArrowLeft from "lucide-solid/icons/arrow-left";
4import atprotoIcon from "../sso/atproto.svg?raw";
5import Stone from "lucide-solid/icons/stone";
6import githubIcon from "../sso/github.svg";
7import theme from "../sso/css/styles.css?inline";
8import adjustments from "./SignIn.css?inline";
9
10export function SignIn() {
11 const params = new URLSearchParams(window.location.search);
12 const setup = params.get("setup");
13 const atproto = !setup && params.has("atproto");
14 const statusQuery = new URLSearchParams();
15 if (setup) statusQuery.set("setup", setup);
16 if (params.get("flow")) statusQuery.set("flow", params.get("flow")!);
17 if (params.get("next")) statusQuery.set("next", params.get("next")!);
18 const [status, { refetch }] = createResource(() => authRequest<{ csrf: string; service: string; setup?: string; providers?: { id: string; name: string }[] }>(`status?${statusQuery}`));
19 const [username, setUsername] = createSignal("");
20 const [password, setPassword] = createSignal("");
21 const [email, setEmail] = createSignal("");
22 const [passwordStep, setPasswordStep] = createSignal(false);
23 const [visible, setVisible] = createSignal(false);
24 const [busy, setBusy] = createSignal(false);
25 const [error, setError] = createSignal(params.has("guest_error") ? (params.get("guest_error") === "denied" ? "That account can't sign in here. Ask Clover for access." : atproto ? "Sign-in couldn't start. Check your handle and try again." : "Sign-in wasn't completed. Choose a provider to try again.") : "");
26 const [notice, setNotice] = createSignal("");
27 let conditional: AbortController | undefined;
28 let disposed = false;
29 const body = () => ({ csrf: status()!.csrf, username: username(), password: password(), email: email(), setup,
30 remember: false, flow: params.get("flow") ?? "", next: params.get("next") ?? "/" });
31 const passkey = async (automatic = false) => {
32 if (!status() || busy()) return;
33 conditional?.abort();
34 if (!automatic) { setBusy(true); setError(""); setNotice(""); }
35 const controller = new AbortController();
36 conditional = controller;
37 let selected = false;
38 try {
39 const request = { ...body(), username: automatic ? "" : username() };
40 const { options, token } = await authRequest<{ options: { publicKey: PublicKeyCredentialRequestOptionsJSON }; token: string }>("passkey/start", request);
41 if (controller.signal.aborted || disposed) return;
42 const credential = await navigator.credentials.get({
43 publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options.publicKey),
44 mediation: automatic ? "conditional" : "optional", signal: controller.signal,
45 });
46 if (!(credential instanceof PublicKeyCredential)) throw new Error("Passkey sign-in was canceled. Try again or use your password.");
47 selected = true; setBusy(true);
48 const result = await authRequest<{ next: string }>("passkey/finish", { csrf: request.csrf, token, remember: false, credential: credential.toJSON() });
49 window.location.assign(result.next);
50 } catch (failure) {
51 if ((!automatic || selected) && !controller.signal.aborted) setError(authReason(failure));
52 } finally { if (!automatic || selected) setBusy(false); }
53 };
54 createEffect(() => {
55 if (!setup && !atproto && !passwordStep() && status()) void (async () => {
56 if (await PublicKeyCredential.isConditionalMediationAvailable?.() && !disposed && !passwordStep()) await passkey(true);
57 })().catch(() => {});
58 });
59 const complete = async () => {
60 if (!status() || busy()) return;
61 conditional?.abort(); setError(""); setNotice("");
62 if (!setup && !passwordStep()) {
63 if (!username().trim()) return;
64 setUsername(username().trim());
65 setPasswordStep(true);
66 return;
67 }
68 setBusy(true);
69 try {
70 const result = await authRequest<{ next: string }>(setup ? "setup" : "password", body());
71 window.location.assign(result.next);
72 } catch (failure) { setError(authReason(failure)); }
73 finally { setBusy(false); }
74 };
75 onMount(() => {
76 const title = document.title;
77 document.title = "sso (snow sign on)";
78 onCleanup(() => { document.title = title; });
79 });
80 onCleanup(() => { disposed = true; conditional?.abort(); });
81 return (
82 <>
83 <style>{theme + adjustments}</style>
84 <main class="pf-v5-c-login__main">
85 <div id="kc-header"><div id="kc-header-wrapper"><div class="kc-logo-text"><span>snow sign on</span></div></div></div>
86 <div class="card-pf">
87 <header><h1 id="kc-page-title">{setup ? "welcome" : `sign in to ${status()?.service?.toLowerCase() ?? "snow globe"}`}</h1></header>
88 <div id="kc-content"><div id="kc-content-wrapper">
89 <Show when={status.error || error()}><div class="alert-error pf-v5-c-alert" role="alert"><span class="pf-v5-c-alert__title">{status.error ? authReason(status.error) : error()}</span></div></Show>
90 <Show when={notice()}><div class="alert-info pf-v5-c-alert" role="status"><span class="pf-v5-c-alert__title">{notice()}</span></div></Show>
91 <Show when={!status.error} fallback={<button class="pf-v5-c-button pf-m-primary pf-m-block" onClick={() => refetch()}>try again</button>}>
92 <Show when={!atproto} fallback={
93 <form action="/auth/guest/start/atproto" method="get" onSubmit={(event) => { if (busy()) { event.preventDefault(); return; } setBusy(true); setError(""); }}>
94 <div class="sign-in-account"><a rel="external" href={`/sign-in?${statusQuery}`}><ArrowLeft size={18} aria-hidden="true" />back</a></div>
95 <input type="hidden" name="next" value={params.get("next") ?? ""} />
96 <div class="pf-v5-c-form__group">
97 <label for="atproto-identifier" class="pf-v5-c-form__label">at protocol handle</label>
98 <input id="atproto-identifier" name="identifier" class="pf-v5-c-form-control" required maxlength={2048} autocomplete="username" autocapitalize="none" spellcheck={false} placeholder="you.bsky.social" aria-describedby="atproto-hint" autofocus ref={(input) => queueMicrotask(() => input.focus())} />
99 <span id="atproto-hint" class="pf-v5-c-helper-text__item-text">requires an existing <a href="https://atproto.com" target="_blank" rel="noopener noreferrer">AT Protocol</a> account.</span>
100 </div>
101 <div id="kc-form-buttons" class="pf-v5-c-form__group"><button class="pf-v5-c-button pf-m-primary pf-m-block" type="submit" disabled={busy() || !status()} aria-busy={busy()}>{busy() ? "connecting…" : "continue"}</button></div>
102 </form>
103 }>
104 <Show when={!setup && !passwordStep() && status()?.providers?.length}>
105 <div id="kc-social-providers" class="guest-providers">
106 <For each={status()?.providers}>{(provider) => <a rel="external" data-provider={provider.id} class="pf-v5-c-button pf-m-primary pf-m-block" href={provider.id === "atproto" ? `/sign-in?${statusQuery}&atproto=1` : `/auth/guest/start/${provider.id}?${new URLSearchParams({ next: params.get("next") ?? "", flow: params.get("flow") ?? "" })}`}>{provider.id === "atproto" ? <span innerHTML={atprotoIcon} /> : provider.id === "astheno" ? <Stone size={18} aria-hidden="true" /> : <img src={githubIcon} width="18" height="18" alt="" />}<span>continue with {provider.name}</span></a>}</For>
107 </div>
108 </Show>
109 <div id="kc-form"><div id="kc-form-wrapper">
110 <form id="kc-form-login" onSubmit={(event) => { event.preventDefault(); void complete(); }}>
111 <Show when={setup} fallback={
112 <Show when={!passwordStep()} fallback={<div class="sign-in-account"><button type="button" onClick={() => { setPassword(""); setVisible(false); setError(""); setNotice(""); setPasswordStep(false); }}><ArrowLeft size={18} aria-hidden="true" />back</button><h2>{username()}</h2><input name="username" type="hidden" autocomplete="username" value={username()} /></div>}>
113 <div class="pf-v5-c-form__group">
114 <label for="username" class="pf-v5-c-form__label">username or email</label>
115 <input id="username" class="pf-v5-c-form-control" name="username" type="text" required autocomplete="username webauthn" value={username()} onInput={(event) => setUsername(event.currentTarget.value)} autofocus ref={(input) => queueMicrotask(() => input.focus())} />
116 </div>
117 </Show>
118 }>
119 <p class="setup-intro">Your account is <b>{status()?.setup ?? "…"}</b>. Add your email and choose a password.</p>
120 <div class="pf-v5-c-form__group">
121 <label for="email" class="pf-v5-c-form__label">email</label>
122 <input id="email" class="pf-v5-c-form-control" name="email" type="email" required autocomplete="email" value={email()} onInput={(event) => setEmail(event.currentTarget.value)} autofocus />
123 </div>
124 </Show>
125 <Show when={setup || passwordStep()}>
126 <div class="pf-v5-c-form__group">
127 <label for="password" class="pf-v5-c-form__label">{setup ? "choose a password" : "password"}</label>
128 <div class="pf-v5-c-input-group">
129 <input id="password" class="pf-v5-c-form-control" name="password" type={visible() ? "text" : "password"} required minLength={setup ? 8 : undefined} maxLength={1024} autocomplete={setup ? "new-password" : "current-password"} value={password()} onInput={(event) => setPassword(event.currentTarget.value)} ref={(input) => { if (!setup) queueMicrotask(() => input.focus()); }} />
130 <button class="pf-v5-c-button pf-m-control" type="button" aria-label={visible() ? "Hide password" : "Show password"} aria-controls="password" data-password-toggle onClick={() => setVisible(!visible())}><i aria-hidden="true" /></button>
131 </div>
132 <Show when={setup}><span class="pf-v5-c-helper-text__item-text">Use at least 8 characters. You can add a passkey next.</span></Show>
133 </div>
134 <Show when={!setup}><div class="pf-v5-c-form__group">
135 <div><span><a href="#" onClick={(event) => { event.preventDefault(); setNotice("Ask Clover for a password reset link."); }}>forgot password?</a></span></div>
136 </div></Show>
137 </Show>
138 <div id="kc-form-buttons" class="pf-v5-c-form__group">
139 <input class="pf-v5-c-button pf-m-primary pf-m-block" name="login" id="kc-login" type="submit" value={setup ? "create account" : "sign in"} disabled={busy() || !status()} aria-busy={busy()} />
140 </div>
141 </form>
142 </div></div>
143 <Show when={!setup}><a id="authenticateWebAuthnButton" href="#" class="pf-v5-c-button pf-m-secondary pf-m-block" aria-disabled={busy() || !status()} onClick={(event) => { event.preventDefault(); void passkey(); }}>sign in with passkey</a></Show>
144 </Show>
145
146 </Show>
147 </div></div>
148 </div>
149 </main>
150 <div id="credit"><a rel="noopener noreferrer" target="_blank" href="https://www.pixiv.net/en/artworks/109102745">art by 紺屋</a></div>
151 </>
152 );
153}