@flaredev/cli 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/bin/flare.js +9 -1
  2. package/dist/index.js +985 -337
  3. package/package.json +3 -2
  4. package/templates/app/app/admin/page.tsx +9 -61
  5. package/templates/app/app/api/openapi.json/route.ts +23 -0
  6. package/templates/app/app/api/reference/route.ts +36 -0
  7. package/templates/app/app/dashboard/account/page.tsx +40 -0
  8. package/templates/app/app/{admin → dashboard}/actions.ts +109 -11
  9. package/templates/app/app/dashboard/import-actions.ts +91 -0
  10. package/templates/app/app/dashboard/layout.tsx +42 -0
  11. package/templates/app/app/dashboard/observability/page.tsx +174 -0
  12. package/templates/app/app/dashboard/page.tsx +123 -9
  13. package/templates/app/app/forgot-password/page.tsx +22 -0
  14. package/templates/app/app/globals.css +109 -4
  15. package/templates/app/app/layout.tsx +28 -26
  16. package/templates/app/app/page.tsx +126 -13
  17. package/templates/app/app/reset-password/page.tsx +31 -0
  18. package/templates/app/app/sign-in/page.tsx +49 -33
  19. package/templates/app/app/sign-up/page.tsx +42 -23
  20. package/templates/app/app/two-factor/page.tsx +25 -0
  21. package/templates/app/app/verify-email/page.tsx +33 -0
  22. package/templates/app/components/account/security-settings.tsx +522 -0
  23. package/templates/app/components/auth/auth-shell.tsx +284 -0
  24. package/templates/app/components/auth/otp-input.tsx +95 -0
  25. package/templates/app/components/auth/password-field.tsx +116 -0
  26. package/templates/app/components/auth/password-forms.tsx +76 -0
  27. package/templates/app/components/auth/provider-icons.tsx +39 -0
  28. package/templates/app/components/auth/sign-in-flow.tsx +306 -0
  29. package/templates/app/components/auth/sign-up-form.tsx +93 -0
  30. package/templates/app/components/auth/social-buttons.tsx +56 -0
  31. package/templates/app/components/auth/two-factor-form.tsx +139 -0
  32. package/templates/app/components/auth/ui.tsx +96 -0
  33. package/templates/app/components/auth/use-resend.ts +44 -0
  34. package/templates/app/components/auth/verify-email-form.tsx +135 -0
  35. package/templates/app/components/{admin/admin-header.tsx → dashboard/dashboard-header.tsx} +78 -78
  36. package/templates/app/components/{admin/resource-nav.tsx → dashboard/dashboard-sidebar.tsx} +66 -9
  37. package/templates/app/components/dashboard/export-button.tsx +41 -0
  38. package/templates/app/components/dashboard/fields/country-field.tsx +152 -0
  39. package/templates/app/components/{admin → dashboard}/fields/field-widget.tsx +186 -128
  40. package/templates/app/components/{admin → dashboard}/fields/file-field.tsx +302 -302
  41. package/templates/app/components/dashboard/fields/multi-select-field.tsx +46 -0
  42. package/templates/app/components/dashboard/fields/phone-field.tsx +86 -0
  43. package/templates/app/components/dashboard/import-dialog.tsx +487 -0
  44. package/templates/app/components/dashboard/page-header.tsx +57 -0
  45. package/templates/app/components/dashboard/resource-form-dialog.tsx +80 -0
  46. package/templates/app/components/{admin → dashboard}/resource-form-page.tsx +61 -55
  47. package/templates/app/components/{admin → dashboard}/resource-form.tsx +165 -139
  48. package/templates/app/components/dashboard/resource-stats.tsx +53 -0
  49. package/templates/app/components/{admin → dashboard}/resource-table.tsx +331 -251
  50. package/templates/app/components/{admin → dashboard}/row-actions.tsx +144 -111
  51. package/templates/app/components/dashboard/stat-card.tsx +69 -0
  52. package/templates/app/components/dashboard/table-selection.tsx +185 -0
  53. package/templates/app/components/dashboard/traffic-chart.tsx +32 -0
  54. package/templates/app/components/marketing/product-preview.tsx +70 -0
  55. package/templates/app/components/marketing/site-header.tsx +39 -0
  56. package/templates/app/components/sign-out-button.tsx +1 -1
  57. package/templates/app/components/ui/checkbox.tsx +25 -0
  58. package/templates/app/components/ui/radio-group.tsx +29 -0
  59. package/templates/app/db/auth-schema.ts +167 -118
  60. package/templates/app/db/flare-schema.ts +33 -1
  61. package/templates/app/lib/analytics.ts +121 -0
  62. package/templates/app/lib/api-docs.ts +16 -0
  63. package/templates/app/lib/audit.ts +80 -0
  64. package/templates/app/lib/auth-client.ts +16 -1
  65. package/templates/app/lib/auth-config.ts +38 -0
  66. package/templates/app/lib/auth-emails.ts +94 -0
  67. package/templates/app/lib/auth.ts +115 -6
  68. package/templates/app/lib/cache.ts +83 -83
  69. package/templates/app/lib/csv.ts +24 -0
  70. package/templates/app/lib/dashboard-nav.ts +15 -0
  71. package/templates/app/lib/{admin.ts → dashboard.ts} +138 -103
  72. package/templates/app/lib/password-rules.ts +159 -0
  73. package/templates/app/lib/site.ts +56 -0
  74. package/templates/app/lib/theme.ts +79 -0
  75. package/templates/app/migrations/0000_init.sql +47 -4
  76. package/templates/app/migrations/meta/0000_snapshot.json +311 -1
  77. package/templates/app/migrations/meta/_journal.json +1 -1
  78. package/templates/app/vite.config.ts +5 -3
  79. package/templates/app/worker-configuration.d.ts +15764 -0
  80. package/templates/locks/package-lock.json +9189 -0
  81. package/templates/locks/pnpm-lock.yaml +6347 -0
  82. package/templates/app/app/admin/layout.tsx +0 -32
  83. package/templates/app/components/auth-form.tsx +0 -120
  84. package/templates/app/lib/admin-nav.ts +0 -15
  85. /package/templates/app/components/{admin → dashboard}/fields/date-field.tsx +0 -0
  86. /package/templates/app/components/{admin → dashboard}/fields/relation-field.tsx +0 -0
  87. /package/templates/app/components/{admin → dashboard}/query.ts +0 -0
  88. /package/templates/app/components/{admin → dashboard}/resource-icon.tsx +0 -0
  89. /package/templates/app/components/{admin → dashboard}/resource-table-toolbar.tsx +0 -0
