bwh-auth 0.6.4 → 0.7.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.
package/dist/index.js CHANGED
@@ -1,1754 +1,3154 @@
1
- // src/forms.tsx
2
- import * as React3 from "react";
3
-
4
- // src/components.ts
5
- var requiredComponentKeys = [
6
- "Button",
7
- "Card",
8
- "CardContent",
9
- "CardDescription",
10
- "CardHeader",
11
- "CardTitle",
12
- "Input",
13
- "Label"
14
- ];
15
- function resolveAuthComponents(components) {
16
- const missing = requiredComponentKeys.filter((key) => !components?.[key]);
17
- if (missing.length > 0) {
18
- throw new Error(`bwh-auth requires injected components: ${missing.join(", ")}`);
19
- }
20
- return components;
21
- }
22
- function resolveAuthButtonComponent(components) {
23
- if (!components?.Button) {
24
- throw new Error("bwh-auth requires an injected Button component");
25
- }
26
- return { Button: components.Button };
27
- }
28
-
29
- // src/passkey-authentication.ts
30
1
  import * as React from "react";
31
-
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { ChevronRight, Key, KeyRound, Plus, Trash2, TriangleAlert } from "lucide-react";
4
+ import { flushSync } from "react-dom";
32
5
  // src/abort-utils.ts
33
6
  function throwIfAborted(signal) {
34
- if (!signal?.aborted) return;
35
- const error = new Error("Passkey authentication was cancelled");
36
- error.name = "AbortError";
37
- throw error;
7
+ if (!signal?.aborted) return;
8
+ const error = /* @__PURE__ */ new Error("Passkey authentication was cancelled");
9
+ error.name = "AbortError";
10
+ throw error;
38
11
  }
39
-
40
12
  // src/webauthn-utils.ts
41
13
  function getCsrfToken(explicitToken) {
42
- if (explicitToken) {
43
- return explicitToken;
44
- }
45
- return document.querySelector('meta[name="csrf-token"]')?.content ?? "";
14
+ if (explicitToken) return explicitToken;
15
+ return document.querySelector("meta[name=\"csrf-token\"]")?.content ?? "";
46
16
  }
47
17
  function base64urlToArrayBuffer(b64) {
48
- const base64 = b64.replace(/-/g, "+").replace(/_/g, "/");
49
- const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
50
- const binary = window.atob(padded);
51
- const bytes = new Uint8Array(binary.length);
52
- for (let i = 0; i < binary.length; i += 1) {
53
- bytes[i] = binary.charCodeAt(i);
54
- }
55
- return bytes.buffer;
18
+ const base64 = b64.replace(/-/g, "+").replace(/_/g, "/");
19
+ const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
20
+ const binary = window.atob(padded);
21
+ const bytes = new Uint8Array(binary.length);
22
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
23
+ return bytes.buffer;
56
24
  }
57
25
  function arrayBufferToBase64url(buffer) {
58
- const bytes = new Uint8Array(buffer);
59
- let binary = "";
60
- for (let i = 0; i < bytes.byteLength; i += 1) {
61
- binary += String.fromCharCode(bytes[i] ?? 0);
62
- }
63
- return window.btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
26
+ const bytes = new Uint8Array(buffer);
27
+ let binary = "";
28
+ for (let i = 0; i < bytes.byteLength; i += 1) binary += String.fromCharCode(bytes[i] ?? 0);
29
+ return window.btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
64
30
  }
65
31
  function isAbortError(error) {
66
- return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
32
+ return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
67
33
  }
68
34
  function getDefaultPasskeyName() {
69
- if (typeof window === "undefined") return "Passkey";
70
- const ua = window.navigator.userAgent;
71
- let browser = "Unknown Browser";
72
- let os = "Unknown OS";
73
- if (ua.includes("Firefox")) browser = "Firefox";
74
- else if (ua.includes("Edg")) browser = "Edge";
75
- else if (ua.includes("Chrome")) browser = "Chrome";
76
- else if (ua.includes("Safari")) browser = "Safari";
77
- if (ua.includes("Mac OS X")) os = "macOS";
78
- else if (ua.includes("Windows")) os = "Windows";
79
- else if (ua.includes("Android")) os = "Android";
80
- else if (ua.includes("iPhone") || ua.includes("iPad")) os = "iOS";
81
- else if (ua.includes("Linux")) os = "Linux";
82
- return `Passkey (${browser} on ${os})`;
35
+ if (typeof window === "undefined") return "Passkey";
36
+ const ua = window.navigator.userAgent;
37
+ let browser = "Unknown Browser";
38
+ let os = "Unknown OS";
39
+ if (ua.includes("Firefox")) browser = "Firefox";
40
+ else if (ua.includes("Edg")) browser = "Edge";
41
+ else if (ua.includes("Chrome")) browser = "Chrome";
42
+ else if (ua.includes("Safari")) browser = "Safari";
43
+ if (ua.includes("Mac OS X")) os = "macOS";
44
+ else if (ua.includes("Windows")) os = "Windows";
45
+ else if (ua.includes("Android")) os = "Android";
46
+ else if (ua.includes("iPhone") || ua.includes("iPad")) os = "iOS";
47
+ else if (ua.includes("Linux")) os = "Linux";
48
+ return `Passkey (${browser} on ${os})`;
83
49
  }
84
50
  async function isConditionalMediationAvailable() {
85
- if (typeof window === "undefined" || !window.PublicKeyCredential) return false;
86
- const credentialConstructor = window.PublicKeyCredential;
87
- if (!credentialConstructor.isConditionalMediationAvailable) return false;
88
- try {
89
- return await credentialConstructor.isConditionalMediationAvailable();
90
- } catch {
91
- return false;
92
- }
51
+ if (typeof window === "undefined" || !window.PublicKeyCredential) return false;
52
+ const credentialConstructor = window.PublicKeyCredential;
53
+ if (!credentialConstructor.isConditionalMediationAvailable) return false;
54
+ try {
55
+ return await credentialConstructor.isConditionalMediationAvailable();
56
+ } catch {
57
+ return false;
58
+ }
93
59
  }
94
60
  async function authenticateWithPasskey({ endpoints = {}, mediation, signal, remember } = {}) {
95
- const authOptionsUrl = endpoints.passkeyAuthOptions ?? "/api/passkeys/auth/options";
96
- const authUrl = endpoints.passkeyAuth ?? "/api/passkeys/auth";
97
- const optRes = await fetch(authOptionsUrl, {
98
- method: "POST",
99
- headers: {
100
- "Content-Type": "application/json",
101
- "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
102
- },
103
- signal
104
- });
105
- if (!optRes.ok) {
106
- throw new Error("Failed to get authentication options");
107
- }
108
- const options = await optRes.json();
109
- throwIfAborted(signal);
110
- const publicKey = {
111
- ...options,
112
- challenge: base64urlToArrayBuffer(options.challenge),
113
- allowCredentials: (options.allowCredentials || []).map((credential2) => ({
114
- ...credential2,
115
- id: base64urlToArrayBuffer(credential2.id)
116
- }))
117
- };
118
- const credential = await navigator.credentials.get({ publicKey, mediation, signal });
119
- throwIfAborted(signal);
120
- if (!credential || credential.type !== "public-key") {
121
- throw new Error("No passkey selected");
122
- }
123
- const pkCredential = credential;
124
- const response = pkCredential.response;
125
- const credentialData = {
126
- id: pkCredential.id,
127
- rawId: arrayBufferToBase64url(pkCredential.rawId),
128
- type: pkCredential.type,
129
- response: {
130
- clientDataJSON: arrayBufferToBase64url(response.clientDataJSON),
131
- authenticatorData: arrayBufferToBase64url(response.authenticatorData),
132
- signature: arrayBufferToBase64url(response.signature),
133
- userHandle: response.userHandle ? arrayBufferToBase64url(response.userHandle) : null
134
- }
135
- };
136
- const authRes = await fetch(authUrl, {
137
- method: "POST",
138
- headers: {
139
- "Content-Type": "application/json",
140
- "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
141
- },
142
- body: JSON.stringify({
143
- credential: credentialData,
144
- ...remember === void 0 ? {} : { remember: typeof remember === "function" ? remember() : remember }
145
- }),
146
- signal
147
- });
148
- const result = await authRes.json();
149
- if (!authRes.ok) {
150
- throw new Error(result.error || result.message || "Authentication failed");
151
- }
152
- return {
153
- result,
154
- redirectUrl: result.redirect || "/"
155
- };
61
+ const authOptionsUrl = endpoints.passkeyAuthOptions ?? "/api/passkeys/auth/options";
62
+ const authUrl = endpoints.passkeyAuth ?? "/api/passkeys/auth";
63
+ const optRes = await fetch(authOptionsUrl, {
64
+ method: "POST",
65
+ headers: {
66
+ "Content-Type": "application/json",
67
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
68
+ },
69
+ signal
70
+ });
71
+ if (!optRes.ok) throw new Error("Failed to get authentication options");
72
+ const options = await optRes.json();
73
+ throwIfAborted(signal);
74
+ const publicKey = {
75
+ ...options,
76
+ challenge: base64urlToArrayBuffer(options.challenge),
77
+ allowCredentials: (options.allowCredentials || []).map((credential) => ({
78
+ ...credential,
79
+ id: base64urlToArrayBuffer(credential.id)
80
+ }))
81
+ };
82
+ const credential = await navigator.credentials.get({
83
+ publicKey,
84
+ mediation,
85
+ signal
86
+ });
87
+ throwIfAborted(signal);
88
+ if (!credential || credential.type !== "public-key") throw new Error("No passkey selected");
89
+ const pkCredential = credential;
90
+ const response = pkCredential.response;
91
+ const credentialData = {
92
+ id: pkCredential.id,
93
+ rawId: arrayBufferToBase64url(pkCredential.rawId),
94
+ type: pkCredential.type,
95
+ response: {
96
+ clientDataJSON: arrayBufferToBase64url(response.clientDataJSON),
97
+ authenticatorData: arrayBufferToBase64url(response.authenticatorData),
98
+ signature: arrayBufferToBase64url(response.signature),
99
+ userHandle: response.userHandle ? arrayBufferToBase64url(response.userHandle) : null
100
+ }
101
+ };
102
+ const authRes = await fetch(authUrl, {
103
+ method: "POST",
104
+ headers: {
105
+ "Content-Type": "application/json",
106
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
107
+ },
108
+ body: JSON.stringify({
109
+ credential: credentialData,
110
+ ...remember === void 0 ? {} : { remember: typeof remember === "function" ? remember() : remember }
111
+ }),
112
+ signal
113
+ });
114
+ const result = await authRes.json();
115
+ if (!authRes.ok) throw new Error(result.error || result.message || "Authentication failed");
116
+ return {
117
+ result,
118
+ redirectUrl: result.redirect || "/"
119
+ };
120
+ }
121
+ var PasswordConfirmationRequiredError = class extends Error {
122
+ constructor() {
123
+ super("Confirm your identity before adding a passkey.");
124
+ this.name = "PasswordConfirmationRequiredError";
125
+ }
126
+ };
127
+ async function assertPasskeyResponse(response, fallback) {
128
+ if (response.ok) return;
129
+ const result = await response.json().catch(() => null);
130
+ if (response.status === 423 && result?.error === "password_confirmation_required") throw new PasswordConfirmationRequiredError();
131
+ const message = typeof result?.error === "string" ? result.error : typeof result?.message === "string" ? result.message : fallback;
132
+ throw new Error(message);
133
+ }
134
+ async function confirmPasswordForPasskey({ password, endpoints = {}, signal }) {
135
+ throwIfAborted(signal);
136
+ await assertPasskeyResponse(await fetch(endpoints.confirmPassword ?? "/api/auth/confirm-password", {
137
+ method: "POST",
138
+ headers: {
139
+ "Content-Type": "application/json",
140
+ Accept: "application/json",
141
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
142
+ },
143
+ body: JSON.stringify({ password }),
144
+ signal
145
+ }), "Password confirmation failed");
146
+ throwIfAborted(signal);
147
+ }
148
+ async function confirmPasskey({ endpoints = {}, signal } = {}) {
149
+ throwIfAborted(signal);
150
+ const headers = {
151
+ "Content-Type": "application/json",
152
+ Accept: "application/json",
153
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
154
+ };
155
+ const response = await fetch(endpoints.passkeyConfirmOptions ?? "/api/passkeys/confirm/options", {
156
+ method: "POST",
157
+ headers,
158
+ signal
159
+ });
160
+ await assertPasskeyResponse(response, "Failed to get confirmation options");
161
+ const options = await response.json();
162
+ throwIfAborted(signal);
163
+ if (!Array.isArray(options.allowCredentials) || options.allowCredentials.length === 0) throw new Error("No existing passkey is available for this account.");
164
+ const credential = await navigator.credentials.get({
165
+ publicKey: {
166
+ ...options,
167
+ challenge: base64urlToArrayBuffer(options.challenge),
168
+ allowCredentials: options.allowCredentials.map((entry) => ({
169
+ ...entry,
170
+ id: base64urlToArrayBuffer(entry.id)
171
+ })),
172
+ userVerification: "required"
173
+ },
174
+ signal
175
+ });
176
+ throwIfAborted(signal);
177
+ if (!credential || credential.type !== "public-key") throw new Error("No passkey selected");
178
+ const key = credential;
179
+ const assertion = key.response;
180
+ await assertPasskeyResponse(await fetch(endpoints.passkeyConfirm ?? "/api/passkeys/confirm", {
181
+ method: "POST",
182
+ headers,
183
+ signal,
184
+ body: JSON.stringify({ credential: {
185
+ id: key.id,
186
+ rawId: arrayBufferToBase64url(key.rawId),
187
+ type: key.type,
188
+ response: {
189
+ clientDataJSON: arrayBufferToBase64url(assertion.clientDataJSON),
190
+ authenticatorData: arrayBufferToBase64url(assertion.authenticatorData),
191
+ signature: arrayBufferToBase64url(assertion.signature),
192
+ userHandle: assertion.userHandle ? arrayBufferToBase64url(assertion.userHandle) : null
193
+ }
194
+ } })
195
+ }), "Passkey confirmation failed");
196
+ throwIfAborted(signal);
156
197
  }
157
198
  async function registerPasskey({ endpoints = {}, name, signal } = {}) {
158
- const registerOptionsUrl = endpoints.passkeyRegisterOptions ?? "/api/passkeys/register/options";
159
- const registerUrl = endpoints.passkeyRegister ?? "/api/passkeys/register";
160
- const passkeyName = name || getDefaultPasskeyName();
161
- const optRes = await fetch(registerOptionsUrl, {
162
- method: "POST",
163
- headers: {
164
- "Content-Type": "application/json",
165
- "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
166
- },
167
- signal
168
- });
169
- if (!optRes.ok) {
170
- throw new Error("Failed to get registration options");
171
- }
172
- const options = await optRes.json();
173
- const publicKey = {
174
- ...options,
175
- challenge: base64urlToArrayBuffer(options.challenge),
176
- user: {
177
- ...options.user,
178
- id: base64urlToArrayBuffer(options.user.id)
179
- },
180
- excludeCredentials: (options.excludeCredentials || []).map((credential2) => ({
181
- ...credential2,
182
- id: base64urlToArrayBuffer(credential2.id)
183
- }))
184
- };
185
- const credential = await navigator.credentials.create({ publicKey, signal });
186
- if (!credential || credential.type !== "public-key") {
187
- throw new Error("Failed to create credential");
188
- }
189
- const pkCredential = credential;
190
- const response = pkCredential.response;
191
- const credentialData = {
192
- id: pkCredential.id,
193
- rawId: arrayBufferToBase64url(pkCredential.rawId),
194
- type: pkCredential.type,
195
- response: {
196
- clientDataJSON: arrayBufferToBase64url(response.clientDataJSON),
197
- attestationObject: arrayBufferToBase64url(response.attestationObject),
198
- transports: response.getTransports ? response.getTransports() : []
199
- }
200
- };
201
- const verifyRes = await fetch(registerUrl, {
202
- method: "POST",
203
- headers: {
204
- "Content-Type": "application/json",
205
- "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
206
- },
207
- body: JSON.stringify({ credential: credentialData, name: passkeyName }),
208
- signal
209
- });
210
- const result = await verifyRes.json();
211
- if (!verifyRes.ok) {
212
- throw new Error(result.error || result.message || "Registration failed");
213
- }
214
- return { result };
215
- }
216
-
199
+ const registerOptionsUrl = endpoints.passkeyRegisterOptions ?? "/api/passkeys/register/options";
200
+ const registerUrl = endpoints.passkeyRegister ?? "/api/passkeys/register";
201
+ const passkeyName = name || getDefaultPasskeyName();
202
+ const optRes = await fetch(registerOptionsUrl, {
203
+ method: "POST",
204
+ headers: {
205
+ "Content-Type": "application/json",
206
+ Accept: "application/json",
207
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
208
+ },
209
+ signal
210
+ });
211
+ await assertPasskeyResponse(optRes, "Failed to get registration options");
212
+ throwIfAborted(signal);
213
+ const options = await optRes.json();
214
+ throwIfAborted(signal);
215
+ const publicKey = {
216
+ ...options,
217
+ challenge: base64urlToArrayBuffer(options.challenge),
218
+ user: {
219
+ ...options.user,
220
+ id: base64urlToArrayBuffer(options.user.id)
221
+ },
222
+ excludeCredentials: (options.excludeCredentials || []).map((credential) => ({
223
+ ...credential,
224
+ id: base64urlToArrayBuffer(credential.id)
225
+ }))
226
+ };
227
+ const credential = await navigator.credentials.create({
228
+ publicKey,
229
+ signal
230
+ });
231
+ throwIfAborted(signal);
232
+ if (!credential || credential.type !== "public-key") throw new Error("Failed to create credential");
233
+ const pkCredential = credential;
234
+ const response = pkCredential.response;
235
+ const credentialData = {
236
+ id: pkCredential.id,
237
+ rawId: arrayBufferToBase64url(pkCredential.rawId),
238
+ type: pkCredential.type,
239
+ response: {
240
+ clientDataJSON: arrayBufferToBase64url(response.clientDataJSON),
241
+ attestationObject: arrayBufferToBase64url(response.attestationObject),
242
+ transports: response.getTransports ? response.getTransports() : []
243
+ }
244
+ };
245
+ const verifyRes = await fetch(registerUrl, {
246
+ method: "POST",
247
+ headers: {
248
+ "Content-Type": "application/json",
249
+ Accept: "application/json",
250
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
251
+ },
252
+ body: JSON.stringify({
253
+ credential: credentialData,
254
+ name: passkeyName
255
+ }),
256
+ signal
257
+ });
258
+ await assertPasskeyResponse(verifyRes, "Registration failed");
259
+ throwIfAborted(signal);
260
+ return { result: await verifyRes.json() };
261
+ }
262
+ // src/auth-request.ts
263
+ /** A failed auth request, carrying what the form needs to explain it. Internal to the package. */
264
+ var AuthRequestError = class extends Error {
265
+ result;
266
+ status;
267
+ retryAfterSeconds;
268
+ constructor(message, result, status = null, retryAfterSeconds = null) {
269
+ super(message);
270
+ this.result = result;
271
+ this.status = status;
272
+ this.retryAfterSeconds = retryAfterSeconds;
273
+ this.name = "AuthRequestError";
274
+ }
275
+ };
276
+ /**
277
+ * Read a `Retry-After` header as whole seconds from now.
278
+ *
279
+ * The header is either a delay in seconds or an HTTP date. Anything unreadable, or a
280
+ * date already in the past, yields `null` so the caller falls back to wording without
281
+ * a number rather than showing a wrong one.
282
+ */
283
+ function parseRetryAfter(value, now = Date.now()) {
284
+ if (value === null || value === void 0) return null;
285
+ const trimmed = value.trim();
286
+ if (trimmed === "") return null;
287
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
288
+ const at = Date.parse(trimmed);
289
+ if (Number.isNaN(at)) return null;
290
+ const seconds = Math.ceil((at - now) / 1e3);
291
+ return seconds > 0 ? seconds : null;
292
+ }
293
+ /** The default text for an HTTP 429, naming the wait when the server sent one. */
294
+ function defaultRateLimitMessage(retryAfterSeconds) {
295
+ if (retryAfterSeconds === null) return "Too many attempts. Please wait a moment and try again.";
296
+ if (retryAfterSeconds < 60) return `Too many attempts. Please try again in ${retryAfterSeconds} second${retryAfterSeconds === 1 ? "" : "s"}.`;
297
+ const minutes = Math.ceil(retryAfterSeconds / 60);
298
+ return `Too many attempts. Please try again in ${minutes} minute${minutes === 1 ? "" : "s"}.`;
299
+ }
300
+ /** Replace a 429's message with `format(retryAfter)`; any other error keeps its own message. */
301
+ function errorMessage(error, fallback, format = null) {
302
+ if (format && error instanceof AuthRequestError && error.status === 429) return format(error.retryAfterSeconds);
303
+ return error instanceof Error ? error.message : fallback;
304
+ }
305
+ async function sendForm(url, body, csrfToken, method = "POST") {
306
+ const response = await fetch(url, {
307
+ method,
308
+ headers: {
309
+ "Content-Type": "application/json",
310
+ "Accept": "application/json",
311
+ "X-CSRF-TOKEN": getCsrfToken(csrfToken)
312
+ },
313
+ body: JSON.stringify(body)
314
+ });
315
+ const status = typeof response.status === "number" ? response.status : null;
316
+ const retryAfter = status === 429 ? parseRetryAfter(response.headers?.get?.("Retry-After")) : null;
317
+ let decoded;
318
+ try {
319
+ decoded = await response.json();
320
+ } catch {
321
+ if (status === 429) throw new AuthRequestError("Too Many Attempts.", {}, status, retryAfter);
322
+ throw new AuthRequestError("The server returned an unexpected response. Please try again.", {}, status);
323
+ }
324
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) throw new AuthRequestError("The server returned an unexpected response. Please try again.", {}, status);
325
+ const result = decoded;
326
+ if (!response.ok) throw new AuthRequestError(result.message || result.error || "Request failed", result, status, retryAfter);
327
+ return result;
328
+ }
329
+ /**
330
+ * Resolve a server-sent redirect into an http(s) URL that is safe to navigate to, or `null`.
331
+ *
332
+ * Relative URLs resolve against the current page; `javascript:`, `data:` and any other
333
+ * scheme are refused, because a navigation to them executes rather than navigates.
334
+ */
335
+ function safeRedirectUrl(url, base) {
336
+ if (typeof url !== "string" || url.trim() === "") return null;
337
+ const resolvedBase = base ?? (typeof window !== "undefined" ? window.location.href : void 0);
338
+ try {
339
+ const parsed = resolvedBase === void 0 ? new URL(url) : new URL(url, resolvedBase);
340
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.toString() : null;
341
+ } catch {
342
+ return null;
343
+ }
344
+ }
345
+ // src/components.ts
346
+ const requiredComponentKeys = [
347
+ "Button",
348
+ "Card",
349
+ "CardContent",
350
+ "CardDescription",
351
+ "CardHeader",
352
+ "CardTitle",
353
+ "Input",
354
+ "Label"
355
+ ];
356
+ function resolveAuthComponents(components) {
357
+ const missing = requiredComponentKeys.filter((key) => !components?.[key]);
358
+ if (missing.length > 0) throw new Error(`bwh-auth requires injected components: ${missing.join(", ")}`);
359
+ return components;
360
+ }
361
+ function resolveAuthButtonComponent(components) {
362
+ if (!components?.Button) throw new Error("bwh-auth requires an injected Button component");
363
+ return { Button: components.Button };
364
+ }
365
+ // src/email-code-form.tsx
366
+ /**
367
+ * A form for a code sent by email: sign-in verification, step-up before a sensitive
368
+ * action, or re-verifying an address. The endpoint and request body are the caller's;
369
+ * this owns the input, the busy state and a synchronous guard so two fast clicks or
370
+ * Enter presses send one request.
371
+ */
372
+ function EmailCodeForm({ components, submitUrl, buildSubmitBody, method = "POST", resendUrl, buildResendBody, csrfToken, codeLength = 6, idPrefix = "email-code", header, unwrapped = false, hideResend = false, testCodeHint, actions, rateLimitMessage = defaultRateLimitMessage, onSubmitStart, onSuccess, onError, onResend, title = "Enter your verification code", description, codeLabel = "Verification Code", submitLabel = "Verify Code", submittingLabel = "Verifying...", resendLabel = "Send a new code", resendingLabel = "Sending...", resentMessage = "A new verification code has been sent." }) {
373
+ const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
374
+ const [code, setCode] = React.useState("");
375
+ const [loading, setLoading] = React.useState(false);
376
+ const [resending, setResending] = React.useState(false);
377
+ const [message, setMessage] = React.useState("");
378
+ const submitting = React.useRef(false);
379
+ const resendInFlight = React.useRef(false);
380
+ const inputId = `${idPrefix}-code`;
381
+ async function onSubmit(event) {
382
+ event.preventDefault();
383
+ if (submitting.current) return;
384
+ submitting.current = true;
385
+ onSubmitStart?.();
386
+ setLoading(true);
387
+ setMessage("");
388
+ try {
389
+ const trimmed = code.trim();
390
+ const result = await sendForm(submitUrl, buildSubmitBody ? buildSubmitBody(trimmed) : { code: trimmed }, csrfToken, method);
391
+ onSuccess?.(result);
392
+ if (!onSuccess) {
393
+ const redirect = safeRedirectUrl(result.redirect);
394
+ if (redirect !== null) window.location.href = redirect;
395
+ }
396
+ } catch (error) {
397
+ setCode("");
398
+ onError?.(errorMessage(error, "Verification failed", rateLimitMessage));
399
+ } finally {
400
+ submitting.current = false;
401
+ setLoading(false);
402
+ }
403
+ }
404
+ async function resend() {
405
+ if (!resendUrl || resendInFlight.current) return;
406
+ resendInFlight.current = true;
407
+ setResending(true);
408
+ setMessage("");
409
+ try {
410
+ const result = await sendForm(resendUrl, buildResendBody ? buildResendBody() : {}, csrfToken);
411
+ onResend?.(result);
412
+ setMessage(typeof result.message === "string" && result.message !== "" ? result.message : resentMessage);
413
+ } catch (error) {
414
+ onError?.(errorMessage(error, "Could not resend verification code", rateLimitMessage));
415
+ } finally {
416
+ resendInFlight.current = false;
417
+ setResending(false);
418
+ }
419
+ }
420
+ const form = /* @__PURE__ */ jsxs("form", {
421
+ className: "space-y-4",
422
+ onSubmit: (event) => void onSubmit(event),
423
+ children: [/* @__PURE__ */ jsxs("div", {
424
+ className: "space-y-1",
425
+ children: [/* @__PURE__ */ jsx(Label, {
426
+ htmlFor: inputId,
427
+ children: codeLabel
428
+ }), /* @__PURE__ */ jsx(Input, {
429
+ id: inputId,
430
+ type: "text",
431
+ inputMode: "numeric",
432
+ pattern: `[0-9]{${codeLength}}`,
433
+ maxLength: codeLength,
434
+ autoComplete: "one-time-code",
435
+ required: true,
436
+ value: code,
437
+ onChange: (event) => setCode(event.target.value.replace(/\D/g, ""))
438
+ })]
439
+ }), /* @__PURE__ */ jsx(Button, {
440
+ type: "submit",
441
+ className: "w-full",
442
+ disabled: loading || code.length !== codeLength,
443
+ children: loading ? submittingLabel : submitLabel
444
+ })]
445
+ });
446
+ const renderedActions = typeof actions === "function" ? actions({
447
+ setMessage,
448
+ busy: loading || resending
449
+ }) : actions;
450
+ const footer = /* @__PURE__ */ jsxs("div", {
451
+ className: "mt-4 space-y-2 text-sm",
452
+ children: [
453
+ resendUrl && !hideResend ? /* @__PURE__ */ jsx(Button, {
454
+ type: "button",
455
+ variant: "outline",
456
+ className: "w-full",
457
+ disabled: resending,
458
+ onClick: () => void resend(),
459
+ children: resending ? resendingLabel : resendLabel
460
+ }) : null,
461
+ renderedActions,
462
+ message ? /* @__PURE__ */ jsx("p", {
463
+ role: "status",
464
+ children: message
465
+ }) : null,
466
+ testCodeHint ? /* @__PURE__ */ jsx("p", { children: testCodeHint }) : null
467
+ ]
468
+ });
469
+ if (unwrapped) return /* @__PURE__ */ jsxs(Fragment, { children: [
470
+ header,
471
+ form,
472
+ footer
473
+ ] });
474
+ return /* @__PURE__ */ jsxs(Card, { children: [/* @__PURE__ */ jsxs(CardHeader, { children: [
475
+ header,
476
+ /* @__PURE__ */ jsx(CardTitle, { children: title }),
477
+ /* @__PURE__ */ jsx(CardDescription, { children: description ?? `Enter the ${codeLength}-digit code sent to your email address.` })
478
+ ] }), /* @__PURE__ */ jsxs(CardContent, { children: [form, footer] })] });
479
+ }
217
480
  // src/passkey-authentication.ts
