bwh-auth 0.2.1 → 0.3.1

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/README.md CHANGED
@@ -23,6 +23,27 @@ The companion Laravel API package is
23
23
  - `PasskeyLoginButton`
24
24
  - `PasskeySection`
25
25
 
26
+ ## Relying-party helpers
27
+
28
+ `relyingApplicationsFrom(value)` validates the sibling-application list an identity provider
29
+ reports into one that is safe to render, and `safeApplicationHref(url)` is the scheme check
30
+ behind it. Neither touches the DOM, so an app can feed them a `#app-initial-data` payload, an
31
+ Inertia shared prop, or anything else it already has.
32
+
33
+ ```ts
34
+ import { relyingApplicationsFrom } from 'bwh-auth';
35
+
36
+ const applications = relyingApplicationsFrom(initialData.applications);
37
+ ```
38
+
39
+ Rendering these entries means putting provider-supplied text into an `href`. `javascript:`
40
+ and `data:` URLs pass a server-side URL-validity check but execute rather than navigate, so
41
+ the scheme is parsed rather than prefix-matched — a `startsWith` test can be walked past with
42
+ leading control characters or unexpected case — and the **parsed** form is returned, so what
43
+ is rendered is exactly what was validated. Unrecognised entries are dropped rather than
44
+ throwing: this is navigation chrome, and one malformed entry must not take down the page it
45
+ appears on.
46
+
26
47
  ## Install
27
48
 
28
49
  Install the published package from npm:
@@ -148,6 +169,21 @@ import { SignupForm, registerPasskey } from 'bwh-auth'
148
169
  />