@@ -0,0 +1,306 @@
1
+ "use client";
2
+
3
+ import { useEffect, useRef, useState } from "react";
4
+ import Link from "next/link";
5
+ import { FingerprintIcon, MailIcon, KeyRoundIcon } from "lucide-react";
6
+ import { authClient } from "@/lib/auth-client";
7
+ import type { SocialProvider } from "@/lib/auth-config";
8
+ import { AuthInput, AuthLabel, Divider, FormMessage, PrimaryButton, SecondaryButton, TextButton } from "./ui";
9
+ import { OtpInput } from "./otp-input";
10
+ import { SocialButtons } from "./social-buttons";
11
+ import { useResend } from "./use-resend";
12
+
13
+ export interface SignInMethods {
14
+ magicLink: boolean;
15
+ emailOtp: boolean;
16
+ passkeys: boolean;
17
+ }
18
+
19
+ interface Props {
20
+ providers: SocialProvider[];
21
+ socialPlacement: "before" | "after";
22
+ socialStyle: "full" | "icon";
23
+ methods: SignInMethods;
24
+ next: string;
25
+ initialError?: string | null;
26
+ initialNotice?: string | null;
27
+ }
28
+
29
+ type Step = "email" | "password" | "link-sent" | "code";
30
+
31
+ /** Messages for Better Auth's error codes, written for the person signing in. */
32
+ export function authErrorMessage(error: { code?: string; message?: string } | null | undefined, fallback = "Something went wrong. Try again."): string {
33
+ switch (error?.code) {
34
+ case "INVALID_EMAIL_OR_PASSWORD":
35
+ return "That email and password don't match.";
36
+ case "EMAIL_NOT_VERIFIED":
37
+ return "Verify your email first: we've sent you a new link.";
38
+ case "INVALID_OTP":
39
+ case "INVALID_CODE":
40
+ case "INVALID_TWO_FACTOR_CODE":
41
+ return "That code isn't right. Check it and try again.";
42
+ case "OTP_EXPIRED":
43
+ return "That code has expired. Ask for a new one.";
44
+ case "TOO_MANY_ATTEMPTS":
45
+ return "Too many attempts. Ask for a new code.";
46
+ case "USER_ALREADY_EXISTS":
47
+ case "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL":
48
+ return "An account with this email already exists. Sign in instead.";
49
+ case "PASSWORD_TOO_SHORT":
50
+ return "Use at least 8 characters.";
51
+ default:
52
+ return error?.message || fallback;
53
+ }
54
+ }
55
+
56
+ const go = (next: string) => {
57
+ window.location.href = next;
58
+ };
59
+
60
+ /**
61
+ * Sign-in in two steps: the email first (with social and passkey sign-in beside it),
62
+ * then the password or an emailed link or code. A password sign-in that needs a
63
+ * second factor continues on /two-factor (see lib/auth-client.ts).
64
+ */
65
+ export function SignInFlow({ providers, socialPlacement, socialStyle, methods, next, initialError, initialNotice }: Props) {
66
+ const [step, setStep] = useState<Step>("email");
67
+ const [email, setEmail] = useState("");
68
+ const [password, setPassword] = useState("");
69
+ const [code, setCode] = useState("");
70
+ const [pending, setPending] = useState<string | null>(null);
71
+ const [error, setError] = useState<string | null>(initialError ?? null);
72
+ const [notice, setNotice] = useState<string | null>(initialNotice ?? null);
73
+ const passwordRef = useRef<HTMLInputElement>(null);
74
+
75
+ // Offer saved passkeys in the email field's autofill (conditional UI), where supported.
76
+ useEffect(() => {
77
+ if (!methods.passkeys || typeof PublicKeyCredential === "undefined") return;
78
+ let cancelled = false;
79
+ PublicKeyCredential.isConditionalMediationAvailable?.().then((available) => {
80
+ if (!available || cancelled) return;
81
+ void authClient.signIn.passkey({ autoFill: true }).then(({ error }) => {
82
+ if (!error) go(next);
83
+ });
84
+ });
85
+ return () => {
86
+ cancelled = true;
87
+ };
88
+ }, [methods.passkeys, next]);
89
+
90
+ useEffect(() => {
91
+ if (step === "password") passwordRef.current?.focus();
92
+ }, [step]);
93
+
94
+ const run = async (label: string, work: () => Promise<void>) => {
95
+ setPending(label);
96
+ setError(null);
97
+ setNotice(null);
98
+ try {
99
+ await work();
100
+ } finally {
101
+ setPending(null);
102
+ }
103
+ };
104
+
105
+ const signInWithPassword = () =>
106
+ run("password", async () => {
107
+ const { data, error } = await authClient.signIn.email({ email, password });
108
+ if (error) return setError(authErrorMessage(error));
109
+ // With two-factor on, the client plugin has already sent us to /two-factor.
110
+ if (data && "twoFactorRedirect" in data && data.twoFactorRedirect) return;
111
+ go(next);
112
+ });
113
+
114
+ const sendLink = () =>
115
+ run("link", async () => {
116
+ const { error } = await authClient.signIn.magicLink({ email, callbackURL: next, errorCallbackURL: "/sign-in?error=link" });
117
+ if (error) return setError(authErrorMessage(error));
118
+ setStep("link-sent");
119
+ });
120
+
121
+ const sendCode = () =>
122
+ run("code", async () => {
123
+ const { error } = await authClient.emailOtp.sendVerificationOtp({ email, type: "sign-in" });
124
+ if (error) return setError(authErrorMessage(error));
125
+ setCode("");
126
+ setStep("code");
127
+ });
128
+
129
+ // Resending leaves the code already in their inbox working; it just sends another.
130
+ const codeResend = useResend(sendCode);
131
+
132
+ const signInWithCode = () =>
133
+ run("verify", async () => {
134
+ const { error } = await authClient.signIn.emailOtp({ email, otp: code.trim() });
135
+ if (error) return setError(authErrorMessage(error));
136
+ go(next);
137
+ });
138
+
139
+ const signInWithPasskey = () =>
140
+ run("passkey", async () => {
141
+ const { error } = await authClient.signIn.passkey();
142
+ if (error) return setError(authErrorMessage(error, "That passkey didn't work. Try again or use your email."));
143
+ go(next);
144
+ });
145
+
146
+ const social = (
147
+ <SocialButtons providers={providers} variant={socialStyle} next={next} onError={setError} />
148
+ );
149
+ const hasSocial = providers.length > 0;
150
+ const changeEmail = (
151
+ <div className="flex items-center justify-between rounded-[calc(var(--radius)-2px)] bg-surface-muted px-3.5 py-2.5 text-sm">
152
+ <span className="truncate text-foreground">{email}</span>
153
+ <TextButton onClick={() => setStep("email")}>Change</TextButton>
154
+ </div>
155
+ );
156
+
157
+ if (step === "link-sent") {
158
+ return (
159
+ <div className="flex flex-col gap-5 text-center">
160
+ <span className="mx-auto grid size-12 place-items-center rounded-full bg-brand/15 text-link">
161
+ <MailIcon className="size-6" />
162
+ </span>
163
+ <div className="flex flex-col gap-1.5">
164
+ <p className="text-base font-medium text-foreground">Check your email</p>
165
+ <p className="text-sm text-foreground-muted">
166
+ We sent a sign-in link to <span className="font-medium text-foreground">{email}</span>. It works once and expires in 5 minutes.
167
+ </p>
168
+ </div>
169
+ <FormMessage>{error}</FormMessage>
170
+ <div className="flex justify-center gap-4">
171
+ <TextButton onClick={sendLink} disabled={pending !== null}>Send it again</TextButton>
172
+ <TextButton onClick={() => setStep("email")}>Use another email</TextButton>
173
+ </div>
174
+ </div>
175
+ );
176
+ }
177
+
178
+ if (step === "code") {
179
+ return (
180
+ <form
181
+ className="flex flex-col gap-4"
182
+ onSubmit={(event) => {
183
+ event.preventDefault();
184
+ void signInWithCode();
185
+ }}
186
+ >
187
+ <p className="text-sm text-foreground-muted">
188
+ Enter the 6-digit code we sent to <span className="font-medium text-foreground">{email}</span>.
189
+ </p>
190
+ <OtpInput value={code} onChange={setCode} onComplete={() => void signInWithCode()} label="Sign-in code" autoFocus disabled={pending === "verify"} />
191
+ <FormMessage>{error}</FormMessage>
192
+ <PrimaryButton type="submit" pending={pending === "verify"} disabled={code.length !== 6}>
193
+ Sign in
194
+ </PrimaryButton>
195
+ <div className="flex justify-center gap-4">
196
+ <TextButton onClick={() => void codeResend.resend()} disabled={codeResend.disabled || pending !== null}>
197
+ {codeResend.label}
198
+ </TextButton>
199
+ <TextButton onClick={() => setStep("email")}>Use another email</TextButton>
200
+ </div>
201
+ </form>
202
+ );
203
+ }
204
+
205
+ if (step === "password") {
206
+ return (
207
+ <form
208
+ className="flex flex-col gap-4"
209
+ onSubmit={(event) => {
210
+ event.preventDefault();
211
+ void signInWithPassword();
212
+ }}
213
+ >
214
+ {changeEmail}
215
+ {/* Keeps the email with the password for password managers. */}
216
+ <input type="email" name="email" value={email} autoComplete="username" readOnly hidden />
217
+ <div className="flex flex-col gap-2">
218
+ <div className="flex items-baseline justify-between">
219
+ <AuthLabel htmlFor="password">Password</AuthLabel>
220
+ <Link href={`/forgot-password?email=${encodeURIComponent(email)}`} className="text-sm text-link hover:underline">
221
+ Forgot password?
222
+ </Link>
223
+ </div>
224
+ <AuthInput
225
+ ref={passwordRef}
226
+ id="password"
227
+ name="password"
228
+ type="password"
229
+ autoComplete="current-password"
230
+ value={password}
231
+ onChange={(event) => setPassword(event.target.value)}
232
+ required
233
+ aria-invalid={Boolean(error) || undefined}
234
+ />
235
+ </div>
236
+ <FormMessage>{error}</FormMessage>
237
+ <PrimaryButton type="submit" pending={pending === "password"}>
238
+ Sign in
239
+ </PrimaryButton>
240
+ {(methods.magicLink || methods.emailOtp) && (
241
+ <>
242
+ <Divider />
243
+ {methods.magicLink && (
244
+ <SecondaryButton onClick={sendLink} disabled={pending !== null}>
245
+ <MailIcon className="size-4" /> Email me a sign-in link
246
+ </SecondaryButton>
247
+ )}
248
+ {methods.emailOtp && (
249
+ <SecondaryButton onClick={sendCode} disabled={pending !== null}>
250
+ <KeyRoundIcon className="size-4" /> Email me a code
251
+ </SecondaryButton>
252
+ )}
253
+ </>
254
+ )}
255
+ </form>
256
+ );
257
+ }
258
+
259
+ return (
260
+ <div className="flex flex-col gap-4">
261
+ {hasSocial && socialPlacement === "before" && (
262
+ <>
263
+ {social}
264
+ <Divider />
265
+ </>
266
+ )}
267
+ <form
268
+ className="flex flex-col gap-4"
269
+ onSubmit={(event) => {
270
+ event.preventDefault();
271
+ setError(null);
272
+ setStep("password");
273
+ }}
274
+ >
275
+ <div className="flex flex-col gap-2">
276
+ <AuthLabel htmlFor="email">Email</AuthLabel>
277
+ <AuthInput
278
+ id="email"
279
+ name="email"
280
+ type="email"
281
+ autoComplete="username webauthn"
282
+ placeholder="you@example.com"
283
+ value={email}
284
+ onChange={(event) => setEmail(event.target.value)}
285
+ required
286
+ autoFocus
287
+ />
288
+ </div>
289
+ <FormMessage tone="success">{notice}</FormMessage>
290
+ <FormMessage>{error}</FormMessage>
291
+ <PrimaryButton type="submit">Continue</PrimaryButton>
292
+ </form>
293
+ {methods.passkeys && (
294
+ <SecondaryButton onClick={signInWithPasskey} disabled={pending !== null}>
295
+ <FingerprintIcon className="size-4" /> Sign in with a passkey
296
+ </SecondaryButton>
297
+ )}
298
+ {hasSocial && socialPlacement === "after" && (
299
+ <>
300
+ <Divider />
301
+ {social}
302
+ </>
303
+ )}
304
+ </div>
305
+ );
306
+ }
@@ -0,0 +1,93 @@
1
+ "use client";
2
+
3
+ import { useState } from "react";
4
+ import { MailIcon } from "lucide-react";
5
+ import { authClient } from "@/lib/auth-client";
6
+ import type { SocialProvider } from "@/lib/auth-config";
7
+ import { checkPassword } from "@/lib/password-rules";
8
+ import { PasswordField } from "./password-field";
9
+ import { authErrorMessage } from "./sign-in-flow";
10
+ import { SocialButtons } from "./social-buttons";
11
+ import { AuthInput, AuthLabel, Divider, FormMessage, PrimaryButton } from "./ui";
12
+
13
+ interface Props {
14
+ providers: SocialProvider[];
15
+ socialPlacement: "before" | "after";
16
+ socialStyle: "full" | "icon";
17
+ next: string;
18
+ /** With email verification required, sign-up ends on "check your email". */
19
+ verifyFirst: boolean;
20
+ }
21
+
22
+ export function SignUpForm({ providers, socialPlacement, socialStyle, next, verifyFirst }: Props) {
23
+ const [values, setValues] = useState({ name: "", email: "", password: "" });
24
+ const [pending, setPending] = useState(false);
25
+ const [error, setError] = useState<string | null>(null);
26
+ const [sent, setSent] = useState(false);
27
+ const set = (key: keyof typeof values) => (event: React.ChangeEvent<HTMLInputElement>) => setValues({ ...values, [key]: event.target.value });
28
+
29
+ const submit = async (event: React.FormEvent) => {
30
+ event.preventDefault();
31
+ setError(null);
32
+ const check = checkPassword(values.password, [values.email, values.name]);
33
+ if (!check.valid) return setError(check.advice ?? "That password is too short.");
34
+ setPending(true);
35
+ const { error } = await authClient.signUp.email({ ...values, callbackURL: next });
36
+ setPending(false);
37
+ if (error) return setError(authErrorMessage(error));
38
+ if (verifyFirst) return setSent(true);
39
+ window.location.href = next;
40
+ };
41
+
42
+ if (sent) {
43
+ return (
44
+ <div className="flex flex-col gap-4 text-center">
45
+ <span className="mx-auto grid size-12 place-items-center rounded-full bg-brand/15 text-link">
46
+ <MailIcon className="size-6" />
47
+ </span>
48
+ <p className="text-base font-medium">Check your email</p>
49
+ <p className="text-sm text-foreground-muted">
50
+ We sent a link to <span className="font-medium text-foreground">{values.email}</span>. Open it to verify your address and sign in.
51
+ </p>
52
+ </div>
53
+ );
54
+ }
55
+
56
+ const social = <SocialButtons providers={providers} variant={socialStyle} next={next} onError={setError} />;
57
+ return (
58
+ <div className="flex flex-col gap-4">
59
+ {providers.length > 0 && socialPlacement === "before" && (
60
+ <>
61
+ {social}
62
+ <Divider />
63
+ </>
64
+ )}
65
+ <form className="flex flex-col gap-4" onSubmit={submit}>
66
+ <div className="flex flex-col gap-2">
67
+ <AuthLabel htmlFor="name">Name</AuthLabel>
68
+ <AuthInput id="name" name="name" autoComplete="name" value={values.name} onChange={set("name")} required autoFocus />
69
+ </div>
70
+ <div className="flex flex-col gap-2">
71
+ <AuthLabel htmlFor="email">Email</AuthLabel>
72
+ <AuthInput id="email" name="email" type="email" autoComplete="email" placeholder="you@example.com" value={values.email} onChange={set("email")} required />
73
+ </div>
74
+ <PasswordField
75
+ id="password"
76
+ value={values.password}
77
+ onChange={(password) => setValues({ ...values, password })}
78
+ avoid={[values.email, values.name]}
79
+ />
80
+ <FormMessage>{error}</FormMessage>
81
+ <PrimaryButton type="submit" pending={pending}>
82
+ Create account
83
+ </PrimaryButton>
84
+ </form>
85
+ {providers.length > 0 && socialPlacement === "after" && (
86
+ <>
87
+ <Divider />
88
+ {social}
89
+ </>
90
+ )}
91
+ </div>
92
+ );
93
+ }
@@ -0,0 +1,56 @@
1
+ "use client";
2
+
3
+ import { useState } from "react";
4
+ import { authClient } from "@/lib/auth-client";
5
+ import type { SocialProvider } from "@/lib/auth-config";
6
+ import { cn } from "@/lib/utils";
7
+ import { PROVIDER_LABELS, ProviderIcon } from "./provider-icons";
8
+
9
+ interface Props {
10
+ providers: SocialProvider[];
11
+ /** "full": a labelled button per provider. "icon": a row of square buttons. */
12
+ variant: "full" | "icon";
13
+ next: string;
14
+ onError: (message: string) => void;
15
+ }
16
+
17
+ /** One button per configured provider; each starts that provider's sign-in and comes back to `next`. */
18
+ export function SocialButtons({ providers, variant, next, onError }: Props) {
19
+ const [pending, setPending] = useState<SocialProvider | null>(null);
20
+ if (providers.length === 0) return null;
21
+
22
+ const start = async (provider: SocialProvider) => {
23
+ setPending(provider);
24
+ const { error } = await authClient.signIn.social({ provider, callbackURL: next, errorCallbackURL: "/sign-in?error=oauth" });
25
+ if (error) {
26
+ setPending(null);
27
+ onError(error.message ?? `Couldn't start ${PROVIDER_LABELS[provider]} sign-in.`);
28
+ }
29
+ };
30
+
31
+ return (
32
+ <div className={cn(variant === "icon" ? "flex justify-center gap-3" : "flex flex-col gap-3")}>
33
+ {providers.map((provider) => (
34
+ <button
35
+ key={provider}
36
+ type="button"
37
+ onClick={() => start(provider)}
38
+ disabled={pending !== null}
39
+ aria-label={variant === "icon" ? `Continue with ${PROVIDER_LABELS[provider]}` : undefined}
40
+ className={cn(
41
+ "inline-flex items-center justify-center gap-2.5 border border-border bg-surface font-medium text-foreground transition-colors hover:bg-surface-muted disabled:opacity-60",
42
+ "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand",
43
+ variant === "icon" ? "size-[74px] rounded-2xl" : "h-11 w-full rounded-[var(--button-radius)] px-4 text-[15px]",
44
+ )}
45
+ >
46
+ {pending === provider ? (
47
+ <span className="size-5 animate-spin rounded-full border-2 border-current border-r-transparent" aria-hidden="true" />
48
+ ) : (
49
+ <ProviderIcon provider={provider} className={variant === "icon" ? "size-6" : "size-5"} />
50
+ )}
51
+ {variant === "full" && `Continue with ${PROVIDER_LABELS[provider]}`}
52
+ </button>
53
+ ))}
54
+ </div>
55
+ );
56
+ }
@@ -0,0 +1,139 @@
1
+ "use client";
2
+
3
+ import { useState } from "react";
4
+ import { authClient } from "@/lib/auth-client";
5
+ import { cn } from "@/lib/utils";
6
+ import { OtpInput } from "./otp-input";
7
+ import { authErrorMessage } from "./sign-in-flow";
8
+ import { useResend } from "./use-resend";
9
+ import { AuthInput, AuthLabel, FormMessage, PrimaryButton, TextButton } from "./ui";
10
+
11
+ type Method = "authenticator" | "email" | "backup";
12
+
13
+ interface Props {
14
+ methods: { authenticator: boolean; email: boolean };
15
+ next: string;
16
+ }
17
+
18
+ const LABELS: Record<Method, string> = { authenticator: "Authenticator app", email: "Email code", backup: "Backup code" };
19
+
20
+ /** The second step of a password sign-in: an authenticator code, an emailed code, or a backup code. */
21
+ export function TwoFactorForm({ methods, next }: Props) {
22
+ const available: Method[] = [...(methods.authenticator ? (["authenticator"] as const) : []), ...(methods.email ? (["email"] as const) : []), "backup"];
23
+ const [method, setMethod] = useState<Method>(available[0]!);
24
+ const [code, setCode] = useState("");
25
+ const [trust, setTrust] = useState(false);
26
+ const [pending, setPending] = useState(false);
27
+ const [error, setError] = useState<string | null>(null);
28
+ const [sent, setSent] = useState(false);
29
+
30
+ const choose = (item: Method) => {
31
+ setMethod(item);
32
+ setCode("");
33
+ setError(null);
34
+ };
35
+
36
+ const sendEmail = async () => {
37
+ setPending(true);
38
+ setError(null);
39
+ const { error } = await authClient.twoFactor.sendOtp();
40
+ setPending(false);
41
+ if (error) return setError(authErrorMessage(error));
42
+ setSent(true);
43
+ };
44
+
45
+ const emailResend = useResend(sendEmail);
46
+
47
+ const verify = async (event?: React.FormEvent) => {
48
+ event?.preventDefault();
49
+ setPending(true);
50
+ setError(null);
51
+ const body = { code: code.trim(), trustDevice: trust };
52
+ const { error } =
53
+ method === "authenticator"
54
+ ? await authClient.twoFactor.verifyTotp(body)
55
+ : method === "email"
56
+ ? await authClient.twoFactor.verifyOtp(body)
57
+ : await authClient.twoFactor.verifyBackupCode(body);
58
+ setPending(false);
59
+ if (error) return setError(authErrorMessage(error));
60
+ window.location.href = next;
61
+ };
62
+
63
+ const waitingForEmail = method === "email" && !sent;
64
+
65
+ return (
66
+ <form className="flex flex-col gap-4" onSubmit={verify}>
67
+ {available.length > 1 && (
68
+ <div role="tablist" aria-label="Verify with" className="grid auto-cols-fr grid-flow-col gap-1 rounded-[calc(var(--radius)+2px)] bg-surface-muted p-1">
69
+ {available.map((item) => (
70
+ <button
71
+ key={item}
72
+ type="button"
73
+ role="tab"
74
+ aria-selected={method === item}
75
+ onClick={() => choose(item)}
76
+ className={cn("rounded-[var(--radius)] px-2 py-1.5 text-xs font-medium text-foreground-muted", method === item && "bg-surface text-foreground shadow-sm")}
77
+ >
78
+ {LABELS[item]}
79
+ </button>
80
+ ))}
81
+ </div>
82
+ )}
83
+ <p className="text-sm text-foreground-muted">
84
+ {method === "authenticator" && "Open your authenticator app and enter the 6-digit code for this account."}
85
+ {method === "email" && (sent ? "We sent a 6-digit code to your email." : "We'll email you a 6-digit code.")}
86
+ {method === "backup" && "Enter one of the backup codes you saved when you set up two-factor. Each works once."}
87
+ </p>
88
+ {waitingForEmail ? (
89
+ <>
90
+ <FormMessage>{error}</FormMessage>
91
+ <PrimaryButton type="button" onClick={sendEmail} pending={pending}>
92
+ Email me a code
93
+ </PrimaryButton>
94
+ </>
95
+ ) : (
96
+ <>
97
+ {method === "backup" ? (
98
+ <div className="flex flex-col gap-2">
99
+ <AuthLabel htmlFor="code">Backup code</AuthLabel>
100
+ <AuthInput
101
+ id="code"
102
+ value={code}
103
+ onChange={(event) => setCode(event.target.value)}
104
+ inputMode="text"
105
+ autoComplete="one-time-code"
106
+ className="text-center font-mono text-lg tracking-[0.2em]"
107
+ required
108
+ autoFocus
109
+ aria-invalid={Boolean(error) || undefined}
110
+ />
111
+ </div>
112
+ ) : (
113
+ <OtpInput
114
+ value={code}
115
+ onChange={setCode}
116
+ onComplete={() => void verify()}
117
+ label={method === "authenticator" ? "Authenticator code" : "Emailed code"}
118
+ autoFocus
119
+ disabled={pending}
120
+ />
121
+ )}
122
+ <label className="flex items-center gap-2 text-sm text-foreground-muted">
123
+ <input type="checkbox" checked={trust} onChange={(event) => setTrust(event.target.checked)} className="size-4 accent-[var(--brand)]" />
124
+ Trust this device for 30 days
125
+ </label>
126
+ <FormMessage>{error}</FormMessage>
127
+ <PrimaryButton type="submit" pending={pending}>
128
+ Verify
129
+ </PrimaryButton>
130
+ {method === "email" && (
131
+ <TextButton onClick={() => void emailResend.resend()} disabled={emailResend.disabled || pending} className="self-center">
132
+ {emailResend.label}
133
+ </TextButton>
134
+ )}
135
+ </>
136
+ )}
137
+ </form>
138
+ );
139
+ }