bwh-auth 0.6.3 → 0.6.5

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,2513 @@
1
- // src/forms.tsx
2
- import * as React3 from "react";
3
-
1
+ import * as React from "react";
2
+ import { ChevronRight, Key, KeyRound, Plus, Trash2, TriangleAlert } from "lucide-react";
3
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
+ import { flushSync } from "react-dom";
4
5
  // src/components.ts
5
- var requiredComponentKeys = [
6
- "Button",
7
- "Card",
8
- "CardContent",
9
- "CardDescription",
10
- "CardHeader",
11
- "CardTitle",
12
- "Input",
13
- "Label"
6
+ const requiredComponentKeys = [
7
+ "Button",
8
+ "Card",
9
+ "CardContent",
10
+ "CardDescription",
11
+ "CardHeader",
12
+ "CardTitle",
13
+ "Input",
14
+ "Label"
14
15
  ];
15
16
  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;
17
+ const missing = requiredComponentKeys.filter((key) => !components?.[key]);
18
+ if (missing.length > 0) throw new Error(`bwh-auth requires injected components: ${missing.join(", ")}`);
19
+ return components;
21
20
  }
22
21
  function resolveAuthButtonComponent(components) {
23
- if (!components?.Button) {
24
- throw new Error("bwh-auth requires an injected Button component");
25
- }
26
- return { Button: components.Button };
22
+ if (!components?.Button) throw new Error("bwh-auth requires an injected Button component");
23
+ return { Button: components.Button };
27
24
  }
28
-
29
- // src/passkey-authentication.ts
30
- import * as React from "react";
31
-
32
25
  // src/abort-utils.ts
33
26
  function throwIfAborted(signal) {
34
- if (!signal?.aborted) return;
35
- const error = new Error("Passkey authentication was cancelled");
36
- error.name = "AbortError";
37
- throw error;
27
+ if (!signal?.aborted) return;
28
+ const error = /* @__PURE__ */ new Error("Passkey authentication was cancelled");
29
+ error.name = "AbortError";
30
+ throw error;
38
31
  }
39
-
40
32
  // src/webauthn-utils.ts
41
33
  function getCsrfToken(explicitToken) {
42
- if (explicitToken) {
43
- return explicitToken;
44
- }
45
- return document.querySelector('meta[name="csrf-token"]')?.content ?? "";
34
+ if (explicitToken) return explicitToken;
35
+ return document.querySelector("meta[name=\"csrf-token\"]")?.content ?? "";
46
36
  }
47
37
  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;
38
+ const base64 = b64.replace(/-/g, "+").replace(/_/g, "/");
39
+ const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
40
+ const binary = window.atob(padded);
41
+ const bytes = new Uint8Array(binary.length);
42
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
43
+ return bytes.buffer;
56
44
  }
57
45
  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, "");
46
+ const bytes = new Uint8Array(buffer);
47
+ let binary = "";
48
+ for (let i = 0; i < bytes.byteLength; i += 1) binary += String.fromCharCode(bytes[i] ?? 0);
49
+ return window.btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
64
50
  }
65
51
  function isAbortError(error) {
66
- return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
52
+ return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
67
53
  }
