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