218
- var PasskeyAuthenticationContext = React.createContext(null);
481
+ const PasskeyAuthenticationContext = React.createContext(null);
219
482
  function usePasskeyAuthentication() {
220
- const pending = React.useRef(null);
221
- const cancel = React.useCallback(async (conditionalOnly = false) => {
222
- const request = pending.current;
223
- if (!request || conditionalOnly && !request.conditional) return;
224
- request.controller.abort();
225
- await request.promise.catch(() => void 0);
226
- }, []);
227
- const authenticate = React.useCallback(async (options = {}) => {
228
- const previous = pending.current;
229
- const controller = new AbortController();
230
- previous?.controller.abort();
231
- const promise = (async () => {
232
- if (previous) await previous.promise.catch(() => void 0);
233
- throwIfAborted(controller.signal);
234
- const result = await authenticateWithPasskey({ ...options, signal: controller.signal });
235
- throwIfAborted(controller.signal);
236
- return result;
237
- })();
238
- const request = { controller, promise, conditional: options.mediation === "conditional" };
239
- pending.current = request;
240
- try {
241
- return await promise;
242
- } finally {
243
- if (pending.current === request) pending.current = null;
244
- }
245
- }, []);
246
- React.useEffect(() => () => {
247
- void cancel();
248
- }, [cancel]);
249
- return React.useMemo(() => ({ authenticate, cancel }), [authenticate, cancel]);
250
- }
251
-
483
+ const pending = React.useRef(null);
484
+ const cancel = React.useCallback(async (conditionalOnly = false) => {
485
+ const request = pending.current;
486
+ if (!request || conditionalOnly && !request.conditional) return;
487
+ request.controller.abort();
488
+ await request.promise.catch(() => void 0);
489
+ }, []);
490
+ const authenticate = React.useCallback(async (options = {}) => {
491
+ const previous = pending.current;
492
+ const controller = new AbortController();
493
+ previous?.controller.abort();
494
+ const promise = (async () => {
495
+ if (previous) await previous.promise.catch(() => void 0);
496
+ throwIfAborted(controller.signal);
497
+ const result = await authenticateWithPasskey({
498
+ ...options,
499
+ signal: controller.signal
500
+ });
501
+ throwIfAborted(controller.signal);
502
+ return result;
503
+ })();
504
+ const request = {
505
+ controller,
506
+ promise,
507
+ conditional: options.mediation === "conditional"
508
+ };
509
+ pending.current = request;
510
+ try {
511
+ return await promise;
512
+ } finally {
513
+ if (pending.current === request) pending.current = null;
514
+ }
515
+ }, []);
516
+ React.useEffect(() => () => {
517
+ cancel();
518
+ }, [cancel]);
519
+ return React.useMemo(() => ({
520
+ authenticate,
521
+ cancel
522
+ }), [authenticate, cancel]);
523
+ }
252
524
  // src/passkey-login-button.tsx
253
- import { KeyRound } from "lucide-react";
254
- import * as React2 from "react";
255
- import { jsx, jsxs } from "react/jsx-runtime";
256
525
  function PasskeyLoginButton({ endpoints = {}, components, className, disabled = false, remember, onSuccess, onError }) {
257
- const { Button } = resolveAuthButtonComponent(components);
258
- const [loading, setLoading] = React2.useState(false);
259
- const [error, setError] = React2.useState(null);
260
- const localAuthentication = usePasskeyAuthentication();
261
- const authentication = React2.useContext(PasskeyAuthenticationContext) ?? localAuthentication;
262
- const inFlight = React2.useRef(false);
263
- const mounted = React2.useRef(true);
264
- const callbacks = React2.useRef({ onSuccess, onError, remember });
265
- React2.useLayoutEffect(() => {
266
- callbacks.current = { onSuccess, onError, remember };
267
- });
268
- React2.useEffect(() => {
269
- mounted.current = true;
270
- return () => {
271
- mounted.current = false;
272
- if (inFlight.current) void authentication.cancel();
273
- };
274
- }, [authentication]);
275
- async function handlePasskeyLogin() {
276
- if (disabled || inFlight.current) return;
277
- inFlight.current = true;
278
- setError(null);
279
- setLoading(true);
280
- try {
281
- const { redirectUrl, result } = await authentication.authenticate({
282
- endpoints,
283
- remember: () => {
284
- const choice = callbacks.current.remember;
285
- return typeof choice === "function" ? choice() : choice ?? false;
286
- }
287
- });
288
- if (!mounted.current) return;
289
- if (callbacks.current.onSuccess) {
290
- callbacks.current.onSuccess(redirectUrl, result);
291
- } else {
292
- window.location.href = redirectUrl;
293
- }
294
- } catch (caughtError) {
295
- if (!mounted.current || isAbortError(caughtError)) {
296
- return;
297
- }
298
- const message = caughtError instanceof Error ? caughtError.message : "Passkey login failed";
299
- if (callbacks.current.onError) callbacks.current.onError(message);
300
- else setError(message);
301
- } finally {
302
- inFlight.current = false;
303
- if (mounted.current) setLoading(false);
304
- }
305
- }
306
- if (typeof window === "undefined" || !window.PublicKeyCredential) {
307
- return null;
308
- }
309
- return /* @__PURE__ */ jsxs("div", { className, children: [
310
- error ? /* @__PURE__ */ jsx("p", { className: "mb-2 text-sm text-destructive", children: error }) : null,
311
- /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", className: "w-full", disabled: disabled || loading, onClick: handlePasskeyLogin, children: [
312
- /* @__PURE__ */ jsx(KeyRound, { "aria-hidden": "true" }),
313
- loading ? "Verifying..." : "Sign in with Passkey"
314
- ] })
315
- ] });
316
- }
317
-
318
- // src/forms.tsx
319
- import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
320
- var AuthRequestError = class extends Error {
321
- constructor(message, result) {
322
- super(message);
323
- this.result = result;
324
- this.name = "AuthRequestError";
325
- }
326
- result;
327
- };
328
- async function postForm(url, body, csrfToken) {
329
- const response = await fetch(url, {
330
- method: "POST",
331
- headers: {
332
- "Content-Type": "application/json",
333
- "Accept": "application/json",
334
- "X-CSRF-TOKEN": getCsrfToken(csrfToken)
335
- },
336
- body: JSON.stringify(body)
337
- });
338
- let decoded;
339
- try {
340
- decoded = await response.json();
341
- } catch {
342
- throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
343
- }
344
- if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) {
345
- throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
346
- }
347
- const result = decoded;
348
- if (!response.ok) {
349
- throw new AuthRequestError(result.message || result.error || "Request failed", result);
350
- }
351
- return result;
526
+ const { Button } = resolveAuthButtonComponent(components);
527
+ const [loading, setLoading] = React.useState(false);
528
+ const [error, setError] = React.useState(null);
529
+ const localAuthentication = usePasskeyAuthentication();
530
+ const authentication = React.useContext(PasskeyAuthenticationContext) ?? localAuthentication;
531
+ const inFlight = React.useRef(false);
532
+ const mounted = React.useRef(true);
533
+ const callbacks = React.useRef({
534
+ onSuccess,
535
+ onError,
536
+ remember
537
+ });
538
+ React.useLayoutEffect(() => {
539
+ callbacks.current = {
540
+ onSuccess,
541
+ onError,
542
+ remember
543
+ };
544
+ });
545
+ React.useEffect(() => {
546
+ mounted.current = true;
547
+ return () => {
548
+ mounted.current = false;
549
+ if (inFlight.current) authentication.cancel();
550
+ };
551
+ }, [authentication]);
552
+ async function handlePasskeyLogin() {
553
+ if (disabled || inFlight.current) return;
554
+ inFlight.current = true;
555
+ setError(null);
556
+ setLoading(true);
557
+ try {
558
+ const { redirectUrl, result } = await authentication.authenticate({
559
+ endpoints,
560
+ remember: () => {
561
+ const choice = callbacks.current.remember;
562
+ return typeof choice === "function" ? choice() : choice ?? false;
563
+ }
564
+ });
565
+ if (!mounted.current) return;
566
+ if (callbacks.current.onSuccess) callbacks.current.onSuccess(redirectUrl, result);
567
+ else window.location.href = redirectUrl;
568
+ } catch (caughtError) {
569
+ if (!mounted.current || isAbortError(caughtError)) return;
570
+ const message = caughtError instanceof Error ? caughtError.message : "Passkey login failed";
571
+ if (callbacks.current.onError) callbacks.current.onError(message);
572
+ else setError(message);
573
+ } finally {
574
+ inFlight.current = false;
575
+ if (mounted.current) setLoading(false);
576
+ }
577
+ }
578
+ if (typeof window === "undefined" || !window.PublicKeyCredential) return null;
579
+ return /* @__PURE__ */ jsxs("div", {
580
+ className,
581
+ children: [error ? /* @__PURE__ */ jsx("p", {
582
+ className: "mb-2 text-sm text-destructive",
583
+ children: error
584
+ }) : null, /* @__PURE__ */ jsxs(Button, {
585
+ type: "button",
586
+ variant: "outline",
587
+ className: "w-full",
588
+ disabled: disabled || loading,
589
+ onClick: handlePasskeyLogin,
590
+ children: [/* @__PURE__ */ jsx(KeyRound, { "aria-hidden": "true" }), loading ? "Verifying..." : "Sign in with Passkey"]
591
+ })]
592
+ });
352
593
  }
594
+ // src/forms.tsx
595
+ const postForm = sendForm;
353
596
  function DefaultRememberMeCheckbox({ checked, onCheckedChange, ...props }) {
354
- return /* @__PURE__ */ jsx2(
355
- "input",
356
- {
357
- ...props,
358
- type: "checkbox",
359
- checked,
360
- onChange: (event) => onCheckedChange(event.target.checked)
361
- }
362
- );
363
- }
364
- function LoginForm({
365
- endpoints = {},
366
- components,
367
- onSuccess,
368
- onError,
369
- initialEmail = "",
370
- onEmailChange,
371
- rememberMeCheckbox: RememberMeCheckbox = DefaultRememberMeCheckbox,
372
- rememberMeLabel = "Keep me signed in",
373
- rememberMeDataTest,
374
- onSubmitStart,
375
- onTwoFactorRequired,
376
- onPasskeySuccess,
377
- unwrapped = false,
378
- passkeySeparator,
379
- enablePasskeys = false,
380
- enablePasskeyAutofill = enablePasskeys
381
- }) {
382
- const { Button, Card, CardContent, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
383
- const [email, setEmail] = React3.useState(initialEmail);
384
- const [password, setPassword] = React3.useState("");
385
- const [remember, setRemember] = React3.useState(false);
386
- const [loading, setLoading] = React3.useState(false);
387
- const [conditionalPasskeyAvailable, setConditionalPasskeyAvailable] = React3.useState(false);
388
- const passkeyAuthentication = usePasskeyAuthentication();
389
- const conditionalInterrupted = React3.useRef(false);
390
- const submitting = React3.useRef(false);
391
- const callbacks = React3.useRef({ onError, onPasskeySuccess, remember });
392
- React3.useLayoutEffect(() => {
393
- callbacks.current = { onError, onPasskeySuccess, remember };
394
- });
395
- const coordinatedAuthentication = React3.useMemo(() => ({
396
- ...passkeyAuthentication,
397
- authenticate: (options) => {
398
- if (options?.mediation !== "conditional") conditionalInterrupted.current = true;
399
- return passkeyAuthentication.authenticate(options);
400
- }
401
- }), [passkeyAuthentication]);
402
- const passkeyEndpoints = React3.useMemo(() => ({
403
- csrfToken: endpoints.csrfToken,
404
- passkeyAuth: endpoints.passkeyAuth,
405
- passkeyAuthOptions: endpoints.passkeyAuthOptions
406
- }), [endpoints.csrfToken, endpoints.passkeyAuth, endpoints.passkeyAuthOptions]);
407
- React3.useEffect(() => {
408
- setConditionalPasskeyAvailable(false);
409
- if (!enablePasskeyAutofill || conditionalInterrupted.current) return;
410
- let active = true;
411
- async function startConditionalPasskeyLogin() {
412
- const available = await isConditionalMediationAvailable();
413
- if (!available || !active || conditionalInterrupted.current) return;
414
- setConditionalPasskeyAvailable(true);
415
- try {
416
- const { redirectUrl, result } = await coordinatedAuthentication.authenticate({
417
- endpoints: passkeyEndpoints,
418
- mediation: "conditional",
419
- remember: () => callbacks.current.remember
420
- });
421
- if (!active) return;
422
- if (callbacks.current.onPasskeySuccess) {
423
- callbacks.current.onPasskeySuccess(redirectUrl, result);
424
- } else {
425
- window.location.href = redirectUrl;
426
- }
427
- } catch (error) {
428
- if (!isAbortError(error) && active) {
429
- callbacks.current.onError?.(error instanceof Error ? error.message : "Passkey login failed");
430
- }
431
- }
432
- }
433
- void startConditionalPasskeyLogin();
434
- return () => {
435
- active = false;
436
- void coordinatedAuthentication.cancel(true);
437
- };
438
- }, [enablePasskeyAutofill, coordinatedAuthentication, passkeyEndpoints]);
439
- async function onSubmit(event) {
440
- event.preventDefault();
441
- if (submitting.current) return;
442
- submitting.current = true;
443
- conditionalInterrupted.current = true;
444
- onSubmitStart?.();
445
- setLoading(true);
446
- try {
447
- await passkeyAuthentication.cancel();
448
- const result = await postForm(endpoints.login ?? "/login", { email, password, remember }, endpoints.csrfToken);
449
- if (result.requires_2fa) {
450
- onTwoFactorRequired?.(result);
451
- if (!onTwoFactorRequired && typeof result.attempt_token === "string") {
452
- window.location.href = `/login/two-factor/${encodeURIComponent(result.attempt_token)}`;
453
- }
454
- return;
455
- }
456
- onSuccess?.(result);
457
- if (!onSuccess && result.redirect) window.location.href = result.redirect;
458
- } catch (error) {
459
- onError?.(error instanceof Error ? error.message : "Login failed");
460
- } finally {
461
- submitting.current = false;
462
- setLoading(false);
463
- }
464
- }
465
- const content = /* @__PURE__ */ jsxs2(Fragment, { children: [
466
- /* @__PURE__ */ jsxs2("form", { className: "space-y-4", onSubmit: (event) => void onSubmit(event), children: [
467
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
468
- /* @__PURE__ */ jsx2(Label, { htmlFor: "login-email", children: "Email" }),
469
- /* @__PURE__ */ jsx2(
470
- Input,
471
- {
472
- id: "login-email",
473
- type: "email",
474
- autoComplete: conditionalPasskeyAvailable ? "username webauthn" : "email",
475
- required: true,
476
- value: email,
477
- onChange: (event) => {
478
- setEmail(event.target.value);
479
- onEmailChange?.(event.target.value);
480
- }
481
- }
482
- )
483
- ] }),
484
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
485
- /* @__PURE__ */ jsx2(Label, { htmlFor: "login-password", children: "Password" }),
486
- /* @__PURE__ */ jsx2(Input, { id: "login-password", type: "password", autoComplete: "current-password", required: true, value: password, onChange: (event) => setPassword(event.target.value) })
487
- ] }),
488
- /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2 text-sm", children: [
489
- /* @__PURE__ */ jsx2(
490
- RememberMeCheckbox,
491
- {
492
- id: "login-remember",
493
- "aria-labelledby": "login-remember-label",
494
- "data-test": rememberMeDataTest,
495
- checked: remember,
496
- onCheckedChange: setRemember
497
- }
498
- ),
499
- /* @__PURE__ */ jsx2(Label, { id: "login-remember-label", htmlFor: "login-remember", children: rememberMeLabel })
500
- ] }),
501
- /* @__PURE__ */ jsx2(Button, { type: "submit", className: "w-full", disabled: loading, children: loading ? "Signing in..." : "Sign In" })
502
- ] }),
503
- enablePasskeys ? /* @__PURE__ */ jsxs2("div", { className: "mt-4", children: [
504
- passkeySeparator,
505
- /* @__PURE__ */ jsx2(PasskeyAuthenticationContext.Provider, { value: coordinatedAuthentication, children: /* @__PURE__ */ jsx2(
506
- PasskeyLoginButton,
507
- {
508
- components: { Button },
509
- endpoints,
510
- disabled: loading,
511
- remember: () => callbacks.current.remember,
512
- onSuccess: (redirectUrl, result) => {
513
- if (onPasskeySuccess) {
514
- onPasskeySuccess(redirectUrl, result);
515
- } else {
516
- window.location.href = redirectUrl;
517
- }
518
- },
519
- onError
520
- }
521
- ) })
522
- ] }) : null
523
- ] });
524
- return unwrapped ? content : /* @__PURE__ */ jsxs2(Card, { children: [
525
- /* @__PURE__ */ jsx2(CardHeader, { children: /* @__PURE__ */ jsx2(CardTitle, { children: "Sign In" }) }),
526
- /* @__PURE__ */ jsx2(CardContent, { children: content })
527
- ] });
597
+ return /* @__PURE__ */ jsx("input", {
598
+ ...props,
599
+ type: "checkbox",
600
+ checked,
601
+ onChange: (event) => onCheckedChange(event.target.checked)
602
+ });
603
+ }
604
+ function LoginForm({ endpoints = {}, components, onSuccess, onError, initialEmail = "", onEmailChange, rememberMeCheckbox: RememberMeCheckbox = DefaultRememberMeCheckbox, rememberMeLabel = "Keep me signed in", rememberMeDataTest, onSubmitStart, onTwoFactorRequired, onPasskeySuccess, unwrapped = false, passkeySeparator, enablePasskeys = false, enablePasskeyAutofill = enablePasskeys }) {
605
+ const { Button, Card, CardContent, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
606
+ const [email, setEmail] = React.useState(initialEmail);
607
+ const [password, setPassword] = React.useState("");
608
+ const [remember, setRemember] = React.useState(false);
609
+ const [loading, setLoading] = React.useState(false);
610
+ const [conditionalPasskeyAvailable, setConditionalPasskeyAvailable] = React.useState(false);
611
+ const passkeyAuthentication = usePasskeyAuthentication();
612
+ const conditionalInterrupted = React.useRef(false);
613
+ const submitting = React.useRef(false);
614
+ const callbacks = React.useRef({
615
+ onError,
616
+ onPasskeySuccess,
617
+ remember
618
+ });
619
+ React.useLayoutEffect(() => {
620
+ callbacks.current = {
621
+ onError,
622
+ onPasskeySuccess,
623
+ remember
624
+ };
625
+ });
626
+ const coordinatedAuthentication = React.useMemo(() => ({
627
+ ...passkeyAuthentication,
628
+ authenticate: (options) => {
629
+ if (options?.mediation !== "conditional") conditionalInterrupted.current = true;
630
+ return passkeyAuthentication.authenticate(options);
631
+ }
632
+ }), [passkeyAuthentication]);
633
+ const passkeyEndpoints = React.useMemo(() => ({
634
+ csrfToken: endpoints.csrfToken,
635
+ passkeyAuth: endpoints.passkeyAuth,
636
+ passkeyAuthOptions: endpoints.passkeyAuthOptions
637
+ }), [
638
+ endpoints.csrfToken,
639
+ endpoints.passkeyAuth,
640
+ endpoints.passkeyAuthOptions
641
+ ]);
642
+ React.useEffect(() => {
643
+ setConditionalPasskeyAvailable(false);
644
+ if (!enablePasskeyAutofill || conditionalInterrupted.current) return;
645
+ let active = true;
646
+ async function startConditionalPasskeyLogin() {
647
+ if (!await isConditionalMediationAvailable() || !active || conditionalInterrupted.current) return;
648
+ setConditionalPasskeyAvailable(true);
649
+ try {
650
+ const { redirectUrl, result } = await coordinatedAuthentication.authenticate({
651
+ endpoints: passkeyEndpoints,
652
+ mediation: "conditional",
653
+ remember: () => callbacks.current.remember
654
+ });
655
+ if (!active) return;
656
+ if (callbacks.current.onPasskeySuccess) callbacks.current.onPasskeySuccess(redirectUrl, result);
657
+ else window.location.href = redirectUrl;
658
+ } catch (error) {
659
+ if (!isAbortError(error) && active) callbacks.current.onError?.(error instanceof Error ? error.message : "Passkey login failed");
660
+ }
661
+ }
662
+ startConditionalPasskeyLogin();
663
+ return () => {
664
+ active = false;
665
+ coordinatedAuthentication.cancel(true);
666
+ };
667
+ }, [
668
+ enablePasskeyAutofill,
669
+ coordinatedAuthentication,
670
+ passkeyEndpoints
671
+ ]);
672
+ async function onSubmit(event) {
673
+ event.preventDefault();
674
+ if (submitting.current) return;
675
+ submitting.current = true;
676
+ conditionalInterrupted.current = true;
677
+ onSubmitStart?.();
678
+ setLoading(true);
679
+ try {
680
+ await passkeyAuthentication.cancel();
681
+ const result = await postForm(endpoints.login ?? "/login", {
682
+ email,
683
+ password,
684
+ remember
685
+ }, endpoints.csrfToken);
686
+ if (result.requires_2fa) {
687
+ onTwoFactorRequired?.(result);
688
+ if (!onTwoFactorRequired && typeof result.attempt_token === "string") window.location.href = `/login/two-factor/${encodeURIComponent(result.attempt_token)}`;
689
+ return;
690
+ }
691
+ onSuccess?.(result);
692
+ if (!onSuccess && result.redirect) window.location.href = result.redirect;
693
+ } catch (error) {
694
+ onError?.(error instanceof Error ? error.message : "Login failed");
695
+ } finally {
696
+ submitting.current = false;
697
+ setLoading(false);
698
+ }
699
+ }
700
+ const content = /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("form", {
701
+ className: "space-y-4",
702
+ onSubmit: (event) => void onSubmit(event),
703
+ children: [
704
+ /* @__PURE__ */ jsxs("div", {
705
+ className: "space-y-1",
706
+ children: [/* @__PURE__ */ jsx(Label, {
707
+ htmlFor: "login-email",
708
+ children: "Email"
709
+ }), /* @__PURE__ */ jsx(Input, {
710
+ id: "login-email",
711
+ type: "email",
712
+ autoComplete: conditionalPasskeyAvailable ? "username webauthn" : "email",
713
+ required: true,
714
+ value: email,
715
+ onChange: (event) => {
716
+ setEmail(event.target.value);
717
+ onEmailChange?.(event.target.value);
718
+ }
719
+ })]
720
+ }),
721
+ /* @__PURE__ */ jsxs("div", {
722
+ className: "space-y-1",
723
+ children: [/* @__PURE__ */ jsx(Label, {
724
+ htmlFor: "login-password",
725
+ children: "Password"
726
+ }), /* @__PURE__ */ jsx(Input, {
727
+ id: "login-password",
728
+ type: "password",
729
+ autoComplete: "current-password",
730
+ required: true,
731
+ value: password,
732
+ onChange: (event) => setPassword(event.target.value)
733
+ })]
734
+ }),
735
+ /* @__PURE__ */ jsxs("div", {
736
+ className: "flex items-center gap-2 text-sm",
737
+ children: [/* @__PURE__ */ jsx(RememberMeCheckbox, {
738
+ id: "login-remember",
739
+ "aria-labelledby": "login-remember-label",
740
+ "data-test": rememberMeDataTest,
741
+ checked: remember,
742
+ onCheckedChange: setRemember
743
+ }), /* @__PURE__ */ jsx(Label, {
744
+ id: "login-remember-label",
745
+ htmlFor: "login-remember",
746
+ children: rememberMeLabel
747
+ })]
748
+ }),
749
+ /* @__PURE__ */ jsx(Button, {
750
+ type: "submit",
751
+ className: "w-full",
752
+ disabled: loading,
753
+ children: loading ? "Signing in..." : "Sign In"
754
+ })
755
+ ]
756
+ }), enablePasskeys ? /* @__PURE__ */ jsxs("div", {
757
+ className: "mt-4",
758
+ children: [passkeySeparator, /* @__PURE__ */ jsx(PasskeyAuthenticationContext.Provider, {
759
+ value: coordinatedAuthentication,
760
+ children: /* @__PURE__ */ jsx(PasskeyLoginButton, {
761
+ components: { Button },
762
+ endpoints,
763
+ disabled: loading,
764
+ remember: () => callbacks.current.remember,
765
+ onSuccess: (redirectUrl, result) => {
766
+ if (onPasskeySuccess) onPasskeySuccess(redirectUrl, result);
767
+ else window.location.href = redirectUrl;
768
+ },
769
+ onError
770
+ })
771
+ })]
772
+ }) : null] });
773
+ return unwrapped ? content : /* @__PURE__ */ jsxs(Card, { children: [/* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Sign In" }) }), /* @__PURE__ */ jsx(CardContent, { children: content })] });
528
774
  }
529
775
  function defaultSignupFields() {
530
- return [
531
- { name: "name", label: "Name", required: true, autoComplete: "name" },
532
- { name: "email", label: "Email", type: "email", required: true, autoComplete: "email" },
533
- { name: "password", label: "Password", type: "password", required: true, autoComplete: "new-password" },
534
- { name: "password_confirmation", label: "Confirm Password", type: "password", required: true, autoComplete: "new-password" }
535
- ];
776
+ return [
777
+ {
778
+ name: "name",
779
+ label: "Name",
780
+ required: true,
781
+ autoComplete: "name"
782
+ },
783
+ {
784
+ name: "email",
785
+ label: "Email",
786
+ type: "email",
787
+ required: true,
788
+ autoComplete: "email"
789
+ },
790
+ {
791
+ name: "password",
792
+ label: "Password",
793
+ type: "password",
794
+ required: true,
795
+ autoComplete: "new-password"
796
+ },
797
+ {
798
+ name: "password_confirmation",
799
+ label: "Confirm Password",
800
+ type: "password",
801
+ required: true,
802
+ autoComplete: "new-password"
803
+ }
804
+ ];
536
805
  }