68
54
  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})`;
55
+ if (typeof window === "undefined") return "Passkey";
56
+ const ua = window.navigator.userAgent;
57
+ let browser = "Unknown Browser";
58
+ let os = "Unknown OS";
59
+ if (ua.includes("Firefox")) browser = "Firefox";
60
+ else if (ua.includes("Edg")) browser = "Edge";
61
+ else if (ua.includes("Chrome")) browser = "Chrome";
62
+ else if (ua.includes("Safari")) browser = "Safari";
63
+ if (ua.includes("Mac OS X")) os = "macOS";
64
+ else if (ua.includes("Windows")) os = "Windows";
65
+ else if (ua.includes("Android")) os = "Android";
66
+ else if (ua.includes("iPhone") || ua.includes("iPad")) os = "iOS";
67
+ else if (ua.includes("Linux")) os = "Linux";
68
+ return `Passkey (${browser} on ${os})`;
83
69
  }
84
70
  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
- }
71
+ if (typeof window === "undefined" || !window.PublicKeyCredential) return false;
72
+ const credentialConstructor = window.PublicKeyCredential;
73
+ if (!credentialConstructor.isConditionalMediationAvailable) return false;
74
+ try {
75
+ return await credentialConstructor.isConditionalMediationAvailable();
76
+ } catch {
77
+ return false;
78
+ }
93
79
  }
94
80
  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
- };
81
+ const authOptionsUrl = endpoints.passkeyAuthOptions ?? "/api/passkeys/auth/options";
82
+ const authUrl = endpoints.passkeyAuth ?? "/api/passkeys/auth";
83
+ const optRes = await fetch(authOptionsUrl, {
84
+ method: "POST",
85
+ headers: {
86
+ "Content-Type": "application/json",
87
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
88
+ },
89
+ signal
90
+ });
91
+ if (!optRes.ok) throw new Error("Failed to get authentication options");
92
+ const options = await optRes.json();
93
+ throwIfAborted(signal);
94
+ const publicKey = {
95
+ ...options,
96
+ challenge: base64urlToArrayBuffer(options.challenge),
97
+ allowCredentials: (options.allowCredentials || []).map((credential) => ({
98
+ ...credential,
99
+ id: base64urlToArrayBuffer(credential.id)
100
+ }))
101
+ };
102
+ const credential = await navigator.credentials.get({
103
+ publicKey,
104
+ mediation,
105
+ signal
106
+ });
107
+ throwIfAborted(signal);
108
+ if (!credential || credential.type !== "public-key") throw new Error("No passkey selected");
109
+ const pkCredential = credential;
110
+ const response = pkCredential.response;
111
+ const credentialData = {
112
+ id: pkCredential.id,
113
+ rawId: arrayBufferToBase64url(pkCredential.rawId),
114
+ type: pkCredential.type,
115
+ response: {
116
+ clientDataJSON: arrayBufferToBase64url(response.clientDataJSON),
117
+ authenticatorData: arrayBufferToBase64url(response.authenticatorData),
118
+ signature: arrayBufferToBase64url(response.signature),
119
+ userHandle: response.userHandle ? arrayBufferToBase64url(response.userHandle) : null
120
+ }
121
+ };
122
+ const authRes = await fetch(authUrl, {
123
+ method: "POST",
124
+ headers: {
125
+ "Content-Type": "application/json",
126
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
127
+ },
128
+ body: JSON.stringify({
129
+ credential: credentialData,
130
+ ...remember === void 0 ? {} : { remember: typeof remember === "function" ? remember() : remember }
131
+ }),
132
+ signal
133
+ });
134
+ const result = await authRes.json();
135
+ if (!authRes.ok) throw new Error(result.error || result.message || "Authentication failed");
136
+ return {
137
+ result,
138
+ redirectUrl: result.redirect || "/"
139
+ };
140
+ }
141
+ var PasswordConfirmationRequiredError = class extends Error {
142
+ constructor() {
143
+ super("Confirm your identity before adding a passkey.");
144
+ this.name = "PasswordConfirmationRequiredError";
145
+ }
146
+ };
147
+ async function assertPasskeyResponse(response, fallback) {
148
+ if (response.ok) return;
149
+ const result = await response.json().catch(() => null);
150
+ if (response.status === 423 && result?.error === "password_confirmation_required") throw new PasswordConfirmationRequiredError();
151
+ const message = typeof result?.error === "string" ? result.error : typeof result?.message === "string" ? result.message : fallback;
152
+ throw new Error(message);
153
+ }
154
+ async function confirmPasswordForPasskey({ password, endpoints = {}, signal }) {
155
+ throwIfAborted(signal);
156
+ await assertPasskeyResponse(await fetch(endpoints.confirmPassword ?? "/api/auth/confirm-password", {
157
+ method: "POST",
158
+ headers: {
159
+ "Content-Type": "application/json",
160
+ Accept: "application/json",
161
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
162
+ },
163
+ body: JSON.stringify({ password }),
164
+ signal
165
+ }), "Password confirmation failed");
166
+ throwIfAborted(signal);
167
+ }
168
+ async function confirmPasskey({ endpoints = {}, signal } = {}) {
169
+ throwIfAborted(signal);
170
+ const headers = {
171
+ "Content-Type": "application/json",
172
+ Accept: "application/json",
173
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
174
+ };
175
+ const response = await fetch(endpoints.passkeyConfirmOptions ?? "/api/passkeys/confirm/options", {
176
+ method: "POST",
177
+ headers,
178
+ signal
179
+ });
180
+ await assertPasskeyResponse(response, "Failed to get confirmation options");
181
+ const options = await response.json();
182
+ throwIfAborted(signal);
183
+ if (!Array.isArray(options.allowCredentials) || options.allowCredentials.length === 0) throw new Error("No existing passkey is available for this account.");
184
+ const credential = await navigator.credentials.get({
185
+ publicKey: {
186
+ ...options,
187
+ challenge: base64urlToArrayBuffer(options.challenge),
188
+ allowCredentials: options.allowCredentials.map((entry) => ({
189
+ ...entry,
190
+ id: base64urlToArrayBuffer(entry.id)
191
+ })),
192
+ userVerification: "required"
193
+ },
194
+ signal
195
+ });
196
+ throwIfAborted(signal);
197
+ if (!credential || credential.type !== "public-key") throw new Error("No passkey selected");
198
+ const key = credential;
199
+ const assertion = key.response;
200
+ await assertPasskeyResponse(await fetch(endpoints.passkeyConfirm ?? "/api/passkeys/confirm", {
201
+ method: "POST",
202
+ headers,
203
+ signal,
204
+ body: JSON.stringify({ credential: {
205
+ id: key.id,
206
+ rawId: arrayBufferToBase64url(key.rawId),
207
+ type: key.type,
208
+ response: {
209
+ clientDataJSON: arrayBufferToBase64url(assertion.clientDataJSON),
210
+ authenticatorData: arrayBufferToBase64url(assertion.authenticatorData),
211
+ signature: arrayBufferToBase64url(assertion.signature),
212
+ userHandle: assertion.userHandle ? arrayBufferToBase64url(assertion.userHandle) : null
213
+ }
214
+ } })
215
+ }), "Passkey confirmation failed");
216
+ throwIfAborted(signal);
156
217
  }
157
218
  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 };
219
+ const registerOptionsUrl = endpoints.passkeyRegisterOptions ?? "/api/passkeys/register/options";
220
+ const registerUrl = endpoints.passkeyRegister ?? "/api/passkeys/register";
221
+ const passkeyName = name || getDefaultPasskeyName();
222
+ const optRes = await fetch(registerOptionsUrl, {
223
+ method: "POST",
224
+ headers: {
225
+ "Content-Type": "application/json",
226
+ Accept: "application/json",
227
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
228
+ },
229
+ signal
230
+ });
231
+ await assertPasskeyResponse(optRes, "Failed to get registration options");
232
+ throwIfAborted(signal);
233
+ const options = await optRes.json();
234
+ throwIfAborted(signal);
235
+ const publicKey = {
236
+ ...options,
237
+ challenge: base64urlToArrayBuffer(options.challenge),
238
+ user: {
239
+ ...options.user,
240
+ id: base64urlToArrayBuffer(options.user.id)
241
+ },
242
+ excludeCredentials: (options.excludeCredentials || []).map((credential) => ({
243
+ ...credential,
244
+ id: base64urlToArrayBuffer(credential.id)
245
+ }))
246
+ };
247
+ const credential = await navigator.credentials.create({
248
+ publicKey,
249
+ signal
250
+ });
251
+ throwIfAborted(signal);
252
+ if (!credential || credential.type !== "public-key") throw new Error("Failed to create credential");
253
+ const pkCredential = credential;
254
+ const response = pkCredential.response;
255
+ const credentialData = {
256
+ id: pkCredential.id,
257
+ rawId: arrayBufferToBase64url(pkCredential.rawId),
258
+ type: pkCredential.type,
259
+ response: {
260
+ clientDataJSON: arrayBufferToBase64url(response.clientDataJSON),
261
+ attestationObject: arrayBufferToBase64url(response.attestationObject),
262
+ transports: response.getTransports ? response.getTransports() : []
263
+ }
264
+ };
265
+ const verifyRes = await fetch(registerUrl, {
266
+ method: "POST",
267
+ headers: {
268
+ "Content-Type": "application/json",
269
+ Accept: "application/json",
270
+ "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken)
271
+ },
272
+ body: JSON.stringify({
273
+ credential: credentialData,
274
+ name: passkeyName
275
+ }),
276
+ signal
277
+ });
278
+ await assertPasskeyResponse(verifyRes, "Registration failed");
279
+ throwIfAborted(signal);
280
+ return { result: await verifyRes.json() };
215
281
  }
216
-
217
282
  // src/passkey-authentication.ts
218
- var PasskeyAuthenticationContext = React.createContext(null);
283
+ const PasskeyAuthenticationContext = React.createContext(null);
219
284
  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]);
285
+ const pending = React.useRef(null);
286
+ const cancel = React.useCallback(async (conditionalOnly = false) => {
287
+ const request = pending.current;
288
+ if (!request || conditionalOnly && !request.conditional) return;
289
+ request.controller.abort();
290
+ await request.promise.catch(() => void 0);
291
+ }, []);
292
+ const authenticate = React.useCallback(async (options = {}) => {
293
+ const previous = pending.current;
294
+ const controller = new AbortController();
295
+ previous?.controller.abort();
296
+ const promise = (async () => {
297
+ if (previous) await previous.promise.catch(() => void 0);
298
+ throwIfAborted(controller.signal);
299
+ const result = await authenticateWithPasskey({
300
+ ...options,
301
+ signal: controller.signal
302
+ });
303
+ throwIfAborted(controller.signal);
304
+ return result;
305
+ })();
306
+ const request = {
307
+ controller,
308
+ promise,
309
+ conditional: options.mediation === "conditional"
310
+ };
311
+ pending.current = request;
312
+ try {
313
+ return await promise;
314
+ } finally {
315
+ if (pending.current === request) pending.current = null;
316
+ }
317
+ }, []);
318
+ React.useEffect(() => () => {
319
+ cancel();
320
+ }, [cancel]);
321
+ return React.useMemo(() => ({
322
+ authenticate,
323
+ cancel
324
+ }), [authenticate, cancel]);
250
325
  }
251
-
252
326
  // 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
327
  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
- ] });
328
+ const { Button } = resolveAuthButtonComponent(components);
329
+ const [loading, setLoading] = React.useState(false);
330
+ const [error, setError] = React.useState(null);
331
+ const localAuthentication = usePasskeyAuthentication();
332
+ const authentication = React.useContext(PasskeyAuthenticationContext) ?? localAuthentication;
333
+ const inFlight = React.useRef(false);
334
+ const mounted = React.useRef(true);
335
+ const callbacks = React.useRef({
336
+ onSuccess,
337
+ onError,
338
+ remember
339
+ });
340
+ React.useLayoutEffect(() => {
341
+ callbacks.current = {
342
+ onSuccess,
343
+ onError,
344
+ remember
345
+ };
346
+ });
347
+ React.useEffect(() => {
348
+ mounted.current = true;
349
+ return () => {
350
+ mounted.current = false;
351
+ if (inFlight.current) authentication.cancel();
352
+ };
353
+ }, [authentication]);
354
+ async function handlePasskeyLogin() {
355
+ if (disabled || inFlight.current) return;
356
+ inFlight.current = true;
357
+ setError(null);
358
+ setLoading(true);
359
+ try {
360
+ const { redirectUrl, result } = await authentication.authenticate({
361
+ endpoints,
362
+ remember: () => {
363
+ const choice = callbacks.current.remember;
364
+ return typeof choice === "function" ? choice() : choice ?? false;
365
+ }
366
+ });
367
+ if (!mounted.current) return;
368
+ if (callbacks.current.onSuccess) callbacks.current.onSuccess(redirectUrl, result);
369
+ else window.location.href = redirectUrl;
370
+ } catch (caughtError) {
371
+ if (!mounted.current || isAbortError(caughtError)) return;
372
+ const message = caughtError instanceof Error ? caughtError.message : "Passkey login failed";
373
+ if (callbacks.current.onError) callbacks.current.onError(message);
374
+ else setError(message);
375
+ } finally {
376
+ inFlight.current = false;
377
+ if (mounted.current) setLoading(false);
378
+ }
379
+ }
380
+ if (typeof window === "undefined" || !window.PublicKeyCredential) return null;
381
+ return /* @__PURE__ */ jsxs("div", {
382
+ className,
383
+ children: [error ? /* @__PURE__ */ jsx("p", {
384
+ className: "mb-2 text-sm text-destructive",
385
+ children: error
386
+ }) : null, /* @__PURE__ */ jsxs(Button, {
387
+ type: "button",
388
+ variant: "outline",
389
+ className: "w-full",
390
+ disabled: disabled || loading,
391
+ onClick: handlePasskeyLogin,
392
+ children: [/* @__PURE__ */ jsx(KeyRound, { "aria-hidden": "true" }), loading ? "Verifying..." : "Sign in with Passkey"]
393
+ })]
394
+ });
316
395
  }
317
-
318
396
  // src/forms.tsx
319
- import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
320
397
  var AuthRequestError = class extends Error {
321
- constructor(message, result) {
322
- super(message);
323
- this.result = result;
324
- this.name = "AuthRequestError";
325
- }
326
- result;
398
+ result;
399
+ constructor(message, result) {
400
+ super(message);
401
+ this.result = result;
402
+ this.name = "AuthRequestError";
403
+ }
327
404
  };
328
405
  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;
406
+ const response = await fetch(url, {
407
+ method: "POST",
408
+ headers: {
409
+ "Content-Type": "application/json",
410
+ "Accept": "application/json",
411
+ "X-CSRF-TOKEN": getCsrfToken(csrfToken)
412
+ },
413
+ body: JSON.stringify(body)
414
+ });
415
+ let decoded;
416
+ try {
417
+ decoded = await response.json();
418
+ } catch {
419
+ throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
420
+ }
421
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
422
+ const result = decoded;
423
+ if (!response.ok) throw new AuthRequestError(result.message || result.error || "Request failed", result);
424
+ return result;
352
425
  }
353
426
  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
- );
427
+ return /* @__PURE__ */ jsx("input", {
428
+ ...props,
429
+ type: "checkbox",
430
+ checked,
431
+ onChange: (event) => onCheckedChange(event.target.checked)
432
+ });
363
433
  }
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
- ] });
434
+ 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 }) {
435
+ const { Button, Card, CardContent, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
436
+ const [email, setEmail] = React.useState(initialEmail);
437
+ const [password, setPassword] = React.useState("");
438
+ const [remember, setRemember] = React.useState(false);
439
+ const [loading, setLoading] = React.useState(false);
440
+ const [conditionalPasskeyAvailable, setConditionalPasskeyAvailable] = React.useState(false);
441
+ const passkeyAuthentication = usePasskeyAuthentication();
442
+ const conditionalInterrupted = React.useRef(false);
443
+ const submitting = React.useRef(false);
444
+ const callbacks = React.useRef({
445
+ onError,
446
+ onPasskeySuccess,
447
+ remember
448
+ });
449
+ React.useLayoutEffect(() => {
450
+ callbacks.current = {
451
+ onError,
452
+ onPasskeySuccess,
453
+ remember
454
+ };
455
+ });
456
+ const coordinatedAuthentication = React.useMemo(() => ({
457
+ ...passkeyAuthentication,
458
+ authenticate: (options) => {
459
+ if (options?.mediation !== "conditional") conditionalInterrupted.current = true;
460
+ return passkeyAuthentication.authenticate(options);
461
+ }
462
+ }), [passkeyAuthentication]);
463
+ const passkeyEndpoints = React.useMemo(() => ({
464
+ csrfToken: endpoints.csrfToken,
465
+ passkeyAuth: endpoints.passkeyAuth,
466
+ passkeyAuthOptions: endpoints.passkeyAuthOptions
467
+ }), [
468
+ endpoints.csrfToken,
469
+ endpoints.passkeyAuth,
470
+ endpoints.passkeyAuthOptions
471
+ ]);
472
+ React.useEffect(() => {
473
+ setConditionalPasskeyAvailable(false);
474
+ if (!enablePasskeyAutofill || conditionalInterrupted.current) return;
475
+ let active = true;
476
+ async function startConditionalPasskeyLogin() {
477
+ if (!await isConditionalMediationAvailable() || !active || conditionalInterrupted.current) return;
478
+ setConditionalPasskeyAvailable(true);
479
+ try {
480
+ const { redirectUrl, result } = await coordinatedAuthentication.authenticate({
481
+ endpoints: passkeyEndpoints,
482
+ mediation: "conditional",
483
+ remember: () => callbacks.current.remember
484
+ });
485
+ if (!active) return;
486
+ if (callbacks.current.onPasskeySuccess) callbacks.current.onPasskeySuccess(redirectUrl, result);
487
+ else window.location.href = redirectUrl;
488
+ } catch (error) {
489
+ if (!isAbortError(error) && active) callbacks.current.onError?.(error instanceof Error ? error.message : "Passkey login failed");
490
+ }
491
+ }
492
+ startConditionalPasskeyLogin();
493
+ return () => {
494
+ active = false;
495
+ coordinatedAuthentication.cancel(true);
496
+ };
497
+ }, [
498
+ enablePasskeyAutofill,
499
+ coordinatedAuthentication,
500
+ passkeyEndpoints
501
+ ]);
502
+ async function onSubmit(event) {
503
+ event.preventDefault();
504
+ if (submitting.current) return;
505
+ submitting.current = true;
506
+ conditionalInterrupted.current = true;
507
+ onSubmitStart?.();
508
+ setLoading(true);
509
+ try {
510
+ await passkeyAuthentication.cancel();
511
+ const result = await postForm(endpoints.login ?? "/login", {
512
+ email,
513
+ password,
514
+ remember
515
+ }, endpoints.csrfToken);
516
+ if (result.requires_2fa) {
517
+ onTwoFactorRequired?.(result);
518
+ if (!onTwoFactorRequired && typeof result.attempt_token === "string") window.location.href = `/login/two-factor/${encodeURIComponent(result.attempt_token)}`;
519
+ return;
520
+ }
521
+ onSuccess?.(result);
522
+ if (!onSuccess && result.redirect) window.location.href = result.redirect;
523
+ } catch (error) {
524
+ onError?.(error instanceof Error ? error.message : "Login failed");
525
+ } finally {
526
+ submitting.current = false;
527
+ setLoading(false);
528
+ }
529
+ }
530
+ const content = /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("form", {
531
+ className: "space-y-4",
532
+ onSubmit: (event) => void onSubmit(event),
533
+ children: [
534
+ /* @__PURE__ */ jsxs("div", {
535
+ className: "space-y-1",
536
+ children: [/* @__PURE__ */ jsx(Label, {
537
+ htmlFor: "login-email",
538
+ children: "Email"
539
+ }), /* @__PURE__ */ jsx(Input, {
540
+ id: "login-email",
541
+ type: "email",
542
+ autoComplete: conditionalPasskeyAvailable ? "username webauthn" : "email",
543
+ required: true,
544
+ value: email,
545
+ onChange: (event) => {
546
+ setEmail(event.target.value);
547
+ onEmailChange?.(event.target.value);
548
+ }
549
+ })]
550
+ }),
551
+ /* @__PURE__ */ jsxs("div", {
552
+ className: "space-y-1",
553
+ children: [/* @__PURE__ */ jsx(Label, {
554
+ htmlFor: "login-password",
555
+ children: "Password"
556
+ }), /* @__PURE__ */ jsx(Input, {
557
+ id: "login-password",
558
+ type: "password",
559
+ autoComplete: "current-password",
560
+ required: true,
561
+ value: password,
562
+ onChange: (event) => setPassword(event.target.value)
563
+ })]
564
+ }),
565
+ /* @__PURE__ */ jsxs("div", {
566
+ className: "flex items-center gap-2 text-sm",
567
+ children: [/* @__PURE__ */ jsx(RememberMeCheckbox, {
568
+ id: "login-remember",
569
+ "aria-labelledby": "login-remember-label",
570
+ "data-test": rememberMeDataTest,
571
+ checked: remember,
572
+ onCheckedChange: setRemember
573
+ }), /* @__PURE__ */ jsx(Label, {
574
+ id: "login-remember-label",
575
+ htmlFor: "login-remember",
576
+ children: rememberMeLabel
577
+ })]
578
+ }),
579
+ /* @__PURE__ */ jsx(Button, {
580
+ type: "submit",
581
+ className: "w-full",
582
+ disabled: loading,
583
+ children: loading ? "Signing in..." : "Sign In"
584
+ })
585
+ ]
586
+ }), enablePasskeys ? /* @__PURE__ */ jsxs("div", {
587
+ className: "mt-4",
588
+ children: [passkeySeparator, /* @__PURE__ */ jsx(PasskeyAuthenticationContext.Provider, {
589
+ value: coordinatedAuthentication,
590
+ children: /* @__PURE__ */ jsx(PasskeyLoginButton, {
591
+ components: { Button },
592
+ endpoints,
593
+ disabled: loading,
594
+ remember: () => callbacks.current.remember,
595
+ onSuccess: (redirectUrl, result) => {
596
+ if (onPasskeySuccess) onPasskeySuccess(redirectUrl, result);
597
+ else window.location.href = redirectUrl;
598
+ },
599
+ onError
600
+ })
601
+ })]
602
+ }) : null] });
603
+ return unwrapped ? content : /* @__PURE__ */ jsxs(Card, { children: [/* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Sign In" }) }), /* @__PURE__ */ jsx(CardContent, { children: content })] });
528
604
  }
529
605
  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
- ];
606
+ return [
607
+ {
608
+ name: "name",
609
+ label: "Name",
610
+ required: true,
611
+ autoComplete: "name"
612
+ },
613
+ {
614
+ name: "email",
615
+ label: "Email",
616
+ type: "email",
617
+ required: true,
618
+ autoComplete: "email"
619
+ },
620
+ {
621
+ name: "password",
622
+ label: "Password",
623
+ type: "password",
624
+ required: true,
625
+ autoComplete: "new-password"
626
+ },
627
+ {
628
+ name: "password_confirmation",
629
+ label: "Confirm Password",
630
+ type: "password",
631
+ required: true,
632
+ autoComplete: "new-password"
633
+ }
634
+ ];
536
635
  }
537
636
  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 : "";
637
+ if (Object.prototype.hasOwnProperty.call(initialValues, field.name)) return initialValues[field.name];
638
+ if (field.initialValue !== void 0) return field.initialValue;
639
+ return field.type === "checkbox" ? false : "";
541
640
  }
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
- ] });
641
+ function SignupForm({ endpoints = {}, components, onSuccess, onError, fields = defaultSignupFields(), initialValues = {}, errors = {}, submitMode = "fetch", title = "Create Account", description, submitLabel = "Create Account", submittingLabel = "Creating account..." }) {
642
+ const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
643
+ const [values, setValues] = React.useState(() => Object.fromEntries(fields.map((field) => [field.name, initialSignupValue(field, initialValues)])));
644
+ const [fieldErrors, setFieldErrors] = React.useState(errors);
645
+ const [loading, setLoading] = React.useState(false);
646
+ async function onSubmit(event) {
647
+ setLoading(true);
648
+ if (submitMode === "native") return;
649
+ event.preventDefault();
650
+ setFieldErrors({});
651
+ try {
652
+ const result = await postForm(endpoints.signup ?? "/register", values, endpoints.csrfToken);
653
+ await onSuccess?.(result, values);
654
+ if (!onSuccess && result.redirect) window.location.href = result.redirect;
655
+ } catch (error) {
656
+ if (error instanceof AuthRequestError && error.result.errors && typeof error.result.errors === "object") setFieldErrors(error.result.errors);
657
+ onError?.(error instanceof Error ? error.message : "Signup failed");
658
+ } finally {
659
+ setLoading(false);
660
+ }
661
+ }
662
+ function setValue(name, value) {
663
+ setValues((current) => ({
664
+ ...current,
665
+ [name]: value
666
+ }));
667
+ }
668
+ 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", {
669
+ className: "space-y-4",
670
+ method: submitMode === "native" ? "POST" : void 0,
671
+ action: endpoints.signup ?? "/register",
672
+ onSubmit: (event) => void onSubmit(event),
673
+ children: [
674
+ submitMode === "native" ? /* @__PURE__ */ jsx("input", {
675
+ type: "hidden",
676
+ name: "_token",
677
+ value: getCsrfToken(endpoints.csrfToken)
678
+ }) : null,
679
+ fields.map((field) => {
680
+ if (field.hiddenWhen?.(values)) return null;
681
+ const error = fieldErrors[field.name]?.[0];
682
+ const value = values[field.name];
683
+ if (field.type === "checkbox") return /* @__PURE__ */ jsxs("div", {
684
+ className: field.containerClassName ?? "space-y-1",
685
+ children: [
686
+ /* @__PURE__ */ jsxs("label", {
687
+ className: "flex items-start gap-2 text-sm",
688
+ children: [/* @__PURE__ */ jsx("input", {
689
+ id: `signup-${field.name}`,
690
+ name: field.name,
691
+ type: "checkbox",
692
+ value: "1",
693
+ checked: Boolean(value),
694
+ onChange: (event) => setValue(field.name, event.target.checked),
695
+ required: field.required
696
+ }), /* @__PURE__ */ jsx("span", { children: field.label })]
697
+ }),
698
+ field.helpText ? /* @__PURE__ */ jsx("p", {
699
+ className: "text-xs text-muted-foreground",
700
+ children: field.helpText
701
+ }) : null,
702
+ error ? /* @__PURE__ */ jsx("p", {
703
+ className: "text-sm text-destructive",
704
+ children: error
705
+ }) : null
706
+ ]
707
+ }, field.name);
708
+ return /* @__PURE__ */ jsxs("div", {
709
+ className: field.containerClassName ?? "space-y-1",
710
+ children: [
711
+ /* @__PURE__ */ jsx(Label, {
712
+ htmlFor: `signup-${field.name}`,
713
+ children: field.label
714
+ }),
715
+ /* @__PURE__ */ jsx(Input, {
716
+ id: `signup-${field.name}`,
717
+ name: field.name,
718
+ type: field.type ?? "text",
719
+ placeholder: field.placeholder,
720
+ required: field.required,
721
+ autoComplete: field.autoComplete,
722
+ minLength: field.minLength,
723
+ maxLength: field.maxLength,
724
+ pattern: field.pattern,
725
+ inputMode: field.inputMode,
726
+ className: field.className,
727
+ "aria-invalid": Boolean(error),
728
+ value: String(value ?? ""),
729
+ onChange: (event) => setValue(field.name, event.target.value)
730
+ }),
731
+ field.helpText ? /* @__PURE__ */ jsx("p", {
732
+ className: "text-xs text-muted-foreground",
733
+ children: field.helpText
734
+ }) : null,
735
+ error ? /* @__PURE__ */ jsx("p", {
736
+ className: "text-sm text-destructive",
737
+ children: error
738
+ }) : null
739
+ ]
740
+ }, field.name);
741
+ }),
742
+ /* @__PURE__ */ jsx(Button, {
743
+ type: "submit",
744
+ className: "w-full",
745
+ disabled: loading,
746
+ children: loading ? submittingLabel : submitLabel
747
+ })
748
+ ]
749
+ }) })] });
645
750
  }
646
751
  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
- ] });
752
+ const { Button, Input, Label } = resolveAuthComponents(components);
753
+ const [email, setEmail] = React.useState("");
754
+ const [loading, setLoading] = React.useState(false);
755
+ const submitting = React.useRef(false);
756
+ async function onSubmit(event) {
757
+ event.preventDefault();
758
+ if (submitting.current) return;
759
+ submitting.current = true;
760
+ onSubmitStart?.();
761
+ setLoading(true);
762
+ try {
763
+ const result = await postForm(endpoints.forgotPassword ?? "/api/auth/forgot-password", { email }, endpoints.csrfToken);
764
+ onSuccess?.(result);
765
+ } catch (error) {
766
+ onError?.(error instanceof Error ? error.message : "Password reset request failed");
767
+ } finally {
768
+ submitting.current = false;
769
+ setLoading(false);
770
+ }
771
+ }
772
+ return /* @__PURE__ */ jsxs("form", {
773
+ className: "space-y-4",
774
+ onSubmit: (event) => void onSubmit(event),
775
+ children: [/* @__PURE__ */ jsxs("div", {
776
+ className: "space-y-1",
777
+ children: [/* @__PURE__ */ jsx(Label, {
778
+ htmlFor: "reset-email",
779
+ children: "Email"
780
+ }), /* @__PURE__ */ jsx(Input, {
781
+ id: "reset-email",
782
+ type: "email",
783
+ autoComplete: "email",
784
+ required: true,
785
+ value: email,
786
+ onChange: (event) => setEmail(event.target.value)
787
+ })]
788
+ }), /* @__PURE__ */ jsx(Button, {
789
+ type: "submit",
790
+ className: submitClassName,
791
+ disabled: loading,
792
+ children: loading ? "Sending..." : "Send Reset Link"
793
+ })]
794
+ });
674
795
  }
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
- ] });
796
+ function ResetPasswordForm({ endpoints = {}, components, onSuccess, onError, onSubmitStart, submitClassName, token: initialToken = "", email: initialEmail = "", idPrefix = "reset-password", minPasswordLength, validatePasswordConfirmation = false, passwordLabel = "Password", passwordConfirmationLabel = "Confirm Password", passwordHelpText }) {
797
+ const { Button, Input, Label } = resolveAuthComponents(components);
798
+ const [email, setEmail] = React.useState(initialEmail);
799
+ const [token, setToken] = React.useState(initialToken);
800
+ const [password, setPassword] = React.useState("");
801
+ const [passwordConfirmation, setPasswordConfirmation] = React.useState("");
802
+ const [loading, setLoading] = React.useState(false);
803
+ const submitting = React.useRef(false);
804
+ async function onSubmit(event) {
805
+ event.preventDefault();
806
+ if (submitting.current) return;
807
+ onSubmitStart?.();
808
+ if (validatePasswordConfirmation && password !== passwordConfirmation) {
809
+ onError?.("Passwords do not match.");
810
+ return;
811
+ }
812
+ if (minPasswordLength !== void 0 && password.length < minPasswordLength) {
813
+ onError?.(`Password must be at least ${minPasswordLength} characters long.`);
814
+ return;
815
+ }
816
+ submitting.current = true;
817
+ setLoading(true);
818
+ try {
819
+ const result = await postForm(endpoints.resetPassword ?? "/api/auth/reset-password", {
820
+ email,
821
+ token,
822
+ password,
823
+ password_confirmation: passwordConfirmation
824
+ }, endpoints.csrfToken);
825
+ onSuccess?.(result);
826
+ } catch (error) {
827
+ onError?.(error instanceof Error ? error.message : "Password reset failed");
828
+ } finally {
829
+ submitting.current = false;
830
+ setLoading(false);
831
+ }
832
+ }
833
+ return /* @__PURE__ */ jsxs("form", {
834
+ className: "space-y-4",
835
+ onSubmit: (event) => void onSubmit(event),
836
+ children: [
837
+ /* @__PURE__ */ jsx(Input, {
838
+ type: "hidden",
839
+ value: token,
840
+ onChange: (event) => setToken(event.target.value)
841
+ }),
842
+ /* @__PURE__ */ jsxs("div", {
843
+ className: "space-y-1",
844
+ children: [/* @__PURE__ */ jsx(Label, {
845
+ htmlFor: `${idPrefix}-email`,
846
+ children: "Email"
847
+ }), /* @__PURE__ */ jsx(Input, {
848
+ id: `${idPrefix}-email`,
849
+ type: "email",
850
+ autoComplete: "email",
851
+ required: true,
852
+ value: email,
853
+ onChange: (event) => setEmail(event.target.value)
854
+ })]
855
+ }),
856
+ /* @__PURE__ */ jsxs("div", {
857
+ className: "space-y-1",
858
+ children: [
859
+ /* @__PURE__ */ jsx(Label, {
860
+ htmlFor: idPrefix,
861
+ children: passwordLabel
862
+ }),
863
+ /* @__PURE__ */ jsx(Input, {
864
+ id: idPrefix,
865
+ type: "password",
866
+ autoComplete: "new-password",
867
+ minLength: minPasswordLength,
868
+ required: true,
869
+ value: password,
870
+ onChange: (event) => setPassword(event.target.value)
871
+ }),
872
+ passwordHelpText ? /* @__PURE__ */ jsx("p", {
873
+ className: "text-xs text-muted-foreground",
874
+ children: passwordHelpText
875
+ }) : null
876
+ ]
877
+ }),
878
+ /* @__PURE__ */ jsxs("div", {
879
+ className: "space-y-1",
880
+ children: [/* @__PURE__ */ jsx(Label, {
881
+ htmlFor: `${idPrefix}-confirmation`,
882
+ children: passwordConfirmationLabel
883
+ }), /* @__PURE__ */ jsx(Input, {
884
+ id: `${idPrefix}-confirmation`,
885
+ type: "password",
886
+ autoComplete: "new-password",
887
+ minLength: minPasswordLength,
888
+ required: true,
889
+ value: passwordConfirmation,
890
+ onChange: (event) => setPasswordConfirmation(event.target.value)
891
+ })]
892
+ }),
893
+ /* @__PURE__ */ jsx(Button, {
894
+ type: "submit",
895
+ className: submitClassName,
896
+ disabled: loading,
897
+ children: loading ? "Resetting..." : "Reset Password"
898
+ })
899
+ ]
900
+ });
744
901
  }
745
902
  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
- ] });
903
+ const { Button, Input, Label } = resolveAuthComponents(components);
904
+ const [currentPassword, setCurrentPassword] = React.useState("");
905
+ const [password, setPassword] = React.useState("");
906
+ const [passwordConfirmation, setPasswordConfirmation] = React.useState("");
907
+ const [loading, setLoading] = React.useState(false);
908
+ async function onSubmit(event) {
909
+ event.preventDefault();
910
+ setLoading(true);
911
+ if (password !== passwordConfirmation) {
912
+ onError?.("New passwords do not match.");
913
+ setLoading(false);
914
+ return;
915
+ }
916
+ try {
917
+ const result = await postForm(endpoints.changePassword ?? "/api/change-password", {
918
+ current_password: currentPassword,
919
+ password,
920
+ password_confirmation: passwordConfirmation
921
+ }, endpoints.csrfToken);
922
+ setCurrentPassword("");
923
+ setPassword("");
924
+ setPasswordConfirmation("");
925
+ onSuccess?.(result);
926
+ } catch (error) {
927
+ onError?.(error instanceof Error ? error.message : "Password change failed");
928
+ } finally {
929
+ setLoading(false);
930
+ }
931
+ }
932
+ return /* @__PURE__ */ jsxs("form", {
933
+ className: "space-y-4",
934
+ onSubmit: (event) => void onSubmit(event),
935
+ children: [
936
+ /* @__PURE__ */ jsxs("div", {
937
+ className: "space-y-1",
938
+ children: [/* @__PURE__ */ jsx(Label, {
939
+ htmlFor: "current-password",
940
+ children: "Current Password"
941
+ }), /* @__PURE__ */ jsx(Input, {
942
+ id: "current-password",
943
+ type: "password",
944
+ autoComplete: "current-password",
945
+ required: true,
946
+ value: currentPassword,
947
+ onChange: (event) => setCurrentPassword(event.target.value)
948
+ })]
949
+ }),
950
+ /* @__PURE__ */ jsxs("div", {
951
+ className: "space-y-1",
952
+ children: [/* @__PURE__ */ jsx(Label, {
953
+ htmlFor: "new-password",
954
+ children: "New Password"
955
+ }), /* @__PURE__ */ jsx(Input, {
956
+ id: "new-password",
957
+ type: "password",
958
+ autoComplete: "new-password",
959
+ minLength: 8,
960
+ required: true,
961
+ value: password,
962
+ onChange: (event) => setPassword(event.target.value)
963
+ })]
964
+ }),
965
+ /* @__PURE__ */ jsxs("div", {
966
+ className: "space-y-1",
967
+ children: [/* @__PURE__ */ jsx(Label, {
968
+ htmlFor: "confirm-password",
969
+ children: "Confirm New Password"
970
+ }), /* @__PURE__ */ jsx(Input, {
971
+ id: "confirm-password",
972
+ type: "password",
973
+ autoComplete: "new-password",
974
+ minLength: 8,
975
+ required: true,
976
+ value: passwordConfirmation,
977
+ onChange: (event) => setPasswordConfirmation(event.target.value)
978
+ })]
979
+ }),
980
+ /* @__PURE__ */ jsx(Button, {
981
+ type: "submit",
982
+ disabled: loading,
983
+ children: loading ? "Changing..." : "Change Password"
984
+ })
985
+ ]
986
+ });
790
987
  }
791
988
  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
- ] });
989
+ const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
990
+ const [currentAttemptToken, setCurrentAttemptToken] = React.useState(attemptToken);
991
+ const [code, setCode] = React.useState("");
992
+ const [loading, setLoading] = React.useState(false);
993
+ const [resending, setResending] = React.useState(false);
994
+ const [message, setMessage] = React.useState("");
995
+ React.useEffect(() => setCurrentAttemptToken(attemptToken), [attemptToken]);
996
+ async function onSubmit(event) {
997
+ event.preventDefault();
998
+ setLoading(true);
999
+ setMessage("");
1000
+ try {
1001
+ const result = await postForm(endpoints.twoFactorVerify ?? "/api/auth/two-factor/verify", {
1002
+ attempt_token: currentAttemptToken,
1003
+ code: code.trim()
1004
+ }, endpoints.csrfToken);
1005
+ onSuccess?.(result);
1006
+ if (!onSuccess && result.redirect) window.location.href = result.redirect;
1007
+ } catch (error) {
1008
+ setCode("");
1009
+ onError?.(error instanceof Error ? error.message : "Verification failed");
1010
+ } finally {
1011
+ setLoading(false);
1012
+ }
1013
+ }
1014
+ async function resend() {
1015
+ setResending(true);
1016
+ setMessage("");
1017
+ try {
1018
+ const result = await postForm(endpoints.twoFactorResend ?? "/api/auth/two-factor/resend", { attempt_token: currentAttemptToken }, endpoints.csrfToken);
1019
+ if (typeof result.attempt_token === "string") setCurrentAttemptToken(result.attempt_token);
1020
+ setMessage(result.message ?? "A new verification code has been sent.");
1021
+ } catch (error) {
1022
+ onError?.(error instanceof Error ? error.message : "Could not resend verification code");
1023
+ } finally {
1024
+ setResending(false);
1025
+ }
1026
+ }
1027
+ async function reportSuspicious() {
1028
+ const url = endpoints.twoFactorReport?.(currentAttemptToken) ?? `/api/auth/two-factor/report/${encodeURIComponent(currentAttemptToken)}`;
1029
+ try {
1030
+ const result = await postForm(url, {}, endpoints.csrfToken);
1031
+ setMessage(result.message ?? "This login attempt has been reported.");
1032
+ onReportSuspicious?.(result);
1033
+ } catch (error) {
1034
+ onError?.(error instanceof Error ? error.message : "Could not report the login attempt");
1035
+ }
1036
+ }
1037
+ return /* @__PURE__ */ jsxs(Card, { children: [/* @__PURE__ */ jsxs(CardHeader, { children: [/* @__PURE__ */ jsx(CardTitle, { children: "Verify Your Login" }), /* @__PURE__ */ jsx(CardDescription, { children: "Enter the 6-digit code sent to your email address." })] }), /* @__PURE__ */ jsxs(CardContent, { children: [/* @__PURE__ */ jsxs("form", {
1038
+ className: "space-y-4",
1039
+ onSubmit: (event) => void onSubmit(event),
1040
+ children: [/* @__PURE__ */ jsxs("div", {
1041
+ className: "space-y-1",
1042
+ children: [/* @__PURE__ */ jsx(Label, {
1043
+ htmlFor: "two-factor-code",
1044
+ children: "Verification Code"
1045
+ }), /* @__PURE__ */ jsx(Input, {
1046
+ id: "two-factor-code",
1047
+ type: "text",
1048
+ inputMode: "numeric",
1049
+ pattern: "[0-9]{6}",
1050
+ maxLength: 6,
1051
+ autoComplete: "one-time-code",
1052
+ required: true,
1053
+ value: code,
1054
+ onChange: (event) => setCode(event.target.value.replace(/\D/g, ""))
1055
+ })]
1056
+ }), /* @__PURE__ */ jsx(Button, {
1057
+ type: "submit",
1058
+ className: "w-full",
1059
+ disabled: loading || code.length !== 6,
1060
+ children: loading ? "Verifying..." : "Verify Code"
1061
+ })]
1062
+ }), /* @__PURE__ */ jsxs("div", {
1063
+ className: "mt-4 space-y-2 text-sm",
1064
+ children: [
1065
+ /* @__PURE__ */ jsx(Button, {
1066
+ type: "button",
1067
+ variant: "outline",
1068
+ className: "w-full",
1069
+ disabled: resending,
1070
+ onClick: () => void resend(),
1071
+ children: resending ? "Sending..." : "Send a new code"
1072
+ }),
1073
+ /* @__PURE__ */ jsx("button", {
1074
+ type: "button",
1075
+ className: "text-sm underline",
1076
+ onClick: () => void reportSuspicious(),
1077
+ children: "This was not me"
1078
+ }),
1079
+ message ? /* @__PURE__ */ jsx("p", { children: message }) : null,
1080
+ appEnv && appEnv !== "production" ? /* @__PURE__ */ jsx("p", { children: "Dev mode: use 999999 to bypass 2FA." }) : null
1081
+ ]
1082
+ })] })] });
876
1083
  }
877
-
878
1084
  // 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
1085
  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
- ] });
1086
+ const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
1087
+ const [passkeys, setPasskeys] = React.useState([]);
1088
+ const [loading, setLoading] = React.useState(true);
1089
+ const [registering, setRegistering] = React.useState(false);
1090
+ const [pendingName, setPendingName] = React.useState("");
1091
+ const [needsConfirmation, setNeedsConfirmation] = React.useState(false);
1092
+ const [password, setPassword] = React.useState("");
1093
+ const [confirmationError, setConfirmationError] = React.useState("");
1094
+ const operation = React.useRef(null);
1095
+ const passwordId = React.useId();
1096
+ React.useEffect(() => {
1097
+ operation.current = null;
1098
+ setRegistering(false);
1099
+ setNeedsConfirmation(false);
1100
+ setPassword("");
1101
+ setConfirmationError("");
1102
+ setPendingName("");
1103
+ return () => {
1104
+ operation.current?.abort();
1105
+ operation.current = null;
1106
+ };
1107
+ }, [
1108
+ endpoints.confirmPassword,
1109
+ endpoints.passkeyConfirmOptions,
1110
+ endpoints.passkeyConfirm,
1111
+ endpoints.passkeyRegisterOptions,
1112
+ endpoints.passkeyRegister,
1113
+ endpoints.csrfToken
1114
+ ]);
1115
+ const listUrl = endpoints.passkeyList ?? "/api/passkeys";
1116
+ const registerOptionsUrl = endpoints.passkeyRegisterOptions ?? "/api/passkeys/register/options";
1117
+ const registerUrl = endpoints.passkeyRegister ?? "/api/passkeys/register";
1118
+ const deleteUrl = endpoints.passkeyDelete ?? ((id) => `/api/passkeys/${id}`);
1119
+ const fetchPasskeys = React.useCallback(async () => {
1120
+ try {
1121
+ const res = await fetch(listUrl);
1122
+ if (res.ok) setPasskeys(await res.json());
1123
+ } catch {
1124
+ onError?.("passkeys", "Failed to load passkeys");
1125
+ } finally {
1126
+ setLoading(false);
1127
+ }
1128
+ }, [listUrl, onError]);
1129
+ React.useEffect(() => {
1130
+ fetchPasskeys();
1131
+ }, [fetchPasskeys]);
1132
+ async function registerPasskey$1(method) {
1133
+ if (operation.current && !operation.current.signal.aborted) return;
1134
+ const controller = new AbortController();
1135
+ operation.current = controller;
1136
+ const name = pendingName || getDefaultPasskeyName();
1137
+ const submittedPassword = password;
1138
+ setPassword("");
1139
+ setConfirmationError("");
1140
+ flushSync(() => setPendingName(name));
1141
+ setRegistering(true);
1142
+ try {
1143
+ if (method === "password") await confirmPasswordForPasskey({
1144
+ password: submittedPassword,
1145
+ endpoints,
1146
+ signal: controller.signal
1147
+ });
1148
+ if (method === "passkey") await confirmPasskey({
1149
+ endpoints,
1150
+ signal: controller.signal
1151
+ });
1152
+ throwIfAborted(controller.signal);
1153
+ await registerPasskey({
1154
+ endpoints: {
1155
+ ...endpoints,
1156
+ passkeyRegisterOptions: registerOptionsUrl,
1157
+ passkeyRegister: registerUrl
1158
+ },
1159
+ name,
1160
+ signal: controller.signal
1161
+ });
1162
+ throwIfAborted(controller.signal);
1163
+ setNeedsConfirmation(false);
1164
+ setPendingName("");
1165
+ onSuccess?.("Passkey registered successfully.");
1166
+ await fetchPasskeys();
1167
+ } catch (caughtError) {
1168
+ if (!controller.signal.aborted && !isAbortError(caughtError)) {
1169
+ if (caughtError instanceof PasswordConfirmationRequiredError) {
1170
+ setNeedsConfirmation(true);
1171
+ if (method) setConfirmationError("Confirmation is still required. Try again or sign in again.");
1172
+ } else {
1173
+ const message = caughtError instanceof Error ? caughtError.message : "Passkey registration failed";
1174
+ if (method) setConfirmationError(message);
1175
+ onError?.("passkeys", message);
1176
+ }
1177
+ }
1178
+ } finally {
1179
+ if (operation.current === controller) {
1180
+ operation.current = null;
1181
+ if (!controller.signal.aborted) setRegistering(false);
1182
+ }
1183
+ }
1184
+ }
1185
+ function cancelConfirmation() {
1186
+ operation.current?.abort();
1187
+ operation.current = null;
1188
+ setRegistering(false);
1189
+ setPassword("");
1190
+ setConfirmationError("");
1191
+ setNeedsConfirmation(false);
1192
+ }
1193
+ async function deletePasskey(id) {
1194
+ try {
1195
+ if (!(await fetch(deleteUrl(id), {
1196
+ method: "DELETE",
1197
+ headers: { "X-CSRF-TOKEN": getCsrfToken(endpoints.csrfToken) }
1198
+ })).ok) throw new Error("Delete failed");
1199
+ setPasskeys((current) => current.filter((passkey) => passkey.id !== id));
1200
+ onSuccess?.("Passkey removed.");
1201
+ } catch {
1202
+ onError?.("passkeys", "Failed to delete passkey");
1203
+ }
1204
+ }
1205
+ const isWebAuthnSupported = typeof window !== "undefined" && !!window.PublicKeyCredential;
1206
+ return /* @__PURE__ */ jsxs(Card, { children: [/* @__PURE__ */ jsxs(CardHeader, { children: [/* @__PURE__ */ jsxs(CardTitle, {
1207
+ className: "flex items-center gap-2",
1208
+ children: [/* @__PURE__ */ jsx(Key, { className: "h-5 w-5" }), "Passkeys"]
1209
+ }), /* @__PURE__ */ jsx(CardDescription, { children: "Manage passkeys for passwordless login." })] }), /* @__PURE__ */ jsxs(CardContent, {
1210
+ className: "space-y-4",
1211
+ children: [
1212
+ !isWebAuthnSupported ? /* @__PURE__ */ jsx("p", {
1213
+ className: "text-sm text-muted-foreground",
1214
+ children: "Your browser does not support passkeys."
1215
+ }) : null,
1216
+ loading ? /* @__PURE__ */ jsx("p", {
1217
+ className: "text-sm text-muted-foreground",
1218
+ children: "Loading passkeys..."
1219
+ }) : passkeys.length === 0 ? /* @__PURE__ */ jsx("p", {
1220
+ className: "text-sm text-muted-foreground",
1221
+ children: "No passkeys registered yet."
1222
+ }) : /* @__PURE__ */ jsx("div", {
1223
+ className: "divide-y rounded-md border",
1224
+ children: passkeys.map((passkey) => /* @__PURE__ */ jsxs("div", {
1225
+ className: "flex items-center justify-between gap-3 p-3",
1226
+ children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("div", {
1227
+ className: "font-medium",
1228
+ children: passkey.name
1229
+ }), /* @__PURE__ */ jsx("div", {
1230
+ className: "text-sm text-muted-foreground",
1231
+ children: new Date(passkey.created_at).toLocaleDateString()
1232
+ })] }), /* @__PURE__ */ jsx(Button, {
1233
+ type: "button",
1234
+ variant: "ghost",
1235
+ size: "icon",
1236
+ "aria-label": "Delete passkey",
1237
+ onClick: () => void deletePasskey(passkey.id),
1238
+ children: /* @__PURE__ */ jsx(Trash2, {})
1239
+ })]
1240
+ }, passkey.id))
1241
+ }),
1242
+ isWebAuthnSupported ? /* @__PURE__ */ jsxs("div", {
1243
+ className: "flex flex-col gap-2 sm:flex-row",
1244
+ children: [/* @__PURE__ */ jsxs("div", {
1245
+ className: "flex-1 space-y-1",
1246
+ children: [/* @__PURE__ */ jsx(Label, {
1247
+ htmlFor: "passkey-name",
1248
+ children: "Passkey name"
1249
+ }), /* @__PURE__ */ jsx(Input, {
1250
+ id: "passkey-name",
1251
+ value: pendingName,
1252
+ onChange: (event) => setPendingName(event.target.value),
1253
+ placeholder: getDefaultPasskeyName()
1254
+ })]
1255
+ }), /* @__PURE__ */ jsxs(Button, {
1256
+ type: "button",
1257
+ className: "self-end",
1258
+ variant: "outline",
1259
+ disabled: registering || needsConfirmation,
1260
+ onClick: () => void registerPasskey$1(),
1261
+ children: [/* @__PURE__ */ jsx(Plus, {}), registering ? "Registering..." : "Add Passkey"]
1262
+ })]
1263
+ }) : null,
1264
+ needsConfirmation ? /* @__PURE__ */ jsxs("div", {
1265
+ role: "group",
1266
+ "aria-label": "Confirm your identity",
1267
+ className: "space-y-3",
1268
+ children: [
1269
+ /* @__PURE__ */ jsx("p", { children: "Confirm your identity to add a passkey. Use your password or an existing passkey." }),
1270
+ /* @__PURE__ */ jsxs("div", {
1271
+ className: "space-y-1",
1272
+ children: [/* @__PURE__ */ jsx(Label, {
1273
+ htmlFor: passwordId,
1274
+ children: "Current password"
1275
+ }), /* @__PURE__ */ jsx(Input, {
1276
+ id: passwordId,
1277
+ type: "password",
1278
+ autoComplete: "current-password",
1279
+ value: password,
1280
+ disabled: registering,
1281
+ onChange: (event) => setPassword(event.target.value)
1282
+ })]
1283
+ }),
1284
+ confirmationError ? /* @__PURE__ */ jsx("p", {
1285
+ role: "alert",
1286
+ children: confirmationError
1287
+ }) : null,
1288
+ /* @__PURE__ */ jsxs("div", {
1289
+ className: "flex flex-wrap gap-2",
1290
+ children: [
1291
+ /* @__PURE__ */ jsx(Button, {
1292
+ type: "button",
1293
+ disabled: registering || password.length === 0,
1294
+ onClick: () => void registerPasskey$1("password"),
1295
+ children: "Confirm password and continue"
1296
+ }),
1297
+ /* @__PURE__ */ jsx(Button, {
1298
+ type: "button",
1299
+ variant: "outline",
1300
+ disabled: registering,
1301
+ onClick: () => void registerPasskey$1("passkey"),
1302
+ children: "Use existing passkey"
1303
+ }),
1304
+ /* @__PURE__ */ jsx(Button, {
1305
+ type: "button",
1306
+ variant: "ghost",
1307
+ onClick: cancelConfirmation,
1308
+ children: "Cancel"
1309
+ })
1310
+ ]
1311
+ })
1312
+ ]
1313
+ }) : null
1314
+ ]
1315
+ })] });
970
1316
  }
971
-
972
1317
  // src/relying-applications.ts
1318
+ /**
1319
+ * Reduce a URL from the wire to one that is safe to put in an `href`, or reject it.
1320
+ *
1321
+ * These arrive as text in the page and end up as a link the browser will follow, so the
1322
+ * scheme is what matters: `javascript:` and `data:` both pass a server-side URL validity
1323
+ * check but execute rather than navigate. Parsing and allowing only http(s) is stronger
1324
+ * than matching a prefix — it normalises away the leading control characters, mixed case,
1325
+ * and escapes that a hand-rolled test can be walked past — and it returns the *parsed*
1326
+ * form, so what gets rendered is exactly what was validated.
1327
+ *
1328
+ * Absolute URLs only, deliberately. These point at other origins; a relative one means the
1329
+ * provider told us something unexpected, and guessing a base for it would be inventing a
1330
+ * destination rather than validating one.
1331
+ */
973
1332
  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
- }
1333
+ try {
1334
+ const parsed = new URL(url);
1335
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.toString() : null;
1336
+ } catch {
1337
+ return null;
1338
+ }
980
1339
  }
1340
+ /**
1341
+ * Validate whatever the page handed over into a list that is safe to render.
1342
+ *
1343
+ * Unrecognised entries are dropped rather than throwing. This is navigation chrome: one
1344
+ * malformed entry, or a provider that has grown a field, must not be able to take down the
1345
+ * page it appears on. Anything that is not a well-formed list degrades to an empty menu.
1346
+ */
981
1347
  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
- });
1348
+ if (!Array.isArray(value)) return [];
1349
+ return value.flatMap((entry) => {
1350
+ if (typeof entry !== "object" || entry === null) return [];
1351
+ const { key, name, url } = entry;
1352
+ if (typeof key !== "string" || typeof name !== "string" || typeof url !== "string") return [];
1353
+ if (key === "" || name.trim() === "") return [];
1354
+ const href = safeApplicationHref(url);
1355
+ return href === null ? [] : [{
1356
+ key,
1357
+ name: name.trim(),
1358
+ url: href
1359
+ }];
1360
+ });
999
1361
  }
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
-
1008
1362
  // src/scope-selection.ts
1363
+ /** Transitive closure of `implications`, with self-references and cycles dropped. */
1009
1364
  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;
1365
+ const closed = {};
1366
+ for (const key of Object.keys(implications)) {
1367
+ const seen = /* @__PURE__ */ new Set();
1368
+ const walk = (id) => {
1369
+ for (const needed of implications[id] ?? []) if (needed !== key && !seen.has(needed)) {
1370
+ seen.add(needed);
1371
+ walk(needed);
1372
+ }
1373
+ };
1374
+ walk(key);
1375
+ if (seen.size > 0) closed[key] = [...seen];
1376
+ }
1377
+ return closed;
1027
1378
  }
1379
+ /** Keeps only entries whose key and every requirement are offered; drops entries left empty. */
1028
1380
  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;
1381
+ const result = {};
1382
+ for (const [key, needed] of Object.entries(implications ?? {})) {
1383
+ if (!offered.has(key) || !Array.isArray(needed)) continue;
1384
+ const kept = needed.filter((id) => offered.has(id));
1385
+ if (kept.length > 0) result[key] = kept;
1386
+ }
1387
+ return result;
1040
1388
  }
1389
+ /** Orders `ids` by `catalog`, removing duplicates and ids not in it. */
1041
1390
  function inCatalogOrder(ids, catalog) {
1042
- const wanted = new Set(ids);
1043
- return catalog.filter((id) => wanted.has(id));
1391
+ const wanted = new Set(ids);
1392
+ return catalog.filter((id) => wanted.has(id));
1044
1393
  }
1394
+ /** Ticking: adds the ids and everything they need. */
1045
1395
  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;
1396
+ const next = new Set(selected);
1397
+ for (const id of ids) {
1398
+ next.add(id);
1399
+ for (const needed of closed[id] ?? []) next.add(needed);
1400
+ }
1401
+ return next;
1054
1402
  }
1403
+ /** Unticking: removes the ids and every selected scope that needs one of them. */
1055
1404
  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;
1405
+ const removed = new Set(ids);
1406
+ const next = new Set(selected);
1407
+ for (const id of ids) next.delete(id);
1408
+ for (const [scope, needed] of Object.entries(closed)) if (needed.some((id) => removed.has(id))) next.delete(scope);
1409
+ return next;
1067
1410
  }
1411
+ /** Selected scopes that need `id`, in catalog order: why `id` is ticked beyond the person's own choice. */
1068
1412
  function neededBy(id, selected, closed) {
1069
- return selected.filter((scope) => scope !== id && (closed[scope] ?? []).includes(id));
1413
+ return selected.filter((scope) => scope !== id && (closed[scope] ?? []).includes(id));
1070
1414
  }
1071
1415
  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));
1416
+ if (a.length !== b.length) return false;
1417
+ const set = new Set(a);
1418
+ return b.every((id) => set.has(id));
1077
1419
  }
1078
-
1079
1420
  // src/scope-picker.tsx
1080
- import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
1421
+ /** Groups limited to offered scopes (first group wins), with the leftovers collected in a final "Other" group. */
1081
1422
  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;
1423
+ if (!Array.isArray(groups) || groups.length === 0) return null;
1424
+ const byId = new Map(scopes.map((scope) => [scope.id, scope]));
1425
+ const placed = /* @__PURE__ */ new Set();
1426
+ const resolved = [];
1427
+ for (const group of groups) {
1428
+ const members = [];
1429
+ for (const id of group.scopes ?? []) {
1430
+ const scope = byId.get(id);
1431
+ if (scope && !placed.has(id)) {
1432
+ placed.add(id);
1433
+ members.push(scope);
1434
+ }
1435
+ }
1436
+ if (members.length > 0) resolved.push({
1437
+ id: group.id,
1438
+ label: group.label,
1439
+ description: group.description ?? null,
1440
+ sensitive: group.sensitive === true,
1441
+ scopes: members
1442
+ });
1443
+ }
1444
+ const rest = scopes.filter((scope) => !placed.has(scope.id));
1445
+ if (rest.length > 0) resolved.push({
1446
+ id: "other",
1447
+ label: "Other permissions",
1448
+ description: null,
1449
+ sensitive: false,
1450
+ scopes: rest
1451
+ });
1452
+ return resolved.length > 0 ? resolved : null;
1106
1453
  }
1107
1454
  function DefaultBadge(props) {
1108
- return /* @__PURE__ */ jsx4("span", { ...props });
1455
+ return /* @__PURE__ */ jsx("span", { ...props });
1109
1456
  }
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"
1457
+ const touchRow = {
1458
+ display: "flex",
1459
+ gap: "0.625rem",
1460
+ alignItems: "flex-start",
1461
+ minHeight: 44,
1462
+ padding: "0.5rem 0",
1463
+ boxSizing: "border-box",
1464
+ overflowWrap: "anywhere"
1118
1465
  };
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"
1466
+ const wrapStyle = {
1467
+ minWidth: 0,
1468
+ overflowWrap: "anywhere"
1469
+ };
1470
+ const mutedStyle = { opacity: .7 };
1471
+ const gridStyle = {
1472
+ display: "grid",
1473
+ gridTemplateColumns: "repeat(auto-fill, minmax(min(100%, 300px), 1fr))",
1474
+ gap: "1rem",
1475
+ alignItems: "start"
1476
+ };
1477
+ const boxStyle = {
1478
+ margin: 0,
1479
+ minWidth: 0,
1480
+ border: "1px solid rgba(128, 128, 128, 0.35)",
1481
+ borderRadius: 10,
1482
+ padding: "0.25rem 1rem 0.75rem"
1126
1483
  };
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
1484
  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
- ] });
1485
+ const { Checkbox, Button, Badge, Alert } = resolveAuthComponents(components);
1486
+ const [open, setOpen] = React.useState({});
1487
+ const catalog = React.useMemo(() => scopes.map((scope) => scope.id), [scopes]);
1488
+ const closed = React.useMemo(() => closeImplications(restrictImplications(implications, new Set(catalog))), [implications, catalog]);
1489
+ const layout = React.useMemo(() => resolveGroups(scopes, groups), [scopes, groups]);
1490
+ const offeredPresets = React.useMemo(() => (presets ?? []).filter((preset) => preset.scopes.length > 0 && preset.scopes.every((id) => catalog.includes(id))), [presets, catalog]);
1491
+ const cascades = Object.keys(closed).length > 0;
1492
+ const chosen = new Set(selected);
1493
+ const commit = (next) => onChange(inCatalogOrder(next, catalog));
1494
+ const toggle = (id, checked) => {
1495
+ if (layout === null && !cascades) {
1496
+ onChange(checked ? [...selected, id] : selected.filter((value) => value !== id));
1497
+ return;
1498
+ }
1499
+ commit(checked ? withScopes(selected, [id], closed) : withoutScopes(selected, [id], closed));
1500
+ };
1501
+ const renderRow = (scope, grouped) => {
1502
+ const id = `${idPrefix}-${scope.id}`;
1503
+ const needers = neededBy(scope.id, selected, closed);
1504
+ const noteId = `${id}-needed`;
1505
+ const row = /* @__PURE__ */ jsxs("label", {
1506
+ htmlFor: id,
1507
+ style: grouped ? {
1508
+ ...touchRow,
1509
+ cursor: "pointer"
1510
+ } : { overflowWrap: "anywhere" },
1511
+ children: [
1512
+ Checkbox ? /* @__PURE__ */ jsx(Checkbox, {
1513
+ id,
1514
+ checked: chosen.has(scope.id),
1515
+ onCheckedChange: (checked) => toggle(scope.id, checked)
1516
+ }) : /* @__PURE__ */ jsx("input", {
1517
+ id,
1518
+ type: "checkbox",
1519
+ checked: chosen.has(scope.id),
1520
+ "aria-describedby": needers.length > 0 ? noteId : void 0,
1521
+ onChange: (event) => toggle(scope.id, event.target.checked),
1522
+ style: grouped ? {
1523
+ flex: "none",
1524
+ width: 16,
1525
+ height: 16,
1526
+ margin: "2px 0 0"
1527
+ } : void 0
1528
+ }),
1529
+ " ",
1530
+ /* @__PURE__ */ jsxs("span", {
1531
+ style: {
1532
+ minWidth: 0,
1533
+ overflowWrap: "anywhere"
1534
+ },
1535
+ children: [
1536
+ /* @__PURE__ */ jsx("code", {
1537
+ style: wrapStyle,
1538
+ children: scope.id
1539
+ }),
1540
+ " ",
1541
+ /* @__PURE__ */ jsx("span", {
1542
+ style: mutedStyle,
1543
+ children: scope.description
1544
+ })
1545
+ ]
1546
+ })
1547
+ ]
1548
+ }, scope.id);
1549
+ if (needers.length === 0) return row;
1550
+ return /* @__PURE__ */ jsxs("div", {
1551
+ style: { minWidth: 0 },
1552
+ children: [row, /* @__PURE__ */ jsxs("small", {
1553
+ id: noteId,
1554
+ style: {
1555
+ ...mutedStyle,
1556
+ display: "block",
1557
+ paddingLeft: grouped ? 26 : 0,
1558
+ overflowWrap: "anywhere"
1559
+ },
1560
+ children: ["needed by ", needers.join(", ")]
1561
+ })]
1562
+ }, scope.id);
1563
+ };
1564
+ if (layout === null) return /* @__PURE__ */ jsxs("fieldset", {
1565
+ style: {
1566
+ display: "grid",
1567
+ gap: "0.25rem",
1568
+ border: 0,
1569
+ padding: 0,
1570
+ minWidth: 0,
1571
+ overflowWrap: "anywhere"
1572
+ },
1573
+ children: [/* @__PURE__ */ jsx("legend", { children: "Permissions" }), scopes.map((scope) => renderRow(scope, false))]
1574
+ });
1575
+ const pressed = offeredPresets.find((preset) => sameSelection(selected, preset.scopes));
1576
+ const plain = layout.filter((group) => !group.sensitive);
1577
+ const sensitive = layout.filter((group) => group.sensitive);
1578
+ const Chip = Badge ?? DefaultBadge;
1579
+ return /* @__PURE__ */ jsxs("div", {
1580
+ style: {
1581
+ display: "grid",
1582
+ gap: "1rem",
1583
+ minWidth: 0,
1584
+ overflowWrap: "anywhere"
1585
+ },
1586
+ children: [
1587
+ /* @__PURE__ */ jsxs("div", {
1588
+ style: {
1589
+ display: "grid",
1590
+ gap: "0.25rem",
1591
+ minWidth: 0,
1592
+ overflowWrap: "anywhere"
1593
+ },
1594
+ children: [/* @__PURE__ */ jsx("strong", { children: "Permissions" }), offeredPresets.length > 0 && /* @__PURE__ */ jsx("span", {
1595
+ style: mutedStyle,
1596
+ children: "Start from a preset, then adjust any permission below. The credential stores exactly the permissions you tick."
1597
+ })]
1598
+ }),
1599
+ offeredPresets.length > 0 && /* @__PURE__ */ jsxs("div", {
1600
+ style: {
1601
+ display: "grid",
1602
+ gap: "0.625rem",
1603
+ minWidth: 0
1604
+ },
1605
+ children: [/* @__PURE__ */ jsx("div", {
1606
+ role: "group",
1607
+ "aria-label": "Presets",
1608
+ style: {
1609
+ display: "flex",
1610
+ flexWrap: "wrap",
1611
+ gap: "0.5rem"
1612
+ },
1613
+ children: offeredPresets.map((preset) => {
1614
+ const isPressed = pressed?.id === preset.id;
1615
+ return /* @__PURE__ */ jsx(Button, {
1616
+ type: "button",
1617
+ variant: isPressed ? "default" : "outline",
1618
+ "aria-pressed": isPressed,
1619
+ style: {
1620
+ height: "auto",
1621
+ minHeight: 44,
1622
+ minWidth: 0,
1623
+ maxWidth: "100%",
1624
+ overflowWrap: "anywhere",
1625
+ whiteSpace: "normal",
1626
+ textAlign: "left"
1627
+ },
1628
+ onClick: () => commit(withScopes([], preset.scopes, closed)),
1629
+ children: preset.label
1630
+ }, preset.id);
1631
+ })
1632
+ }), /* @__PURE__ */ jsx("p", {
1633
+ "aria-live": "polite",
1634
+ style: {
1635
+ margin: 0,
1636
+ ...mutedStyle,
1637
+ overflowWrap: "anywhere"
1638
+ },
1639
+ children: pressed ? pressed.description : "Custom selection. Pick a preset to replace it, or keep adjusting below."
1640
+ })]
1641
+ }),
1642
+ plain.length > 0 && /* @__PURE__ */ jsx("div", {
1643
+ style: gridStyle,
1644
+ children: plain.map((group) => /* @__PURE__ */ jsxs("fieldset", {
1645
+ style: {
1646
+ ...boxStyle,
1647
+ display: "grid",
1648
+ gridTemplateColumns: "minmax(0, 1fr)"
1649
+ },
1650
+ children: [/* @__PURE__ */ jsx("legend", {
1651
+ style: {
1652
+ padding: "0 0.375rem",
1653
+ fontWeight: 600,
1654
+ overflowWrap: "anywhere"
1655
+ },
1656
+ children: group.label
1657
+ }), group.scopes.map((scope) => renderRow(scope, true))]
1658
+ }, group.id))
1659
+ }),
1660
+ sensitive.map((group) => {
1661
+ const ids = group.scopes.map((scope) => scope.id);
1662
+ const count = ids.filter((id) => chosen.has(id)).length;
1663
+ const state = count === 0 ? "none" : count === ids.length ? "all" : "some";
1664
+ const parentId = `${idPrefix}-group-${group.id}`;
1665
+ const listId = `${parentId}-scopes`;
1666
+ const isOpen = open[group.id] === true;
1667
+ const warning = group.description !== null && group.description !== "" ? group.description : null;
1668
+ return /* @__PURE__ */ jsxs("fieldset", {
1669
+ style: {
1670
+ ...boxStyle,
1671
+ display: "grid",
1672
+ gridTemplateColumns: "minmax(0, 1fr)",
1673
+ gap: "0.375rem",
1674
+ paddingBottom: "0.875rem"
1675
+ },
1676
+ children: [
1677
+ /* @__PURE__ */ jsxs("legend", {
1678
+ style: {
1679
+ padding: "0 0.375rem",
1680
+ fontWeight: 600,
1681
+ display: "flex",
1682
+ alignItems: "center",
1683
+ gap: "0.5rem",
1684
+ maxWidth: "100%",
1685
+ minWidth: 0
1686
+ },
1687
+ children: [/* @__PURE__ */ jsx("span", {
1688
+ style: { overflowWrap: "anywhere" },
1689
+ children: group.label
1690
+ }), /* @__PURE__ */ jsx(Chip, {
1691
+ style: {
1692
+ fontSize: 12,
1693
+ fontWeight: 500,
1694
+ border: "1px solid currentColor",
1695
+ borderRadius: 999,
1696
+ padding: "3px 8px",
1697
+ lineHeight: 1
1698
+ },
1699
+ children: "Sensitive"
1700
+ })]
1701
+ }),
1702
+ warning !== null && (() => {
1703
+ const content = /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(TriangleAlert, {
1704
+ "aria-hidden": "true",
1705
+ size: 16,
1706
+ style: {
1707
+ flex: "none",
1708
+ marginTop: 2
1709
+ }
1710
+ }), /* @__PURE__ */ jsx("span", {
1711
+ style: {
1712
+ minWidth: 0,
1713
+ overflowWrap: "anywhere"
1714
+ },
1715
+ children: warning
1716
+ })] });
1717
+ const style = {
1718
+ margin: "0.25rem 0 0",
1719
+ display: "flex",
1720
+ gap: "0.5rem",
1721
+ alignItems: "flex-start"
1722
+ };
1723
+ return Alert ? /* @__PURE__ */ jsx(Alert, {
1724
+ style,
1725
+ children: content
1726
+ }) : /* @__PURE__ */ jsx("p", {
1727
+ style: {
1728
+ ...style,
1729
+ color: "#b45309"
1730
+ },
1731
+ children: content
1732
+ });
1733
+ })(),
1734
+ /* @__PURE__ */ jsxs("label", {
1735
+ htmlFor: parentId,
1736
+ style: {
1737
+ ...touchRow,
1738
+ cursor: "pointer"
1739
+ },
1740
+ children: [
1741
+ /* @__PURE__ */ jsx("input", {
1742
+ id: parentId,
1743
+ type: "checkbox",
1744
+ checked: state === "all",
1745
+ "aria-checked": state === "some" ? "mixed" : state === "all",
1746
+ ref: (element) => {
1747
+ if (element) element.indeterminate = state === "some";
1748
+ },
1749
+ onChange: () => commit(state === "all" ? withoutScopes(selected, ids, closed) : withScopes(selected, ids, closed)),
1750
+ style: {
1751
+ flex: "none",
1752
+ width: 16,
1753
+ height: 16,
1754
+ margin: "2px 0 0"
1755
+ }
1756
+ }),
1757
+ " ",
1758
+ /* @__PURE__ */ jsxs("span", {
1759
+ style: {
1760
+ minWidth: 0,
1761
+ overflowWrap: "anywhere"
1762
+ },
1763
+ children: [
1764
+ /* @__PURE__ */ jsx("strong", { children: group.label }),
1765
+ " ",
1766
+ /* @__PURE__ */ jsx("span", {
1767
+ style: mutedStyle,
1768
+ 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.`
1769
+ })
1770
+ ]
1771
+ })
1772
+ ]
1773
+ }),
1774
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs(Button, {
1775
+ type: "button",
1776
+ variant: "ghost",
1777
+ "aria-expanded": isOpen,
1778
+ "aria-controls": listId,
1779
+ style: {
1780
+ height: "auto",
1781
+ minHeight: 44,
1782
+ minWidth: 0,
1783
+ maxWidth: "100%",
1784
+ overflowWrap: "anywhere",
1785
+ whiteSpace: "normal",
1786
+ textAlign: "left"
1787
+ },
1788
+ onClick: () => setOpen((current) => ({
1789
+ ...current,
1790
+ [group.id]: !isOpen
1791
+ })),
1792
+ children: [
1793
+ /* @__PURE__ */ jsx(ChevronRight, {
1794
+ "aria-hidden": "true",
1795
+ size: 16,
1796
+ style: {
1797
+ flex: "none",
1798
+ transition: "transform 120ms",
1799
+ transform: isOpen ? "rotate(90deg)" : "none"
1800
+ }
1801
+ }),
1802
+ isOpen ? "Hide" : "Adjust",
1803
+ " individual ",
1804
+ group.label,
1805
+ " permissions"
1806
+ ]
1807
+ }) }),
1808
+ isOpen && /* @__PURE__ */ jsx("div", {
1809
+ id: listId,
1810
+ style: {
1811
+ ...gridStyle,
1812
+ minWidth: 0,
1813
+ columnGap: "1.5rem",
1814
+ gap: "0 1.5rem",
1815
+ paddingLeft: "1.5rem",
1816
+ marginLeft: 7,
1817
+ borderLeft: "2px solid rgba(128, 128, 128, 0.35)"
1818
+ },
1819
+ children: group.scopes.map((scope) => renderRow(scope, true))
1820
+ })
1821
+ ]
1822
+ }, group.id);
1823
+ }),
1824
+ /* @__PURE__ */ jsxs("div", {
1825
+ style: {
1826
+ borderTop: "1px solid rgba(128, 128, 128, 0.35)",
1827
+ paddingTop: "0.875rem",
1828
+ display: "grid",
1829
+ gap: "0.5rem"
1830
+ },
1831
+ children: [/* @__PURE__ */ jsx("p", {
1832
+ style: {
1833
+ margin: 0,
1834
+ fontWeight: 500
1835
+ },
1836
+ role: "status",
1837
+ children: selected.length === 0 ? "No permissions selected." : `This credential will request ${selected.length} ${selected.length === 1 ? "permission" : "permissions"}:`
1838
+ }), selected.length > 0 && /* @__PURE__ */ jsx("p", {
1839
+ style: {
1840
+ margin: 0,
1841
+ display: "flex",
1842
+ flexWrap: "wrap",
1843
+ gap: "0.375rem"
1844
+ },
1845
+ children: selected.map((id) => /* @__PURE__ */ jsx("code", {
1846
+ style: { overflowWrap: "anywhere" },
1847
+ children: id
1848
+ }, id))
1849
+ })]
1850
+ })
1851
+ ]
1852
+ });
1290
1853
  }