149
170
  ```
150
171
 
172
+ Consumers can preserve app-specific login state and design-system checkboxes
173
+ without rebuilding the form:
174
+
175
+ ```tsx
176
+ <LoginForm
177
+ components={getShadcnComponents()}
178
+ initialEmail={verifiedEmail}
179
+ onEmailChange={setForgotPasswordEmail}
180
+ rememberMeCheckbox={Checkbox}
181
+ rememberMeLabel="Remember me"
182
+ rememberMeDataTest="login-remember-me"
183
+ onSubmitStart={clearLoginMessages}
184
+ />
185
+ ```
186
+
151
187
  The explicit passkey button and conditional autofill both default to the Laravel package routes:
152
188
 
153
189
  - `POST /api/passkeys/auth/options`
package/dist/index.cjs CHANGED
@@ -45,7 +45,9 @@ __export(index_exports, {
45
45
  getDefaultPasskeyName: () => getDefaultPasskeyName,
46
46
  isAbortError: () => isAbortError,
47
47
  isConditionalMediationAvailable: () => isConditionalMediationAvailable,
48
- registerPasskey: () => registerPasskey
48
+ registerPasskey: () => registerPasskey,
49
+ relyingApplicationsFrom: () => relyingApplicationsFrom,
50
+ safeApplicationHref: () => safeApplicationHref
49
51
  });
50
52
  module.exports = __toCommonJS(index_exports);
51
53
 
@@ -312,24 +314,50 @@ async function postForm(url, body, csrfToken) {
312
314
  },
313
315
  body: JSON.stringify(body)
314
316
  });
315
- const result = await response.json();
317
+ let decoded;
318
+ try {
319
+ decoded = await response.json();
320
+ } catch {
321
+ throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
322
+ }
323
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) {
324
+ throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
325
+ }
326
+ const result = decoded;
316
327
  if (!response.ok) {
317
328
  throw new AuthRequestError(result.message || result.error || "Request failed", result);
318
329
  }
319
330
  return result;
320
331
  }
332
+ function DefaultRememberMeCheckbox({ checked, onCheckedChange, ...props }) {
333
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
334
+ "input",
335
+ {
336
+ ...props,
337
+ type: "checkbox",
338
+ checked,
339
+ onChange: (event) => onCheckedChange(event.target.checked)
340
+ }
341
+ );
342
+ }
321
343
  function LoginForm({
322
344
  endpoints = {},
323
345
  components,
324
346
  onSuccess,
325
347
  onError,
348
+ initialEmail = "",
349
+ onEmailChange,
350
+ rememberMeCheckbox: RememberMeCheckbox = DefaultRememberMeCheckbox,
351
+ rememberMeLabel = "Keep me signed in",
352
+ rememberMeDataTest,
353
+ onSubmitStart,
326
354
  onTwoFactorRequired,
327
355
  onPasskeySuccess,
328
356
  enablePasskeys = false,
329
357
  enablePasskeyAutofill = enablePasskeys
330
358
  }) {
331
359
  const { Button, Card, CardContent, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
332
- const [email, setEmail] = React2.useState("");
360
+ const [email, setEmail] = React2.useState(initialEmail);
333
361
  const [password, setPassword] = React2.useState("");
334
362
  const [remember, setRemember] = React2.useState(false);
335
363
  const [loading, setLoading] = React2.useState(false);
@@ -373,6 +401,7 @@ function LoginForm({
373
401
  }, [enablePasskeyAutofill, onError, onPasskeySuccess, passkeyEndpoints]);
374
402
  async function onSubmit(event) {
375
403
  event.preventDefault();
404
+ onSubmitStart?.();
376
405
  setLoading(true);
377
406
  try {
378
407
  const result = await postForm(endpoints.login ?? "/login", { email, password, remember }, endpoints.csrfToken);
@@ -397,15 +426,37 @@ function LoginForm({
397
426
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("form", { className: "space-y-4", onSubmit: (event) => void onSubmit(event), children: [
398
427
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "space-y-1", children: [
399
428
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Label, { htmlFor: "login-email", children: "Email" }),
400
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Input, { id: "login-email", type: "email", autoComplete: conditionalPasskeyAvailable ? "username webauthn" : "email", required: true, value: email, onChange: (event) => setEmail(event.target.value) })
429
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
430
+ Input,
431
+ {
432
+ id: "login-email",
433
+ type: "email",
434
+ autoComplete: conditionalPasskeyAvailable ? "username webauthn" : "email",
435
+ required: true,
436
+ value: email,
437
+ onChange: (event) => {
438
+ setEmail(event.target.value);
439
+ onEmailChange?.(event.target.value);
440
+ }
441
+ }
442
+ )
401
443
  ] }),
402
444
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "space-y-1", children: [
403
445
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Label, { htmlFor: "login-password", children: "Password" }),
404
446
  /* @__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) })
405
447
  ] }),
406
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { className: "flex items-center gap-2 text-sm", children: [
407
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("input", { type: "checkbox", checked: remember, onChange: (event) => setRemember(event.target.checked) }),
408
- "Keep me signed in"
448
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-center gap-2 text-sm", children: [
449
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
450
+ RememberMeCheckbox,
451
+ {
452
+ id: "login-remember",
453
+ "aria-labelledby": "login-remember-label",
454
+ "data-test": rememberMeDataTest,
455
+ checked: remember,
456
+ onCheckedChange: setRemember
457
+ }
458
+ ),
459
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Label, { id: "login-remember-label", htmlFor: "login-remember", children: rememberMeLabel })
409
460
  ] }),
410
461
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Button, { type: "submit", className: "w-full", disabled: loading, children: loading ? "Signing in..." : "Sign In" })
411
462
  ] }),
@@ -831,6 +882,35 @@ function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
831
882
  ] })
832
883
  ] });
833
884
  }
885
+
886
+ // src/relying-applications.ts
887
+ function safeApplicationHref(url) {
888
+ try {
889
+ const parsed = new URL(url);
890
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.toString() : null;
891
+ } catch {
892
+ return null;
893
+ }
894
+ }
895
+ function relyingApplicationsFrom(value) {
896
+ if (!Array.isArray(value)) {
897
+ return [];
898
+ }
899
+ return value.flatMap((entry) => {
900
+ if (typeof entry !== "object" || entry === null) {
901
+ return [];
902
+ }
903
+ const { key, name, url } = entry;
904
+ if (typeof key !== "string" || typeof name !== "string" || typeof url !== "string") {
905
+ return [];
906
+ }
907
+ if (key === "" || name.trim() === "") {
908
+ return [];
909
+ }
910
+ const href = safeApplicationHref(url);
911
+ return href === null ? [] : [{ key, name: name.trim(), url: href }];
912
+ });
913
+ }
834
914
  // Annotate the CommonJS export names for ESM import in node:
835
915
  0 && (module.exports = {
836
916
  ChangePasswordForm,
@@ -848,5 +928,7 @@ function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
848
928
  getDefaultPasskeyName,
849
929
  isAbortError,
850
930
  isConditionalMediationAvailable,
851
- registerPasskey
931
+ registerPasskey,
932
+ relyingApplicationsFrom,
933
+ safeApplicationHref
852
934
  });
package/dist/index.d.cts CHANGED
@@ -1,4 +1,3 @@
1
- import * as react_jsx_runtime from 'react/jsx-runtime';
2
1
  import * as React from 'react';
3
2
 
4
3
  interface AuthEndpointConfig {
@@ -85,9 +84,22 @@ interface AuthFormProps {
85
84
  onSuccess?: (result: AuthJsonResponse) => void;
86
85
  onError?: (message: string) => void;
87
86
  }
87
+ interface LoginRememberMeCheckboxProps {
88
+ id: string;
89
+ checked: boolean;
90
+ onCheckedChange: (checked: boolean) => void;
91
+ 'aria-labelledby'?: string;
92
+ 'data-test'?: string;
93
+ }
88
94
  interface LoginFormProps extends AuthFormProps {
89
95
  enablePasskeys?: boolean;
90
96
  enablePasskeyAutofill?: boolean;
97
+ initialEmail?: string;
98
+ onEmailChange?: (email: string) => void;
99
+ rememberMeCheckbox?: React.ComponentType<LoginRememberMeCheckboxProps>;
100
+ rememberMeLabel?: React.ReactNode;
101
+ rememberMeDataTest?: string;
102
+ onSubmitStart?: () => void;
91
103
  onTwoFactorRequired?: (result: AuthJsonResponse & {
92
104
  attempt_token?: string;
93
105
  }) => void;
@@ -113,12 +125,12 @@ interface TwoFactorFormProps extends AuthFormProps {
113
125
  appEnv?: string;
114
126
  onReportSuspicious?: (result: AuthJsonResponse) => void;
115
127
  }
116
- declare function LoginForm({ endpoints, components, onSuccess, onError, onTwoFactorRequired, onPasskeySuccess, enablePasskeys, enablePasskeyAutofill, }: LoginFormProps): react_jsx_runtime.JSX.Element;
117
- declare function SignupForm({ endpoints, components, onSuccess, onError, fields, initialValues, errors, submitMode, title, description, submitLabel, submittingLabel, }: SignupFormProps): react_jsx_runtime.JSX.Element;
118
- declare function PasswordResetRequestForm({ endpoints, components, onSuccess, onError }: AuthFormProps): react_jsx_runtime.JSX.Element;
119
- declare function ResetPasswordForm({ endpoints, components, onSuccess, onError, token: initialToken, email: initialEmail }: ResetPasswordFormProps): react_jsx_runtime.JSX.Element;
120
- declare function ChangePasswordForm({ endpoints, components, onSuccess, onError }: AuthFormProps): react_jsx_runtime.JSX.Element;
121
- declare function TwoFactorForm({ endpoints, components, attemptToken, appEnv, onSuccess, onError, onReportSuspicious }: TwoFactorFormProps): react_jsx_runtime.JSX.Element;
128
+ declare function LoginForm({ endpoints, components, onSuccess, onError, initialEmail, onEmailChange, rememberMeCheckbox: RememberMeCheckbox, rememberMeLabel, rememberMeDataTest, onSubmitStart, onTwoFactorRequired, onPasskeySuccess, enablePasskeys, enablePasskeyAutofill, }: LoginFormProps): React.JSX.Element;
129
+ declare function SignupForm({ endpoints, components, onSuccess, onError, fields, initialValues, errors, submitMode, title, description, submitLabel, submittingLabel, }: SignupFormProps): React.JSX.Element;
130
+ declare function PasswordResetRequestForm({ endpoints, components, onSuccess, onError }: AuthFormProps): React.JSX.Element;
131
+ declare function ResetPasswordForm({ endpoints, components, onSuccess, onError, token: initialToken, email: initialEmail }: ResetPasswordFormProps): React.JSX.Element;
132
+ declare function ChangePasswordForm({ endpoints, components, onSuccess, onError }: AuthFormProps): React.JSX.Element;
133
+ declare function TwoFactorForm({ endpoints, components, attemptToken, appEnv, onSuccess, onError, onReportSuspicious }: TwoFactorFormProps): React.JSX.Element;
122
134
 
123
135
  interface PasskeyLoginButtonProps {
124
136
  endpoints?: AuthEndpointConfig;
@@ -127,7 +139,7 @@ interface PasskeyLoginButtonProps {
127
139
  onSuccess?: (redirectUrl: string, result: AuthJsonResponse) => void;
128
140
  onError?: (message: string) => void;
129
141
  }
130
- declare function PasskeyLoginButton({ endpoints, components, className, onSuccess, onError }: PasskeyLoginButtonProps): react_jsx_runtime.JSX.Element | null;
142
+ declare function PasskeyLoginButton({ endpoints, components, className, onSuccess, onError }: PasskeyLoginButtonProps): React.JSX.Element | null;
131
143
 
132
144
  interface PasskeySectionProps {
133
145
  endpoints?: AuthEndpointConfig;
@@ -135,7 +147,45 @@ interface PasskeySectionProps {
135
147
  onSuccess?: (message: string) => void;
136
148
  onError?: (field: string, message: string) => void;
137
149
  }
138
- declare function PasskeySection({ endpoints, components, onSuccess, onError }: PasskeySectionProps): react_jsx_runtime.JSX.Element;
150
+ declare function PasskeySection({ endpoints, components, onSuccess, onError }: PasskeySectionProps): React.JSX.Element;
151
+
152
+ /**
153
+ * The sibling applications an identity provider reports for the signed-in person.
154
+ *
155
+ * Every relying party receives this list the same way — server-side, injected per request
156
+ * from the session rather than compiled into a bundle — but each one carries it into the
157
+ * page differently: a `#app-initial-data` script tag, an Inertia shared prop, a Blade loop.
158
+ * What they cannot afford to do differently is decide which entries are safe to render, so
159
+ * that decision lives here and the transport stays the application's business.
160
+ */
161
+ interface RelyingApplication {
162
+ key: string;
163
+ name: string;
164
+ url: string;
165
+ }
166
+ /**
167
+ * Reduce a URL from the wire to one that is safe to put in an `href`, or reject it.
168
+ *
169
+ * These arrive as text in the page and end up as a link the browser will follow, so the
170
+ * scheme is what matters: `javascript:` and `data:` both pass a server-side URL validity
171
+ * check but execute rather than navigate. Parsing and allowing only http(s) is stronger
172
+ * than matching a prefix — it normalises away the leading control characters, mixed case,
173
+ * and escapes that a hand-rolled test can be walked past — and it returns the *parsed*
174
+ * form, so what gets rendered is exactly what was validated.
175
+ *
176
+ * Absolute URLs only, deliberately. These point at other origins; a relative one means the
177
+ * provider told us something unexpected, and guessing a base for it would be inventing a
178
+ * destination rather than validating one.
179
+ */
180
+ declare function safeApplicationHref(url: string): string | null;
181
+ /**
182
+ * Validate whatever the page handed over into a list that is safe to render.
183
+ *
184
+ * Unrecognised entries are dropped rather than throwing. This is navigation chrome: one
185
+ * malformed entry, or a provider that has grown a field, must not be able to take down the
186
+ * page it appears on. Anything that is not a well-formed list degrades to an empty menu.
187
+ */
188
+ declare function relyingApplicationsFrom(value: unknown): RelyingApplication[];
139
189
 