537
806
  function initialSignupValue(field, initialValues) {
538
- if (Object.prototype.hasOwnProperty.call(initialValues, field.name)) return initialValues[field.name];
539
- if (field.initialValue !== void 0) return field.initialValue;
540
- return field.type === "checkbox" ? false : "";
541
- }
542
- function SignupForm({
543
- endpoints = {},
544
- components,
545
- onSuccess,
546
- onError,
547
- fields = defaultSignupFields(),
548
- initialValues = {},
549
- errors = {},
550
- submitMode = "fetch",
551
- title = "Create Account",
552
- description,
553
- submitLabel = "Create Account",
554
- submittingLabel = "Creating account..."
555
- }) {
556
- const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
557
- const [values, setValues] = React3.useState(() => Object.fromEntries(
558
- fields.map((field) => [field.name, initialSignupValue(field, initialValues)])
559
- ));
560
- const [fieldErrors, setFieldErrors] = React3.useState(errors);
561
- const [loading, setLoading] = React3.useState(false);
562
- async function onSubmit(event) {
563
- setLoading(true);
564
- if (submitMode === "native") {
565
- return;
566
- }
567
- event.preventDefault();
568
- setFieldErrors({});
569
- try {
570
- const result = await postForm(endpoints.signup ?? "/register", values, endpoints.csrfToken);
571
- await onSuccess?.(result, values);
572
- if (!onSuccess && result.redirect) window.location.href = result.redirect;
573
- } catch (error) {
574
- if (error instanceof AuthRequestError && error.result.errors && typeof error.result.errors === "object") {
575
- setFieldErrors(error.result.errors);
576
- }
577
- onError?.(error instanceof Error ? error.message : "Signup failed");
578
- } finally {
579
- setLoading(false);
580
- }
581
- }
582
- function setValue(name, value) {
583
- setValues((current) => ({ ...current, [name]: value }));
584
- }
585
- return /* @__PURE__ */ jsxs2(Card, { children: [
586
- /* @__PURE__ */ jsxs2(CardHeader, { children: [
587
- /* @__PURE__ */ jsx2(CardTitle, { children: title }),
588
- description ? /* @__PURE__ */ jsx2(CardDescription, { children: description }) : null
589
- ] }),
590
- /* @__PURE__ */ jsx2(CardContent, { children: /* @__PURE__ */ jsxs2("form", { className: "space-y-4", method: submitMode === "native" ? "POST" : void 0, action: endpoints.signup ?? "/register", onSubmit: (event) => void onSubmit(event), children: [
591
- submitMode === "native" ? /* @__PURE__ */ jsx2("input", { type: "hidden", name: "_token", value: getCsrfToken(endpoints.csrfToken) }) : null,
592
- fields.map((field) => {
593
- if (field.hiddenWhen?.(values)) return null;
594
- const error = fieldErrors[field.name]?.[0];
595
- const value = values[field.name];
596
- if (field.type === "checkbox") {
597
- return /* @__PURE__ */ jsxs2("div", { className: field.containerClassName ?? "space-y-1", children: [
598
- /* @__PURE__ */ jsxs2("label", { className: "flex items-start gap-2 text-sm", children: [
599
- /* @__PURE__ */ jsx2(
600
- "input",
601
- {
602
- id: `signup-${field.name}`,
603
- name: field.name,
604
- type: "checkbox",
605
- value: "1",
606
- checked: Boolean(value),
607
- onChange: (event) => setValue(field.name, event.target.checked),
608
- required: field.required
609
- }
610
- ),
611
- /* @__PURE__ */ jsx2("span", { children: field.label })
612
- ] }),
613
- field.helpText ? /* @__PURE__ */ jsx2("p", { className: "text-xs text-muted-foreground", children: field.helpText }) : null,
614
- error ? /* @__PURE__ */ jsx2("p", { className: "text-sm text-destructive", children: error }) : null
615
- ] }, field.name);
616
- }
617
- return /* @__PURE__ */ jsxs2("div", { className: field.containerClassName ?? "space-y-1", children: [
618
- /* @__PURE__ */ jsx2(Label, { htmlFor: `signup-${field.name}`, children: field.label }),
619
- /* @__PURE__ */ jsx2(
620
- Input,
621
- {
622
- id: `signup-${field.name}`,
623
- name: field.name,
624
- type: field.type ?? "text",
625
- placeholder: field.placeholder,
626
- required: field.required,
627
- autoComplete: field.autoComplete,
628
- minLength: field.minLength,
629
- maxLength: field.maxLength,
630
- pattern: field.pattern,
631
- inputMode: field.inputMode,
632
- className: field.className,
633
- "aria-invalid": Boolean(error),
634
- value: String(value ?? ""),
635
- onChange: (event) => setValue(field.name, event.target.value)
636
- }
637
- ),
638
- field.helpText ? /* @__PURE__ */ jsx2("p", { className: "text-xs text-muted-foreground", children: field.helpText }) : null,
639
- error ? /* @__PURE__ */ jsx2("p", { className: "text-sm text-destructive", children: error }) : null
640
- ] }, field.name);
641
- }),
642
- /* @__PURE__ */ jsx2(Button, { type: "submit", className: "w-full", disabled: loading, children: loading ? submittingLabel : submitLabel })
643
- ] }) })
644
- ] });
645
- }
646
- function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onError, onSubmitStart, submitClassName }) {
647
- const { Button, Input, Label } = resolveAuthComponents(components);
648
- const [email, setEmail] = React3.useState("");
649
- const [loading, setLoading] = React3.useState(false);
650
- const submitting = React3.useRef(false);
651
- async function onSubmit(event) {
652
- event.preventDefault();
653
- if (submitting.current) return;
654
- submitting.current = true;
655
- onSubmitStart?.();
656
- setLoading(true);
657
- try {
658
- const result = await postForm(endpoints.forgotPassword ?? "/api/auth/forgot-password", { email }, endpoints.csrfToken);
659
- onSuccess?.(result);
660
- } catch (error) {
661
- onError?.(error instanceof Error ? error.message : "Password reset request failed");
662
- } finally {
663
- submitting.current = false;
664
- setLoading(false);
665
- }
666
- }
667
- return /* @__PURE__ */ jsxs2("form", { className: "space-y-4", onSubmit: (event) => void onSubmit(event), children: [
668
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
669
- /* @__PURE__ */ jsx2(Label, { htmlFor: "reset-email", children: "Email" }),
670
- /* @__PURE__ */ jsx2(Input, { id: "reset-email", type: "email", autoComplete: "email", required: true, value: email, onChange: (event) => setEmail(event.target.value) })
671
- ] }),
672
- /* @__PURE__ */ jsx2(Button, { type: "submit", className: submitClassName, disabled: loading, children: loading ? "Sending..." : "Send Reset Link" })
673
- ] });
674
- }
675
- function ResetPasswordForm({
676
- endpoints = {},
677
- components,
678
- onSuccess,
679
- onError,
680
- onSubmitStart,
681
- submitClassName,
682
- token: initialToken = "",
683
- email: initialEmail = "",
684
- idPrefix = "reset-password",
685
- minPasswordLength,
686
- validatePasswordConfirmation = false,
687
- passwordLabel = "Password",
688
- passwordConfirmationLabel = "Confirm Password",
689
- passwordHelpText
690
- }) {
691
- const { Button, Input, Label } = resolveAuthComponents(components);
692
- const [email, setEmail] = React3.useState(initialEmail);
693
- const [token, setToken] = React3.useState(initialToken);
694
- const [password, setPassword] = React3.useState("");
695
- const [passwordConfirmation, setPasswordConfirmation] = React3.useState("");
696
- const [loading, setLoading] = React3.useState(false);
697
- const submitting = React3.useRef(false);
698
- async function onSubmit(event) {
699
- event.preventDefault();
700
- if (submitting.current) return;
701
- onSubmitStart?.();
702
- if (validatePasswordConfirmation && password !== passwordConfirmation) {
703
- onError?.("Passwords do not match.");
704
- return;
705
- }
706
- if (minPasswordLength !== void 0 && password.length < minPasswordLength) {
707
- onError?.(`Password must be at least ${minPasswordLength} characters long.`);
708
- return;
709
- }
710
- submitting.current = true;
711
- setLoading(true);
712
- try {
713
- const result = await postForm(endpoints.resetPassword ?? "/api/auth/reset-password", {
714
- email,
715
- token,
716
- password,
717
- password_confirmation: passwordConfirmation
718
- }, endpoints.csrfToken);
719
- onSuccess?.(result);
720
- } catch (error) {
721
- onError?.(error instanceof Error ? error.message : "Password reset failed");
722
- } finally {
723
- submitting.current = false;
724
- setLoading(false);
725
- }
726
- }
727
- return /* @__PURE__ */ jsxs2("form", { className: "space-y-4", onSubmit: (event) => void onSubmit(event), children: [
728
- /* @__PURE__ */ jsx2(Input, { type: "hidden", value: token, onChange: (event) => setToken(event.target.value) }),
729
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
730
- /* @__PURE__ */ jsx2(Label, { htmlFor: `${idPrefix}-email`, children: "Email" }),
731
- /* @__PURE__ */ jsx2(Input, { id: `${idPrefix}-email`, type: "email", autoComplete: "email", required: true, value: email, onChange: (event) => setEmail(event.target.value) })
732
- ] }),
733
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
734
- /* @__PURE__ */ jsx2(Label, { htmlFor: idPrefix, children: passwordLabel }),
735
- /* @__PURE__ */ jsx2(Input, { id: idPrefix, type: "password", autoComplete: "new-password", minLength: minPasswordLength, required: true, value: password, onChange: (event) => setPassword(event.target.value) }),
736
- passwordHelpText ? /* @__PURE__ */ jsx2("p", { className: "text-xs text-muted-foreground", children: passwordHelpText }) : null
737
- ] }),
738
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
739
- /* @__PURE__ */ jsx2(Label, { htmlFor: `${idPrefix}-confirmation`, children: passwordConfirmationLabel }),
740
- /* @__PURE__ */ jsx2(Input, { id: `${idPrefix}-confirmation`, type: "password", autoComplete: "new-password", minLength: minPasswordLength, required: true, value: passwordConfirmation, onChange: (event) => setPasswordConfirmation(event.target.value) })
741
- ] }),
742
- /* @__PURE__ */ jsx2(Button, { type: "submit", className: submitClassName, disabled: loading, children: loading ? "Resetting..." : "Reset Password" })
743
- ] });
744
- }
745
- function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError }) {
746
- const { Button, Input, Label } = resolveAuthComponents(components);
747
- const [currentPassword, setCurrentPassword] = React3.useState("");
748
- const [password, setPassword] = React3.useState("");
749
- const [passwordConfirmation, setPasswordConfirmation] = React3.useState("");
750
- const [loading, setLoading] = React3.useState(false);
751
- async function onSubmit(event) {
752
- event.preventDefault();
753
- setLoading(true);
754
- if (password !== passwordConfirmation) {
755
- onError?.("New passwords do not match.");
756
- setLoading(false);
757
- return;
758
- }
759
- try {
760
- const result = await postForm(endpoints.changePassword ?? "/api/change-password", {
761
- current_password: currentPassword,
762
- password,
763
- password_confirmation: passwordConfirmation
764
- }, endpoints.csrfToken);
765
- setCurrentPassword("");
766
- setPassword("");
767
- setPasswordConfirmation("");
768
- onSuccess?.(result);
769
- } catch (error) {
770
- onError?.(error instanceof Error ? error.message : "Password change failed");
771
- } finally {
772
- setLoading(false);
773
- }
774
- }
775
- return /* @__PURE__ */ jsxs2("form", { className: "space-y-4", onSubmit: (event) => void onSubmit(event), children: [
776
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
777
- /* @__PURE__ */ jsx2(Label, { htmlFor: "current-password", children: "Current Password" }),
778
- /* @__PURE__ */ jsx2(Input, { id: "current-password", type: "password", autoComplete: "current-password", required: true, value: currentPassword, onChange: (event) => setCurrentPassword(event.target.value) })
779
- ] }),
780
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
781
- /* @__PURE__ */ jsx2(Label, { htmlFor: "new-password", children: "New Password" }),
782
- /* @__PURE__ */ jsx2(Input, { id: "new-password", type: "password", autoComplete: "new-password", minLength: 8, required: true, value: password, onChange: (event) => setPassword(event.target.value) })
783
- ] }),
784
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
785
- /* @__PURE__ */ jsx2(Label, { htmlFor: "confirm-password", children: "Confirm New Password" }),
786
- /* @__PURE__ */ jsx2(Input, { id: "confirm-password", type: "password", autoComplete: "new-password", minLength: 8, required: true, value: passwordConfirmation, onChange: (event) => setPasswordConfirmation(event.target.value) })
787
- ] }),
788
- /* @__PURE__ */ jsx2(Button, { type: "submit", disabled: loading, children: loading ? "Changing..." : "Change Password" })
789
- ] });
790
- }
791
- function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, onSuccess, onError, onReportSuspicious }) {
792
- const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
793
- const [currentAttemptToken, setCurrentAttemptToken] = React3.useState(attemptToken);
794
- const [code, setCode] = React3.useState("");
795
- const [loading, setLoading] = React3.useState(false);
796
- const [resending, setResending] = React3.useState(false);
797
- const [message, setMessage] = React3.useState("");
798
- React3.useEffect(() => setCurrentAttemptToken(attemptToken), [attemptToken]);
799
- async function onSubmit(event) {
800
- event.preventDefault();
801
- setLoading(true);
802
- setMessage("");
803
- try {
804
- const result = await postForm(endpoints.twoFactorVerify ?? "/api/auth/two-factor/verify", {
805
- attempt_token: currentAttemptToken,
806
- code: code.trim()
807
- }, endpoints.csrfToken);
808
- onSuccess?.(result);
809
- if (!onSuccess && result.redirect) window.location.href = result.redirect;
810
- } catch (error) {
811
- setCode("");
812
- onError?.(error instanceof Error ? error.message : "Verification failed");
813
- } finally {
814
- setLoading(false);
815
- }
816
- }
817
- async function resend() {
818
- setResending(true);
819
- setMessage("");
820
- try {
821
- const result = await postForm(endpoints.twoFactorResend ?? "/api/auth/two-factor/resend", {
822
- attempt_token: currentAttemptToken
823
- }, endpoints.csrfToken);
824
- if (typeof result.attempt_token === "string") setCurrentAttemptToken(result.attempt_token);
825
- setMessage(result.message ?? "A new verification code has been sent.");
826
- } catch (error) {
827
- onError?.(error instanceof Error ? error.message : "Could not resend verification code");
828
- } finally {
829
- setResending(false);
830
- }
831
- }
832
- async function reportSuspicious() {
833
- const url = endpoints.twoFactorReport?.(currentAttemptToken) ?? `/api/auth/two-factor/report/${encodeURIComponent(currentAttemptToken)}`;
834
- try {
835
- const result = await postForm(url, {}, endpoints.csrfToken);
836
- setMessage(result.message ?? "This login attempt has been reported.");
837
- onReportSuspicious?.(result);
838
- } catch (error) {
839
- onError?.(error instanceof Error ? error.message : "Could not report the login attempt");
840
- }
841
- }
842
- return /* @__PURE__ */ jsxs2(Card, { children: [
843
- /* @__PURE__ */ jsxs2(CardHeader, { children: [
844
- /* @__PURE__ */ jsx2(CardTitle, { children: "Verify Your Login" }),
845
- /* @__PURE__ */ jsx2(CardDescription, { children: "Enter the 6-digit code sent to your email address." })
846
- ] }),
847
- /* @__PURE__ */ jsxs2(CardContent, { children: [
848
- /* @__PURE__ */ jsxs2("form", { className: "space-y-4", onSubmit: (event) => void onSubmit(event), children: [
849
- /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
850
- /* @__PURE__ */ jsx2(Label, { htmlFor: "two-factor-code", children: "Verification Code" }),
851
- /* @__PURE__ */ jsx2(
852
- Input,
853
- {
854
- id: "two-factor-code",
855
- type: "text",
856
- inputMode: "numeric",
857
- pattern: "[0-9]{6}",
858
- maxLength: 6,
859
- autoComplete: "one-time-code",
860
- required: true,
861
- value: code,
862
- onChange: (event) => setCode(event.target.value.replace(/\D/g, ""))
863
- }
864
- )
865
- ] }),
866
- /* @__PURE__ */ jsx2(Button, { type: "submit", className: "w-full", disabled: loading || code.length !== 6, children: loading ? "Verifying..." : "Verify Code" })
867
- ] }),
868
- /* @__PURE__ */ jsxs2("div", { className: "mt-4 space-y-2 text-sm", children: [
869
- /* @__PURE__ */ jsx2(Button, { type: "button", variant: "outline", className: "w-full", disabled: resending, onClick: () => void resend(), children: resending ? "Sending..." : "Send a new code" }),
870
- /* @__PURE__ */ jsx2("button", { type: "button", className: "text-sm underline", onClick: () => void reportSuspicious(), children: "This was not me" }),
871
- message ? /* @__PURE__ */ jsx2("p", { children: message }) : null,
872
- appEnv && appEnv !== "production" ? /* @__PURE__ */ jsx2("p", { children: "Dev mode: use 999999 to bypass 2FA." }) : null
873
- ] })
874
- ] })
875
- ] });
876
- }
877
-
807
+ if (Object.prototype.hasOwnProperty.call(initialValues, field.name)) return initialValues[field.name];
808
+ if (field.initialValue !== void 0) return field.initialValue;
809
+ return field.type === "checkbox" ? false : "";
810
+ }
811
+ function SignupForm({ endpoints = {}, components, onSuccess, onError, fields = defaultSignupFields(), initialValues = {}, errors = {}, submitMode = "fetch", title = "Create Account", description, submitLabel = "Create Account", submittingLabel = "Creating account..." }) {
812
+ const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
813
+ const [values, setValues] = React.useState(() => Object.fromEntries(fields.map((field) => [field.name, initialSignupValue(field, initialValues)])));
814
+ const [fieldErrors, setFieldErrors] = React.useState(errors);
815
+ const [loading, setLoading] = React.useState(false);
816
+ async function onSubmit(event) {
817
+ setLoading(true);
818
+ if (submitMode === "native") return;
819
+ event.preventDefault();
820
+ setFieldErrors({});
821
+ try {
822
+ const result = await postForm(endpoints.signup ?? "/register", values, endpoints.csrfToken);
823
+ await onSuccess?.(result, values);
824
+ if (!onSuccess && result.redirect) window.location.href = result.redirect;
825
+ } catch (error) {
826
+ if (error instanceof AuthRequestError && error.result.errors && typeof error.result.errors === "object") setFieldErrors(error.result.errors);
827
+ onError?.(error instanceof Error ? error.message : "Signup failed");
828
+ } finally {
829
+ setLoading(false);
830
+ }
831
+ }
832
+ function setValue(name, value) {
833
+ setValues((current) => ({
834
+ ...current,
835
+ [name]: value
836
+ }));
837
+ }
838
+ return /* @__PURE__ */ jsxs(Card, { children: [/* @__PURE__ */ jsxs(CardHeader, { children: [/* @__PURE__ */ jsx(CardTitle, { children: title }), description ? /* @__PURE__ */ jsx(CardDescription, { children: description }) : null] }), /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsxs("form", {
839
+ className: "space-y-4",
840
+ method: submitMode === "native" ? "POST" : void 0,
841
+ action: endpoints.signup ?? "/register",
842
+ onSubmit: (event) => void onSubmit(event),
843
+ children: [
844
+ submitMode === "native" ? /* @__PURE__ */ jsx("input", {
845
+ type: "hidden",
846
+ name: "_token",
847
+ value: getCsrfToken(endpoints.csrfToken)
848
+ }) : null,
849
+ fields.map((field) => {
850
+ if (field.hiddenWhen?.(values)) return null;
851
+ const error = fieldErrors[field.name]?.[0];
852
+ const value = values[field.name];
853
+ if (field.type === "checkbox") return /* @__PURE__ */ jsxs("div", {
854
+ className: field.containerClassName ?? "space-y-1",
855
+ children: [
856
+ /* @__PURE__ */ jsxs("label", {
857
+ className: "flex items-start gap-2 text-sm",
858
+ children: [/* @__PURE__ */ jsx("input", {
859
+ id: `signup-${field.name}`,
860
+ name: field.name,
861
+ type: "checkbox",
862
+ value: "1",
863
+ checked: Boolean(value),
864
+ onChange: (event) => setValue(field.name, event.target.checked),
865
+ required: field.required
866
+ }), /* @__PURE__ */ jsx("span", { children: field.label })]
867
+ }),
868
+ field.helpText ? /* @__PURE__ */ jsx("p", {
869
+ className: "text-xs text-muted-foreground",
870
+ children: field.helpText
871
+ }) : null,
872
+ error ? /* @__PURE__ */ jsx("p", {
873
+ className: "text-sm text-destructive",
874
+ children: error
875
+ }) : null
876
+ ]
877
+ }, field.name);
878
+ return /* @__PURE__ */ jsxs("div", {
879
+ className: field.containerClassName ?? "space-y-1",
880
+ children: [
881
+ /* @__PURE__ */ jsx(Label, {
882
+ htmlFor: `signup-${field.name}`,
883
+ children: field.label
884
+ }),
885
+ /* @__PURE__ */ jsx(Input, {
886
+ id: `signup-${field.name}`,
887
+ name: field.name,
888
+ type: field.type ?? "text",
889
+ placeholder: field.placeholder,
890
+ required: field.required,
891
+ autoComplete: field.autoComplete,
892
+ minLength: field.minLength,
893
+ maxLength: field.maxLength,
894
+ pattern: field.pattern,
895
+ inputMode: field.inputMode,
896
+ className: field.className,
897
+ "aria-invalid": Boolean(error),
898
+ value: String(value ?? ""),
899
+ onChange: (event) => setValue(field.name, event.target.value)
900
+ }),
901
+ field.helpText ? /* @__PURE__ */ jsx("p", {
902
+ className: "text-xs text-muted-foreground",
903
+ children: field.helpText
904
+ }) : null,
905
+ error ? /* @__PURE__ */ jsx("p", {
906
+ className: "text-sm text-destructive",
907
+ children: error
908
+ }) : null
909
+ ]
910
+ }, field.name);
911
+ }),
912
+ /* @__PURE__ */ jsx(Button, {
913
+ type: "submit",
914
+ className: "w-full",
915
+ disabled: loading,
916
+ children: loading ? submittingLabel : submitLabel
917
+ })
918
+ ]
919
+ }) })] });
920
+ }
921
+ function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onError, onSubmitStart, submitClassName, onRedirect, rateLimitMessage = defaultRateLimitMessage }) {
922
+ const { Button, Input, Label } = resolveAuthComponents(components);
923
+ const [email, setEmail] = React.useState("");
924
+ const [loading, setLoading] = React.useState(false);
925
+ const submitting = React.useRef(false);
926
+ async function onSubmit(event) {
927
+ event.preventDefault();
928
+ if (submitting.current) return;
929
+ submitting.current = true;
930
+ onSubmitStart?.();
931
+ setLoading(true);
932
+ try {
933
+ const result = await postForm(endpoints.forgotPassword ?? "/api/auth/forgot-password", { email }, endpoints.csrfToken);
934
+ onSuccess?.(result);
935
+ const redirect = safeRedirectUrl(result.redirect);
936
+ if (redirect !== null) {
937
+ if (onRedirect) onRedirect(redirect, result);
938
+ else window.location.assign(redirect);
939
+ }
940
+ } catch (error) {
941
+ onError?.(errorMessage(error, "Password reset request failed", rateLimitMessage));
942
+ } finally {
943
+ submitting.current = false;
944
+ setLoading(false);
945
+ }
946
+ }
947
+ return /* @__PURE__ */ jsxs("form", {
948
+ className: "space-y-4",
949
+ onSubmit: (event) => void onSubmit(event),
950
+ children: [/* @__PURE__ */ jsxs("div", {
951
+ className: "space-y-1",
952
+ children: [/* @__PURE__ */ jsx(Label, {
953
+ htmlFor: "reset-email",
954
+ children: "Email"
955
+ }), /* @__PURE__ */ jsx(Input, {
956
+ id: "reset-email",
957
+ type: "email",
958
+ autoComplete: "email",
959
+ required: true,
960
+ value: email,
961
+ onChange: (event) => setEmail(event.target.value)
962
+ })]
963
+ }), /* @__PURE__ */ jsx(Button, {
964
+ type: "submit",
965
+ className: submitClassName,
966
+ disabled: loading,
967
+ children: loading ? "Sending..." : "Send Reset Link"
968
+ })]
969
+ });
970
+ }
971
+ function ResetPasswordForm({ endpoints = {}, components, onSuccess, onError, onSubmitStart, submitClassName, token: initialToken = "", email: initialEmail = "", idPrefix = "reset-password", minPasswordLength, validatePasswordConfirmation = false, passwordLabel = "Password", passwordConfirmationLabel = "Confirm Password", passwordHelpText }) {
972
+ const { Button, Input, Label } = resolveAuthComponents(components);
973
+ const [email, setEmail] = React.useState(initialEmail);
974
+ const [token, setToken] = React.useState(initialToken);
975
+ const [password, setPassword] = React.useState("");
976
+ const [passwordConfirmation, setPasswordConfirmation] = React.useState("");
977
+ const [loading, setLoading] = React.useState(false);
978
+ const submitting = React.useRef(false);
979
+ async function onSubmit(event) {
980
+ event.preventDefault();
981
+ if (submitting.current) return;
982
+ onSubmitStart?.();
983
+ if (validatePasswordConfirmation && password !== passwordConfirmation) {
984
+ onError?.("Passwords do not match.");
985
+ return;
986
+ }
987
+ if (minPasswordLength !== void 0 && password.length < minPasswordLength) {
988
+ onError?.(`Password must be at least ${minPasswordLength} characters long.`);
989
+ return;
990
+ }
991
+ submitting.current = true;
992
+ setLoading(true);
993
+ try {
994
+ const result = await postForm(endpoints.resetPassword ?? "/api/auth/reset-password", {
995
+ email,
996
+ token,
997
+ password,
998
+ password_confirmation: passwordConfirmation
999
+ }, endpoints.csrfToken);
1000
+ onSuccess?.(result);
1001
+ } catch (error) {
1002
+ onError?.(error instanceof Error ? error.message : "Password reset failed");
1003
+ } finally {
1004
+ submitting.current = false;
1005
+ setLoading(false);
1006
+ }
1007
+ }
1008
+ return /* @__PURE__ */ jsxs("form", {
1009
+ className: "space-y-4",
1010
+ onSubmit: (event) => void onSubmit(event),
1011
+ children: [
1012
+ /* @__PURE__ */ jsx(Input, {
1013
+ type: "hidden",
1014
+ value: token,
1015
+ onChange: (event) => setToken(event.target.value)
1016
+ }),
1017
+ /* @__PURE__ */ jsxs("div", {
1018
+ className: "space-y-1",
1019
+ children: [/* @__PURE__ */ jsx(Label, {
1020
+ htmlFor: `${idPrefix}-email`,
1021
+ children: "Email"
1022
+ }), /* @__PURE__ */ jsx(Input, {
1023
+ id: `${idPrefix}-email`,
1024
+ type: "email",
1025
+ autoComplete: "email",
1026
+ required: true,
1027
+ value: email,
1028
+ onChange: (event) => setEmail(event.target.value)
1029
+ })]
1030
+ }),
1031
+ /* @__PURE__ */ jsxs("div", {
1032
+ className: "space-y-1",
1033
+ children: [
1034
+ /* @__PURE__ */ jsx(Label, {
1035
+ htmlFor: idPrefix,
1036
+ children: passwordLabel
1037
+ }),
1038
+ /* @__PURE__ */ jsx(Input, {
1039
+ id: idPrefix,
1040
+ type: "password",
1041
+ autoComplete: "new-password",
1042
+ minLength: minPasswordLength,
1043
+ required: true,
1044
+ value: password,
1045
+ onChange: (event) => setPassword(event.target.value)
1046
+ }),
1047
+ passwordHelpText ? /* @__PURE__ */ jsx("p", {
1048
+ className: "text-xs text-muted-foreground",
1049
+ children: passwordHelpText
1050
+ }) : null
1051
+ ]
1052
+ }),
1053
+ /* @__PURE__ */ jsxs("div", {
1054
+ className: "space-y-1",
1055
+ children: [/* @__PURE__ */ jsx(Label, {
1056
+ htmlFor: `${idPrefix}-confirmation`,
1057
+ children: passwordConfirmationLabel
1058
+ }), /* @__PURE__ */ jsx(Input, {
1059
+ id: `${idPrefix}-confirmation`,
1060
+ type: "password",
1061
+ autoComplete: "new-password",
1062
+ minLength: minPasswordLength,
1063
+ required: true,
1064
+ value: passwordConfirmation,
1065
+ onChange: (event) => setPasswordConfirmation(event.target.value)
1066
+ })]
1067
+ }),
1068
+ /* @__PURE__ */ jsx(Button, {
1069
+ type: "submit",
1070
+ className: submitClassName,
1071
+ disabled: loading,
1072
+ children: loading ? "Resetting..." : "Reset Password"
1073
+ })
1074
+ ]
1075
+ });
1076
+ }
1077
+ function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError, method = "POST" }) {
1078
+ const { Button, Input, Label } = resolveAuthComponents(components);
1079
+ const [currentPassword, setCurrentPassword] = React.useState("");
1080
+ const [password, setPassword] = React.useState("");
1081
+ const [passwordConfirmation, setPasswordConfirmation] = React.useState("");
1082
+ const [loading, setLoading] = React.useState(false);
1083
+ const submitting = React.useRef(false);
1084
+ async function onSubmit(event) {
1085
+ event.preventDefault();
1086
+ if (submitting.current) return;
1087
+ if (password !== passwordConfirmation) {
1088
+ onError?.("New passwords do not match.");
1089
+ return;
1090
+ }
1091
+ submitting.current = true;
1092
+ setLoading(true);
1093
+ try {
1094
+ const result = await postForm(endpoints.changePassword ?? "/api/change-password", {
1095
+ current_password: currentPassword,
1096
+ password,
1097
+ password_confirmation: passwordConfirmation
1098
+ }, endpoints.csrfToken, method);
1099
+ setCurrentPassword("");
1100
+ setPassword("");
1101
+ setPasswordConfirmation("");
1102
+ onSuccess?.(result);
1103
+ } catch (error) {
1104
+ onError?.(error instanceof Error ? error.message : "Password change failed");
1105
+ } finally {
1106
+ submitting.current = false;
1107
+ setLoading(false);
1108
+ }
1109
+ }
1110
+ return /* @__PURE__ */ jsxs("form", {
1111
+ className: "space-y-4",
1112
+ onSubmit: (event) => void onSubmit(event),
1113
+ children: [
1114
+ /* @__PURE__ */ jsxs("div", {
1115
+ className: "space-y-1",
1116
+ children: [/* @__PURE__ */ jsx(Label, {
1117
+ htmlFor: "current-password",
1118
+ children: "Current Password"
1119
+ }), /* @__PURE__ */ jsx(Input, {
1120
+ id: "current-password",
1121
+ type: "password",
1122
+ autoComplete: "current-password",
1123
+ required: true,
1124
+ value: currentPassword,
1125
+ onChange: (event) => setCurrentPassword(event.target.value)
1126
+ })]
1127
+ }),
1128
+ /* @__PURE__ */ jsxs("div", {
1129
+ className: "space-y-1",
1130
+ children: [/* @__PURE__ */ jsx(Label, {
1131
+ htmlFor: "new-password",
1132
+ children: "New Password"
1133
+ }), /* @__PURE__ */ jsx(Input, {
1134
+ id: "new-password",
1135
+ type: "password",
1136
+ autoComplete: "new-password",
1137
+ minLength: 8,
1138
+ required: true,
1139
+ value: password,
1140
+ onChange: (event) => setPassword(event.target.value)
1141
+ })]
1142
+ }),
1143
+ /* @__PURE__ */ jsxs("div", {
1144
+ className: "space-y-1",
1145
+ children: [/* @__PURE__ */ jsx(Label, {
1146
+ htmlFor: "confirm-password",
1147
+ children: "Confirm New Password"
1148
+ }), /* @__PURE__ */ jsx(Input, {
1149
+ id: "confirm-password",
1150
+ type: "password",
1151
+ autoComplete: "new-password",
1152
+ minLength: 8,
1153
+ required: true,
1154
+ value: passwordConfirmation,
1155
+ onChange: (event) => setPasswordConfirmation(event.target.value)
1156
+ })]
1157
+ }),
1158
+ /* @__PURE__ */ jsx(Button, {
1159
+ type: "submit",
1160
+ disabled: loading,
1161
+ children: loading ? "Changing..." : "Change Password"
1162
+ })
1163
+ ]
1164
+ });
1165
+ }
1166
+ function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, testCodeHint, header, hideResend = false, hideReportSuspicious = false, reportSuspiciousLabel = "This was not me", reportedMessage = "This login attempt has been reported.", rateLimitMessage = null, onSubmitStart, onSuccess, onError, onReportSuspicious, title = "Verify Your Login", ...copy }) {
1167
+ const { Button } = resolveAuthComponents(components);
1168
+ const [currentAttemptToken, setCurrentAttemptToken] = React.useState(attemptToken);
1169
+ const reporting = React.useRef(false);
1170
+ const [reportPending, setReportPending] = React.useState(false);
1171
+ React.useEffect(() => setCurrentAttemptToken(attemptToken), [attemptToken]);
1172
+ const hint = testCodeHint !== void 0 ? testCodeHint : appEnv && appEnv !== "production" ? "Dev mode: use 999999 to bypass 2FA." : null;
1173
+ async function reportSuspicious({ setMessage }) {
1174
+ if (reporting.current) return;
1175
+ reporting.current = true;
1176
+ setReportPending(true);
1177
+ const url = endpoints.twoFactorReport?.(currentAttemptToken) ?? `/api/auth/two-factor/report/${encodeURIComponent(currentAttemptToken)}`;
1178
+ try {
1179
+ const result = await postForm(url, {}, endpoints.csrfToken);
1180
+ setMessage(typeof result.message === "string" && result.message !== "" ? result.message : reportedMessage);
1181
+ onReportSuspicious?.(result);
1182
+ } catch (error) {
1183
+ onError?.(errorMessage(error, "Could not report the login attempt", rateLimitMessage));
1184
+ } finally {
1185
+ reporting.current = false;
1186
+ setReportPending(false);
1187
+ }
1188
+ }
1189
+ return /* @__PURE__ */ jsx(EmailCodeForm, {
1190
+ ...copy,
1191
+ title,
1192
+ components,
1193
+ idPrefix: "two-factor",
1194
+ csrfToken: endpoints.csrfToken,
1195
+ submitUrl: endpoints.twoFactorVerify ?? "/api/auth/two-factor/verify",
1196
+ buildSubmitBody: (code) => ({
1197
+ attempt_token: currentAttemptToken,
1198
+ code
1199
+ }),
1200
+ resendUrl: endpoints.twoFactorResend ?? "/api/auth/two-factor/resend",
1201
+ buildResendBody: () => ({ attempt_token: currentAttemptToken }),
1202
+ onResend: (result) => {
1203
+ if (typeof result.attempt_token === "string") setCurrentAttemptToken(result.attempt_token);
1204
+ },
1205
+ header,
1206
+ hideResend,
1207
+ testCodeHint: hint,
1208
+ rateLimitMessage,
1209
+ onSubmitStart,
1210
+ onSuccess,
1211
+ onError,
1212
+ actions: hideReportSuspicious ? void 0 : (actions) => /* @__PURE__ */ jsx(Button, {
1213
+ type: "button",
1214
+ variant: "link",
1215
+ size: "sm",
1216
+ className: "h-auto px-0 text-sm",
1217
+ disabled: reportPending,
1218
+ onClick: () => void reportSuspicious(actions),
1219
+ children: reportSuspiciousLabel
1220
+ })
1221
+ });
1222
+ }
878
1223
  // src/passkey-section.tsx