1291
-
1292
1854
  // src/api-credentials-section.tsx
1293
- import { Fragment as Fragment3, jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
1855
+ /**
1856
+ * A person's credentials for apps that use the API: personal API tokens (for
1857
+ * connectors that ask for a key) and OAuth apps (for connectors that run the
1858
+ * authorization-code flow).
1859
+ *
1860
+ * Each secret arrives once, in the response that created it, and lives only
1861
+ * in this component's memory; afterwards only the lists are reloaded, so it is
1862
+ * never part of page props or browser history.
1863
+ */
1294
1864
  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
- ] });
1865
+ const { Card, CardContent, CardDescription, CardHeader, CardTitle } = resolveAuthComponents(components);
1866
+ const [index, setIndex] = React.useState(null);
1867
+ const [issued, setIssued] = React.useState([]);
1868
+ const issuedKey = React.useRef(0);
1869
+ const addIssued = React.useCallback((credential) => {
1870
+ issuedKey.current += 1;
1871
+ const key = issuedKey.current;
1872
+ setIssued((current) => [...current, {
1873
+ key,
1874
+ credential
1875
+ }]);
1876
+ }, []);
1877
+ const [loadError, setLoadError] = React.useState(null);
1878
+ const onErrorRef = React.useRef(onError);
1879
+ onErrorRef.current = onError;
1880
+ const generation = React.useRef(0);
1881
+ const context = React.useRef({
1882
+ indexUrl,
1883
+ csrfToken,
1884
+ request
1885
+ });
1886
+ context.current = {
1887
+ indexUrl,
1888
+ csrfToken,
1889
+ request
1890
+ };
1891
+ const reload = React.useCallback(async () => {
1892
+ generation.current += 1;
1893
+ const mine = generation.current;
1894
+ const { indexUrl: url, csrfToken: token, request: send } = context.current;
1895
+ const result = await credentialRequest("GET", url, void 0, token, send);
1896
+ if (mine !== generation.current) return;
1897
+ if (result.ok) {
1898
+ setIndex(result.data);
1899
+ setLoadError(null);
1900
+ } else {
1901
+ setLoadError(result.message);
1902
+ onErrorRef.current?.("api-credentials", result.message);
1903
+ }
1904
+ }, []);
1905
+ React.useEffect(() => {
1906
+ setIndex(null);
1907
+ reload();
1908
+ }, [
1909
+ indexUrl,
1910
+ csrfToken,
1911
+ reload
1912
+ ]);
1913
+ const shared = {
1914
+ components,
1915
+ csrfToken,
1916
+ request,
1917
+ onError,
1918
+ onSuccess,
1919
+ removeLocally: React.useCallback((list, id) => {
1920
+ setIndex((current) => current === null ? current : list === "tokens" ? {
1921
+ ...current,
1922
+ tokens: current.tokens.filter((token) => token.id !== id)
1923
+ } : {
1924
+ ...current,
1925
+ apps: current.apps.filter((app) => app.id !== id)
1926
+ });
1927
+ }, [])
1928
+ };
1929
+ 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", {
1930
+ style: {
1931
+ display: "grid",
1932
+ gap: "1.5rem",
1933
+ minWidth: 0,
1934
+ overflowWrap: "anywhere"
1935
+ },
1936
+ children: [
1937
+ links.length > 0 && /* @__PURE__ */ jsx("dl", {
1938
+ style: {
1939
+ display: "grid",
1940
+ gap: "0.5rem",
1941
+ minWidth: 0
1942
+ },
1943
+ children: links.map((link) => /* @__PURE__ */ jsxs("div", {
1944
+ style: { minWidth: 0 },
1945
+ children: [/* @__PURE__ */ jsx("dt", { children: link.label }), /* @__PURE__ */ jsxs("dd", {
1946
+ style: {
1947
+ margin: 0,
1948
+ overflowWrap: "anywhere"
1949
+ },
1950
+ children: [
1951
+ /* @__PURE__ */ jsx("code", { children: link.url }),
1952
+ " ",
1953
+ /* @__PURE__ */ jsx(CopyButton, {
1954
+ text: link.url,
1955
+ label: link.label,
1956
+ components
1957
+ })
1958
+ ]
1959
+ })]
1960
+ }, link.label))
1961
+ }),
1962
+ issued.map(({ key, credential }) => /* @__PURE__ */ jsx(IssuedNotice, {
1963
+ issued: credential,
1964
+ components,
1965
+ onDismiss: () => setIssued((current) => current.filter((entry) => entry.key !== key))
1966
+ }, key)),
1967
+ loadError !== null && /* @__PURE__ */ jsx("p", {
1968
+ role: "alert",
1969
+ children: loadError
1970
+ }),
1971
+ index !== null && /* @__PURE__ */ jsxs(Fragment, { children: [(index.issue_token_href === null || index.register_app_href === null) && /* @__PURE__ */ jsx("p", {
1972
+ role: "status",
1973
+ children: "Creating new credentials is unavailable right now. You can still revoke existing ones."
1974
+ }), /* @__PURE__ */ jsxs("div", {
1975
+ "data-layout": layout,
1976
+ style: layout === "columns" ? {
1977
+ display: "grid",
1978
+ gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 460px), 1fr))",
1979
+ gap: "1.5rem",
1980
+ alignItems: "start",
1981
+ minWidth: 0
1982
+ } : {
1983
+ display: "grid",
1984
+ gridTemplateColumns: "minmax(0, 1fr)",
1985
+ gap: "1.5rem",
1986
+ minWidth: 0
1987
+ },
1988
+ children: [/* @__PURE__ */ jsx(TokenSection, {
1989
+ index,
1990
+ ...shared,
1991
+ onIssued: addIssued,
1992
+ reload
1993
+ }), /* @__PURE__ */ jsx(AppSection, {
1994
+ index,
1995
+ ...shared,
1996
+ onIssued: addIssued,
1997
+ reload
1998
+ })]
1999
+ })] })
2000
+ ]
2001
+ }) })] });
1376
2002
  }