140
190
  declare function getCsrfToken(explicitToken?: string): string;
141
191
  declare function base64urlToArrayBuffer(b64: string): ArrayBuffer;
@@ -163,4 +213,4 @@ declare function isConditionalMediationAvailable(): Promise<boolean>;
163
213
  declare function authenticateWithPasskey({ endpoints, mediation, signal }?: AuthenticateWithPasskeyOptions): Promise<PasskeyAuthenticationResult>;
164
214
  declare function registerPasskey({ endpoints, name, signal }?: RegisterPasskeyOptions): Promise<PasskeyRegistrationResult>;
165
215
 
166
- export { type AuthButtonComponent, type AuthButtonComponentInput, type AuthButtonComponentProps, type AuthButtonSize, type AuthButtonVariant, type AuthComponentInput, type AuthComponentOverrides, type AuthComponentSet, type AuthComponentSuperset, type AuthComponents, type AuthContainerComponentProps, type AuthEndpointConfig, type AuthInputComponentProps, type AuthJsonResponse, type AuthLabelComponentProps, type AuthSignupField, type AuthSignupValues, type AuthValidationErrors, ChangePasswordForm, LoginForm, type Passkey, PasskeyLoginButton, PasskeySection, PasswordResetRequestForm, ResetPasswordForm, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, getCsrfToken, getDefaultPasskeyName, isAbortError, isConditionalMediationAvailable, registerPasskey };
216
+ export { type AuthButtonComponent, type AuthButtonComponentInput, type AuthButtonComponentProps, type AuthButtonSize, type AuthButtonVariant, type AuthComponentInput, type AuthComponentOverrides, type AuthComponentSet, type AuthComponentSuperset, type AuthComponents, type AuthContainerComponentProps, type AuthEndpointConfig, type AuthInputComponentProps, type AuthJsonResponse, type AuthLabelComponentProps, type AuthSignupField, type AuthSignupValues, type AuthValidationErrors, ChangePasswordForm, LoginForm, type LoginFormProps, type LoginRememberMeCheckboxProps, type Passkey, PasskeyLoginButton, PasskeySection, PasswordResetRequestForm, type RelyingApplication, ResetPasswordForm, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, getCsrfToken, getDefaultPasskeyName, isAbortError, isConditionalMediationAvailable, registerPasskey, relyingApplicationsFrom, safeApplicationHref };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import * as react_jsx_runtime from 'react/jsx-runtime';
2
1
  import * as React from 'react';