879
- import { Key, Plus, Trash2 } from "lucide-react";
880
- import * as React4 from "react";
881
- import { flushSync } from "react-dom";
882
- import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
883
1224
  function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
884
- const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
885
- const [passkeys, setPasskeys] = React4.useState([]);
886
- const [loading, setLoading] = React4.useState(true);
887
- const [registering, setRegistering] = React4.useState(false);
888
- const [pendingName, setPendingName] = React4.useState("");
889
- const listUrl = endpoints.passkeyList ?? "/api/passkeys";
890
- const registerOptionsUrl = endpoints.passkeyRegisterOptions ?? "/api/passkeys/register/options";
891
- const registerUrl = endpoints.passkeyRegister ?? "/api/passkeys/register";
892
- const deleteUrl = endpoints.passkeyDelete ?? ((id) => `/api/passkeys/${id}`);
893
- const fetchPasskeys = React4.useCallback(async () => {
894
- try {
895
- const res = await fetch(listUrl);
896
- if (res.ok) {
897
- setPasskeys(await res.json());
898
- }
899
- } catch {
900
- onError?.("passkeys", "Failed to load passkeys");
901
- } finally {
902
- setLoading(false);
903
- }
904
- }, [listUrl, onError]);
905
- React4.useEffect(() => {
906
- void fetchPasskeys();
907
- }, [fetchPasskeys]);
908
- async function registerPasskey2() {
909
- const name = pendingName || getDefaultPasskeyName();
910
- flushSync(() => setPendingName(name));
911
- setRegistering(true);
912
- try {
913
- await registerPasskey({ endpoints: { ...endpoints, passkeyRegisterOptions: registerOptionsUrl, passkeyRegister: registerUrl }, name });
914
- setPendingName("");
915
- onSuccess?.("Passkey registered successfully.");
916
- await fetchPasskeys();
917
- } catch (caughtError) {
918
- if (!isAbortError(caughtError)) {
919
- onError?.("passkeys", caughtError instanceof Error ? caughtError.message : "Passkey registration failed");
920
- }
921
- } finally {
922
- setRegistering(false);
923
- }
924
- }
925
- async function deletePasskey(id) {
926
- try {
927
- const res = await fetch(deleteUrl(id), {
928
- method: "DELETE",
929
- headers: { "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken) }
930
- });
931
- if (!res.ok) {
932
- throw new Error("Delete failed");
933
- }
934
- setPasskeys((current) => current.filter((passkey) => passkey.id !== id));
935
- onSuccess?.("Passkey removed.");
936
- } catch {
937
- onError?.("passkeys", "Failed to delete passkey");
938
- }
939
- }
940
- const isWebAuthnSupported = typeof window !== "undefined" && !!window.PublicKeyCredential;
941
- return /* @__PURE__ */ jsxs3(Card, { children: [
942
- /* @__PURE__ */ jsxs3(CardHeader, { children: [
943
- /* @__PURE__ */ jsxs3(CardTitle, { className: "flex items-center gap-2", children: [
944
- /* @__PURE__ */ jsx3(Key, { className: "h-5 w-5" }),
945
- "Passkeys"
946
- ] }),
947
- /* @__PURE__ */ jsx3(CardDescription, { children: "Manage passkeys for passwordless login." })
948
- ] }),
949
- /* @__PURE__ */ jsxs3(CardContent, { className: "space-y-4", children: [
950
- !isWebAuthnSupported ? /* @__PURE__ */ jsx3("p", { className: "text-sm text-muted-foreground", children: "Your browser does not support passkeys." }) : null,
951
- loading ? /* @__PURE__ */ jsx3("p", { className: "text-sm text-muted-foreground", children: "Loading passkeys..." }) : passkeys.length === 0 ? /* @__PURE__ */ jsx3("p", { className: "text-sm text-muted-foreground", children: "No passkeys registered yet." }) : /* @__PURE__ */ jsx3("div", { className: "divide-y rounded-md border", children: passkeys.map((passkey) => /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-between gap-3 p-3", children: [
952
- /* @__PURE__ */ jsxs3("div", { children: [
953
- /* @__PURE__ */ jsx3("div", { className: "font-medium", children: passkey.name }),
954
- /* @__PURE__ */ jsx3("div", { className: "text-sm text-muted-foreground", children: new Date(passkey.created_at).toLocaleDateString() })
955
- ] }),
956
- /* @__PURE__ */ jsx3(Button, { type: "button", variant: "ghost", size: "icon", "aria-label": "Delete passkey", onClick: () => void deletePasskey(passkey.id), children: /* @__PURE__ */ jsx3(Trash2, {}) })
957
- ] }, passkey.id)) }),
958
- isWebAuthnSupported ? /* @__PURE__ */ jsxs3("div", { className: "flex flex-col gap-2 sm:flex-row", children: [
959
- /* @__PURE__ */ jsxs3("div", { className: "flex-1 space-y-1", children: [
960
- /* @__PURE__ */ jsx3(Label, { htmlFor: "passkey-name", children: "Passkey name" }),
961
- /* @__PURE__ */ jsx3(Input, { id: "passkey-name", value: pendingName, onChange: (event) => setPendingName(event.target.value), placeholder: getDefaultPasskeyName() })
962
- ] }),
963
- /* @__PURE__ */ jsxs3(Button, { type: "button", className: "self-end", variant: "outline", disabled: registering, onClick: () => void registerPasskey2(), children: [
964
- /* @__PURE__ */ jsx3(Plus, {}),
965
- registering ? "Registering..." : "Add Passkey"
966
- ] })
967
- ] }) : null
968
- ] })
969
- ] });
970
- }
971
-
1225
+ const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
1226
+ const [passkeys, setPasskeys] = React.useState([]);
1227
+ const [loading, setLoading] = React.useState(true);
1228
+ const [registering, setRegistering] = React.useState(false);
1229
+ const [pendingName, setPendingName] = React.useState("");
1230
+ const [needsConfirmation, setNeedsConfirmation] = React.useState(false);
1231
+ const [password, setPassword] = React.useState("");
1232
+ const [confirmationError, setConfirmationError] = React.useState("");
1233
+ const operation = React.useRef(null);
1234
+ const passwordId = React.useId();
1235
+ React.useEffect(() => {
1236
+ operation.current = null;
1237
+ setRegistering(false);
1238
+ setNeedsConfirmation(false);
1239
+ setPassword("");
1240
+ setConfirmationError("");
1241
+ setPendingName("");
1242
+ return () => {
1243
+ operation.current?.abort();
1244
+ operation.current = null;
1245
+ };
1246
+ }, [
1247
+ endpoints.confirmPassword,
1248
+ endpoints.passkeyConfirmOptions,
1249
+ endpoints.passkeyConfirm,
1250
+ endpoints.passkeyRegisterOptions,
1251
+ endpoints.passkeyRegister,
1252
+ endpoints.csrfToken
1253
+ ]);
1254
+ const listUrl = endpoints.passkeyList ?? "/api/passkeys";
1255
+ const registerOptionsUrl = endpoints.passkeyRegisterOptions ?? "/api/passkeys/register/options";
1256
+ const registerUrl = endpoints.passkeyRegister ?? "/api/passkeys/register";
1257
+ const deleteUrl = endpoints.passkeyDelete ?? ((id) => `/api/passkeys/${id}`);
1258
+ const fetchPasskeys = React.useCallback(async () => {
1259
+ try {
1260
+ const res = await fetch(listUrl);
1261
+ if (res.ok) setPasskeys(await res.json());
1262
+ } catch {
1263
+ onError?.("passkeys", "Failed to load passkeys");
1264
+ } finally {
1265
+ setLoading(false);
1266
+ }
1267
+ }, [listUrl, onError]);
1268
+ React.useEffect(() => {
1269
+ fetchPasskeys();
1270
+ }, [fetchPasskeys]);
1271
+ async function registerPasskey$1(method) {
1272
+ if (operation.current && !operation.current.signal.aborted) return;
1273
+ const controller = new AbortController();
1274
+ operation.current = controller;
1275
+ const name = pendingName || getDefaultPasskeyName();
1276
+ const submittedPassword = password;
1277
+ setPassword("");
1278
+ setConfirmationError("");
1279
+ flushSync(() => setPendingName(name));
1280
+ setRegistering(true);
1281
+ try {
1282
+ if (method === "password") await confirmPasswordForPasskey({
1283
+ password: submittedPassword,
1284
+ endpoints,
1285
+ signal: controller.signal
1286
+ });
1287
+ if (method === "passkey") await confirmPasskey({
1288
+ endpoints,
1289
+ signal: controller.signal
1290
+ });
1291
+ throwIfAborted(controller.signal);
1292
+ await registerPasskey({
1293
+ endpoints: {
1294
+ ...endpoints,
1295
+ passkeyRegisterOptions: registerOptionsUrl,
1296
+ passkeyRegister: registerUrl
1297
+ },
1298
+ name,
1299
+ signal: controller.signal
1300
+ });
1301
+ throwIfAborted(controller.signal);
1302
+ setNeedsConfirmation(false);
1303
+ setPendingName("");
1304
+ onSuccess?.("Passkey registered successfully.");
1305
+ await fetchPasskeys();
1306
+ } catch (caughtError) {
1307
+ if (!controller.signal.aborted && !isAbortError(caughtError)) {
1308
+ if (caughtError instanceof PasswordConfirmationRequiredError) {
1309
+ setNeedsConfirmation(true);
1310
+ if (method) setConfirmationError("Confirmation is still required. Try again or sign in again.");
1311
+ } else {
1312
+ const message = caughtError instanceof Error ? caughtError.message : "Passkey registration failed";
1313
+ if (method) setConfirmationError(message);
1314
+ onError?.("passkeys", message);
1315
+ }
1316
+ }
1317
+ } finally {
1318
+ if (operation.current === controller) {
1319
+ operation.current = null;
1320
+ if (!controller.signal.aborted) setRegistering(false);
1321
+ }
1322
+ }
1323
+ }
1324
+ function cancelConfirmation() {
1325
+ operation.current?.abort();
1326
+ operation.current = null;
1327
+ setRegistering(false);
1328
+ setPassword("");
1329
+ setConfirmationError("");
1330
+ setNeedsConfirmation(false);
1331
+ }
1332
+ async function deletePasskey(id) {
1333
+ try {
1334
+ if (!(await fetch(deleteUrl(id), {
1335
+ method: "DELETE",
1336
+ headers: { "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken) }
1337
+ })).ok) throw new Error("Delete failed");
1338
+ setPasskeys((current) => current.filter((passkey) => passkey.id !== id));
1339
+ onSuccess?.("Passkey removed.");
1340
+ } catch {
1341
+ onError?.("passkeys", "Failed to delete passkey");
1342
+ }
1343
+ }
1344
+ const isWebAuthnSupported = typeof window !== "undefined" && !!window.PublicKeyCredential;
1345
+ return /* @__PURE__ */ jsxs(Card, { children: [/* @__PURE__ */ jsxs(CardHeader, { children: [/* @__PURE__ */ jsxs(CardTitle, {
1346
+ className: "flex items-center gap-2",
1347
+ children: [/* @__PURE__ */ jsx(Key, { className: "h-5 w-5" }), "Passkeys"]
1348
+ }), /* @__PURE__ */ jsx(CardDescription, { children: "Manage passkeys for passwordless login." })] }), /* @__PURE__ */ jsxs(CardContent, {
1349
+ className: "space-y-4",
1350
+ children: [
1351
+ !isWebAuthnSupported ? /* @__PURE__ */ jsx("p", {
1352
+ className: "text-sm text-muted-foreground",
1353
+ children: "Your browser does not support passkeys."
1354
+ }) : null,
1355
+ loading ? /* @__PURE__ */ jsx("p", {
1356
+ className: "text-sm text-muted-foreground",
1357
+ children: "Loading passkeys..."
1358
+ }) : passkeys.length === 0 ? /* @__PURE__ */ jsx("p", {
1359
+ className: "text-sm text-muted-foreground",
1360
+ children: "No passkeys registered yet."
1361
+ }) : /* @__PURE__ */ jsx("div", {
1362
+ className: "divide-y rounded-md border",
1363
+ children: passkeys.map((passkey) => /* @__PURE__ */ jsxs("div", {
1364
+ className: "flex items-center justify-between gap-3 p-3",
1365
+ children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("div", {
1366
+ className: "font-medium",
1367
+ children: passkey.name
1368
+ }), /* @__PURE__ */ jsx("div", {
1369
+ className: "text-sm text-muted-foreground",
1370
+ children: new Date(passkey.created_at).toLocaleDateString()
1371
+ })] }), /* @__PURE__ */ jsx(Button, {
1372
+ type: "button",
1373
+ variant: "ghost",
1374
+ size: "icon",
1375
+ "aria-label": "Delete passkey",
1376
+ onClick: () => void deletePasskey(passkey.id),
1377
+ children: /* @__PURE__ */ jsx(Trash2, {})
1378
+ })]
1379
+ }, passkey.id))
1380
+ }),
1381
+ isWebAuthnSupported ? /* @__PURE__ */ jsxs("div", {
1382
+ className: "flex flex-col gap-2 sm:flex-row",
1383
+ children: [/* @__PURE__ */ jsxs("div", {
1384
+ className: "flex-1 space-y-1",
1385
+ children: [/* @__PURE__ */ jsx(Label, {
1386
+ htmlFor: "passkey-name",
1387
+ children: "Passkey name"
1388
+ }), /* @__PURE__ */ jsx(Input, {
1389
+ id: "passkey-name",
1390
+ value: pendingName,
1391
+ onChange: (event) => setPendingName(event.target.value),
1392
+ placeholder: getDefaultPasskeyName()
1393
+ })]
1394
+ }), /* @__PURE__ */ jsxs(Button, {
1395
+ type: "button",
1396
+ className: "self-end",
1397
+ variant: "outline",
1398
+ disabled: registering || needsConfirmation,
1399
+ onClick: () => void registerPasskey$1(),
1400
+ children: [/* @__PURE__ */ jsx(Plus, {}), registering ? "Registering..." : "Add Passkey"]
1401
+ })]
1402
+ }) : null,
1403
+ needsConfirmation ? /* @__PURE__ */ jsxs("div", {
1404
+ role: "group",
1405
+ "aria-label": "Confirm your identity",
1406
+ className: "space-y-3",
1407
+ children: [
1408
+ /* @__PURE__ */ jsx("p", { children: "Confirm your identity to add a passkey. Use your password or an existing passkey." }),
1409
+ /* @__PURE__ */ jsxs("div", {
1410
+ className: "space-y-1",
1411
+ children: [/* @__PURE__ */ jsx(Label, {
1412
+ htmlFor: passwordId,
1413
+ children: "Current password"
1414
+ }), /* @__PURE__ */ jsx(Input, {
1415
+ id: passwordId,
1416
+ type: "password",
1417
+ autoComplete: "current-password",
1418
+ value: password,
1419
+ disabled: registering,
1420
+ onChange: (event) => setPassword(event.target.value)
1421
+ })]
1422
+ }),
1423
+ confirmationError ? /* @__PURE__ */ jsx("p", {
1424
+ role: "alert",
1425
+ children: confirmationError
1426
+ }) : null,
1427
+ /* @__PURE__ */ jsxs("div", {
1428
+ className: "flex flex-wrap gap-2",
1429
+ children: [
1430
+ /* @__PURE__ */ jsx(Button, {
1431
+ type: "button",
1432
+ disabled: registering || password.length === 0,
1433
+ onClick: () => void registerPasskey$1("password"),
1434
+ children: "Confirm password and continue"
1435
+ }),
1436
+ /* @__PURE__ */ jsx(Button, {
1437
+ type: "button",
1438
+ variant: "outline",
1439
+ disabled: registering,
1440
+ onClick: () => void registerPasskey$1("passkey"),
1441
+ children: "Use existing passkey"
1442
+ }),
1443
+ /* @__PURE__ */ jsx(Button, {
1444
+ type: "button",
1445
+ variant: "ghost",
1446
+ onClick: cancelConfirmation,
1447
+ children: "Cancel"
1448
+ })
1449
+ ]
1450
+ })
1451
+ ]
1452
+ }) : null
1453
+ ]
1454
+ })] });
1455
+ }
972
1456
  // src/relying-applications.ts
1457
+ /**
1458
+ * Reduce a URL from the wire to one that is safe to put in an `href`, or reject it.
1459
+ *
1460
+ * These arrive as text in the page and end up as a link the browser will follow, so the
1461
+ * scheme is what matters: `javascript:` and `data:` both pass a server-side URL validity
1462
+ * check but execute rather than navigate. Parsing and allowing only http(s) is stronger
1463
+ * than matching a prefix — it normalises away the leading control characters, mixed case,
1464
+ * and escapes that a hand-rolled test can be walked past — and it returns the *parsed*
1465
+ * form, so what gets rendered is exactly what was validated.
1466
+ *
1467
+ * Absolute URLs only, deliberately. These point at other origins; a relative one means the
1468
+ * provider told us something unexpected, and guessing a base for it would be inventing a
1469
+ * destination rather than validating one.
1470
+ */
973
1471
  function safeApplicationHref(url) {
974
- try {
975
- const parsed = new URL(url);
976
- return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.toString() : null;
977
- } catch {
978
- return null;
979
- }
1472
+ try {
1473
+ const parsed = new URL(url);
1474
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.toString() : null;
1475
+ } catch {
1476
+ return null;
1477
+ }
980
1478
  }
1479
+ /**
1480
+ * Validate whatever the page handed over into a list that is safe to render.
1481
+ *
1482
+ * Unrecognised entries are dropped rather than throwing. This is navigation chrome: one
1483
+ * malformed entry, or a provider that has grown a field, must not be able to take down the
1484
+ * page it appears on. Anything that is not a well-formed list degrades to an empty menu.
1485
+ */
981
1486
  function relyingApplicationsFrom(value) {
982
- if (!Array.isArray(value)) {
983
- return [];
984
- }
985
- return value.flatMap((entry) => {
986
- if (typeof entry !== "object" || entry === null) {
987
- return [];
988
- }
989
- const { key, name, url } = entry;
990
- if (typeof key !== "string" || typeof name !== "string" || typeof url !== "string") {
991
- return [];
992
- }
993
- if (key === "" || name.trim() === "") {
994
- return [];
995
- }
996
- const href = safeApplicationHref(url);
997
- return href === null ? [] : [{ key, name: name.trim(), url: href }];
998
- });
999
- }
1000
-
1001
- // src/api-credentials-section.tsx
1002
- import * as React6 from "react";
1003
-
1004
- // src/scope-picker.tsx
1005
- import { ChevronRight, TriangleAlert } from "lucide-react";
1006
- import * as React5 from "react";
1007
-
1487
+ if (!Array.isArray(value)) return [];
1488
+ return value.flatMap((entry) => {
1489
+ if (typeof entry !== "object" || entry === null) return [];
1490
+ const { key, name, url } = entry;
1491
+ if (typeof key !== "string" || typeof name !== "string" || typeof url !== "string") return [];
1492
+ if (key === "" || name.trim() === "") return [];
1493
+ const href = safeApplicationHref(url);
1494
+ return href === null ? [] : [{
1495
+ key,
1496
+ name: name.trim(),
1497
+ url: href
1498
+ }];
1499
+ });
1500
+ }
1008
1501
  // src/scope-selection.ts
1502
+ /** Transitive closure of `implications`, with self-references and cycles dropped. */
1009
1503
  function closeImplications(implications) {
1010
- const closed = {};
1011
- for (const key of Object.keys(implications)) {
1012
- const seen = /* @__PURE__ */ new Set();
1013
- const walk = (id) => {
1014
- for (const needed of implications[id] ?? []) {
1015
- if (needed !== key && !seen.has(needed)) {
1016
- seen.add(needed);
1017
- walk(needed);
1018
- }
1019
- }
1020
- };
1021
- walk(key);
1022
- if (seen.size > 0) {
1023
- closed[key] = [...seen];
1024
- }
1025
- }
1026
- return closed;
1504
+ const closed = {};
1505
+ for (const key of Object.keys(implications)) {
1506
+ const seen = /* @__PURE__ */ new Set();
1507
+ const walk = (id) => {
1508
+ for (const needed of implications[id] ?? []) if (needed !== key && !seen.has(needed)) {
1509
+ seen.add(needed);
1510
+ walk(needed);
1511
+ }
1512
+ };
1513
+ walk(key);
1514
+ if (seen.size > 0) closed[key] = [...seen];
1515
+ }
1516
+ return closed;
1027
1517
  }