1377
2003
  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
- ] });
2004
+ const { Button, Input, Label, RadioGroup } = resolveAuthComponents(components);
2005
+ const [name, setName] = React.useState("");
2006
+ const [scopes, setScopes] = React.useState([]);
2007
+ const [lifetime, setLifetime] = React.useState(index.token_lifetimes[0] ?? "");
2008
+ const tokenScopes = React.useMemo(() => [...index.token_scopes ?? index.scopes, ...index.token_connection_scopes ?? []], [
2009
+ index.token_scopes,
2010
+ index.scopes,
2011
+ index.token_connection_scopes
2012
+ ]);
2013
+ const connectionIds = new Set((index.token_connection_scopes ?? []).map((scope) => scope.id));
2014
+ 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;
2015
+ const effectiveLifetime = lifetimes.includes(lifetime) ? lifetime : lifetimes[0] ?? "";
2016
+ const [busy, setBusy] = React.useState(false);
2017
+ const [error, setError] = React.useState(null);
2018
+ async function create(event) {
2019
+ event.preventDefault();
2020
+ if (index.issue_token_href === null) return;
2021
+ setBusy(true);
2022
+ const result = await credentialRequest("POST", index.issue_token_href, {
2023
+ name,
2024
+ scopes,
2025
+ lifetime: effectiveLifetime
2026
+ }, csrfToken, request);
2027
+ setBusy(false);
2028
+ if (!result.ok) {
2029
+ setError(result.message);
2030
+ onError?.("api-tokens", result.message);
2031
+ return;
2032
+ }
2033
+ setError(null);
2034
+ setName("");
2035
+ setScopes([]);
2036
+ onIssued(result.data);
2037
+ onSuccess?.("API token created.");
2038
+ await reload();
2039
+ }
2040
+ const [pending, setPending] = React.useState([]);
2041
+ async function revoke(token) {
2042
+ if (pending.includes(token.id)) return;
2043
+ setPending((current) => [...current, token.id]);
2044
+ const result = await credentialRequest("DELETE", token.revoke_href, void 0, csrfToken, request);
2045
+ if (!result.ok) {
2046
+ setPending((current) => current.filter((id) => id !== token.id));
2047
+ setError(result.message);
2048
+ onError?.("api-tokens", result.message);
2049
+ return;
2050
+ }
2051
+ setError(null);
2052
+ removeLocally("tokens", token.id);
2053
+ onSuccess?.("API token revoked.");
2054
+ await reload();
2055
+ setPending((current) => current.filter((id) => id !== token.id));
2056
+ }
2057
+ return /* @__PURE__ */ jsxs("section", {
2058
+ style: {
2059
+ display: "grid",
2060
+ gap: "0.75rem",
2061
+ minWidth: 0
2062
+ },
2063
+ children: [
2064
+ /* @__PURE__ */ jsx("h3", { children: "API tokens" }),
2065
+ index.issue_token_href !== null && /* @__PURE__ */ jsxs("form", {
2066
+ onSubmit: create,
2067
+ style: {
2068
+ display: "grid",
2069
+ gap: "0.75rem",
2070
+ minWidth: 0
2071
+ },
2072
+ children: [
2073
+ /* @__PURE__ */ jsxs("div", {
2074
+ style: {
2075
+ display: "grid",
2076
+ gap: "0.25rem"
2077
+ },
2078
+ children: [/* @__PURE__ */ jsx(Label, {
2079
+ htmlFor: "api-token-name",
2080
+ children: "Token name"
2081
+ }), /* @__PURE__ */ jsx(Input, {
2082
+ id: "api-token-name",
2083
+ value: name,
2084
+ maxLength: 120,
2085
+ onChange: (event) => setName(event.target.value)
2086
+ })]
2087
+ }),
2088
+ /* @__PURE__ */ jsx(ScopePicker, {
2089
+ idPrefix: "api-token-scope",
2090
+ scopes: tokenScopes,
2091
+ groups: index.token_scope_groups ?? index.scope_groups,
2092
+ presets: index.token_scope_presets ?? index.scope_presets,
2093
+ implications: index.token_scope_implications ?? index.scope_implications,
2094
+ selected: scopes,
2095
+ onChange: setScopes,
2096
+ components
2097
+ }),
2098
+ /* @__PURE__ */ jsxs("fieldset", {
2099
+ style: {
2100
+ display: "grid",
2101
+ gap: "0.25rem",
2102
+ border: 0,
2103
+ padding: 0
2104
+ },
2105
+ children: [/* @__PURE__ */ jsx("legend", { children: "Expires after" }), RadioGroup ? /* @__PURE__ */ jsx(RadioGroup, {
2106
+ name: "api-token-lifetime",
2107
+ value: effectiveLifetime,
2108
+ onValueChange: setLifetime,
2109
+ options: lifetimes.map((spec) => ({
2110
+ value: spec,
2111
+ label: describeDuration(spec)
2112
+ }))
2113
+ }) : lifetimes.map((spec) => /* @__PURE__ */ jsxs("label", { children: [
2114
+ /* @__PURE__ */ jsx("input", {
2115
+ type: "radio",
2116
+ name: "api-token-lifetime",
2117
+ checked: effectiveLifetime === spec,
2118
+ onChange: () => setLifetime(spec)
2119
+ }),
2120
+ " ",
2121
+ describeDuration(spec)
2122
+ ] }, spec))]
2123
+ }),
2124
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, {
2125
+ type: "submit",
2126
+ disabled: busy || name.trim() === "" || scopes.length === 0 || effectiveLifetime === "",
2127
+ children: "Create API token"
2128
+ }) })
2129
+ ]
2130
+ }),
2131
+ error !== null && /* @__PURE__ */ jsx("p", {
2132
+ role: "alert",
2133
+ children: error
2134
+ }),
2135
+ /* @__PURE__ */ jsx("ul", {
2136
+ style: {
2137
+ display: "grid",
2138
+ gap: "0.5rem",
2139
+ listStyle: "none",
2140
+ padding: 0,
2141
+ margin: 0,
2142
+ minWidth: 0
2143
+ },
2144
+ children: index.tokens.map((token) => /* @__PURE__ */ jsxs("li", {
2145
+ style: {
2146
+ minWidth: 0,
2147
+ overflowWrap: "anywhere"
2148
+ },
2149
+ children: [
2150
+ /* @__PURE__ */ jsx("strong", { children: token.name }),
2151
+ " · ",
2152
+ token.scopes.join(", "),
2153
+ token.connection === true && /* @__PURE__ */ jsx(Fragment, { children: " · MCP connection" }),
2154
+ token.expires_at !== null && /* @__PURE__ */ jsxs(Fragment, { children: [" · expires ", new Date(token.expires_at).toLocaleString()] }),
2155
+ " ",
2156
+ /* @__PURE__ */ jsx(Button, {
2157
+ type: "button",
2158
+ disabled: pending.includes(token.id),
2159
+ onClick: () => void revoke(token),
2160
+ children: "Revoke"
2161
+ })
2162
+ ]
2163
+ }, token.id))
2164
+ })
2165
+ ]
2166
+ });
1482
2167
  }