3
2
 
4
3
  interface AuthEndpointConfig {
@@ -85,9 +84,22 @@ interface AuthFormProps {
85
84
  onSuccess?: (result: AuthJsonResponse) => void;
86
85
  onError?: (message: string) => void;
87
86
  }
87
+ interface LoginRememberMeCheckboxProps {
88
+ id: string;
89
+ checked: boolean;
90
+ onCheckedChange: (checked: boolean) => void;
91
+ 'aria-labelledby'?: string;
92
+ 'data-test'?: string;
93
+ }
88
94
  interface LoginFormProps extends AuthFormProps {
89
95
  enablePasskeys?: boolean;
90
96
  enablePasskeyAutofill?: boolean;
97
+ initialEmail?: string;
98
+ onEmailChange?: (email: string) => void;
99
+ rememberMeCheckbox?: React.ComponentType<LoginRememberMeCheckboxProps>;
100
+ rememberMeLabel?: React.ReactNode;
101
+ rememberMeDataTest?: string;
102
+ onSubmitStart?: () => void;
91
103
  onTwoFactorRequired?: (result: AuthJsonResponse & {
92
104
  attempt_token?: string;
93
105
  }) => void;
@@ -113,12 +125,12 @@ interface TwoFactorFormProps extends AuthFormProps {
113
125
  appEnv?: string;
114
126
  onReportSuspicious?: (result: AuthJsonResponse) => void;
115
127
  }
116
- declare function LoginForm({ endpoints, components, onSuccess, onError, onTwoFactorRequired, onPasskeySuccess, enablePasskeys, enablePasskeyAutofill, }: LoginFormProps): react_jsx_runtime.JSX.Element;
117
- declare function SignupForm({ endpoints, components, onSuccess, onError, fields, initialValues, errors, submitMode, title, description, submitLabel, submittingLabel, }: SignupFormProps): react_jsx_runtime.JSX.Element;
118
- declare function PasswordResetRequestForm({ endpoints, components, onSuccess, onError }: AuthFormProps): react_jsx_runtime.JSX.Element;
119
- declare function ResetPasswordForm({ endpoints, components, onSuccess, onError, token: initialToken, email: initialEmail }: ResetPasswordFormProps): react_jsx_runtime.JSX.Element;
120
- declare function ChangePasswordForm({ endpoints, components, onSuccess, onError }: AuthFormProps): react_jsx_runtime.JSX.Element;
121
- declare function TwoFactorForm({ endpoints, components, attemptToken, appEnv, onSuccess, onError, onReportSuspicious }: TwoFactorFormProps): react_jsx_runtime.JSX.Element;
128
+ declare function LoginForm({ endpoints, components, onSuccess, onError, initialEmail, onEmailChange, rememberMeCheckbox: RememberMeCheckbox, rememberMeLabel, rememberMeDataTest, onSubmitStart, onTwoFactorRequired, onPasskeySuccess, enablePasskeys, enablePasskeyAutofill, }: LoginFormProps): React.JSX.Element;
129
+ declare function SignupForm({ endpoints, components, onSuccess, onError, fields, initialValues, errors, submitMode, title, description, submitLabel, submittingLabel, }: SignupFormProps): React.JSX.Element;
130
+ declare function PasswordResetRequestForm({ endpoints, components, onSuccess, onError }: AuthFormProps): React.JSX.Element;
131
+ declare function ResetPasswordForm({ endpoints, components, onSuccess, onError, token: initialToken, email: initialEmail }: ResetPasswordFormProps): React.JSX.Element;
132
+ declare function ChangePasswordForm({ endpoints, components, onSuccess, onError }: AuthFormProps): React.JSX.Element;
133
+ declare function TwoFactorForm({ endpoints, components, attemptToken, appEnv, onSuccess, onError, onReportSuspicious }: TwoFactorFormProps): React.JSX.Element;
122
134
 
123
135
  interface PasskeyLoginButtonProps {
124
136
  endpoints?: AuthEndpointConfig;
@@ -127,7 +139,7 @@ interface PasskeyLoginButtonProps {
127
139
  onSuccess?: (redirectUrl: string, result: AuthJsonResponse) => void;
128
140
  onError?: (message: string) => void;
129
141
  }
130
- declare function PasskeyLoginButton({ endpoints, components, className, onSuccess, onError }: PasskeyLoginButtonProps): react_jsx_runtime.JSX.Element | null;
142
+ declare function PasskeyLoginButton({ endpoints, components, className, onSuccess, onError }: PasskeyLoginButtonProps): React.JSX.Element | null;
131
143
 
132
144
  interface PasskeySectionProps {
133
145
  endpoints?: AuthEndpointConfig;
@@ -135,7 +147,45 @@ interface PasskeySectionProps {
135
147
  onSuccess?: (message: string) => void;
136
148
  onError?: (field: string, message: string) => void;
137
149
  }
138
- declare function PasskeySection({ endpoints, components, onSuccess, onError }: PasskeySectionProps): react_jsx_runtime.JSX.Element;
150
+ declare function PasskeySection({ endpoints, components, onSuccess, onError }: PasskeySectionProps): React.JSX.Element;
151
+
152
+ /**
153
+ * The sibling applications an identity provider reports for the signed-in person.
154
+ *
155
+ * Every relying party receives this list the same way — server-side, injected per request
156
+ * from the session rather than compiled into a bundle — but each one carries it into the
157
+ * page differently: a `#app-initial-data` script tag, an Inertia shared prop, a Blade loop.
158
+ * What they cannot afford to do differently is decide which entries are safe to render, so
159
+ * that decision lives here and the transport stays the application's business.
160
+ */
161
+ interface RelyingApplication {
162
+ key: string;
163
+ name: string;
164
+ url: string;
165
+ }
166
+ /**
167
+ * Reduce a URL from the wire to one that is safe to put in an `href`, or reject it.
168
+ *
169
+ * These arrive as text in the page and end up as a link the browser will follow, so the
170
+ * scheme is what matters: `javascript:` and `data:` both pass a server-side URL validity
171
+ * check but execute rather than navigate. Parsing and allowing only http(s) is stronger
172
+ * than matching a prefix — it normalises away the leading control characters, mixed case,
173
+ * and escapes that a hand-rolled test can be walked past — and it returns the *parsed*
174
+ * form, so what gets rendered is exactly what was validated.
175
+ *
176
+ * Absolute URLs only, deliberately. These point at other origins; a relative one means the
177
+ * provider told us something unexpected, and guessing a base for it would be inventing a
178
+ * destination rather than validating one.
179
+ */
180
+ declare function safeApplicationHref(url: string): string | null;
181
+ /**
182
+ * Validate whatever the page handed over into a list that is safe to render.
183
+ *
184
+ * Unrecognised entries are dropped rather than throwing. This is navigation chrome: one
185
+ * malformed entry, or a provider that has grown a field, must not be able to take down the
186
+ * page it appears on. Anything that is not a well-formed list degrades to an empty menu.
187
+ */
188
+ declare function relyingApplicationsFrom(value: unknown): RelyingApplication[];
139
189
 
140
190
  declare function getCsrfToken(explicitToken?: string): string;
141
191
  declare function base64urlToArrayBuffer(b64: string): ArrayBuffer;
@@ -163,4 +213,4 @@ declare function isConditionalMediationAvailable(): Promise<boolean>;
163
213
  declare function authenticateWithPasskey({ endpoints, mediation, signal }?: AuthenticateWithPasskeyOptions): Promise<PasskeyAuthenticationResult>;
164
214
  declare function registerPasskey({ endpoints, name, signal }?: RegisterPasskeyOptions): Promise<PasskeyRegistrationResult>;
165
215
 
166
- export { type AuthButtonComponent, type AuthButtonComponentInput, type AuthButtonComponentProps, type AuthButtonSize, type AuthButtonVariant, type AuthComponentInput, type AuthComponentOverrides, type AuthComponentSet, type AuthComponentSuperset, type AuthComponents, type AuthContainerComponentProps, type AuthEndpointConfig, type AuthInputComponentProps, type AuthJsonResponse, type AuthLabelComponentProps, type AuthSignupField, type AuthSignupValues, type AuthValidationErrors, ChangePasswordForm, LoginForm, type Passkey, PasskeyLoginButton, PasskeySection, PasswordResetRequestForm, ResetPasswordForm, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, getCsrfToken, getDefaultPasskeyName, isAbortError, isConditionalMediationAvailable, registerPasskey };
216
+ export { type AuthButtonComponent, type AuthButtonComponentInput, type AuthButtonComponentProps, type AuthButtonSize, type AuthButtonVariant, type AuthComponentInput, type AuthComponentOverrides, type AuthComponentSet, type AuthComponentSuperset, type AuthComponents, type AuthContainerComponentProps, type AuthEndpointConfig, type AuthInputComponentProps, type AuthJsonResponse, type AuthLabelComponentProps, type AuthSignupField, type AuthSignupValues, type AuthValidationErrors, ChangePasswordForm, LoginForm, type LoginFormProps, type LoginRememberMeCheckboxProps, type Passkey, PasskeyLoginButton, PasskeySection, PasswordResetRequestForm, type RelyingApplication, ResetPasswordForm, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, getCsrfToken, getDefaultPasskeyName, isAbortError, isConditionalMediationAvailable, registerPasskey, relyingApplicationsFrom, safeApplicationHref };
package/dist/index.js CHANGED
@@ -261,24 +261,50 @@ async function postForm(url, body, csrfToken) {
261
261
  },
262
262
  body: JSON.stringify(body)
263
263
  });
264
- const result = await response.json();
264
+ let decoded;
265
+ try {
266
+ decoded = await response.json();
267
+ } catch {
268
+ throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
269
+ }
270
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) {
271
+ throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
272
+ }
273
+ const result = decoded;
265
274
  if (!response.ok) {
266
275
  throw new AuthRequestError(result.message || result.error || "Request failed", result);
267
276
  }
268
277
  return result;
269
278
  }