1518
+ /** Keeps only entries whose key and every requirement are offered; drops entries left empty. */
1028
1519
  function restrictImplications(implications, offered) {
1029
- const result = {};
1030
- for (const [key, needed] of Object.entries(implications ?? {})) {
1031
- if (!offered.has(key) || !Array.isArray(needed)) {
1032
- continue;
1033
- }
1034
- const kept = needed.filter((id) => offered.has(id));
1035
- if (kept.length > 0) {
1036
- result[key] = kept;
1037
- }
1038
- }
1039
- return result;
1520
+ const result = {};
1521
+ for (const [key, needed] of Object.entries(implications ?? {})) {
1522
+ if (!offered.has(key) || !Array.isArray(needed)) continue;
1523
+ const kept = needed.filter((id) => offered.has(id));
1524
+ if (kept.length > 0) result[key] = kept;
1525
+ }
1526
+ return result;
1040
1527
  }
1528
+ /** Orders `ids` by `catalog`, removing duplicates and ids not in it. */
1041
1529
  function inCatalogOrder(ids, catalog) {
1042
- const wanted = new Set(ids);
1043
- return catalog.filter((id) => wanted.has(id));
1530
+ const wanted = new Set(ids);
1531
+ return catalog.filter((id) => wanted.has(id));
1044
1532
  }
1533
+ /** Ticking: adds the ids and everything they need. */
1045
1534
  function withScopes(selected, ids, closed) {
1046
- const next = new Set(selected);
1047
- for (const id of ids) {
1048
- next.add(id);
1049
- for (const needed of closed[id] ?? []) {
1050
- next.add(needed);
1051
- }
1052
- }
1053
- return next;
1535
+ const next = new Set(selected);
1536
+ for (const id of ids) {
1537
+ next.add(id);
1538
+ for (const needed of closed[id] ?? []) next.add(needed);
1539
+ }
1540
+ return next;
1054
1541
  }
1542
+ /** Unticking: removes the ids and every selected scope that needs one of them. */
1055
1543
  function withoutScopes(selected, ids, closed) {
1056
- const removed = new Set(ids);
1057
- const next = new Set(selected);
1058
- for (const id of ids) {
1059
- next.delete(id);
1060
- }
1061
- for (const [scope, needed] of Object.entries(closed)) {
1062
- if (needed.some((id) => removed.has(id))) {
1063
- next.delete(scope);
1064
- }
1065
- }
1066
- return next;
1544
+ const removed = new Set(ids);
1545
+ const next = new Set(selected);
1546
+ for (const id of ids) next.delete(id);
1547
+ for (const [scope, needed] of Object.entries(closed)) if (needed.some((id) => removed.has(id))) next.delete(scope);
1548
+ return next;
1067
1549
  }
1550
+ /** Selected scopes that need `id`, in catalog order: why `id` is ticked beyond the person's own choice. */
1068
1551
  function neededBy(id, selected, closed) {
1069
- return selected.filter((scope) => scope !== id && (closed[scope] ?? []).includes(id));
1552
+ return selected.filter((scope) => scope !== id && (closed[scope] ?? []).includes(id));
1070
1553
  }
1071
1554
  function sameSelection(a, b) {
1072
- if (a.length !== b.length) {
1073
- return false;
1074
- }
1075
- const set = new Set(a);
1076
- return b.every((id) => set.has(id));
1555
+ if (a.length !== b.length) return false;
1556
+ const set = new Set(a);
1557
+ return b.every((id) => set.has(id));
1077
1558
  }
1078
-
1079
1559
  // src/scope-picker.tsx
1080
- import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
1560
+ /** Groups limited to offered scopes (first group wins), with the leftovers collected in a final "Other" group. */
1081
1561
  function resolveGroups(scopes, groups) {
1082
- if (!Array.isArray(groups) || groups.length === 0) {
1083
- return null;
1084
- }
1085
- const byId = new Map(scopes.map((scope) => [scope.id, scope]));
1086
- const placed = /* @__PURE__ */ new Set();
1087
- const resolved = [];
1088
- for (const group of groups) {
1089
- const members = [];
1090
- for (const id of group.scopes ?? []) {
1091
- const scope = byId.get(id);
1092
- if (scope && !placed.has(id)) {
1093
- placed.add(id);
1094
- members.push(scope);
1095
- }
1096
- }
1097
- if (members.length > 0) {
1098
- resolved.push({ id: group.id, label: group.label, description: group.description ?? null, sensitive: group.sensitive === true, scopes: members });
1099
- }
1100
- }
1101
- const rest = scopes.filter((scope) => !placed.has(scope.id));
1102
- if (rest.length > 0) {
1103
- resolved.push({ id: "other", label: "Other permissions", description: null, sensitive: false, scopes: rest });
1104
- }
1105
- return resolved.length > 0 ? resolved : null;
1562
+ if (!Array.isArray(groups) || groups.length === 0) return null;
1563
+ const byId = new Map(scopes.map((scope) => [scope.id, scope]));
1564
+ const placed = /* @__PURE__ */ new Set();
1565
+ const resolved = [];
1566
+ for (const group of groups) {
1567
+ const members = [];
1568
+ for (const id of group.scopes ?? []) {
1569
+ const scope = byId.get(id);
1570
+ if (scope && !placed.has(id)) {
1571
+ placed.add(id);
1572
+ members.push(scope);
1573
+ }
1574
+ }
1575
+ if (members.length > 0) resolved.push({
1576
+ id: group.id,
1577
+ label: group.label,
1578
+ description: group.description ?? null,
1579
+ sensitive: group.sensitive === true,
1580
+ scopes: members
1581
+ });
1582
+ }
1583
+ const rest = scopes.filter((scope) => !placed.has(scope.id));
1584
+ if (rest.length > 0) resolved.push({
1585
+ id: "other",
1586
+ label: "Other permissions",
1587
+ description: null,
1588
+ sensitive: false,
1589
+ scopes: rest
1590
+ });
1591
+ return resolved.length > 0 ? resolved : null;
1106
1592
  }
1107
1593
  function DefaultBadge(props) {
1108
- return /* @__PURE__ */ jsx4("span", { ...props });
1109
- }
1110
- var touchRow = {
1111
- display: "flex",
1112
- gap: "0.625rem",
1113
- alignItems: "flex-start",
1114
- minHeight: 44,
1115
- padding: "0.5rem 0",
1116
- boxSizing: "border-box",
1117
- overflowWrap: "anywhere"
1594
+ return /* @__PURE__ */ jsx("span", { ...props });
1595
+ }
1596
+ const touchRow = {
1597
+ display: "flex",
1598
+ gap: "0.625rem",
1599
+ alignItems: "flex-start",
1600
+ minHeight: 44,
1601
+ padding: "0.5rem 0",
1602
+ boxSizing: "border-box",
1603
+ overflowWrap: "anywhere"
1604
+ };
1605
+ const wrapStyle = {
1606
+ minWidth: 0,
1607
+ overflowWrap: "anywhere"
1118
1608
  };
1119
- var wrapStyle = { minWidth: 0, overflowWrap: "anywhere" };
1120
- var mutedStyle = { opacity: 0.7 };
1121
- var gridStyle = {
1122
- display: "grid",
1123
- gridTemplateColumns: "repeat(auto-fill, minmax(min(100%, 300px), 1fr))",
1124
- gap: "1rem",
1125
- alignItems: "start"
1609
+ const mutedStyle = { opacity: .7 };
1610
+ const gridStyle = {
1611
+ display: "grid",
1612
+ gridTemplateColumns: "repeat(auto-fill, minmax(min(100%, 300px), 1fr))",
1613
+ gap: "1rem",
1614
+ alignItems: "start"
1615
+ };
1616
+ const boxStyle = {
1617
+ margin: 0,
1618
+ minWidth: 0,
1619
+ border: "1px solid rgba(128, 128, 128, 0.35)",
1620
+ borderRadius: 10,
1621
+ padding: "0.25rem 1rem 0.75rem"
1126
1622
  };
1127
- var boxStyle = { margin: 0, minWidth: 0, border: "1px solid rgba(128, 128, 128, 0.35)", borderRadius: 10, padding: "0.25rem 1rem 0.75rem" };
1128
1623
  function ScopePicker({ idPrefix, scopes, groups, presets, implications, selected, onChange, components }) {
1129
- const { Checkbox, Button, Badge, Alert } = resolveAuthComponents(components);
1130
- const [open, setOpen] = React5.useState({});
1131
- const catalog = React5.useMemo(() => scopes.map((scope) => scope.id), [scopes]);
1132
- const closed = React5.useMemo(() => closeImplications(restrictImplications(implications, new Set(catalog))), [implications, catalog]);
1133
- const layout = React5.useMemo(() => resolveGroups(scopes, groups), [scopes, groups]);
1134
- const offeredPresets = React5.useMemo(
1135
- () => (presets ?? []).filter((preset) => preset.scopes.length > 0 && preset.scopes.every((id) => catalog.includes(id))),
1136
- [presets, catalog]
1137
- );
1138
- const cascades = Object.keys(closed).length > 0;
1139
- const chosen = new Set(selected);
1140
- const commit = (next) => onChange(inCatalogOrder(next, catalog));
1141
- const toggle = (id, checked) => {
1142
- if (layout === null && !cascades) {
1143
- onChange(checked ? [...selected, id] : selected.filter((value) => value !== id));
1144
- return;
1145
- }
1146
- commit(checked ? withScopes(selected, [id], closed) : withoutScopes(selected, [id], closed));
1147
- };
1148
- const renderRow = (scope, grouped) => {
1149
- const id = `${idPrefix}-${scope.id}`;
1150
- const needers = neededBy(scope.id, selected, closed);
1151
- const noteId = `${id}-needed`;
1152
- const row = /* @__PURE__ */ jsxs4("label", { htmlFor: id, style: grouped ? { ...touchRow, cursor: "pointer" } : { overflowWrap: "anywhere" }, children: [
1153
- Checkbox ? /* @__PURE__ */ jsx4(Checkbox, { id, checked: chosen.has(scope.id), onCheckedChange: (checked) => toggle(scope.id, checked) }) : /* @__PURE__ */ jsx4(
1154
- "input",
1155
- {
1156
- id,
1157
- type: "checkbox",
1158
- checked: chosen.has(scope.id),
1159
- "aria-describedby": needers.length > 0 ? noteId : void 0,
1160
- onChange: (event) => toggle(scope.id, event.target.checked),
1161
- style: grouped ? { flex: "none", width: 16, height: 16, margin: "2px 0 0" } : void 0
1162
- }
1163
- ),
1164
- " ",
1165
- /* @__PURE__ */ jsxs4("span", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1166
- /* @__PURE__ */ jsx4("code", { style: wrapStyle, children: scope.id }),
1167
- " ",
1168
- /* @__PURE__ */ jsx4("span", { style: mutedStyle, children: scope.description })
1169
- ] })
1170
- ] }, scope.id);
1171
- if (needers.length === 0) {
1172
- return row;
1173
- }
1174
- return /* @__PURE__ */ jsxs4("div", { style: { minWidth: 0 }, children: [
1175
- row,
1176
- /* @__PURE__ */ jsxs4("small", { id: noteId, style: { ...mutedStyle, display: "block", paddingLeft: grouped ? 26 : 0, overflowWrap: "anywhere" }, children: [
1177
- "needed by ",
1178
- needers.join(", ")
1179
- ] })
1180
- ] }, scope.id);
1181
- };
1182
- if (layout === null) {
1183
- return /* @__PURE__ */ jsxs4("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0, minWidth: 0, overflowWrap: "anywhere" }, children: [
1184
- /* @__PURE__ */ jsx4("legend", { children: "Permissions" }),
1185
- scopes.map((scope) => renderRow(scope, false))
1186
- ] });
1187
- }
1188
- const pressed = offeredPresets.find((preset) => sameSelection(selected, preset.scopes));
1189
- const plain = layout.filter((group) => !group.sensitive);
1190
- const sensitive = layout.filter((group) => group.sensitive);
1191
- const Chip = Badge ?? DefaultBadge;
1192
- return /* @__PURE__ */ jsxs4("div", { style: { display: "grid", gap: "1rem", minWidth: 0, overflowWrap: "anywhere" }, children: [
1193
- /* @__PURE__ */ jsxs4("div", { style: { display: "grid", gap: "0.25rem", minWidth: 0, overflowWrap: "anywhere" }, children: [
1194
- /* @__PURE__ */ jsx4("strong", { children: "Permissions" }),
1195
- offeredPresets.length > 0 && /* @__PURE__ */ jsx4("span", { style: mutedStyle, children: "Start from a preset, then adjust any permission below. The credential stores exactly the permissions you tick." })
1196
- ] }),
1197
- offeredPresets.length > 0 && /* @__PURE__ */ jsxs4("div", { style: { display: "grid", gap: "0.625rem", minWidth: 0 }, children: [
1198
- /* @__PURE__ */ jsx4("div", { role: "group", "aria-label": "Presets", style: { display: "flex", flexWrap: "wrap", gap: "0.5rem" }, children: offeredPresets.map((preset) => {
1199
- const isPressed = pressed?.id === preset.id;
1200
- return /* @__PURE__ */ jsx4(
1201
- Button,
1202
- {
1203
- type: "button",
1204
- variant: isPressed ? "default" : "outline",
1205
- "aria-pressed": isPressed,
1206
- style: { height: "auto", minHeight: 44, minWidth: 0, maxWidth: "100%", overflowWrap: "anywhere", whiteSpace: "normal", textAlign: "left" },
1207
- onClick: () => commit(withScopes([], preset.scopes, closed)),
1208
- children: preset.label
1209
- },
1210
- preset.id
1211
- );
1212
- }) }),
1213
- /* @__PURE__ */ jsx4("p", { "aria-live": "polite", style: { margin: 0, ...mutedStyle, overflowWrap: "anywhere" }, children: pressed ? pressed.description : "Custom selection. Pick a preset to replace it, or keep adjusting below." })
1214
- ] }),
1215
- plain.length > 0 && /* @__PURE__ */ jsx4("div", { style: gridStyle, children: plain.map((group) => /* @__PURE__ */ jsxs4("fieldset", { style: { ...boxStyle, display: "grid", gridTemplateColumns: "minmax(0, 1fr)" }, children: [
1216
- /* @__PURE__ */ jsx4("legend", { style: { padding: "0 0.375rem", fontWeight: 600, overflowWrap: "anywhere" }, children: group.label }),
1217
- group.scopes.map((scope) => renderRow(scope, true))
1218
- ] }, group.id)) }),
1219
- sensitive.map((group) => {
1220
- const ids = group.scopes.map((scope) => scope.id);
1221
- const count = ids.filter((id) => chosen.has(id)).length;
1222
- const state = count === 0 ? "none" : count === ids.length ? "all" : "some";
1223
- const parentId = `${idPrefix}-group-${group.id}`;
1224
- const listId = `${parentId}-scopes`;
1225
- const isOpen = open[group.id] === true;
1226
- const warning = group.description !== null && group.description !== "" ? group.description : null;
1227
- return /* @__PURE__ */ jsxs4("fieldset", { style: { ...boxStyle, display: "grid", gridTemplateColumns: "minmax(0, 1fr)", gap: "0.375rem", paddingBottom: "0.875rem" }, children: [
1228
- /* @__PURE__ */ jsxs4("legend", { style: { padding: "0 0.375rem", fontWeight: 600, display: "flex", alignItems: "center", gap: "0.5rem", maxWidth: "100%", minWidth: 0 }, children: [
1229
- /* @__PURE__ */ jsx4("span", { style: { overflowWrap: "anywhere" }, children: group.label }),
1230
- /* @__PURE__ */ jsx4(Chip, { style: { fontSize: 12, fontWeight: 500, border: "1px solid currentColor", borderRadius: 999, padding: "3px 8px", lineHeight: 1 }, children: "Sensitive" })
1231
- ] }),
1232
- warning !== null && (() => {
1233
- const content = /* @__PURE__ */ jsxs4(Fragment2, { children: [
1234
- /* @__PURE__ */ jsx4(TriangleAlert, { "aria-hidden": "true", size: 16, style: { flex: "none", marginTop: 2 } }),
1235
- /* @__PURE__ */ jsx4("span", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: warning })
1236
- ] });
1237
- const style = { margin: "0.25rem 0 0", display: "flex", gap: "0.5rem", alignItems: "flex-start" };
1238
- return Alert ? /* @__PURE__ */ jsx4(Alert, { style, children: content }) : /* @__PURE__ */ jsx4("p", { style: { ...style, color: "#b45309" }, children: content });
1239
- })(),
1240
- /* @__PURE__ */ jsxs4("label", { htmlFor: parentId, style: { ...touchRow, cursor: "pointer" }, children: [
1241
- /* @__PURE__ */ jsx4(
1242
- "input",
1243
- {
1244
- id: parentId,
1245
- type: "checkbox",
1246
- checked: state === "all",
1247
- "aria-checked": state === "some" ? "mixed" : state === "all",
1248
- ref: (element) => {
1249
- if (element) {
1250
- element.indeterminate = state === "some";
1251
- }
1252
- },
1253
- onChange: () => commit(state === "all" ? withoutScopes(selected, ids, closed) : withScopes(selected, ids, closed)),
1254
- style: { flex: "none", width: 16, height: 16, margin: "2px 0 0" }
1255
- }
1256
- ),
1257
- " ",
1258
- /* @__PURE__ */ jsxs4("span", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1259
- /* @__PURE__ */ jsx4("strong", { children: group.label }),
1260
- " ",
1261
- /* @__PURE__ */ jsx4("span", { style: mutedStyle, children: state === "all" ? `All ${ids.length} ${group.label} permissions are selected.` : state === "some" ? `${count} of ${ids.length} ${group.label} permissions are selected.` : `Selects all ${ids.length} ${group.label} permissions.` })
1262
- ] })
1263
- ] }),
1264
- /* @__PURE__ */ jsx4("div", { children: /* @__PURE__ */ jsxs4(
1265
- Button,
1266
- {
1267
- type: "button",
1268
- variant: "ghost",
1269
- "aria-expanded": isOpen,
1270
- "aria-controls": listId,
1271
- style: { height: "auto", minHeight: 44, minWidth: 0, maxWidth: "100%", overflowWrap: "anywhere", whiteSpace: "normal", textAlign: "left" },
1272
- onClick: () => setOpen((current) => ({ ...current, [group.id]: !isOpen })),
1273
- children: [
1274
- /* @__PURE__ */ jsx4(ChevronRight, { "aria-hidden": "true", size: 16, style: { flex: "none", transition: "transform 120ms", transform: isOpen ? "rotate(90deg)" : "none" } }),
1275
- isOpen ? "Hide" : "Adjust",
1276
- " individual ",
1277
- group.label,
1278
- " permissions"
1279
- ]
1280
- }
1281
- ) }),
1282
- isOpen && /* @__PURE__ */ jsx4("div", { id: listId, style: { ...gridStyle, minWidth: 0, columnGap: "1.5rem", gap: "0 1.5rem", paddingLeft: "1.5rem", marginLeft: 7, borderLeft: "2px solid rgba(128, 128, 128, 0.35)" }, children: group.scopes.map((scope) => renderRow(scope, true)) })
1283
- ] }, group.id);
1284
- }),
1285
- /* @__PURE__ */ jsxs4("div", { style: { borderTop: "1px solid rgba(128, 128, 128, 0.35)", paddingTop: "0.875rem", display: "grid", gap: "0.5rem" }, children: [
1286
- /* @__PURE__ */ jsx4("p", { style: { margin: 0, fontWeight: 500 }, role: "status", children: selected.length === 0 ? "No permissions selected." : `This credential will request ${selected.length} ${selected.length === 1 ? "permission" : "permissions"}:` }),
1287
- selected.length > 0 && /* @__PURE__ */ jsx4("p", { style: { margin: 0, display: "flex", flexWrap: "wrap", gap: "0.375rem" }, children: selected.map((id) => /* @__PURE__ */ jsx4("code", { style: { overflowWrap: "anywhere" }, children: id }, id)) })
1288
- ] })
1289
- ] });
1290
- }
1291
-
1624
+ const { Checkbox, Button, Badge, Alert } = resolveAuthComponents(components);
1625
+ const [open, setOpen] = React.useState({});
1626
+ const catalog = React.useMemo(() => scopes.map((scope) => scope.id), [scopes]);
1627
+ const closed = React.useMemo(() => closeImplications(restrictImplications(implications, new Set(catalog))), [implications, catalog]);
1628
+ const layout = React.useMemo(() => resolveGroups(scopes, groups), [scopes, groups]);
1629
+ const offeredPresets = React.useMemo(() => (presets ?? []).filter((preset) => preset.scopes.length > 0 && preset.scopes.every((id) => catalog.includes(id))), [presets, catalog]);
1630
+ const cascades = Object.keys(closed).length > 0;
1631
+ const chosen = new Set(selected);
1632
+ const commit = (next) => onChange(inCatalogOrder(next, catalog));
1633
+ const toggle = (id, checked) => {
1634
+ if (layout === null && !cascades) {
1635
+ onChange(checked ? [...selected, id] : selected.filter((value) => value !== id));
1636
+ return;
1637
+ }
1638
+ commit(checked ? withScopes(selected, [id], closed) : withoutScopes(selected, [id], closed));
1639
+ };
1640
+ const renderRow = (scope, grouped) => {
1641
+ const id = `${idPrefix}-${scope.id}`;
1642
+ const needers = neededBy(scope.id, selected, closed);
1643
+ const noteId = `${id}-needed`;
1644
+ const row = /* @__PURE__ */ jsxs("label", {
1645
+ htmlFor: id,
1646
+ style: grouped ? {
1647
+ ...touchRow,
1648
+ cursor: "pointer"
1649
+ } : { overflowWrap: "anywhere" },
1650
+ children: [
1651
+ Checkbox ? /* @__PURE__ */ jsx(Checkbox, {
1652
+ id,
1653
+ checked: chosen.has(scope.id),
1654
+ onCheckedChange: (checked) => toggle(scope.id, checked)
1655
+ }) : /* @__PURE__ */ jsx("input", {
1656
+ id,
1657
+ type: "checkbox",
1658
+ checked: chosen.has(scope.id),
1659
+ "aria-describedby": needers.length > 0 ? noteId : void 0,
1660
+ onChange: (event) => toggle(scope.id, event.target.checked),
1661
+ style: grouped ? {
1662
+ flex: "none",
1663
+ width: 16,
1664
+ height: 16,
1665
+ margin: "2px 0 0"
1666
+ } : void 0
1667
+ }),
1668
+ " ",
1669
+ /* @__PURE__ */ jsxs("span", {
1670
+ style: {
1671
+ minWidth: 0,
1672
+ overflowWrap: "anywhere"
1673
+ },
1674
+ children: [
1675
+ /* @__PURE__ */ jsx("code", {
1676
+ style: wrapStyle,
1677
+ children: scope.id
1678
+ }),
1679
+ " ",
1680
+ /* @__PURE__ */ jsx("span", {
1681
+ style: mutedStyle,
1682
+ children: scope.description
1683
+ })
1684
+ ]
1685
+ })
1686
+ ]
1687
+ }, scope.id);
1688
+ if (needers.length === 0) return row;
1689
+ return /* @__PURE__ */ jsxs("div", {
1690
+ style: { minWidth: 0 },
1691
+ children: [row, /* @__PURE__ */ jsxs("small", {
1692
+ id: noteId,
1693
+ style: {
1694
+ ...mutedStyle,
1695
+ display: "block",
1696
+ paddingLeft: grouped ? 26 : 0,
1697
+ overflowWrap: "anywhere"
1698
+ },
1699
+ children: ["needed by ", needers.join(", ")]
1700
+ })]
1701
+ }, scope.id);
1702
+ };
1703
+ if (layout === null) return /* @__PURE__ */ jsxs("fieldset", {
1704
+ style: {
1705
+ display: "grid",
1706
+ gap: "0.25rem",
1707
+ border: 0,
1708
+ padding: 0,
1709
+ minWidth: 0,
1710
+ overflowWrap: "anywhere"
1711
+ },
1712
+ children: [/* @__PURE__ */ jsx("legend", { children: "Permissions" }), scopes.map((scope) => renderRow(scope, false))]
1713
+ });
1714
+ const pressed = offeredPresets.find((preset) => sameSelection(selected, preset.scopes));
1715
+ const plain = layout.filter((group) => !group.sensitive);
1716
+ const sensitive = layout.filter((group) => group.sensitive);
1717
+ const Chip = Badge ?? DefaultBadge;
1718
+ return /* @__PURE__ */ jsxs("div", {
1719
+ style: {
1720
+ display: "grid",
1721
+ gap: "1rem",
1722
+ minWidth: 0,
1723
+ overflowWrap: "anywhere"
1724
+ },
1725
+ children: [
1726
+ /* @__PURE__ */ jsxs("div", {
1727
+ style: {
1728
+ display: "grid",
1729
+ gap: "0.25rem",
1730
+ minWidth: 0,
1731
+ overflowWrap: "anywhere"
1732
+ },
1733
+ children: [/* @__PURE__ */ jsx("strong", { children: "Permissions" }), offeredPresets.length > 0 && /* @__PURE__ */ jsx("span", {
1734
+ style: mutedStyle,
1735
+ children: "Start from a preset, then adjust any permission below. The credential stores exactly the permissions you tick."
1736
+ })]
1737
+ }),
1738
+ offeredPresets.length > 0 && /* @__PURE__ */ jsxs("div", {
1739
+ style: {
1740
+ display: "grid",
1741
+ gap: "0.625rem",
1742
+ minWidth: 0
1743
+ },
1744
+ children: [/* @__PURE__ */ jsx("div", {
1745
+ role: "group",
1746
+ "aria-label": "Presets",
1747
+ style: {
1748
+ display: "flex",
1749
+ flexWrap: "wrap",
1750
+ gap: "0.5rem"
1751
+ },
1752
+ children: offeredPresets.map((preset) => {
1753
+ const isPressed = pressed?.id === preset.id;
1754
+ return /* @__PURE__ */ jsx(Button, {
1755
+ type: "button",
1756
+ variant: isPressed ? "default" : "outline",
1757
+ "aria-pressed": isPressed,
1758
+ style: {
1759
+ height: "auto",
1760
+ minHeight: 44,
1761
+ minWidth: 0,
1762
+ maxWidth: "100%",
1763
+ overflowWrap: "anywhere",
1764
+ whiteSpace: "normal",
1765
+ textAlign: "left"
1766
+ },
1767
+ onClick: () => commit(withScopes([], preset.scopes, closed)),
1768
+ children: preset.label
1769
+ }, preset.id);
1770
+ })
1771
+ }), /* @__PURE__ */ jsx("p", {
1772
+ "aria-live": "polite",
1773
+ style: {
1774
+ margin: 0,
1775
+ ...mutedStyle,
1776
+ overflowWrap: "anywhere"
1777
+ },
1778
+ children: pressed ? pressed.description : "Custom selection. Pick a preset to replace it, or keep adjusting below."
1779
+ })]
1780
+ }),
1781
+ plain.length > 0 && /* @__PURE__ */ jsx("div", {
1782
+ style: gridStyle,
1783
+ children: plain.map((group) => /* @__PURE__ */ jsxs("fieldset", {
1784
+ style: {
1785
+ ...boxStyle,
1786
+ display: "grid",
1787
+ gridTemplateColumns: "minmax(0, 1fr)"
1788
+ },
1789
+ children: [/* @__PURE__ */ jsx("legend", {
1790
+ style: {
1791
+ padding: "0 0.375rem",
1792
+ fontWeight: 600,
1793
+ overflowWrap: "anywhere"
1794
+ },
1795
+ children: group.label
1796
+ }), group.scopes.map((scope) => renderRow(scope, true))]
1797
+ }, group.id))
1798
+ }),
1799
+ sensitive.map((group) => {
1800
+ const ids = group.scopes.map((scope) => scope.id);
1801
+ const count = ids.filter((id) => chosen.has(id)).length;
1802
+ const state = count === 0 ? "none" : count === ids.length ? "all" : "some";
1803
+ const parentId = `${idPrefix}-group-${group.id}`;
1804
+ const listId = `${parentId}-scopes`;
1805
+ const isOpen = open[group.id] === true;
1806
+ const warning = group.description !== null && group.description !== "" ? group.description : null;
1807
+ return /* @__PURE__ */ jsxs("fieldset", {
1808
+ style: {
1809
+ ...boxStyle,
1810
+ display: "grid",
1811
+ gridTemplateColumns: "minmax(0, 1fr)",
1812
+ gap: "0.375rem",
1813
+ paddingBottom: "0.875rem"
1814
+ },
1815
+ children: [
1816
+ /* @__PURE__ */ jsxs("legend", {
1817
+ style: {
1818
+ padding: "0 0.375rem",
1819
+ fontWeight: 600,
1820
+ display: "flex",
1821
+ alignItems: "center",
1822
+ gap: "0.5rem",
1823
+ maxWidth: "100%",
1824
+ minWidth: 0
1825
+ },
1826
+ children: [/* @__PURE__ */ jsx("span", {
1827
+ style: { overflowWrap: "anywhere" },
1828
+ children: group.label
1829
+ }), /* @__PURE__ */ jsx(Chip, {
1830
+ style: {
1831
+ fontSize: 12,
1832
+ fontWeight: 500,
1833
+ border: "1px solid currentColor",
1834
+ borderRadius: 999,
1835
+ padding: "3px 8px",
1836
+ lineHeight: 1
1837
+ },
1838
+ children: "Sensitive"
1839
+ })]
1840
+ }),
1841
+ warning !== null && (() => {
1842
+ const content = /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(TriangleAlert, {
1843
+ "aria-hidden": "true",
1844
+ size: 16,
1845
+ style: {
1846
+ flex: "none",
1847
+ marginTop: 2
1848
+ }
1849
+ }), /* @__PURE__ */ jsx("span", {
1850
+ style: {
1851
+ minWidth: 0,
1852
+ overflowWrap: "anywhere"
1853
+ },
1854
+ children: warning
1855
+ })] });
1856
+ const style = {
1857
+ margin: "0.25rem 0 0",
1858
+ display: "flex",
1859
+ gap: "0.5rem",
1860
+ alignItems: "flex-start"
1861
+ };
1862
+ return Alert ? /* @__PURE__ */ jsx(Alert, {
1863
+ style,
1864
+ children: content
1865
+ }) : /* @__PURE__ */ jsx("p", {
1866
+ style: {
1867
+ ...style,
1868
+ color: "#b45309"
1869
+ },
1870
+ children: content
1871
+ });
1872
+ })(),
1873
+ /* @__PURE__ */ jsxs("label", {
1874
+ htmlFor: parentId,
1875
+ style: {
1876
+ ...touchRow,
1877
+ cursor: "pointer"
1878
+ },
1879
+ children: [
1880
+ /* @__PURE__ */ jsx("input", {
1881
+ id: parentId,
1882
+ type: "checkbox",
1883
+ checked: state === "all",
1884
+ "aria-checked": state === "some" ? "mixed" : state === "all",
1885
+ ref: (element) => {
1886
+ if (element) element.indeterminate = state === "some";
1887
+ },
1888
+ onChange: () => commit(state === "all" ? withoutScopes(selected, ids, closed) : withScopes(selected, ids, closed)),
1889
+ style: {
1890
+ flex: "none",
1891
+ width: 16,
1892
+ height: 16,
1893
+ margin: "2px 0 0"
1894
+ }
1895
+ }),
1896
+ " ",
1897
+ /* @__PURE__ */ jsxs("span", {
1898
+ style: {
1899
+ minWidth: 0,
1900
+ overflowWrap: "anywhere"
1901
+ },
1902
+ children: [
1903
+ /* @__PURE__ */ jsx("strong", { children: group.label }),
1904
+ " ",
1905
+ /* @__PURE__ */ jsx("span", {
1906
+ style: mutedStyle,
1907
+ children: state === "all" ? `All ${ids.length} ${group.label} permissions are selected.` : state === "some" ? `${count} of ${ids.length} ${group.label} permissions are selected.` : `Selects all ${ids.length} ${group.label} permissions.`
1908
+ })
1909
+ ]
1910
+ })
1911
+ ]
1912
+ }),
1913
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs(Button, {
1914
+ type: "button",
1915
+ variant: "ghost",
1916
+ "aria-expanded": isOpen,
1917
+ "aria-controls": listId,
1918
+ style: {
1919
+ height: "auto",
1920
+ minHeight: 44,
1921
+ minWidth: 0,
1922
+ maxWidth: "100%",
1923
+ overflowWrap: "anywhere",
1924
+ whiteSpace: "normal",
1925
+ textAlign: "left"
1926
+ },
1927
+ onClick: () => setOpen((current) => ({
1928
+ ...current,
1929
+ [group.id]: !isOpen
1930
+ })),
1931
+ children: [
1932
+ /* @__PURE__ */ jsx(ChevronRight, {
1933
+ "aria-hidden": "true",
1934
+ size: 16,
1935
+ style: {
1936
+ flex: "none",
1937
+ transition: "transform 120ms",
1938
+ transform: isOpen ? "rotate(90deg)" : "none"
1939
+ }
1940
+ }),
1941
+ isOpen ? "Hide" : "Adjust",
1942
+ " individual ",
1943
+ group.label,
1944
+ " permissions"
1945
+ ]
1946
+ }) }),
1947
+ isOpen && /* @__PURE__ */ jsx("div", {
1948
+ id: listId,
1949
+ style: {
1950
+ ...gridStyle,
1951
+ minWidth: 0,
1952
+ columnGap: "1.5rem",
1953
+ gap: "0 1.5rem",
1954
+ paddingLeft: "1.5rem",
1955
+ marginLeft: 7,
1956
+ borderLeft: "2px solid rgba(128, 128, 128, 0.35)"
1957
+ },
1958
+ children: group.scopes.map((scope) => renderRow(scope, true))
1959
+ })
1960
+ ]
1961
+ }, group.id);
1962
+ }),
1963
+ /* @__PURE__ */ jsxs("div", {
1964
+ style: {
1965
+ borderTop: "1px solid rgba(128, 128, 128, 0.35)",
1966
+ paddingTop: "0.875rem",
1967
+ display: "grid",
1968
+ gap: "0.5rem"
1969
+ },
1970
+ children: [/* @__PURE__ */ jsx("p", {
1971
+ style: {
1972
+ margin: 0,
1973
+ fontWeight: 500
1974
+ },
1975
+ role: "status",
1976
+ children: selected.length === 0 ? "No permissions selected." : `This credential will request ${selected.length} ${selected.length === 1 ? "permission" : "permissions"}:`
1977
+ }), selected.length > 0 && /* @__PURE__ */ jsx("p", {
1978
+ style: {
1979
+ margin: 0,
1980
+ display: "flex",
1981
+ flexWrap: "wrap",
1982
+ gap: "0.375rem"
1983
+ },
1984
+ children: selected.map((id) => /* @__PURE__ */ jsx("code", {
1985
+ style: { overflowWrap: "anywhere" },
1986
+ children: id
1987
+ }, id))
1988
+ })]
1989
+ })
1990
+ ]
1991
+ });
1992
+ }
1292
1993
  // src/api-credentials-section.tsx