1483
2168
  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
- ] });
2169
+ const { Button, Input, Label, Textarea, RadioGroup } = resolveAuthComponents(components);
2170
+ const [name, setName] = React.useState("");
2171
+ const [redirects, setRedirects] = React.useState("");
2172
+ const [confidential, setConfidential] = React.useState(true);
2173
+ const [scopes, setScopes] = React.useState([]);
2174
+ const [busy, setBusy] = React.useState(false);
2175
+ const [error, setError] = React.useState(null);
2176
+ const redirectUris = redirects.split("\n").map((line) => line.trim()).filter((line) => line !== "");
2177
+ async function register(event) {
2178
+ event.preventDefault();
2179
+ if (index.register_app_href === null) return;
2180
+ setBusy(true);
2181
+ const result = await credentialRequest("POST", index.register_app_href, {
2182
+ name,
2183
+ redirect_uris: redirectUris,
2184
+ confidential,
2185
+ scopes
2186
+ }, csrfToken, request);
2187
+ setBusy(false);
2188
+ if (!result.ok) {
2189
+ setError(result.message);
2190
+ onError?.("oauth-apps", result.message);
2191
+ return;
2192
+ }
2193
+ setError(null);
2194
+ setName("");
2195
+ setRedirects("");
2196
+ setScopes([]);
2197
+ onIssued(result.data);
2198
+ onSuccess?.("OAuth app registered.");
2199
+ await reload();
2200
+ }
2201
+ const [pending, setPending] = React.useState([]);
2202
+ async function remove(app) {
2203
+ if (pending.includes(app.id)) return;
2204
+ setPending((current) => [...current, app.id]);
2205
+ const result = await credentialRequest("DELETE", app.delete_href, void 0, csrfToken, request);
2206
+ if (!result.ok) {
2207
+ setPending((current) => current.filter((id) => id !== app.id));
2208
+ setError(result.message);
2209
+ onError?.("oauth-apps", result.message);
2210
+ return;
2211
+ }
2212
+ setError(null);
2213
+ removeLocally("apps", app.id);
2214
+ onSuccess?.("OAuth app deleted and its tokens revoked.");
2215
+ await reload();
2216
+ setPending((current) => current.filter((id) => id !== app.id));
2217
+ }
2218
+ return /* @__PURE__ */ jsxs("section", {
2219
+ style: {
2220
+ display: "grid",
2221
+ gap: "0.75rem",
2222
+ minWidth: 0
2223
+ },
2224
+ children: [
2225
+ /* @__PURE__ */ jsx("h3", { children: "OAuth apps" }),
2226
+ index.register_app_href !== null && /* @__PURE__ */ jsxs("form", {
2227
+ onSubmit: register,
2228
+ style: {
2229
+ display: "grid",
2230
+ gap: "0.75rem",
2231
+ minWidth: 0
2232
+ },
2233
+ children: [
2234
+ /* @__PURE__ */ jsxs("div", {
2235
+ style: {
2236
+ display: "grid",
2237
+ gap: "0.25rem"
2238
+ },
2239
+ children: [/* @__PURE__ */ jsx(Label, {
2240
+ htmlFor: "oauth-app-name",
2241
+ children: "App name"
2242
+ }), /* @__PURE__ */ jsx(Input, {
2243
+ id: "oauth-app-name",
2244
+ value: name,
2245
+ maxLength: 120,
2246
+ onChange: (event) => setName(event.target.value)
2247
+ })]
2248
+ }),
2249
+ /* @__PURE__ */ jsxs("div", {
2250
+ style: {
2251
+ display: "grid",
2252
+ gap: "0.25rem"
2253
+ },
2254
+ children: [/* @__PURE__ */ jsx(Label, {
2255
+ htmlFor: "oauth-app-redirects",
2256
+ children: "Redirect URIs (one per line)"
2257
+ }), Textarea ? /* @__PURE__ */ jsx(Textarea, {
2258
+ id: "oauth-app-redirects",
2259
+ rows: 3,
2260
+ value: redirects,
2261
+ onChange: (event) => setRedirects(event.target.value)
2262
+ }) : /* @__PURE__ */ jsx("textarea", {
2263
+ id: "oauth-app-redirects",
2264
+ rows: 3,
2265
+ value: redirects,
2266
+ onChange: (event) => setRedirects(event.target.value)
2267
+ })]
2268
+ }),
2269
+ /* @__PURE__ */ jsxs("fieldset", {
2270
+ style: {
2271
+ display: "grid",
2272
+ gap: "0.25rem",
2273
+ border: 0,
2274
+ padding: 0
2275
+ },
2276
+ children: [/* @__PURE__ */ jsx("legend", { children: "Client type" }), RadioGroup ? /* @__PURE__ */ jsx(RadioGroup, {
2277
+ name: "oauth-app-type",
2278
+ value: confidential ? "confidential" : "public",
2279
+ onValueChange: (value) => setConfidential(value === "confidential"),
2280
+ options: [{
2281
+ value: "confidential",
2282
+ label: "Confidential: the app keeps a client secret on its server"
2283
+ }, {
2284
+ value: "public",
2285
+ label: "Public: no secret, PKCE only"
2286
+ }]
2287
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("label", { children: [/* @__PURE__ */ jsx("input", {
2288
+ type: "radio",
2289
+ name: "oauth-app-type",
2290
+ checked: confidential,
2291
+ onChange: () => setConfidential(true)
2292
+ }), " Confidential: the app keeps a client secret on its server"] }), /* @__PURE__ */ jsxs("label", { children: [/* @__PURE__ */ jsx("input", {
2293
+ type: "radio",
2294
+ name: "oauth-app-type",
2295
+ checked: !confidential,
2296
+ onChange: () => setConfidential(false)
2297
+ }), " Public: no secret, PKCE only"] })] })]
2298
+ }),
2299
+ /* @__PURE__ */ jsx(ScopePicker, {
2300
+ idPrefix: "oauth-app-scope",
2301
+ scopes: index.scopes,
2302
+ groups: index.scope_groups,
2303
+ presets: index.scope_presets,
2304
+ implications: index.scope_implications,
2305
+ selected: scopes,
2306
+ onChange: setScopes,
2307
+ components
2308
+ }),
2309
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, {
2310
+ type: "submit",
2311
+ disabled: busy || name.trim() === "" || redirectUris.length === 0 || scopes.length === 0,
2312
+ children: "Register OAuth app"
2313
+ }) })
2314
+ ]
2315
+ }),
2316
+ error !== null && /* @__PURE__ */ jsx("p", {
2317
+ role: "alert",
2318
+ children: error
2319
+ }),
2320
+ /* @__PURE__ */ jsx("ul", {
2321
+ style: {
2322
+ display: "grid",
2323
+ gap: "0.5rem",
2324
+ listStyle: "none",
2325
+ padding: 0,
2326
+ margin: 0,
2327
+ minWidth: 0
2328
+ },
2329
+ children: index.apps.map((app) => /* @__PURE__ */ jsxs("li", {
2330
+ style: {
2331
+ minWidth: 0,
2332
+ overflowWrap: "anywhere"
2333
+ },
2334
+ children: [
2335
+ /* @__PURE__ */ jsx("strong", { children: app.name }),
2336
+ " · client ID ",
2337
+ /* @__PURE__ */ jsx("code", { children: app.id }),
2338
+ " · ",
2339
+ app.confidential ? "confidential" : "public",
2340
+ /* @__PURE__ */ jsx("br", {}),
2341
+ app.redirect_uris.join(", "),
2342
+ /* @__PURE__ */ jsx("br", {}),
2343
+ "May request: ",
2344
+ app.scopes.join(", "),
2345
+ " ",
2346
+ /* @__PURE__ */ jsx(Button, {
2347
+ type: "button",
2348
+ disabled: pending.includes(app.id),
2349
+ onClick: () => void remove(app),
2350
+ children: "Delete"
2351
+ })
2352
+ ]
2353
+ }, app.id))
2354
+ })
2355
+ ]
2356
+ });
1604
2357
  }
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
- ] });
2358
+ function IssuedNotice({ issued, components, onDismiss }) {
2359
+ const { Button } = resolveAuthComponents(components);
2360
+ const values = issued.kind === "token" ? [{
2361
+ label: "API token",
2362
+ url: issued.token
2363
+ }] : [{
2364
+ label: "Client ID",
2365
+ url: issued.client_id
2366
+ }, ...issued.client_secret !== null ? [{
2367
+ label: "Client secret",
2368
+ url: issued.client_secret
2369
+ }] : []];
2370
+ return /* @__PURE__ */ jsxs("div", {
2371
+ role: "status",
2372
+ style: {
2373
+ display: "grid",
2374
+ gap: "0.5rem",
2375
+ minWidth: 0
2376
+ },
2377
+ children: [
2378
+ /* @__PURE__ */ jsxs("p", {
2379
+ style: { overflowWrap: "anywhere" },
2380
+ children: [issued.kind === "token" ? `API token “${issued.name}” created.` : `OAuth app “${issued.name}” registered.`, " Copy it now: it will not be shown again."]
2381
+ }),
2382
+ values.map((value) => /* @__PURE__ */ jsxs("div", {
2383
+ style: {
2384
+ minWidth: 0,
2385
+ overflowWrap: "anywhere"
2386
+ },
2387
+ children: [
2388
+ value.label,
2389
+ ": ",
2390
+ /* @__PURE__ */ jsx("code", { children: value.url }),
2391
+ " ",
2392
+ /* @__PURE__ */ jsx(CopyButton, {
2393
+ text: value.url,
2394
+ label: value.label,
2395
+ components
2396
+ })
2397
+ ]
2398
+ }, value.label)),
2399
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, {
2400
+ type: "button",
2401
+ onClick: onDismiss,
2402
+ children: "Done"
2403
+ }) })
2404
+ ]
2405
+ });
1629
2406
  }