279
+ function DefaultRememberMeCheckbox({ checked, onCheckedChange, ...props }) {
280
+ return /* @__PURE__ */ jsx2(
281
+ "input",
282
+ {
283
+ ...props,
284
+ type: "checkbox",
285
+ checked,
286
+ onChange: (event) => onCheckedChange(event.target.checked)
287
+ }
288
+ );
289
+ }
270
290
  function LoginForm({
271
291
  endpoints = {},
272
292
  components,
273
293
  onSuccess,
274
294
  onError,
295
+ initialEmail = "",
296
+ onEmailChange,
297
+ rememberMeCheckbox: RememberMeCheckbox = DefaultRememberMeCheckbox,
298
+ rememberMeLabel = "Keep me signed in",
299
+ rememberMeDataTest,
300
+ onSubmitStart,
275
301
  onTwoFactorRequired,
276
302
  onPasskeySuccess,
277
303
  enablePasskeys = false,
278
304
  enablePasskeyAutofill = enablePasskeys
279
305
  }) {
280
306
  const { Button, Card, CardContent, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
281
- const [email, setEmail] = React2.useState("");
307
+ const [email, setEmail] = React2.useState(initialEmail);
282
308
  const [password, setPassword] = React2.useState("");
283
309
  const [remember, setRemember] = React2.useState(false);
284
310
  const [loading, setLoading] = React2.useState(false);
@@ -322,6 +348,7 @@ function LoginForm({
322
348
  }, [enablePasskeyAutofill, onError, onPasskeySuccess, passkeyEndpoints]);
323
349
  async function onSubmit(event) {
324
350
  event.preventDefault();
351
+ onSubmitStart?.();
325
352
  setLoading(true);
326
353
  try {
327
354
  const result = await postForm(endpoints.login ?? "/login", { email, password, remember }, endpoints.csrfToken);
@@ -346,15 +373,37 @@ function LoginForm({
346
373
  /* @__PURE__ */ jsxs2("form", { className: "space-y-4", onSubmit: (event) => void onSubmit(event), children: [
347
374
  /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
348
375
  /* @__PURE__ */ jsx2(Label, { htmlFor: "login-email", children: "Email" }),
349
- /* @__PURE__ */ jsx2(Input, { id: "login-email", type: "email", autoComplete: conditionalPasskeyAvailable ? "username webauthn" : "email", required: true, value: email, onChange: (event) => setEmail(event.target.value) })
376
+ /* @__PURE__ */ jsx2(
377
+ Input,
378
+ {
379
+ id: "login-email",
380
+ type: "email",
381
+ autoComplete: conditionalPasskeyAvailable ? "username webauthn" : "email",
382
+ required: true,
383
+ value: email,
384
+ onChange: (event) => {
385
+ setEmail(event.target.value);
386
+ onEmailChange?.(event.target.value);
387
+ }
388
+ }
389
+ )
350
390
  ] }),
351
391
  /* @__PURE__ */ jsxs2("div", { className: "space-y-1", children: [
352
392
  /* @__PURE__ */ jsx2(Label, { htmlFor: "login-password", children: "Password" }),
353
393
  /* @__PURE__ */ jsx2(Input, { id: "login-password", type: "password", autoComplete: "current-password", required: true, value: password, onChange: (event) => setPassword(event.target.value) })
354
394
  ] }),
355
- /* @__PURE__ */ jsxs2("label", { className: "flex items-center gap-2 text-sm", children: [
356
- /* @__PURE__ */ jsx2("input", { type: "checkbox", checked: remember, onChange: (event) => setRemember(event.target.checked) }),
357
- "Keep me signed in"
395
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2 text-sm", children: [
396
+ /* @__PURE__ */ jsx2(
397
+ RememberMeCheckbox,
398
+ {
399
+ id: "login-remember",
400
+ "aria-labelledby": "login-remember-label",
401
+ "data-test": rememberMeDataTest,
402
+ checked: remember,
403
+ onCheckedChange: setRemember
404
+ }
405
+ ),
406
+ /* @__PURE__ */ jsx2(Label, { id: "login-remember-label", htmlFor: "login-remember", children: rememberMeLabel })
358
407
  ] }),
359
408
  /* @__PURE__ */ jsx2(Button, { type: "submit", className: "w-full", disabled: loading, children: loading ? "Signing in..." : "Sign In" })
360
409
  ] }),
@@ -780,6 +829,35 @@ function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
780
829
  ] })