1293
- import { Fragment as Fragment3, jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
1994
+ /**
1995
+ * A person's credentials for apps that use the API: personal API tokens (for
1996
+ * connectors that ask for a key) and OAuth apps (for connectors that run the
1997
+ * authorization-code flow).
1998
+ *
1999
+ * Each secret arrives once, in the response that created it, and lives only
2000
+ * in this component's memory; afterwards only the lists are reloaded, so it is
2001
+ * never part of page props or browser history.
2002
+ */
1294
2003
  function ApiCredentialsSection({ indexUrl, components, links = [], csrfToken, request, onSuccess, onError, layout = "stacked" }) {
1295
- const { Card, CardContent, CardDescription, CardHeader, CardTitle } = resolveAuthComponents(components);
1296
- const [index, setIndex] = React6.useState(null);
1297
- const [issued, setIssued] = React6.useState([]);
1298
- const issuedKey = React6.useRef(0);
1299
- const addIssued = React6.useCallback((credential) => {
1300
- issuedKey.current += 1;
1301
- const key = issuedKey.current;
1302
- setIssued((current) => [...current, { key, credential }]);
1303
- }, []);
1304
- const [loadError, setLoadError] = React6.useState(null);
1305
- const onErrorRef = React6.useRef(onError);
1306
- onErrorRef.current = onError;
1307
- const generation = React6.useRef(0);
1308
- const context = React6.useRef({ indexUrl, csrfToken, request });
1309
- context.current = { indexUrl, csrfToken, request };
1310
- const reload = React6.useCallback(async () => {
1311
- generation.current += 1;
1312
- const mine = generation.current;
1313
- const { indexUrl: url, csrfToken: token, request: send } = context.current;
1314
- const result = await credentialRequest("GET", url, void 0, token, send);
1315
- if (mine !== generation.current) {
1316
- return;
1317
- }
1318
- if (result.ok) {
1319
- setIndex(result.data);
1320
- setLoadError(null);
1321
- } else {
1322
- setLoadError(result.message);
1323
- onErrorRef.current?.("api-credentials", result.message);
1324
- }
1325
- }, []);
1326
- React6.useEffect(() => {
1327
- setIndex(null);
1328
- void reload();
1329
- }, [indexUrl, csrfToken, reload]);
1330
- const removeLocally = React6.useCallback((list, id) => {
1331
- setIndex(
1332
- (current) => current === null ? current : list === "tokens" ? { ...current, tokens: current.tokens.filter((token) => token.id !== id) } : { ...current, apps: current.apps.filter((app) => app.id !== id) }
1333
- );
1334
- }, []);
1335
- const shared = { components, csrfToken, request, onError, onSuccess, removeLocally };
1336
- return /* @__PURE__ */ jsxs5(Card, { children: [
1337
- /* @__PURE__ */ jsxs5(CardHeader, { children: [
1338
- /* @__PURE__ */ jsx5(CardTitle, { children: "API access" }),
1339
- /* @__PURE__ */ jsx5(CardDescription, { children: "Connect apps that use the API. Register an OAuth app for apps that sign you in, or create an API token for apps that ask for a key. Each carries only the permissions you choose, and never more than your own access." })
1340
- ] }),
1341
- /* @__PURE__ */ jsx5(CardContent, { children: /* @__PURE__ */ jsxs5("div", { style: { display: "grid", gap: "1.5rem", minWidth: 0, overflowWrap: "anywhere" }, children: [
1342
- links.length > 0 && /* @__PURE__ */ jsx5("dl", { style: { display: "grid", gap: "0.5rem", minWidth: 0 }, children: links.map((link) => /* @__PURE__ */ jsxs5("div", { style: { minWidth: 0 }, children: [
1343
- /* @__PURE__ */ jsx5("dt", { children: link.label }),
1344
- /* @__PURE__ */ jsxs5("dd", { style: { margin: 0, overflowWrap: "anywhere" }, children: [
1345
- /* @__PURE__ */ jsx5("code", { children: link.url }),
1346
- " ",
1347
- /* @__PURE__ */ jsx5(CopyButton, { text: link.url, label: link.label, components })
1348
- ] })
1349
- ] }, link.label)) }),
1350
- issued.map(({ key, credential }) => /* @__PURE__ */ jsx5(
1351
- IssuedNotice,
1352
- {
1353
- issued: credential,
1354
- components,
1355
- onDismiss: () => setIssued((current) => current.filter((entry) => entry.key !== key))
1356
- },
1357
- key
1358
- )),
1359
- loadError !== null && /* @__PURE__ */ jsx5("p", { role: "alert", children: loadError }),
1360
- index !== null && /* @__PURE__ */ jsxs5(Fragment3, { children: [
1361
- (index.issue_token_href === null || index.register_app_href === null) && /* @__PURE__ */ jsx5("p", { role: "status", children: "Creating new credentials is unavailable right now. You can still revoke existing ones." }),
1362
- /* @__PURE__ */ jsxs5(
1363
- "div",
1364
- {
1365
- "data-layout": layout,
1366
- style: layout === "columns" ? { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 460px), 1fr))", gap: "1.5rem", alignItems: "start", minWidth: 0 } : { display: "grid", gridTemplateColumns: "minmax(0, 1fr)", gap: "1.5rem", minWidth: 0 },
1367
- children: [
1368
- /* @__PURE__ */ jsx5(TokenSection, { index, ...shared, onIssued: addIssued, reload }),
1369
- /* @__PURE__ */ jsx5(AppSection, { index, ...shared, onIssued: addIssued, reload })
1370
- ]
1371
- }
1372
- )
1373
- ] })
1374
- ] }) })
1375
- ] });
2004
+ const { Card, CardContent, CardDescription, CardHeader, CardTitle } = resolveAuthComponents(components);
2005
+ const [index, setIndex] = React.useState(null);
2006
+ const [issued, setIssued] = React.useState([]);
2007
+ const issuedKey = React.useRef(0);
2008
+ const addIssued = React.useCallback((credential) => {
2009
+ issuedKey.current += 1;
2010
+ const key = issuedKey.current;
2011
+ setIssued((current) => [...current, {
2012
+ key,
2013
+ credential
2014
+ }]);
2015
+ }, []);
2016
+ const [loadError, setLoadError] = React.useState(null);
2017
+ const onErrorRef = React.useRef(onError);
2018
+ onErrorRef.current = onError;
2019
+ const generation = React.useRef(0);
2020
+ const context = React.useRef({
2021
+ indexUrl,
2022
+ csrfToken,
2023
+ request
2024
+ });
2025
+ context.current = {
2026
+ indexUrl,
2027
+ csrfToken,
2028
+ request
2029
+ };
2030
+ const reload = React.useCallback(async () => {
2031
+ generation.current += 1;
2032
+ const mine = generation.current;
2033
+ const { indexUrl: url, csrfToken: token, request: send } = context.current;
2034
+ const result = await credentialRequest("GET", url, void 0, token, send);
2035
+ if (mine !== generation.current) return;
2036
+ if (result.ok) {
2037
+ setIndex(result.data);
2038
+ setLoadError(null);
2039
+ } else {
2040
+ setLoadError(result.message);
2041
+ onErrorRef.current?.("api-credentials", result.message);
2042
+ }
2043
+ }, []);
2044
+ React.useEffect(() => {
2045
+ setIndex(null);
2046
+ reload();
2047
+ }, [
2048
+ indexUrl,
2049
+ csrfToken,
2050
+ reload
2051
+ ]);
2052
+ const shared = {
2053
+ components,
2054
+ csrfToken,
2055
+ request,
2056
+ onError,
2057
+ onSuccess,
2058
+ removeLocally: React.useCallback((list, id) => {
2059
+ setIndex((current) => current === null ? current : list === "tokens" ? {
2060
+ ...current,
2061
+ tokens: current.tokens.filter((token) => token.id !== id)
2062
+ } : {
2063
+ ...current,
2064
+ apps: current.apps.filter((app) => app.id !== id)
2065
+ });
2066
+ }, [])
2067
+ };
2068
+ return /* @__PURE__ */ jsxs(Card, { children: [/* @__PURE__ */ jsxs(CardHeader, { children: [/* @__PURE__ */ jsx(CardTitle, { children: "API access" }), /* @__PURE__ */ jsx(CardDescription, { children: "Connect apps that use the API. Register an OAuth app for apps that sign you in, or create an API token for apps that ask for a key. Each carries only the permissions you choose, and never more than your own access." })] }), /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsxs("div", {
2069
+ style: {
2070
+ display: "grid",
2071
+ gap: "1.5rem",
2072
+ minWidth: 0,
2073
+ overflowWrap: "anywhere"
2074
+ },
2075
+ children: [
2076
+ links.length > 0 && /* @__PURE__ */ jsx("dl", {
2077
+ style: {
2078
+ display: "grid",
2079
+ gap: "0.5rem",
2080
+ minWidth: 0
2081
+ },
2082
+ children: links.map((link) => /* @__PURE__ */ jsxs("div", {
2083
+ style: { minWidth: 0 },
2084
+ children: [/* @__PURE__ */ jsx("dt", { children: link.label }), /* @__PURE__ */ jsxs("dd", {
2085
+ style: {
2086
+ margin: 0,
2087
+ overflowWrap: "anywhere"
2088
+ },
2089
+ children: [
2090
+ /* @__PURE__ */ jsx("code", { children: link.url }),
2091
+ " ",
2092
+ /* @__PURE__ */ jsx(CopyButton, {
2093
+ text: link.url,
2094
+ label: link.label,
2095
+ components
2096
+ })
2097
+ ]
2098
+ })]
2099
+ }, link.label))
2100
+ }),
2101
+ issued.map(({ key, credential }) => /* @__PURE__ */ jsx(IssuedNotice, {
2102
+ issued: credential,
2103
+ components,
2104
+ onDismiss: () => setIssued((current) => current.filter((entry) => entry.key !== key))
2105
+ }, key)),
2106
+ loadError !== null && /* @__PURE__ */ jsx("p", {
2107
+ role: "alert",
2108
+ children: loadError
2109
+ }),
2110
+ index !== null && /* @__PURE__ */ jsxs(Fragment, { children: [(index.issue_token_href === null || index.register_app_href === null) && /* @__PURE__ */ jsx("p", {
2111
+ role: "status",
2112
+ children: "Creating new credentials is unavailable right now. You can still revoke existing ones."
2113
+ }), /* @__PURE__ */ jsxs("div", {
2114
+ "data-layout": layout,
2115
+ style: layout === "columns" ? {
2116
+ display: "grid",
2117
+ gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 460px), 1fr))",
2118
+ gap: "1.5rem",
2119
+ alignItems: "start",
2120
+ minWidth: 0
2121
+ } : {
2122
+ display: "grid",
2123
+ gridTemplateColumns: "minmax(0, 1fr)",
2124
+ gap: "1.5rem",
2125
+ minWidth: 0
2126
+ },
2127
+ children: [/* @__PURE__ */ jsx(TokenSection, {
2128
+ index,
2129
+ ...shared,
2130
+ onIssued: addIssued,
2131
+ reload
2132
+ }), /* @__PURE__ */ jsx(AppSection, {
2133
+ index,
2134
+ ...shared,
2135
+ onIssued: addIssued,
2136
+ reload
2137
+ })]
2138
+ })] })
2139
+ ]
2140
+ }) })] });
1376
2141
  }
1377
2142
  function TokenSection({ index, components, csrfToken, request, onIssued, reload, onSuccess, onError, removeLocally }) {
1378
- const { Button, Input, Label, RadioGroup } = resolveAuthComponents(components);
1379
- const [name, setName] = React6.useState("");
1380
- const [scopes, setScopes] = React6.useState([]);
1381
- const [lifetime, setLifetime] = React6.useState(index.token_lifetimes[0] ?? "");
1382
- const tokenScopes = React6.useMemo(
1383
- () => [...index.token_scopes ?? index.scopes, ...index.token_connection_scopes ?? []],
1384
- [index.token_scopes, index.scopes, index.token_connection_scopes]
1385
- );
1386
- const connectionIds = new Set((index.token_connection_scopes ?? []).map((scope) => scope.id));
1387
- const lifetimes = index.connection_token_lifetimes && index.connection_token_lifetimes.length > 0 && scopes.some((id) => connectionIds.has(id)) ? index.connection_token_lifetimes : index.token_lifetimes;
1388
- const effectiveLifetime = lifetimes.includes(lifetime) ? lifetime : lifetimes[0] ?? "";
1389
- const [busy, setBusy] = React6.useState(false);
1390
- const [error, setError] = React6.useState(null);
1391
- async function create(event) {
1392
- event.preventDefault();
1393
- if (index.issue_token_href === null) {
1394
- return;
1395
- }
1396
- setBusy(true);
1397
- const result = await credentialRequest("POST", index.issue_token_href, { name, scopes, lifetime: effectiveLifetime }, csrfToken, request);
1398
- setBusy(false);
1399
- if (!result.ok) {
1400
- setError(result.message);
1401
- onError?.("api-tokens", result.message);
1402
- return;
1403
- }
1404
- setError(null);
1405
- setName("");
1406
- setScopes([]);
1407
- onIssued(result.data);
1408
- onSuccess?.("API token created.");
1409
- await reload();
1410
- }
1411
- const [pending, setPending] = React6.useState([]);
1412
- async function revoke(token) {
1413
- if (pending.includes(token.id)) {
1414
- return;
1415
- }
1416
- setPending((current) => [...current, token.id]);
1417
- const result = await credentialRequest("DELETE", token.revoke_href, void 0, csrfToken, request);
1418
- if (!result.ok) {
1419
- setPending((current) => current.filter((id) => id !== token.id));
1420
- setError(result.message);
1421
- onError?.("api-tokens", result.message);
1422
- return;
1423
- }
1424
- setError(null);
1425
- removeLocally("tokens", token.id);
1426
- onSuccess?.("API token revoked.");
1427
- await reload();
1428
- setPending((current) => current.filter((id) => id !== token.id));
1429
- }
1430
- return /* @__PURE__ */ jsxs5("section", { style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1431
- /* @__PURE__ */ jsx5("h3", { children: "API tokens" }),
1432
- index.issue_token_href !== null && /* @__PURE__ */ jsxs5("form", { onSubmit: create, style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1433
- /* @__PURE__ */ jsxs5("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1434
- /* @__PURE__ */ jsx5(Label, { htmlFor: "api-token-name", children: "Token name" }),
1435
- /* @__PURE__ */ jsx5(Input, { id: "api-token-name", value: name, maxLength: 120, onChange: (event) => setName(event.target.value) })
1436
- ] }),
1437
- /* @__PURE__ */ jsx5(
1438
- ScopePicker,
1439
- {
1440
- idPrefix: "api-token-scope",
1441
- scopes: tokenScopes,
1442
- groups: index.token_scope_groups ?? index.scope_groups,
1443
- presets: index.token_scope_presets ?? index.scope_presets,
1444
- implications: index.token_scope_implications ?? index.scope_implications,
1445
- selected: scopes,
1446
- onChange: setScopes,
1447
- components
1448
- }
1449
- ),
1450
- /* @__PURE__ */ jsxs5("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0 }, children: [
1451
- /* @__PURE__ */ jsx5("legend", { children: "Expires after" }),
1452
- RadioGroup ? /* @__PURE__ */ jsx5(
1453
- RadioGroup,
1454
- {
1455
- name: "api-token-lifetime",
1456
- value: effectiveLifetime,
1457
- onValueChange: setLifetime,
1458
- options: lifetimes.map((spec) => ({ value: spec, label: describeDuration(spec) }))
1459
- }
1460
- ) : lifetimes.map((spec) => /* @__PURE__ */ jsxs5("label", { children: [
1461
- /* @__PURE__ */ jsx5("input", { type: "radio", name: "api-token-lifetime", checked: effectiveLifetime === spec, onChange: () => setLifetime(spec) }),
1462
- " ",
1463
- describeDuration(spec)
1464
- ] }, spec))
1465
- ] }),
1466
- /* @__PURE__ */ jsx5("div", { children: /* @__PURE__ */ jsx5(Button, { type: "submit", disabled: busy || name.trim() === "" || scopes.length === 0 || effectiveLifetime === "", children: "Create API token" }) })
1467
- ] }),
1468
- error !== null && /* @__PURE__ */ jsx5("p", { role: "alert", children: error }),
1469
- /* @__PURE__ */ jsx5("ul", { style: { display: "grid", gap: "0.5rem", listStyle: "none", padding: 0, margin: 0, minWidth: 0 }, children: index.tokens.map((token) => /* @__PURE__ */ jsxs5("li", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1470
- /* @__PURE__ */ jsx5("strong", { children: token.name }),
1471
- " \xB7 ",
1472
- token.scopes.join(", "),
1473
- token.connection === true && /* @__PURE__ */ jsx5(Fragment3, { children: " \xB7 MCP connection" }),
1474
- token.expires_at !== null && /* @__PURE__ */ jsxs5(Fragment3, { children: [
1475
- " \xB7 expires ",
1476
- new Date(token.expires_at).toLocaleString()
1477
- ] }),
1478
- " ",
1479
- /* @__PURE__ */ jsx5(Button, { type: "button", disabled: pending.includes(token.id), onClick: () => void revoke(token), children: "Revoke" })
1480
- ] }, token.id)) })
1481
- ] });
2143
+ const { Button, Input, Label, RadioGroup } = resolveAuthComponents(components);
2144
+ const [name, setName] = React.useState("");
2145
+ const [scopes, setScopes] = React.useState([]);
2146
+ const [lifetime, setLifetime] = React.useState(index.token_lifetimes[0] ?? "");
2147
+ const tokenScopes = React.useMemo(() => [...index.token_scopes ?? index.scopes, ...index.token_connection_scopes ?? []], [
2148
+ index.token_scopes,
2149
+ index.scopes,
2150
+ index.token_connection_scopes
2151
+ ]);
2152
+ const connectionIds = new Set((index.token_connection_scopes ?? []).map((scope) => scope.id));
2153
+ const lifetimes = index.connection_token_lifetimes && index.connection_token_lifetimes.length > 0 && scopes.some((id) => connectionIds.has(id)) ? index.connection_token_lifetimes : index.token_lifetimes;
2154
+ const effectiveLifetime = lifetimes.includes(lifetime) ? lifetime : lifetimes[0] ?? "";
2155
+ const [busy, setBusy] = React.useState(false);
2156
+ const [error, setError] = React.useState(null);
2157
+ async function create(event) {
2158
+ event.preventDefault();
2159
+ if (index.issue_token_href === null) return;
2160
+ setBusy(true);
2161
+ const result = await credentialRequest("POST", index.issue_token_href, {
2162
+ name,
2163
+ scopes,
2164
+ lifetime: effectiveLifetime
2165
+ }, csrfToken, request);
2166
+ setBusy(false);
2167
+ if (!result.ok) {
2168
+ setError(result.message);
2169
+ onError?.("api-tokens", result.message);
2170
+ return;
2171
+ }
2172
+ setError(null);
2173
+ setName("");
2174
+ setScopes([]);
2175
+ onIssued(result.data);
2176
+ onSuccess?.("API token created.");
2177
+ await reload();
2178
+ }
2179
+ const [pending, setPending] = React.useState([]);
2180
+ async function revoke(token) {
2181
+ if (pending.includes(token.id)) return;
2182
+ setPending((current) => [...current, token.id]);
2183
+ const result = await credentialRequest("DELETE", token.revoke_href, void 0, csrfToken, request);
2184
+ if (!result.ok) {
2185
+ setPending((current) => current.filter((id) => id !== token.id));
2186
+ setError(result.message);
2187
+ onError?.("api-tokens", result.message);
2188
+ return;
2189
+ }
2190
+ setError(null);
2191
+ removeLocally("tokens", token.id);
2192
+ onSuccess?.("API token revoked.");
2193
+ await reload();
2194
+ setPending((current) => current.filter((id) => id !== token.id));
2195
+ }
2196
+ return /* @__PURE__ */ jsxs("section", {
2197
+ style: {
2198
+ display: "grid",
2199
+ gap: "0.75rem",
2200
+ minWidth: 0
2201
+ },
2202
+ children: [
2203
+ /* @__PURE__ */ jsx("h3", { children: "API tokens" }),
2204
+ index.issue_token_href !== null && /* @__PURE__ */ jsxs("form", {
2205
+ onSubmit: create,
2206
+ style: {
2207
+ display: "grid",
2208
+ gap: "0.75rem",
2209
+ minWidth: 0
2210
+ },
2211
+ children: [
2212
+ /* @__PURE__ */ jsxs("div", {
2213
+ style: {
2214
+ display: "grid",
2215
+ gap: "0.25rem"
2216
+ },
2217
+ children: [/* @__PURE__ */ jsx(Label, {
2218
+ htmlFor: "api-token-name",
2219
+ children: "Token name"
2220
+ }), /* @__PURE__ */ jsx(Input, {
2221
+ id: "api-token-name",
2222
+ value: name,
2223
+ maxLength: 120,
2224
+ onChange: (event) => setName(event.target.value)
2225
+ })]
2226
+ }),
2227
+ /* @__PURE__ */ jsx(ScopePicker, {
2228
+ idPrefix: "api-token-scope",
2229
+ scopes: tokenScopes,
2230
+ groups: index.token_scope_groups ?? index.scope_groups,
2231
+ presets: index.token_scope_presets ?? index.scope_presets,
2232
+ implications: index.token_scope_implications ?? index.scope_implications,
2233
+ selected: scopes,
2234
+ onChange: setScopes,
2235
+ components
2236
+ }),
2237
+ /* @__PURE__ */ jsxs("fieldset", {
2238
+ style: {
2239
+ display: "grid",
2240
+ gap: "0.25rem",
2241
+ border: 0,
2242
+ padding: 0
2243
+ },
2244
+ children: [/* @__PURE__ */ jsx("legend", { children: "Expires after" }), RadioGroup ? /* @__PURE__ */ jsx(RadioGroup, {
2245
+ name: "api-token-lifetime",
2246
+ value: effectiveLifetime,
2247
+ onValueChange: setLifetime,
2248
+ options: lifetimes.map((spec) => ({
2249
+ value: spec,
2250
+ label: describeDuration(spec)
2251
+ }))
2252
+ }) : lifetimes.map((spec) => /* @__PURE__ */ jsxs("label", { children: [
2253
+ /* @__PURE__ */ jsx("input", {
2254
+ type: "radio",
2255
+ name: "api-token-lifetime",
2256
+ checked: effectiveLifetime === spec,
2257
+ onChange: () => setLifetime(spec)
2258
+ }),
2259
+ " ",
2260
+ describeDuration(spec)
2261
+ ] }, spec))]
2262
+ }),
2263
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, {
2264
+ type: "submit",
2265
+ disabled: busy || name.trim() === "" || scopes.length === 0 || effectiveLifetime === "",
2266
+ children: "Create API token"
2267
+ }) })
2268
+ ]
2269
+ }),
2270
+ error !== null && /* @__PURE__ */ jsx("p", {
2271
+ role: "alert",
2272
+ children: error
2273
+ }),
2274
+ /* @__PURE__ */ jsx("ul", {
2275
+ style: {
2276
+ display: "grid",
2277
+ gap: "0.5rem",
2278
+ listStyle: "none",
2279
+ padding: 0,
2280
+ margin: 0,
2281
+ minWidth: 0
2282
+ },
2283
+ children: index.tokens.map((token) => /* @__PURE__ */ jsxs("li", {
2284
+ style: {
2285
+ minWidth: 0,
2286
+ overflowWrap: "anywhere"
2287
+ },
2288
+ children: [
2289
+ /* @__PURE__ */ jsx("strong", { children: token.name }),
2290
+ " · ",
2291
+ token.scopes.join(", "),
2292
+ token.connection === true && /* @__PURE__ */ jsx(Fragment, { children: " · MCP connection" }),
2293
+ token.expires_at !== null && /* @__PURE__ */ jsxs(Fragment, { children: [" · expires ", new Date(token.expires_at).toLocaleString()] }),
2294
+ " ",
2295
+ /* @__PURE__ */ jsx(Button, {
2296
+ type: "button",
2297
+ disabled: pending.includes(token.id),
2298
+ onClick: () => void revoke(token),
2299
+ children: "Revoke"
2300
+ })
2301
+ ]
2302
+ }, token.id))
2303
+ })
2304
+ ]
2305
+ });
1482
2306
  }