1630
2407
  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
- ] });
2408
+ const { Button } = resolveAuthComponents(components);
2409
+ const [state, setState] = React.useState("idle");
2410
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
2411
+ type: "button",
2412
+ "aria-label": `Copy ${label}`,
2413
+ onClick: async () => {
2414
+ if (typeof navigator === "undefined" || typeof navigator.clipboard?.writeText !== "function") {
2415
+ setState("failed");
2416
+ return;
2417
+ }
2418
+ try {
2419
+ await navigator.clipboard.writeText(text);
2420
+ setState("copied");
2421
+ } catch {
2422
+ setState("failed");
2423
+ }
2424
+ },
2425
+ children: state === "copied" ? "Copied" : "Copy"
2426
+ }), state === "failed" && /* @__PURE__ */ jsx("span", {
2427
+ role: "status",
2428
+ children: " Copying is unavailable here; select the text and copy it manually."
2429
+ })] });
1656
2430
  }
2431
+ /** PT4H → "4 hours", P30D → "30 days", P1Y → "1 year". Unknown shapes are shown as given. */
1657
2432
  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;
2433
+ const match = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/.exec(spec);
2434
+ if (!match) return spec;
2435
+ const units = [
2436
+ "year",
2437
+ "month",
2438
+ "week",
2439
+ "day",
2440
+ "hour",
2441
+ "minute"
2442
+ ];
2443
+ const parts = match.slice(1).map((value, position) => value ? `${Number(value)} ${units[position]}${Number(value) === 1 ? "" : "s"}` : null).filter((part) => part !== null);
2444
+ return parts.length > 0 ? parts.join(" ") : spec;
1665
2445
  }