781
830
  ] });
782
831
  }
832
+
833
+ // src/relying-applications.ts
834
+ function safeApplicationHref(url) {
835
+ try {
836
+ const parsed = new URL(url);
837
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.toString() : null;
838
+ } catch {
839
+ return null;
840
+ }
841
+ }
842
+ function relyingApplicationsFrom(value) {
843
+ if (!Array.isArray(value)) {
844
+ return [];
845
+ }
846
+ return value.flatMap((entry) => {
847
+ if (typeof entry !== "object" || entry === null) {
848
+ return [];
849
+ }
850
+ const { key, name, url } = entry;
851
+ if (typeof key !== "string" || typeof name !== "string" || typeof url !== "string") {
852
+ return [];
853
+ }
854
+ if (key === "" || name.trim() === "") {
855
+ return [];
856
+ }
857
+ const href = safeApplicationHref(url);
858
+ return href === null ? [] : [{ key, name: name.trim(), url: href }];
859
+ });
860
+ }
783
861
  export {
784
862
  ChangePasswordForm,
785
863
  LoginForm,
@@ -796,5 +874,7 @@ export {
796
874
  getDefaultPasskeyName,
797
875
  isAbortError,
798
876
  isConditionalMediationAvailable,
799
- registerPasskey
877
+ registerPasskey,
878
+ relyingApplicationsFrom,
879
+ safeApplicationHref
800
880
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bwh-auth",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Shared React auth UI and browser WebAuthn helpers for BWH applications.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -30,8 +30,10 @@
30
30
  "scripts": {
31
31
  "build": "tsup src/index.ts --format esm,cjs --dts --dts-resolve",
32
32
  "release": "node scripts/release.mjs",
33
+ "test": "vitest run",
33
34
  "typecheck": "tsc --noEmit",
34
- "prepare": "pnpm run build"
35
+ "prepare": "pnpm run build",
36
+ "postinstall": "node scripts/spotlight-noindex.mjs"
35
37
  },
36
38
  "peerDependencies": {
37
39
  "lucide-react": ">=0.468.0 <2.0.0",
@@ -39,13 +41,19 @@
39
41
  "react-dom": "^18.3.0 || ^19.0.0"
40
42
  },
41
43
  "devDependencies": {
42
- "@types/react": "^19.2.14",
43
- "@types/react-dom": "^19.2.3",
44
+ "@testing-library/dom": "^10.4.2",
45
+ "@testing-library/react": "^16.3.3",
46
+ "@types/node": "^26.4.1",
47
+ "@types/react": "^19.2.18",
48
+ "@types/react-dom": "^19.2.7",
44
49
  "esbuild": "0.28.2",
50
+ "jsdom": "^27.4.0",
45
51
  "lucide-react": "^0.577.0",
46
- "react": "^19.2.6",
47
- "react-dom": "^19.2.6",
52
+ "react": "^19.2.8",
53
+ "react-dom": "^19.2.8",
54
+ "spotlight-noindex": "1.1.1",
48
55
  "tsup": "^8.5.1",
49
- "typescript": "^5.9.3"
56
+ "typescript": "^5.9.3",
57
+ "vitest": "^3.2.7"
50
58
  }
51
59
  }