1483
2307
  function AppSection({ index, components, csrfToken, request, onIssued, reload, onSuccess, onError, removeLocally }) {
1484
- const { Button, Input, Label, Textarea, RadioGroup } = resolveAuthComponents(components);
1485
- const [name, setName] = React6.useState("");
1486
- const [redirects, setRedirects] = React6.useState("");
1487
- const [confidential, setConfidential] = React6.useState(true);
1488
- const [scopes, setScopes] = React6.useState([]);
1489
- const [busy, setBusy] = React6.useState(false);
1490
- const [error, setError] = React6.useState(null);
1491
- const redirectUris = redirects.split("\n").map((line) => line.trim()).filter((line) => line !== "");
1492
- async function register(event) {
1493
- event.preventDefault();
1494
- if (index.register_app_href === null) {
1495
- return;
1496
- }
1497
- setBusy(true);
1498
- const result = await credentialRequest(
1499
- "POST",
1500
- index.register_app_href,
1501
- { name, redirect_uris: redirectUris, confidential, scopes },
1502
- csrfToken,
1503
- request
1504
- );
1505
- setBusy(false);
1506
- if (!result.ok) {
1507
- setError(result.message);
1508
- onError?.("oauth-apps", result.message);
1509
- return;
1510
- }
1511
- setError(null);
1512
- setName("");
1513
- setRedirects("");
1514
- setScopes([]);
1515
- onIssued(result.data);
1516
- onSuccess?.("OAuth app registered.");
1517
- await reload();
1518
- }
1519
- const [pending, setPending] = React6.useState([]);
1520
- async function remove(app) {
1521
- if (pending.includes(app.id)) {
1522
- return;
1523
- }
1524
- setPending((current) => [...current, app.id]);
1525
- const result = await credentialRequest("DELETE", app.delete_href, void 0, csrfToken, request);
1526
- if (!result.ok) {
1527
- setPending((current) => current.filter((id) => id !== app.id));
1528
- setError(result.message);
1529
- onError?.("oauth-apps", result.message);
1530
- return;
1531
- }
1532
- setError(null);
1533
- removeLocally("apps", app.id);
1534
- onSuccess?.("OAuth app deleted and its tokens revoked.");
1535
- await reload();
1536
- setPending((current) => current.filter((id) => id !== app.id));
1537
- }
1538
- return /* @__PURE__ */ jsxs5("section", { style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1539
- /* @__PURE__ */ jsx5("h3", { children: "OAuth apps" }),
1540
- index.register_app_href !== null && /* @__PURE__ */ jsxs5("form", { onSubmit: register, style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1541
- /* @__PURE__ */ jsxs5("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1542
- /* @__PURE__ */ jsx5(Label, { htmlFor: "oauth-app-name", children: "App name" }),
1543
- /* @__PURE__ */ jsx5(Input, { id: "oauth-app-name", value: name, maxLength: 120, onChange: (event) => setName(event.target.value) })
1544
- ] }),
1545
- /* @__PURE__ */ jsxs5("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1546
- /* @__PURE__ */ jsx5(Label, { htmlFor: "oauth-app-redirects", children: "Redirect URIs (one per line)" }),
1547
- Textarea ? /* @__PURE__ */ jsx5(Textarea, { id: "oauth-app-redirects", rows: 3, value: redirects, onChange: (event) => setRedirects(event.target.value) }) : /* @__PURE__ */ jsx5("textarea", { id: "oauth-app-redirects", rows: 3, value: redirects, onChange: (event) => setRedirects(event.target.value) })
1548
- ] }),
1549
- /* @__PURE__ */ jsxs5("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0 }, children: [
1550
- /* @__PURE__ */ jsx5("legend", { children: "Client type" }),
1551
- RadioGroup ? /* @__PURE__ */ jsx5(
1552
- RadioGroup,
1553
- {
1554
- name: "oauth-app-type",
1555
- value: confidential ? "confidential" : "public",
1556
- onValueChange: (value) => setConfidential(value === "confidential"),
1557
- options: [
1558
- { value: "confidential", label: "Confidential: the app keeps a client secret on its server" },
1559
- { value: "public", label: "Public: no secret, PKCE only" }
1560
- ]
1561
- }
1562
- ) : /* @__PURE__ */ jsxs5(Fragment3, { children: [
1563
- /* @__PURE__ */ jsxs5("label", { children: [
1564
- /* @__PURE__ */ jsx5("input", { type: "radio", name: "oauth-app-type", checked: confidential, onChange: () => setConfidential(true) }),
1565
- " Confidential: the app keeps a client secret on its server"
1566
- ] }),
1567
- /* @__PURE__ */ jsxs5("label", { children: [
1568
- /* @__PURE__ */ jsx5("input", { type: "radio", name: "oauth-app-type", checked: !confidential, onChange: () => setConfidential(false) }),
1569
- " Public: no secret, PKCE only"
1570
- ] })
1571
- ] })
1572
- ] }),
1573
- /* @__PURE__ */ jsx5(
1574
- ScopePicker,
1575
- {
1576
- idPrefix: "oauth-app-scope",
1577
- scopes: index.scopes,
1578
- groups: index.scope_groups,
1579
- presets: index.scope_presets,
1580
- implications: index.scope_implications,
1581
- selected: scopes,
1582
- onChange: setScopes,
1583
- components
1584
- }
1585
- ),
1586
- /* @__PURE__ */ jsx5("div", { children: /* @__PURE__ */ jsx5(Button, { type: "submit", disabled: busy || name.trim() === "" || redirectUris.length === 0 || scopes.length === 0, children: "Register OAuth app" }) })
1587
- ] }),
1588
- error !== null && /* @__PURE__ */ jsx5("p", { role: "alert", children: error }),
1589
- /* @__PURE__ */ jsx5("ul", { style: { display: "grid", gap: "0.5rem", listStyle: "none", padding: 0, margin: 0, minWidth: 0 }, children: index.apps.map((app) => /* @__PURE__ */ jsxs5("li", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1590
- /* @__PURE__ */ jsx5("strong", { children: app.name }),
1591
- " \xB7 client ID ",
1592
- /* @__PURE__ */ jsx5("code", { children: app.id }),
1593
- " \xB7 ",
1594
- app.confidential ? "confidential" : "public",
1595
- /* @__PURE__ */ jsx5("br", {}),
1596
- app.redirect_uris.join(", "),
1597
- /* @__PURE__ */ jsx5("br", {}),
1598
- "May request: ",
1599
- app.scopes.join(", "),
1600
- " ",
1601
- /* @__PURE__ */ jsx5(Button, { type: "button", disabled: pending.includes(app.id), onClick: () => void remove(app), children: "Delete" })
1602
- ] }, app.id)) })
1603
- ] });
1604
- }
1605
- function IssuedNotice({
1606
- issued,
1607
- components,
1608
- onDismiss
1609
- }) {
1610
- const { Button } = resolveAuthComponents(components);
1611
- const values = issued.kind === "token" ? [{ label: "API token", url: issued.token }] : [
1612
- { label: "Client ID", url: issued.client_id },
1613
- ...issued.client_secret !== null ? [{ label: "Client secret", url: issued.client_secret }] : []
1614
- ];
1615
- return /* @__PURE__ */ jsxs5("div", { role: "status", style: { display: "grid", gap: "0.5rem", minWidth: 0 }, children: [
1616
- /* @__PURE__ */ jsxs5("p", { style: { overflowWrap: "anywhere" }, children: [
1617
- issued.kind === "token" ? `API token \u201C${issued.name}\u201D created.` : `OAuth app \u201C${issued.name}\u201D registered.`,
1618
- " Copy it now: it will not be shown again."
1619
- ] }),
1620
- values.map((value) => /* @__PURE__ */ jsxs5("div", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1621
- value.label,
1622
- ": ",
1623
- /* @__PURE__ */ jsx5("code", { children: value.url }),
1624
- " ",
1625
- /* @__PURE__ */ jsx5(CopyButton, { text: value.url, label: value.label, components })
1626
- ] }, value.label)),
1627
- /* @__PURE__ */ jsx5("div", { children: /* @__PURE__ */ jsx5(Button, { type: "button", onClick: onDismiss, children: "Done" }) })
1628
- ] });
2308
+ const { Button, Input, Label, Textarea, RadioGroup } = resolveAuthComponents(components);
2309
+ const [name, setName] = React.useState("");
2310
+ const [redirects, setRedirects] = React.useState("");
2311
+ const [confidential, setConfidential] = React.useState(true);
2312
+ const [scopes, setScopes] = React.useState([]);
2313
+ const [busy, setBusy] = React.useState(false);
2314
+ const [error, setError] = React.useState(null);
2315
+ const redirectUris = redirects.split("\n").map((line) => line.trim()).filter((line) => line !== "");
2316
+ async function register(event) {
2317
+ event.preventDefault();
2318
+ if (index.register_app_href === null) return;
2319
+ setBusy(true);
2320
+ const result = await credentialRequest("POST", index.register_app_href, {
2321
+ name,
2322
+ redirect_uris: redirectUris,
2323
+ confidential,
2324
+ scopes
2325
+ }, csrfToken, request);
2326
+ setBusy(false);
2327
+ if (!result.ok) {
2328
+ setError(result.message);
2329
+ onError?.("oauth-apps", result.message);
2330
+ return;
2331
+ }
2332
+ setError(null);
2333
+ setName("");
2334
+ setRedirects("");
2335
+ setScopes([]);
2336
+ onIssued(result.data);
2337
+ onSuccess?.("OAuth app registered.");
2338
+ await reload();
2339
+ }
2340
+ const [pending, setPending] = React.useState([]);
2341
+ async function remove(app) {
2342
+ if (pending.includes(app.id)) return;
2343
+ setPending((current) => [...current, app.id]);
2344
+ const result = await credentialRequest("DELETE", app.delete_href, void 0, csrfToken, request);
2345
+ if (!result.ok) {
2346
+ setPending((current) => current.filter((id) => id !== app.id));
2347
+ setError(result.message);
2348
+ onError?.("oauth-apps", result.message);
2349
+ return;
2350
+ }
2351
+ setError(null);
2352
+ removeLocally("apps", app.id);
2353
+ onSuccess?.("OAuth app deleted and its tokens revoked.");
2354
+ await reload();
2355
+ setPending((current) => current.filter((id) => id !== app.id));
2356
+ }
2357
+ return /* @__PURE__ */ jsxs("section", {
2358
+ style: {
2359
+ display: "grid",
2360
+ gap: "0.75rem",
2361
+ minWidth: 0
2362
+ },
2363
+ children: [
2364
+ /* @__PURE__ */ jsx("h3", { children: "OAuth apps" }),
2365
+ index.register_app_href !== null && /* @__PURE__ */ jsxs("form", {
2366
+ onSubmit: register,
2367
+ style: {
2368
+ display: "grid",
2369
+ gap: "0.75rem",
2370
+ minWidth: 0
2371
+ },
2372
+ children: [
2373
+ /* @__PURE__ */ jsxs("div", {
2374
+ style: {
2375
+ display: "grid",
2376
+ gap: "0.25rem"
2377
+ },
2378
+ children: [/* @__PURE__ */ jsx(Label, {
2379
+ htmlFor: "oauth-app-name",
2380
+ children: "App name"
2381
+ }), /* @__PURE__ */ jsx(Input, {
2382
+ id: "oauth-app-name",
2383
+ value: name,
2384
+ maxLength: 120,
2385
+ onChange: (event) => setName(event.target.value)
2386
+ })]
2387
+ }),
2388
+ /* @__PURE__ */ jsxs("div", {
2389
+ style: {
2390
+ display: "grid",
2391
+ gap: "0.25rem"
2392
+ },
2393
+ children: [/* @__PURE__ */ jsx(Label, {
2394
+ htmlFor: "oauth-app-redirects",
2395
+ children: "Redirect URIs (one per line)"
2396
+ }), Textarea ? /* @__PURE__ */ jsx(Textarea, {
2397
+ id: "oauth-app-redirects",
2398
+ rows: 3,
2399
+ value: redirects,
2400
+ onChange: (event) => setRedirects(event.target.value)
2401
+ }) : /* @__PURE__ */ jsx("textarea", {
2402
+ id: "oauth-app-redirects",
2403
+ rows: 3,
2404
+ value: redirects,
2405
+ onChange: (event) => setRedirects(event.target.value)
2406
+ })]
2407
+ }),
2408
+ /* @__PURE__ */ jsxs("fieldset", {
2409
+ style: {
2410
+ display: "grid",
2411
+ gap: "0.25rem",
2412
+ border: 0,
2413
+ padding: 0
2414
+ },
2415
+ children: [/* @__PURE__ */ jsx("legend", { children: "Client type" }), RadioGroup ? /* @__PURE__ */ jsx(RadioGroup, {
2416
+ name: "oauth-app-type",
2417
+ value: confidential ? "confidential" : "public",
2418
+ onValueChange: (value) => setConfidential(value === "confidential"),
2419
+ options: [{
2420
+ value: "confidential",
2421
+ label: "Confidential: the app keeps a client secret on its server"
2422
+ }, {
2423
+ value: "public",
2424
+ label: "Public: no secret, PKCE only"
2425
+ }]
2426
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("label", { children: [/* @__PURE__ */ jsx("input", {
2427
+ type: "radio",
2428
+ name: "oauth-app-type",
2429
+ checked: confidential,
2430
+ onChange: () => setConfidential(true)
2431
+ }), " Confidential: the app keeps a client secret on its server"] }), /* @__PURE__ */ jsxs("label", { children: [/* @__PURE__ */ jsx("input", {
2432
+ type: "radio",
2433
+ name: "oauth-app-type",
2434
+ checked: !confidential,
2435
+ onChange: () => setConfidential(false)
2436
+ }), " Public: no secret, PKCE only"] })] })]
2437
+ }),
2438
+ /* @__PURE__ */ jsx(ScopePicker, {
2439
+ idPrefix: "oauth-app-scope",
2440
+ scopes: index.scopes,
2441
+ groups: index.scope_groups,
2442
+ presets: index.scope_presets,
2443
+ implications: index.scope_implications,
2444
+ selected: scopes,
2445
+ onChange: setScopes,
2446
+ components
2447
+ }),
2448
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, {
2449
+ type: "submit",
2450
+ disabled: busy || name.trim() === "" || redirectUris.length === 0 || scopes.length === 0,
2451
+ children: "Register OAuth app"
2452
+ }) })
2453
+ ]
2454
+ }),
2455
+ error !== null && /* @__PURE__ */ jsx("p", {
2456
+ role: "alert",
2457
+ children: error
2458
+ }),
2459
+ /* @__PURE__ */ jsx("ul", {
2460
+ style: {
2461
+ display: "grid",
2462
+ gap: "0.5rem",
2463
+ listStyle: "none",
2464
+ padding: 0,
2465
+ margin: 0,
2466
+ minWidth: 0
2467
+ },
2468
+ children: index.apps.map((app) => /* @__PURE__ */ jsxs("li", {
2469
+ style: {
2470
+ minWidth: 0,
2471
+ overflowWrap: "anywhere"
2472
+ },
2473
+ children: [
2474
+ /* @__PURE__ */ jsx("strong", { children: app.name }),
2475
+ " · client ID ",
2476
+ /* @__PURE__ */ jsx("code", { children: app.id }),
2477
+ " · ",
2478
+ app.confidential ? "confidential" : "public",
2479
+ /* @__PURE__ */ jsx("br", {}),
2480
+ app.redirect_uris.join(", "),
2481
+ /* @__PURE__ */ jsx("br", {}),
2482
+ "May request: ",
2483
+ app.scopes.join(", "),
2484
+ " ",
2485
+ /* @__PURE__ */ jsx(Button, {
2486
+ type: "button",
2487
+ disabled: pending.includes(app.id),
2488
+ onClick: () => void remove(app),
2489
+ children: "Delete"
2490
+ })
2491
+ ]
2492
+ }, app.id))
2493
+ })
2494
+ ]
2495
+ });
2496
+ }
2497
+ function IssuedNotice({ issued, components, onDismiss }) {
2498
+ const { Button } = resolveAuthComponents(components);
2499
+ const values = issued.kind === "token" ? [{
2500
+ label: "API token",
2501
+ url: issued.token
2502
+ }] : [{
2503
+ label: "Client ID",
2504
+ url: issued.client_id
2505
+ }, ...issued.client_secret !== null ? [{
2506
+ label: "Client secret",
2507
+ url: issued.client_secret
2508
+ }] : []];
2509
+ return /* @__PURE__ */ jsxs("div", {
2510
+ role: "status",
2511
+ style: {
2512
+ display: "grid",
2513
+ gap: "0.5rem",
2514
+ minWidth: 0
2515
+ },
2516
+ children: [
2517
+ /* @__PURE__ */ jsxs("p", {
2518
+ style: { overflowWrap: "anywhere" },
2519
+ children: [issued.kind === "token" ? `API token “${issued.name}” created.` : `OAuth app “${issued.name}” registered.`, " Copy it now: it will not be shown again."]
2520
+ }),
2521
+ values.map((value) => /* @__PURE__ */ jsxs("div", {
2522
+ style: {
2523
+ minWidth: 0,
2524
+ overflowWrap: "anywhere"
2525
+ },
2526
+ children: [
2527
+ value.label,
2528
+ ": ",
2529
+ /* @__PURE__ */ jsx("code", { children: value.url }),
2530
+ " ",
2531
+ /* @__PURE__ */ jsx(CopyButton, {
2532
+ text: value.url,
2533
+ label: value.label,
2534
+ components
2535
+ })
2536
+ ]
2537
+ }, value.label)),
2538
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, {
2539
+ type: "button",
2540
+ onClick: onDismiss,
2541
+ children: "Done"
2542
+ }) })
2543
+ ]
2544
+ });
1629
2545
  }
1630
2546
  function CopyButton({ text, label, components }) {
1631
- const { Button } = resolveAuthComponents(components);
1632
- const [state, setState] = React6.useState("idle");
1633
- return /* @__PURE__ */ jsxs5(Fragment3, { children: [
1634
- /* @__PURE__ */ jsx5(
1635
- Button,
1636
- {
1637
- type: "button",
1638
- "aria-label": `Copy ${label}`,
1639
- onClick: async () => {
1640
- if (typeof navigator === "undefined" || typeof navigator.clipboard?.writeText !== "function") {
1641
- setState("failed");
1642
- return;
1643
- }
1644
- try {
1645
- await navigator.clipboard.writeText(text);
1646
- setState("copied");
1647
- } catch {
1648
- setState("failed");
1649
- }
1650
- },
1651
- children: state === "copied" ? "Copied" : "Copy"
1652
- }
1653
- ),
1654
- state === "failed" && /* @__PURE__ */ jsx5("span", { role: "status", children: " Copying is unavailable here; select the text and copy it manually." })
1655
- ] });
2547
+ const { Button } = resolveAuthComponents(components);
2548
+ const [state, setState] = React.useState("idle");
2549
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
2550
+ type: "button",
2551
+ "aria-label": `Copy ${label}`,
2552
+ onClick: async () => {
2553
+ if (typeof navigator === "undefined" || typeof navigator.clipboard?.writeText !== "function") {
2554
+ setState("failed");
2555
+ return;
2556
+ }
2557
+ try {
2558
+ await navigator.clipboard.writeText(text);
2559
+ setState("copied");
2560
+ } catch {
2561
+ setState("failed");
2562
+ }
2563
+ },
2564
+ children: state === "copied" ? "Copied" : "Copy"
2565
+ }), state === "failed" && /* @__PURE__ */ jsx("span", {
2566
+ role: "status",
2567
+ children: " Copying is unavailable here; select the text and copy it manually."
2568
+ })] });
1656
2569
  }
2570
+ /** PT4H → "4 hours", P30D → "30 days", P1Y → "1 year". Unknown shapes are shown as given. */
1657
2571
  function describeDuration(spec) {
1658
- const match = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/.exec(spec);
1659
- if (!match) {
1660
- return spec;
1661
- }
1662
- const units = ["year", "month", "week", "day", "hour", "minute"];
1663
- const parts = match.slice(1).map((value, position) => value ? `${Number(value)} ${units[position]}${Number(value) === 1 ? "" : "s"}` : null).filter((part) => part !== null);
1664
- return parts.length > 0 ? parts.join(" ") : spec;
2572
+ const match = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/.exec(spec);
2573
+ if (!match) return spec;
2574
+ const units = [
2575
+ "year",
2576
+ "month",
2577
+ "week",
2578
+ "day",
2579
+ "hour",
2580
+ "minute"
2581
+ ];
2582
+ const parts = match.slice(1).map((value, position) => value ? `${Number(value)} ${units[position]}${Number(value) === 1 ? "" : "s"}` : null).filter((part) => part !== null);
2583
+ return parts.length > 0 ? parts.join(" ") : spec;
1665
2584
  }
1666
2585
  async function credentialRequest(method, url, body, csrfToken, request) {
1667
- if (request !== void 0) {
1668
- let result;
1669
- try {
1670
- result = await request(method, url, body);
1671
- } catch {
1672
- return { ok: false, status: 0, message: "The server could not be reached. Check the connection and try again." };
1673
- }
1674
- return result.ok ? { ok: true, status: result.status, data: unwrapData(result.payload) } : result;
1675
- }
1676
- let response;
1677
- try {
1678
- response = await fetch(url, {
1679
- method,
1680
- credentials: "same-origin",
1681
- headers: {
1682
- Accept: "application/json",
1683
- ...body !== void 0 ? { "Content-Type": "application/json" } : {},
1684
- ...method !== "GET" ? { "X-CSRF-TOKEN": getCsrfToken(csrfToken) } : {}
1685
- },
1686
- body: body !== void 0 ? JSON.stringify(body) : void 0
1687
- });
1688
- } catch {
1689
- return { ok: false, status: 0, message: "The server could not be reached. Check the connection and try again." };
1690
- }
1691
- const payload = await response.json().catch(() => null);
1692
- if (response.ok) {
1693
- return { ok: true, status: response.status, data: unwrapData(payload) };
1694
- }
1695
- return { ok: false, status: response.status, message: refusalMessage(response.status, payload) };
2586
+ if (request !== void 0) {
2587
+ let result;
2588
+ try {
2589
+ result = await request(method, url, body);
2590
+ } catch {
2591
+ return {
2592
+ ok: false,
2593
+ status: 0,
2594
+ message: "The server could not be reached. Check the connection and try again."
2595
+ };
2596
+ }
2597
+ return result.ok ? {
2598
+ ok: true,
2599
+ status: result.status,
2600
+ data: unwrapData(result.payload)
2601
+ } : result;
2602
+ }
2603
+ let response;
2604
+ try {
2605
+ response = await fetch(url, {
2606
+ method,
2607
+ credentials: "same-origin",
2608
+ headers: {
2609
+ Accept: "application/json",
2610
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {},
2611
+ ...method !== "GET" ? { "X-CSRF-TOKEN": getCsrfToken(csrfToken) } : {}
2612
+ },
2613
+ body: body !== void 0 ? JSON.stringify(body) : void 0
2614
+ });
2615
+ } catch {
2616
+ return {
2617
+ ok: false,
2618
+ status: 0,
2619
+ message: "The server could not be reached. Check the connection and try again."
2620
+ };
2621
+ }
2622
+ const payload = await response.json().catch(() => null);
2623
+ if (response.ok) return {
2624
+ ok: true,
2625
+ status: response.status,
2626
+ data: unwrapData(payload)
2627
+ };
2628
+ return {
2629
+ ok: false,
2630
+ status: response.status,
2631
+ message: refusalMessage(response.status, payload)
2632
+ };
1696
2633
  }