1666
2446
  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) };
2447
+ if (request !== void 0) {
2448
+ let result;
2449
+ try {
2450
+ result = await request(method, url, body);
2451
+ } catch {
2452
+ return {
2453
+ ok: false,
2454
+ status: 0,
2455
+ message: "The server could not be reached. Check the connection and try again."
2456
+ };
2457
+ }
2458
+ return result.ok ? {
2459
+ ok: true,
2460
+ status: result.status,
2461
+ data: unwrapData(result.payload)
2462
+ } : result;
2463
+ }
2464
+ let response;
2465
+ try {
2466
+ response = await fetch(url, {
2467
+ method,
2468
+ credentials: "same-origin",
2469
+ headers: {
2470
+ Accept: "application/json",
2471
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {},
2472
+ ...method !== "GET" ? { "X-CSRF-TOKEN": getCsrfToken(csrfToken) } : {}
2473
+ },
2474
+ body: body !== void 0 ? JSON.stringify(body) : void 0
2475
+ });
2476
+ } catch {
2477
+ return {
2478
+ ok: false,
2479
+ status: 0,
2480
+ message: "The server could not be reached. Check the connection and try again."
2481
+ };
2482
+ }
2483
+ const payload = await response.json().catch(() => null);
2484
+ if (response.ok) return {
2485
+ ok: true,
2486
+ status: response.status,
2487
+ data: unwrapData(payload)
2488
+ };
2489
+ return {
2490
+ ok: false,
2491
+ status: response.status,
2492
+ message: refusalMessage(response.status, payload)
2493
+ };
1696
2494
  }
1697
2495
  function unwrapData(payload) {
1698
- return typeof payload === "object" && payload !== null && "data" in payload ? payload.data : payload;
2496
+ return typeof payload === "object" && payload !== null && "data" in payload ? payload.data : payload;
1699
2497
  }
1700
2498
  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.";
2499
+ if (status === 401 || status === 419) return "Your session has expired. Reload the page and sign in again.";
2500
+ if (typeof payload === "object" && payload !== null) {
2501
+ const errors = payload.errors;
2502
+ if (errors && typeof errors === "object") {
2503
+ const first = Object.values(errors)[0];
2504
+ if (Array.isArray(first) && typeof first[0] === "string") return first[0];
2505
+ }
2506
+ const message = payload.message;
2507
+ if (typeof message === "string" && message !== "") return message;
2508
+ }
2509
+ if (status === 403) return "You do not have permission to do that.";
2510
+ if (status === 404) return "That credential no longer exists, or creating credentials is unavailable right now.";
2511
+ return "That action could not be completed.";
1724
2512
  }
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
1754
- };
2513
+ export { ApiCredentialsSection, ChangePasswordForm, LoginForm, PasskeyLoginButton, PasskeySection, PasswordConfirmationRequiredError, PasswordResetRequestForm, ResetPasswordForm, ScopePicker, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, closeImplications, confirmPasskey, confirmPasswordForPasskey, describeDuration, getCsrfToken, getDefaultPasskeyName, inCatalogOrder, isAbortError, isConditionalMediationAvailable, neededBy, registerPasskey, relyingApplicationsFrom, restrictImplications, safeApplicationHref, sameSelection, withScopes, withoutScopes };