1697
2634
  function unwrapData(payload) {
1698
- return typeof payload === "object" && payload !== null && "data" in payload ? payload.data : payload;
2635
+ return typeof payload === "object" && payload !== null && "data" in payload ? payload.data : payload;
1699
2636
  }
1700
2637
  function refusalMessage(status, payload) {
1701
- if (status === 401 || status === 419) {
1702
- return "Your session has expired. Reload the page and sign in again.";
1703
- }
1704
- if (typeof payload === "object" && payload !== null) {
1705
- const errors = payload.errors;
1706
- if (errors && typeof errors === "object") {
1707
- const first = Object.values(errors)[0];
1708
- if (Array.isArray(first) && typeof first[0] === "string") {
1709
- return first[0];
1710
- }
1711
- }
1712
- const message = payload.message;
1713
- if (typeof message === "string" && message !== "") {
1714
- return message;
1715
- }
1716
- }
1717
- if (status === 403) {
1718
- return "You do not have permission to do that.";
1719
- }
1720
- if (status === 404) {
1721
- return "That credential no longer exists, or creating credentials is unavailable right now.";
1722
- }
1723
- return "That action could not be completed.";
1724
- }
1725
- export {
1726
- ApiCredentialsSection,
1727
- ChangePasswordForm,
1728
- LoginForm,
1729
- PasskeyLoginButton,
1730
- PasskeySection,
1731
- PasswordResetRequestForm,
1732
- ResetPasswordForm,
1733
- ScopePicker,
1734
- SignupForm,
1735
- TwoFactorForm,
1736
- arrayBufferToBase64url,
1737
- authenticateWithPasskey,
1738
- base64urlToArrayBuffer,
1739
- closeImplications,
1740
- describeDuration,
1741
- getCsrfToken,
1742
- getDefaultPasskeyName,
1743
- inCatalogOrder,
1744
- isAbortError,
1745
- isConditionalMediationAvailable,
1746
- neededBy,
1747
- registerPasskey,
1748
- relyingApplicationsFrom,
1749
- restrictImplications,
1750
- safeApplicationHref,
1751
- sameSelection,
1752
- withScopes,
1753
- withoutScopes
2638
+ if (status === 401 || status === 419) return "Your session has expired. Reload the page and sign in again.";
2639
+ if (typeof payload === "object" && payload !== null) {
2640
+ const errors = payload.errors;
2641
+ if (errors && typeof errors === "object") {
2642
+ const first = Object.values(errors)[0];
2643
+ if (Array.isArray(first) && typeof first[0] === "string") return first[0];
2644
+ }
2645
+ const message = payload.message;
2646
+ if (typeof message === "string" && message !== "") return message;
2647
+ }
2648
+ if (status === 403) return "You do not have permission to do that.";
2649
+ if (status === 404) return "That credential no longer exists, or creating credentials is unavailable right now.";
2650
+ return "That action could not be completed.";
2651
+ }
2652
+ // src/auth-browser-help.tsx
2653
+ const AUTOMATED_AGENTS = /HeadlessChrome|PhantomJS|Prerender|Google-Safety|BingPreview|Barracuda|Mimecast|Proofpoint|SkypeUriPreview/i;
2654
+ const IN_APP_BROWSERS = [
2655
+ [/FBAN\/Messenger|MessengerForiOS|MessengerLite/, "Messenger"],
2656
+ [/Instagram/, "Instagram"],
2657
+ [/FBAN|FBAV|FB_IAB|FBIOS/, "Facebook"],
2658
+ [/LinkedInApp/, "LinkedIn"],
2659
+ [/Snapchat/, "Snapchat"],
2660
+ [/Pinterest/, "Pinterest"],
2661
+ [/musical_ly|BytedanceWebview|TikTok/, "TikTok"],
2662
+ [/MicroMessenger/, "WeChat"],
2663
+ [/\bLine\//, "LINE"],
2664
+ [/\bTwitter\b/, "X"],
2665
+ [/\bGSA\//, "Google"],
2666
+ [/Android.*;\s?wv\)/, void 0]
2667
+ ];
2668
+ const IOS_WEBVIEW = /(?:iPhone|iPod|iPad).*AppleWebKit(?!.*Safari\/)/;
2669
+ /** Read the current browser's environment. Returns `{}` during server rendering. */
2670
+ function readAuthBrowserEnvironment() {
2671
+ if (typeof window === "undefined" || typeof navigator === "undefined") return {};
2672
+ const environment = {
2673
+ userAgent: navigator.userAgent,
2674
+ webdriver: navigator.webdriver === true,
2675
+ cookieEnabled: navigator.cookieEnabled
2676
+ };
2677
+ try {
2678
+ environment.framed = window.self !== window.top;
2679
+ } catch {
2680
+ environment.framed = true;
2681
+ }
2682
+ environment.cookiesWritable = probeCookies();
2683
+ try {
2684
+ environment.standalone = navigator.standalone === true || typeof window.matchMedia === "function" && window.matchMedia("(display-mode: standalone)").matches;
2685
+ } catch {
2686
+ environment.standalone = false;
2687
+ }
2688
+ try {
2689
+ const key = "__bwh_auth_storage_probe";
2690
+ window.localStorage.setItem(key, "1");
2691
+ window.localStorage.removeItem(key);
2692
+ environment.storageAvailable = true;
2693
+ } catch {
2694
+ environment.storageAvailable = false;
2695
+ }
2696
+ return environment;
2697
+ }
2698
+ function probeCookies() {
2699
+ if (typeof document === "undefined") return true;
2700
+ const name = "__bwh_auth_cookie_probe";
2701
+ const secure = typeof location !== "undefined" && location.protocol === "https:" ? "; Secure" : "";
2702
+ try {
2703
+ document.cookie = `${name}=1; path=/; SameSite=Lax${secure}`;
2704
+ const written = document.cookie.split(";").some((part) => part.trim() === `${name}=1`);
2705
+ document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax${secure}`;
2706
+ return written;
2707
+ } catch {
2708
+ return false;
2709
+ }
2710
+ }
2711
+ /** Name the conditions in `environment` that are likely to break sign-in, most fundamental first. */
2712
+ function detectAuthBrowserIssues(environment = readAuthBrowserEnvironment()) {
2713
+ const issues = [];
2714
+ const userAgent = environment.userAgent ?? "";
2715
+ if (environment.webdriver === true || AUTOMATED_AGENTS.test(userAgent)) issues.push({ kind: "automated" });
2716
+ if (environment.framed === true) issues.push({ kind: "framed" });
2717
+ const inApp = IN_APP_BROWSERS.find(([pattern]) => pattern.test(userAgent));
2718
+ if (inApp) issues.push(inApp[1] === void 0 ? { kind: "in-app-browser" } : {
2719
+ kind: "in-app-browser",
2720
+ app: inApp[1]
2721
+ });
2722
+ else if (environment.standalone !== true && IOS_WEBVIEW.test(userAgent)) issues.push({ kind: "in-app-browser" });
2723
+ if (environment.cookieEnabled === false || environment.cookiesWritable === false) issues.push({ kind: "cookies-disabled" });
2724
+ if (environment.storageAvailable === false) issues.push({ kind: "storage-unavailable" });
2725
+ return issues;
2726
+ }
2727
+ function defaultCopy(issue) {
2728
+ switch (issue.kind) {
2729
+ case "automated": return {
2730
+ title: "This page was opened automatically",
2731
+ body: "Email security scanners and link previews can open sign-in links before you do, which may use them up. If your link no longer works, request a new one and open it yourself."
2732
+ };
2733
+ case "framed": return {
2734
+ title: "This page is shown inside another page",
2735
+ body: "Signing in may not work in a preview or embedded view. Open this page in its own browser tab."
2736
+ };
2737
+ case "in-app-browser": return {
2738
+ title: issue.app ? `You are using ${issue.app}'s built-in browser` : "You are using an in-app browser",
2739
+ body: "Signing in may not work here, and you may not stay signed in. Open this page in your usual browser: use the app's menu and choose to open in the browser, or copy the link and paste it there."
2740
+ };
2741
+ case "cookies-disabled": return {
2742
+ title: "Cookies are blocked",
2743
+ body: "Signing in needs cookies for this site. Allow cookies in your browser settings, then reload this page."
2744
+ };
2745
+ case "storage-unavailable": return {
2746
+ title: "This browser is blocking site storage",
2747
+ body: "Some sign-in steps may not work in a private or restricted window. If you have trouble, try a regular browser window."
2748
+ };
2749
+ }
2750
+ }
2751
+ /**
2752
+ * Guidance for browsers and contexts that commonly break sign-in links and flows.
2753
+ *
2754
+ * Detection runs after mount, so server rendering and the first client render show
2755
+ * nothing and hydrate identically. Nothing renders when no issue applies.
2756
+ */
2757
+ function AuthBrowserHelp({ components, issues: givenIssues, environment, ignore = [], messages = {}, url, className, onDetect }) {
2758
+ if (!components?.Button) throw new Error("bwh-auth requires an injected Button component");
2759
+ const { Button, Alert } = components;
2760
+ const [detected, setDetected] = React.useState([]);
2761
+ const [copyState, setCopyState] = React.useState("idle");
2762
+ const onDetectRef = React.useRef(onDetect);
2763
+ onDetectRef.current = onDetect;
2764
+ const environmentKey = environment ? JSON.stringify(environment) : "";
2765
+ React.useEffect(() => {
2766
+ if (givenIssues !== void 0) return;
2767
+ const found = detectAuthBrowserIssues(environment ?? readAuthBrowserEnvironment());
2768
+ setDetected(found);
2769
+ onDetectRef.current?.(found);
2770
+ }, [givenIssues === void 0, environmentKey]);
2771
+ const shown = (givenIssues ?? detected).filter((issue) => !ignore.includes(issue.kind));
2772
+ if (shown.length === 0) return null;
2773
+ function targetUrl() {
2774
+ return url ?? (typeof window !== "undefined" ? window.location.href : "");
2775
+ }
2776
+ async function copyLink() {
2777
+ try {
2778
+ await navigator.clipboard.writeText(targetUrl());
2779
+ setCopyState("copied");
2780
+ } catch {
2781
+ setCopyState("failed");
2782
+ }
2783
+ }
2784
+ function action(issue) {
2785
+ switch (issue.kind) {
2786
+ case "framed": return /* @__PURE__ */ jsx(Button, {
2787
+ type: "button",
2788
+ variant: "outline",
2789
+ size: "sm",
2790
+ onClick: () => window.open(targetUrl(), "_blank", "noopener,noreferrer"),
2791
+ children: "Open in a new tab"
2792
+ });
2793
+ case "in-app-browser": return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
2794
+ type: "button",
2795
+ variant: "outline",
2796
+ size: "sm",
2797
+ onClick: () => void copyLink(),
2798
+ children: copyState === "copied" ? "Link copied" : "Copy link"
2799
+ }), copyState === "failed" ? /* @__PURE__ */ jsx("p", {
2800
+ className: "text-sm",
2801
+ children: "Copying was blocked. Copy the address from the address bar instead."
2802
+ }) : null] });
2803
+ case "cookies-disabled": return /* @__PURE__ */ jsx(Button, {
2804
+ type: "button",
2805
+ variant: "outline",
2806
+ size: "sm",
2807
+ onClick: () => window.location.reload(),
2808
+ children: "Reload"
2809
+ });
2810
+ default: return null;
2811
+ }
2812
+ }
2813
+ return /* @__PURE__ */ jsx("div", {
2814
+ className: className ?? "space-y-3",
2815
+ "data-auth-browser-help": "",
2816
+ children: shown.map((issue) => {
2817
+ const fallback = defaultCopy(issue);
2818
+ const override = messages[issue.kind];
2819
+ const copy = {
2820
+ title: override?.title ?? fallback.title,
2821
+ body: override?.body ?? fallback.body
2822
+ };
2823
+ const content = /* @__PURE__ */ jsxs("div", {
2824
+ className: "space-y-2",
2825
+ children: [
2826
+ /* @__PURE__ */ jsx("p", {
2827
+ className: "font-medium",
2828
+ children: copy.title
2829
+ }),
2830
+ /* @__PURE__ */ jsx("p", {
2831
+ className: "text-sm",
2832
+ children: copy.body
2833
+ }),
2834
+ action(issue)
2835
+ ]
2836
+ });
2837
+ return Alert ? /* @__PURE__ */ jsx(Alert, {
2838
+ "data-issue": issue.kind,
2839
+ children: content
2840
+ }, issue.kind) : /* @__PURE__ */ jsx("div", {
2841
+ role: "status",
2842
+ "data-issue": issue.kind,
2843
+ children: content
2844
+ }, issue.kind);
2845
+ })
2846
+ });
2847
+ }
2848
+ // src/sign-in-history.tsx
2849
+ /** The events `SignInHistory` shows by default: sign-in attempts and their second factor. */
2850
+ const SIGN_IN_AUDIT_EVENTS = [
2851
+ "login_succeeded",
2852
+ "login_failed",
2853
+ "login_blocked",
2854
+ "passkey_login_succeeded",
2855
+ "passkey_login_failed",
2856
+ "two_factor_succeeded",
2857
+ "two_factor_failed",
2858
+ "two_factor_reported_suspicious"
2859
+ ];
2860
+ const DEFAULT_EVENT_LABELS = {
2861
+ login_succeeded: "Signed in",
2862
+ login_failed: "Sign-in failed",
2863
+ login_blocked: "Sign-in blocked",
2864
+ logged_out: "Signed out",
2865
+ two_factor_challenge_created: "Verification code sent",
2866
+ two_factor_succeeded: "Verification code accepted",
2867
+ two_factor_failed: "Verification code rejected",
2868
+ two_factor_reported_suspicious: "Reported as not me",
2869
+ passkey_registered: "Passkey added",
2870
+ passkey_deleted: "Passkey removed",
2871
+ passkey_login_succeeded: "Signed in with a passkey",
2872
+ passkey_login_failed: "Passkey sign-in failed",
2873
+ password_reset_requested: "Password reset requested",
2874
+ password_reset_completed: "Password reset",
2875
+ password_changed: "Password changed"
2876
+ };
2877
+ const DEFAULT_METHOD_LABELS = {
2878
+ password: "Password",
2879
+ passkey: "Passkey",
2880
+ two_factor: "Email code"
1754
2881
  };
2882
+ function isNullableString(value) {
2883
+ return value === null || typeof value === "string";
2884
+ }
2885
+ function parseEntry(value) {
2886
+ if (typeof value !== "object" || value === null) return null;
2887
+ const row = value;
2888
+ if (typeof row.id !== "number" || typeof row.event !== "string") return null;
2889
+ const metadata = typeof row.metadata === "object" && row.metadata !== null && !Array.isArray(row.metadata) ? row.metadata : null;
2890
+ const location = typeof row.location === "string" ? row.location : typeof metadata?.location === "string" ? metadata.location : null;
2891
+ return {
2892
+ id: row.id,
2893
+ user_id: typeof row.user_id === "number" ? row.user_id : null,
2894
+ acting_user_id: typeof row.acting_user_id === "number" ? row.acting_user_id : null,
2895
+ email: isNullableString(row.email) ? row.email : null,
2896
+ event: row.event,
2897
+ auth_method: isNullableString(row.auth_method) ? row.auth_method : null,
2898
+ succeeded: row.succeeded === true || row.succeeded === 1,
2899
+ reason: isNullableString(row.reason) ? row.reason : null,
2900
+ ip_address: isNullableString(row.ip_address) ? row.ip_address : null,
2901
+ user_agent: isNullableString(row.user_agent) ? row.user_agent : null,
2902
+ session_id: isNullableString(row.session_id) ? row.session_id : null,
2903
+ is_suspicious: row.is_suspicious === true || row.is_suspicious === 1,
2904
+ metadata,
2905
+ created_at: isNullableString(row.created_at) ? row.created_at : null,
2906
+ updated_at: isNullableString(row.updated_at) ? row.updated_at : null,
2907
+ location
2908
+ };
2909
+ }
2910
+ /**
2911
+ * Validate an audit-log response into a page that is safe to render, or `null` if it is not one.
2912
+ * Malformed rows are dropped rather than failing the whole page.
2913
+ */
2914
+ function parseAuthAuditLogPage(payload) {
2915
+ if (typeof payload !== "object" || payload === null || !Array.isArray(payload.data)) return null;
2916
+ const page = payload;
2917
+ const data = page.data.flatMap((row) => {
2918
+ const entry = parseEntry(row);
2919
+ return entry === null ? [] : [entry];
2920
+ });
2921
+ const number = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
2922
+ const currentPage = number(page.current_page, 1);
2923
+ return {
2924
+ current_page: currentPage,
2925
+ data,
2926
+ last_page: number(page.last_page, currentPage),
2927
+ per_page: number(page.per_page, data.length),
2928
+ total: number(page.total, data.length),
2929
+ from: typeof page.from === "number" ? page.from : null,
2930
+ to: typeof page.to === "number" ? page.to : null,
2931
+ next_page_url: typeof page.next_page_url === "string" ? page.next_page_url : null,
2932
+ prev_page_url: typeof page.prev_page_url === "string" ? page.prev_page_url : null
2933
+ };
2934
+ }
2935
+ function withQuery(url, params) {
2936
+ const query = new URLSearchParams(params).toString();
2937
+ const hashIndex = url.indexOf("#");
2938
+ const base = hashIndex === -1 ? url : url.slice(0, hashIndex);
2939
+ return `${base}${base.includes("?") ? "&" : "?"}${query}`;
2940
+ }
2941
+ function refusal(status, payload) {
2942
+ if (status === 401 || status === 419) return "Your session has expired. Reload the page and sign in again.";
2943
+ if (status === 404) return "Sign-in history is not available.";
2944
+ if (status === 403) return "You do not have permission to view this sign-in history.";
2945
+ const message = typeof payload === "object" && payload !== null ? payload.message : void 0;
2946
+ return typeof message === "string" && message !== "" ? message : "Sign-in history could not be loaded.";
2947
+ }
2948
+ async function loadPage(url, request) {
2949
+ const unreachable = "The server could not be reached. Check the connection and try again.";
2950
+ let status;
2951
+ let payload;
2952
+ if (request) {
2953
+ let result;
2954
+ try {
2955
+ result = await request(url);
2956
+ } catch {
2957
+ return {
2958
+ ok: false,
2959
+ message: unreachable
2960
+ };
2961
+ }
2962
+ if (!result.ok) return {
2963
+ ok: false,
2964
+ message: result.message
2965
+ };
2966
+ status = result.status;
2967
+ payload = result.payload;
2968
+ } else {
2969
+ let response;
2970
+ try {
2971
+ response = await fetch(url, {
2972
+ method: "GET",
2973
+ credentials: "same-origin",
2974
+ headers: {
2975
+ Accept: "application/json",
2976
+ "X-Requested-With": "XMLHttpRequest"
2977
+ }
2978
+ });
2979
+ } catch {
2980
+ return {
2981
+ ok: false,
2982
+ message: unreachable
2983
+ };
2984
+ }
2985
+ status = response.status;
2986
+ payload = await response.json().catch(() => null);
2987
+ if (!response.ok) return {
2988
+ ok: false,
2989
+ message: refusal(status, payload)
2990
+ };
2991
+ }
2992
+ const page = parseAuthAuditLogPage(payload);
2993
+ return page === null ? {
2994
+ ok: false,
2995
+ message: "The server returned an unexpected response. Please try again."
2996
+ } : {
2997
+ ok: true,
2998
+ page
2999
+ };
3000
+ }
3001
+ function defaultFormatTime(iso) {
3002
+ const date = new Date(iso);
3003
+ return Number.isNaN(date.getTime()) ? iso : date.toLocaleString();
3004
+ }
3005
+ /**
3006
+ * The signed-in person's recent sign-in activity, read from auth-laravel's audit-log
3007
+ * endpoint (`GET /api/auth/audit-log`, enabled by `bherila-auth.audit.routes_enabled`,
3008
+ * session-authenticated). Newest first, with "Load more" for older pages.
3009
+ */
3010
+ function SignInHistory({ components, url = "/api/auth/audit-log", perPage = 20, events = SIGN_IN_AUDIT_EVENTS, request, formatTime = defaultFormatTime, eventLabels = {}, methodLabels = {}, emptyMessage = "No sign-in activity yet.", label = "Sign-in history", className, onError }) {
3011
+ if (!components?.Button) throw new Error("bwh-auth requires an injected Button component");
3012
+ const { Button, Alert, Badge } = components;
3013
+ const [rows, setRows] = React.useState([]);
3014
+ const [page, setPage] = React.useState(null);
3015
+ const [loading, setLoading] = React.useState(true);
3016
+ const [error, setError] = React.useState(null);
3017
+ const size = Math.min(Math.max(Math.trunc(perPage) || 20, 1), 100);
3018
+ const generation = React.useRef(0);
3019
+ const context = React.useRef({
3020
+ request,
3021
+ onError
3022
+ });
3023
+ context.current = {
3024
+ request,
3025
+ onError
3026
+ };
3027
+ const load = React.useCallback(async (pageNumber) => {
3028
+ generation.current += 1;
3029
+ const mine = generation.current;
3030
+ setLoading(true);
3031
+ setError(null);
3032
+ const result = await loadPage(withQuery(url, {
3033
+ per_page: String(size),
3034
+ page: String(pageNumber)
3035
+ }), context.current.request);
3036
+ if (mine !== generation.current) return;
3037
+ setLoading(false);
3038
+ if (!result.ok) {
3039
+ setError(result.message);
3040
+ context.current.onError?.(result.message);
3041
+ return;
3042
+ }
3043
+ setPage(result.page);
3044
+ setRows((current) => {
3045
+ if (pageNumber === 1) return result.page.data;
3046
+ const seen = new Set(current.map((row) => row.id));
3047
+ return [...current, ...result.page.data.filter((row) => !seen.has(row.id))];
3048
+ });
3049
+ }, [url, size]);
3050
+ React.useEffect(() => {
3051
+ setRows([]);
3052
+ setPage(null);
3053
+ load(1);
3054
+ return () => {
3055
+ generation.current += 1;
3056
+ };
3057
+ }, [load]);
3058
+ const shown = events === "all" ? rows : rows.filter((row) => events.includes(row.event));
3059
+ const showLocation = shown.some((row) => row.location);
3060
+ const hasMore = page !== null && page.current_page < page.last_page;
3061
+ const nextPage = page === null ? 1 : page.current_page + 1;
3062
+ const tag = (text, kind) => Badge ? /* @__PURE__ */ jsx(Badge, {
3063
+ "data-kind": kind,
3064
+ children: text
3065
+ }) : /* @__PURE__ */ jsx("span", {
3066
+ "data-kind": kind,
3067
+ children: text
3068
+ });
3069
+ const errorView = error === null ? null : Alert ? /* @__PURE__ */ jsx(Alert, { children: error }) : /* @__PURE__ */ jsx("p", {
3070
+ role: "alert",
3071
+ children: error
3072
+ });
3073
+ return /* @__PURE__ */ jsxs("div", {
3074
+ className: className ?? "space-y-3",
3075
+ children: [
3076
+ page === null && loading ? /* @__PURE__ */ jsx("p", {
3077
+ role: "status",
3078
+ children: "Loading sign-in history..."
3079
+ }) : null,
3080
+ page !== null && shown.length === 0 && !hasMore ? /* @__PURE__ */ jsx("p", { children: emptyMessage }) : null,
3081
+ shown.length > 0 ? /* @__PURE__ */ jsx("div", {
3082
+ className: "overflow-x-auto",
3083
+ children: /* @__PURE__ */ jsxs("table", {
3084
+ className: "w-full text-sm",
3085
+ "aria-label": label,
3086
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
3087
+ /* @__PURE__ */ jsx("th", {
3088
+ scope: "col",
3089
+ className: "text-left",
3090
+ children: "Time"
3091
+ }),
3092
+ /* @__PURE__ */ jsx("th", {
3093
+ scope: "col",
3094
+ className: "text-left",
3095
+ children: "Activity"
3096
+ }),
3097
+ /* @__PURE__ */ jsx("th", {
3098
+ scope: "col",
3099
+ className: "text-left",
3100
+ children: "Method"
3101
+ }),
3102
+ /* @__PURE__ */ jsx("th", {
3103
+ scope: "col",
3104
+ className: "text-left",
3105
+ children: "IP address"
3106
+ }),
3107
+ showLocation ? /* @__PURE__ */ jsx("th", {
3108
+ scope: "col",
3109
+ className: "text-left",
3110
+ children: "Location"
3111
+ }) : null,
3112
+ /* @__PURE__ */ jsx("th", {
3113
+ scope: "col",
3114
+ className: "text-left",
3115
+ children: "Result"
3116
+ })
3117
+ ] }) }), /* @__PURE__ */ jsx("tbody", { children: shown.map((row) => /* @__PURE__ */ jsxs("tr", {
3118
+ "data-event": row.event,
3119
+ children: [
3120
+ /* @__PURE__ */ jsx("td", { children: row.created_at ? /* @__PURE__ */ jsx("time", {
3121
+ dateTime: row.created_at,
3122
+ children: formatTime(row.created_at)
3123
+ }) : "—" }),
3124
+ /* @__PURE__ */ jsx("td", { children: eventLabels[row.event] ?? DEFAULT_EVENT_LABELS[row.event] ?? row.event }),
3125
+ /* @__PURE__ */ jsx("td", { children: row.auth_method ? methodLabels[row.auth_method] ?? DEFAULT_METHOD_LABELS[row.auth_method] ?? row.auth_method : "—" }),
3126
+ /* @__PURE__ */ jsx("td", { children: row.ip_address ?? "—" }),
3127
+ showLocation ? /* @__PURE__ */ jsx("td", { children: row.location ?? "—" }) : null,
3128
+ /* @__PURE__ */ jsx("td", { children: /* @__PURE__ */ jsxs("span", {
3129
+ className: "inline-flex flex-wrap gap-1",
3130
+ children: [row.event === "login_blocked" ? tag("Blocked", "blocked") : tag(row.succeeded ? "Succeeded" : "Failed", row.succeeded ? "succeeded" : "failed"), row.is_suspicious ? tag("Flagged", "suspicious") : null]
3131
+ }) })
3132
+ ]
3133
+ }, row.id)) })]
3134
+ })
3135
+ }) : null,
3136
+ errorView,
3137
+ error !== null ? /* @__PURE__ */ jsx(Button, {
3138
+ type: "button",
3139
+ variant: "outline",
3140
+ size: "sm",
3141
+ onClick: () => void load(nextPage),
3142
+ children: "Try again"
3143
+ }) : hasMore ? /* @__PURE__ */ jsx(Button, {
3144
+ type: "button",
3145
+ variant: "outline",
3146
+ size: "sm",
3147
+ disabled: loading,
3148
+ onClick: () => void load(nextPage),
3149
+ children: loading ? "Loading..." : "Load more"
3150
+ }) : null
3151
+ ]
3152
+ });
3153
+ }
3154
+ export { ApiCredentialsSection, AuthBrowserHelp, ChangePasswordForm, EmailCodeForm, LoginForm, PasskeyLoginButton, PasskeySection, PasswordConfirmationRequiredError, PasswordResetRequestForm, ResetPasswordForm, SIGN_IN_AUDIT_EVENTS, ScopePicker, SignInHistory, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, closeImplications, confirmPasskey, confirmPasswordForPasskey, describeDuration, detectAuthBrowserIssues, getCsrfToken, getDefaultPasskeyName, inCatalogOrder, isAbortError, isConditionalMediationAvailable, neededBy, parseAuthAuditLogPage, readAuthBrowserEnvironment, registerPasskey, relyingApplicationsFrom, restrictImplications, safeApplicationHref, sameSelection, withScopes, withoutScopes };