@udibo/oauth2 0.53.0 → 0.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/SECURITY.md +3 -3
- package/dist/identity/events.d.ts +1 -1
- package/dist/identity/lockout.d.ts +52 -2
- package/dist/identity/lockout.js +36 -0
- package/dist/identity/migration.d.ts +62 -5
- package/dist/identity/migration.js +62 -4
- package/dist/identity/service.d.ts +7 -1
- package/dist/identity/service.js +52 -10
- package/dist/react/components/account-internal.d.ts +45 -0
- package/dist/react/components/account-internal.js +111 -0
- package/dist/react/components/change-password-form.d.ts +171 -0
- package/dist/react/components/change-password-form.js +130 -0
- package/dist/react/components/class-names.d.ts +3 -2
- package/dist/react/components/class-names.js +3 -2
- package/dist/react/components/internal.d.ts +1 -0
- package/dist/react/components/internal.js +2 -2
- package/dist/react/components/linked-accounts.d.ts +212 -0
- package/dist/react/components/linked-accounts.js +98 -0
- package/dist/react/components/mod.d.ts +12 -1
- package/dist/react/components/mod.js +8 -0
- package/dist/react/components/session-list.d.ts +204 -0
- package/dist/react/components/session-list.js +86 -0
- package/dist/react/components/types.d.ts +23 -3
- package/dist/testing/contract/lockout-store.d.ts +9 -2
- package/dist/testing/contract/lockout-store.js +97 -2
- package/package.json +1 -1
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* {@link ChangePasswordForm} — a default, accessible, unstyled form for a
|
|
3
|
+
* signed-in person to change their password, or to set a first one on an
|
|
4
|
+
* account that signs in without a password. Built on {@link useAuthForm}: it
|
|
5
|
+
* collects the passwords, checks the confirmation and length on the client,
|
|
6
|
+
* and hands the values to your `onSubmit`.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import { type ReactNode } from "react";
|
|
11
|
+
import type { AuthFormState } from "./use-auth-form.ts";
|
|
12
|
+
import type { BaseAuthFormProps } from "./types.ts";
|
|
13
|
+
/** Values collected by {@link ChangePasswordForm}. */
|
|
14
|
+
export type ChangePasswordValues = {
|
|
15
|
+
/**
|
|
16
|
+
* The current password. Always `""` when `hasPassword` is `false`, since
|
|
17
|
+
* the field is not rendered.
|
|
18
|
+
*/
|
|
19
|
+
currentPassword: string;
|
|
20
|
+
/** The new password. */
|
|
21
|
+
newPassword: string;
|
|
22
|
+
/** Confirmation of the new password; the form blocks a mismatch. */
|
|
23
|
+
confirmPassword: string;
|
|
24
|
+
/**
|
|
25
|
+
* Whether to sign out the account's other sessions with the change. Fixed
|
|
26
|
+
* by the `revokeOtherSessions` prop unless it is `"optional"`, when the
|
|
27
|
+
* person's checkbox decides.
|
|
28
|
+
*/
|
|
29
|
+
revokeOtherSessions: boolean;
|
|
30
|
+
};
|
|
31
|
+
/** Visible text overrides for {@link ChangePasswordForm}. */
|
|
32
|
+
export interface ChangePasswordLabels {
|
|
33
|
+
/** Label for the current-password field. Default: `"Current password"`. */
|
|
34
|
+
currentPassword?: string;
|
|
35
|
+
/** Label for the new-password field. Default: `"New password"`. */
|
|
36
|
+
newPassword?: string;
|
|
37
|
+
/** Label for the confirmation field. Default: `"Confirm new password"`. */
|
|
38
|
+
confirmPassword?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Submit button text. Default: `"Update password"`, or `"Set password"`
|
|
41
|
+
* when `hasPassword` is `false`.
|
|
42
|
+
*/
|
|
43
|
+
submit?: string;
|
|
44
|
+
/**
|
|
45
|
+
* Submit button text while submitting. Default: `"Updating…"`, or
|
|
46
|
+
* `"Setting…"` when `hasPassword` is `false`.
|
|
47
|
+
*/
|
|
48
|
+
submitting?: string;
|
|
49
|
+
/** Mismatch message on the confirmation field. Default: `"Passwords do not match."`. */
|
|
50
|
+
passwordMismatch?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Message on the new-password field when it is shorter than `minLength`.
|
|
53
|
+
* Default: `"Use at least {minLength} characters."`.
|
|
54
|
+
*/
|
|
55
|
+
tooShort?: string;
|
|
56
|
+
/**
|
|
57
|
+
* Label of the checkbox shown when `revokeOtherSessions` is `"optional"`.
|
|
58
|
+
* Default: `"Sign out of my other sessions"`.
|
|
59
|
+
*/
|
|
60
|
+
revokeOtherSessions?: string;
|
|
61
|
+
/**
|
|
62
|
+
* Text under the fields when `revokeOtherSessions` is `true`. Default:
|
|
63
|
+
* `"Your other sessions will be signed out."`. Pass `""` to show none.
|
|
64
|
+
*/
|
|
65
|
+
revokeOtherSessionsNotice?: string;
|
|
66
|
+
/**
|
|
67
|
+
* Status message after a successful submit. Default: `"Password updated."`,
|
|
68
|
+
* or `"Password set."` when `hasPassword` is `false`.
|
|
69
|
+
*/
|
|
70
|
+
success?: string;
|
|
71
|
+
}
|
|
72
|
+
/** Props for {@link ChangePasswordForm}. */
|
|
73
|
+
export interface ChangePasswordFormProps extends BaseAuthFormProps<ChangePasswordValues> {
|
|
74
|
+
/**
|
|
75
|
+
* Whether the account has a password now. Default: `true`, which asks for
|
|
76
|
+
* the current password. Pass `false` for an account that signs in another
|
|
77
|
+
* way — a social account, a passkey or an emailed code — to set a first
|
|
78
|
+
* password: the current-password field is dropped and the button reads
|
|
79
|
+
* "Set password". Confirm it is the account owner on your server before
|
|
80
|
+
* setting one, since no current password proves it.
|
|
81
|
+
*
|
|
82
|
+
* Your server decides between setting and changing from the account it has
|
|
83
|
+
* stored, never from this prop or an empty `currentPassword`: refuse a
|
|
84
|
+
* request without the current password for an account that has one.
|
|
85
|
+
* Should it return `fieldErrors.currentPassword` anyway — `hasPassword` was
|
|
86
|
+
* stale — the form shows that message in its error summary, since there is
|
|
87
|
+
* no field to attach it to.
|
|
88
|
+
*/
|
|
89
|
+
hasPassword?: boolean;
|
|
90
|
+
/**
|
|
91
|
+
* What happens to the account's other sessions. Default: `true` — the
|
|
92
|
+
* change signs them out, the form says so, and `onSubmit` receives
|
|
93
|
+
* `revokeOtherSessions: true`. `"optional"` renders a checkbox, checked to
|
|
94
|
+
* start, so the person decides. `false` keeps them and says nothing. Your
|
|
95
|
+
* server performs the sign-out; this only states and forwards the intent.
|
|
96
|
+
*
|
|
97
|
+
* A no-JavaScript post carries the same choice as `revokeOtherSessions`:
|
|
98
|
+
* `"true"` or `"false"` from a hidden field when the prop fixes it, or
|
|
99
|
+
* `"true"` from the checked checkbox (absent when unchecked) in
|
|
100
|
+
* `"optional"` mode.
|
|
101
|
+
*/
|
|
102
|
+
revokeOtherSessions?: boolean | "optional";
|
|
103
|
+
/**
|
|
104
|
+
* Shortest new password to accept. Sets the field's `minlength` and blocks
|
|
105
|
+
* a shorter one on the client. Enforce your password policy on the server
|
|
106
|
+
* too; this only saves a round trip.
|
|
107
|
+
*/
|
|
108
|
+
minLength?: number;
|
|
109
|
+
/** Text overrides. */
|
|
110
|
+
labels?: ChangePasswordLabels;
|
|
111
|
+
/**
|
|
112
|
+
* Render-prop escape hatch. When provided, you own the markup and receive
|
|
113
|
+
* the live {@link AuthFormState}; the component still owns state, the
|
|
114
|
+
* client-side checks and submit.
|
|
115
|
+
*/
|
|
116
|
+
children?: (state: AuthFormState<ChangePasswordValues>) => ReactNode;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* A ready-to-use change-password form, which also sets a first password on an
|
|
120
|
+
* account without one (`hasPassword={false}`). Wire `onSubmit` to your server
|
|
121
|
+
* and return `{ fieldErrors: { currentPassword: "…" } }` for a wrong current
|
|
122
|
+
* password, or `{ fieldErrors: { newPassword: "…" } }` for one your policy
|
|
123
|
+
* refuses; focus moves to the first errored field.
|
|
124
|
+
*
|
|
125
|
+
* After a successful submit the password fields are cleared and a status
|
|
126
|
+
* message appears above the form, which stays in place.
|
|
127
|
+
*
|
|
128
|
+
* @example Change a password, signing out other sessions
|
|
129
|
+
* ```tsx
|
|
130
|
+
* import { ChangePasswordForm } from "@udibo/oauth2/react/components";
|
|
131
|
+
*
|
|
132
|
+
* function ChangePassword() {
|
|
133
|
+
* return (
|
|
134
|
+
* <ChangePasswordForm
|
|
135
|
+
* minLength={12}
|
|
136
|
+
* onSubmit={async (values) => {
|
|
137
|
+
* const response = await fetch("/account/password", {
|
|
138
|
+
* method: "POST",
|
|
139
|
+
* headers: { "content-type": "application/json" },
|
|
140
|
+
* body: JSON.stringify(values),
|
|
141
|
+
* });
|
|
142
|
+
* if (!response.ok) return await response.json();
|
|
143
|
+
* }}
|
|
144
|
+
* />
|
|
145
|
+
* );
|
|
146
|
+
* }
|
|
147
|
+
* ```
|
|
148
|
+
*
|
|
149
|
+
* @example Set a first password on a social or passkey account
|
|
150
|
+
* ```tsx
|
|
151
|
+
* import { ChangePasswordForm } from "@udibo/oauth2/react/components";
|
|
152
|
+
*
|
|
153
|
+
* function SetPassword(props: { hasPassword: boolean }) {
|
|
154
|
+
* return (
|
|
155
|
+
* <ChangePasswordForm
|
|
156
|
+
* hasPassword={props.hasPassword}
|
|
157
|
+
* revokeOtherSessions="optional"
|
|
158
|
+
* onSubmit={async (values) => {
|
|
159
|
+
* const response = await fetch("/account/password", {
|
|
160
|
+
* method: "PUT",
|
|
161
|
+
* headers: { "content-type": "application/json" },
|
|
162
|
+
* body: JSON.stringify(values),
|
|
163
|
+
* });
|
|
164
|
+
* if (!response.ok) return await response.json();
|
|
165
|
+
* }}
|
|
166
|
+
* />
|
|
167
|
+
* );
|
|
168
|
+
* }
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
export declare function ChangePasswordForm(props: ChangePasswordFormProps): ReactNode;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* {@link ChangePasswordForm} — a default, accessible, unstyled form for a
|
|
4
|
+
* signed-in person to change their password, or to set a first one on an
|
|
5
|
+
* account that signs in without a password. Built on {@link useAuthForm}: it
|
|
6
|
+
* collects the passwords, checks the confirmation and length on the client,
|
|
7
|
+
* and hands the values to your `onSubmit`.
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
import { useEffect, useState } from "react";
|
|
12
|
+
import { useAuthForm } from "./use-auth-form.js";
|
|
13
|
+
import { AuthFormShell, SubmitButton, TextField, useFocusFirstError, } from "./internal.js";
|
|
14
|
+
import { useAuthFormClassNames } from "./class-names.js";
|
|
15
|
+
function withoutCurrentPasswordField(result) {
|
|
16
|
+
const message = result?.fieldErrors?.currentPassword;
|
|
17
|
+
if (!result || message === undefined)
|
|
18
|
+
return result;
|
|
19
|
+
const { currentPassword: _moved, ...fieldErrors } = result.fieldErrors ?? {};
|
|
20
|
+
return { ...result, error: result.error || message, fieldErrors };
|
|
21
|
+
}
|
|
22
|
+
const CLEARED_PASSWORDS = {
|
|
23
|
+
currentPassword: "",
|
|
24
|
+
newPassword: "",
|
|
25
|
+
confirmPassword: "",
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* A ready-to-use change-password form, which also sets a first password on an
|
|
29
|
+
* account without one (`hasPassword={false}`). Wire `onSubmit` to your server
|
|
30
|
+
* and return `{ fieldErrors: { currentPassword: "…" } }` for a wrong current
|
|
31
|
+
* password, or `{ fieldErrors: { newPassword: "…" } }` for one your policy
|
|
32
|
+
* refuses; focus moves to the first errored field.
|
|
33
|
+
*
|
|
34
|
+
* After a successful submit the password fields are cleared and a status
|
|
35
|
+
* message appears above the form, which stays in place.
|
|
36
|
+
*
|
|
37
|
+
* @example Change a password, signing out other sessions
|
|
38
|
+
* ```tsx
|
|
39
|
+
* import { ChangePasswordForm } from "@udibo/oauth2/react/components";
|
|
40
|
+
*
|
|
41
|
+
* function ChangePassword() {
|
|
42
|
+
* return (
|
|
43
|
+
* <ChangePasswordForm
|
|
44
|
+
* minLength={12}
|
|
45
|
+
* onSubmit={async (values) => {
|
|
46
|
+
* const response = await fetch("/account/password", {
|
|
47
|
+
* method: "POST",
|
|
48
|
+
* headers: { "content-type": "application/json" },
|
|
49
|
+
* body: JSON.stringify(values),
|
|
50
|
+
* });
|
|
51
|
+
* if (!response.ok) return await response.json();
|
|
52
|
+
* }}
|
|
53
|
+
* />
|
|
54
|
+
* );
|
|
55
|
+
* }
|
|
56
|
+
* ```
|
|
57
|
+
*
|
|
58
|
+
* @example Set a first password on a social or passkey account
|
|
59
|
+
* ```tsx
|
|
60
|
+
* import { ChangePasswordForm } from "@udibo/oauth2/react/components";
|
|
61
|
+
*
|
|
62
|
+
* function SetPassword(props: { hasPassword: boolean }) {
|
|
63
|
+
* return (
|
|
64
|
+
* <ChangePasswordForm
|
|
65
|
+
* hasPassword={props.hasPassword}
|
|
66
|
+
* revokeOtherSessions="optional"
|
|
67
|
+
* onSubmit={async (values) => {
|
|
68
|
+
* const response = await fetch("/account/password", {
|
|
69
|
+
* method: "PUT",
|
|
70
|
+
* headers: { "content-type": "application/json" },
|
|
71
|
+
* body: JSON.stringify(values),
|
|
72
|
+
* });
|
|
73
|
+
* if (!response.ok) return await response.json();
|
|
74
|
+
* }}
|
|
75
|
+
* />
|
|
76
|
+
* );
|
|
77
|
+
* }
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export function ChangePasswordForm(props) {
|
|
81
|
+
const { onSubmit, hasPassword = true, revokeOtherSessions = true, minLength, className, labels, children, } = props;
|
|
82
|
+
const [submittedWithPassword, setSubmittedWithPassword] = useState(hasPassword);
|
|
83
|
+
const normalize = (values) => ({
|
|
84
|
+
...values,
|
|
85
|
+
currentPassword: hasPassword ? values.currentPassword : "",
|
|
86
|
+
revokeOtherSessions: revokeOtherSessions === "optional"
|
|
87
|
+
? values.revokeOtherSessions
|
|
88
|
+
: revokeOtherSessions,
|
|
89
|
+
});
|
|
90
|
+
const { onSuccess } = props;
|
|
91
|
+
const form = useAuthForm({
|
|
92
|
+
initialValues: {
|
|
93
|
+
...CLEARED_PASSWORDS,
|
|
94
|
+
revokeOtherSessions: revokeOtherSessions !== false,
|
|
95
|
+
},
|
|
96
|
+
onSubmit: async (values) => {
|
|
97
|
+
setSubmittedWithPassword(hasPassword);
|
|
98
|
+
const result = await onSubmit(normalize(values));
|
|
99
|
+
return hasPassword ? result : withoutCurrentPasswordField(result);
|
|
100
|
+
},
|
|
101
|
+
onSuccess: onSuccess ? (values) => onSuccess(normalize(values)) : undefined,
|
|
102
|
+
validate: (values) => {
|
|
103
|
+
const errors = {};
|
|
104
|
+
if (minLength !== undefined && values.newPassword.length < minLength) {
|
|
105
|
+
errors.newPassword =
|
|
106
|
+
labels?.tooShort ?? `Use at least ${minLength} characters.`;
|
|
107
|
+
}
|
|
108
|
+
if (values.newPassword !== values.confirmPassword) {
|
|
109
|
+
errors.confirmPassword =
|
|
110
|
+
labels?.passwordMismatch ?? "Passwords do not match.";
|
|
111
|
+
}
|
|
112
|
+
return errors;
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
const { setValue, setValues, succeeded, submitCount } = form;
|
|
116
|
+
useEffect(() => {
|
|
117
|
+
if (succeeded)
|
|
118
|
+
setValues(CLEARED_PASSWORDS);
|
|
119
|
+
}, [succeeded, submitCount, setValues]);
|
|
120
|
+
useEffect(() => {
|
|
121
|
+
setValue("revokeOtherSessions", revokeOtherSessions !== false);
|
|
122
|
+
}, [revokeOtherSessions, setValue]);
|
|
123
|
+
useFocusFirstError(form);
|
|
124
|
+
const classNames = useAuthFormClassNames(props.classNames);
|
|
125
|
+
const revokeField = form.getFieldProps("revokeOtherSessions");
|
|
126
|
+
const notice = labels?.revokeOtherSessionsNotice ??
|
|
127
|
+
"Your other sessions will be signed out.";
|
|
128
|
+
return (_jsxs(AuthFormShell, { name: hasPassword ? "change-password" : "set-password", form: form, className: className, classNames: classNames, render: children, action: props.action, method: props.method ?? "post", formRef: props.formRef, aboveForm: form.succeeded ? (_jsx("div", { "data-oauth2-success": "", role: "status", className: classNames.success, children: labels?.success ??
|
|
129
|
+
(submittedWithPassword ? "Password updated." : "Password set.") })) : null, children: [hasPassword ? (_jsx(TextField, { fieldProps: form.getFieldProps("currentPassword"), label: labels?.currentPassword ?? "Current password", type: "password", autoComplete: "current-password", required: true, error: form.errors.currentPassword })) : null, _jsx(TextField, { fieldProps: form.getFieldProps("newPassword"), label: labels?.newPassword ?? "New password", type: "password", autoComplete: "new-password", minLength: minLength, required: true, error: form.errors.newPassword }), _jsx(TextField, { fieldProps: form.getFieldProps("confirmPassword"), label: labels?.confirmPassword ?? "Confirm new password", type: "password", autoComplete: "new-password", required: true, error: form.errors.confirmPassword }), revokeOtherSessions === "optional" ? (_jsx("div", { "data-oauth2-field": "revokeOtherSessions", className: classNames.field, children: _jsxs("label", { htmlFor: revokeField.id, "data-oauth2-label": "", className: classNames.label, children: [_jsx("input", { ...revokeField, value: "true", type: "checkbox", "data-oauth2-input": "", className: classNames.input }), labels?.revokeOtherSessions ?? "Sign out of my other sessions"] }) })) : (_jsx("input", { type: "hidden", name: "revokeOtherSessions", value: String(revokeOtherSessions) })), revokeOtherSessions === true && notice ? (_jsx("p", { "data-oauth2-revoke-notice": "", className: classNames.hint, children: notice })) : null, _jsx(SubmitButton, { isSubmitting: form.isSubmitting, label: labels?.submit ?? (hasPassword ? "Update password" : "Set password"), submittingLabel: labels?.submitting ?? (hasPassword ? "Updating…" : "Setting…") })] }));
|
|
130
|
+
}
|
|
@@ -68,8 +68,9 @@ export interface AuthFormClassNamesProviderProps {
|
|
|
68
68
|
* own `classNames` prop — overrides the inherited map slot by slot, leaving the
|
|
69
69
|
* slots it does not name intact.
|
|
70
70
|
*
|
|
71
|
-
* It themes the auth **forms
|
|
72
|
-
* and
|
|
71
|
+
* It themes the auth **forms**, `ChangePasswordForm` included; `UserMenu`,
|
|
72
|
+
* `SessionList` and `LinkedAccounts` are deliberately outside its reach and
|
|
73
|
+
* take their classes from their own `className` / `classNames` props.
|
|
73
74
|
*
|
|
74
75
|
* An inline `classNames` literal is fine here — the published map is cached on
|
|
75
76
|
* the slot values rather than on the object's identity, so re-rendering with an
|
|
@@ -92,8 +92,9 @@ export function AuthFormClassNamesScope(props) {
|
|
|
92
92
|
* own `classNames` prop — overrides the inherited map slot by slot, leaving the
|
|
93
93
|
* slots it does not name intact.
|
|
94
94
|
*
|
|
95
|
-
* It themes the auth **forms
|
|
96
|
-
* and
|
|
95
|
+
* It themes the auth **forms**, `ChangePasswordForm` included; `UserMenu`,
|
|
96
|
+
* `SessionList` and `LinkedAccounts` are deliberately outside its reach and
|
|
97
|
+
* take their classes from their own `className` / `classNames` props.
|
|
97
98
|
*
|
|
98
99
|
* An inline `classNames` literal is fine here — the published map is cached on
|
|
99
100
|
* the slot values rather than on the object's identity, so re-rendering with an
|
|
@@ -20,9 +20,9 @@ export function SubmitButton(props) {
|
|
|
20
20
|
return (_jsx("div", { "data-oauth2-actions": "", className: classNames.actions, children: _jsx("button", { type: "submit", "aria-disabled": isSubmitting ? true : undefined, onClick: isSubmitting ? ignoreActivation : undefined, "data-oauth2-submit": "", className: classNames.submit, children: isSubmitting ? submittingLabel : label }) }));
|
|
21
21
|
}
|
|
22
22
|
export function TextField(props) {
|
|
23
|
-
const { fieldProps, label, type = "text", autoComplete, required, error, inputRef, children, } = props;
|
|
23
|
+
const { fieldProps, label, type = "text", autoComplete, required, minLength, error, inputRef, children, } = props;
|
|
24
24
|
const classNames = useAuthFormClassNames();
|
|
25
|
-
return (_jsxs("div", { "data-oauth2-field": fieldProps.name, className: classNames.field, children: [_jsx("label", { htmlFor: fieldProps.id, "data-oauth2-label": "", className: classNames.label, children: label }), _jsx("input", { ...fieldProps, type: type, autoComplete: autoComplete, required: required, "data-oauth2-input": "", className: classNames.input, ref: inputRef }), children, error ? (_jsx("p", { id: `${fieldProps.id}-error`, role: "alert", "data-oauth2-error": "", className: classNames.error, children: error })) : null] }));
|
|
25
|
+
return (_jsxs("div", { "data-oauth2-field": fieldProps.name, className: classNames.field, children: [_jsx("label", { htmlFor: fieldProps.id, "data-oauth2-label": "", className: classNames.label, children: label }), _jsx("input", { ...fieldProps, type: type, autoComplete: autoComplete, required: required, minLength: minLength, "data-oauth2-input": "", className: classNames.input, ref: inputRef }), children, error ? (_jsx("p", { id: `${fieldProps.id}-error`, role: "alert", "data-oauth2-error": "", className: classNames.error, children: error })) : null] }));
|
|
26
26
|
}
|
|
27
27
|
export function ErrorSummary(props) {
|
|
28
28
|
const { error, focusTrigger } = props;
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* {@link LinkedAccounts} — a default, accessible, unstyled list of the social
|
|
3
|
+
* and federated accounts linked to an account, with "Disconnect" on each and
|
|
4
|
+
* "Connect …" for the providers it can still link. The accounts come in as
|
|
5
|
+
* data and each action goes out through a callback; the component never loads,
|
|
6
|
+
* links or unlinks anything itself.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import type { ReactNode } from "react";
|
|
11
|
+
import type { AccountActionHandler, BaseClassNames, SocialProvider } from "./types.ts";
|
|
12
|
+
/** One linked account, as {@link LinkedAccounts} renders it. */
|
|
13
|
+
export interface LinkedAccount {
|
|
14
|
+
/**
|
|
15
|
+
* The link's identifier: an opaque, non-secret id such as a public row id,
|
|
16
|
+
* never a provider token. It is handed back to `onUnlink`, and although it
|
|
17
|
+
* is not displayed as text, it is written into the page — `data-oauth2-*`
|
|
18
|
+
* attributes and the hidden `identityId` input a no-JavaScript submit posts.
|
|
19
|
+
*/
|
|
20
|
+
id: string;
|
|
21
|
+
/** The provider's name, such as `"GitHub"`. */
|
|
22
|
+
providerName: string;
|
|
23
|
+
/** The email address the provider reported for this account. */
|
|
24
|
+
email?: string | null;
|
|
25
|
+
/** When the account was linked. */
|
|
26
|
+
linkedAt?: Date;
|
|
27
|
+
/**
|
|
28
|
+
* Set `false` when disconnecting this account would leave no way to sign in,
|
|
29
|
+
* so the row shows the `lastMethod` text instead of a "Disconnect" button.
|
|
30
|
+
* Your server must still refuse that unlink: this only keeps the button
|
|
31
|
+
* from being offered.
|
|
32
|
+
*/
|
|
33
|
+
canUnlink?: boolean;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Per-slot class hooks for {@link LinkedAccounts}: the shared
|
|
37
|
+
* {@link BaseClassNames} `root` plus the list's own slots. Each element also
|
|
38
|
+
* carries the stable `data-oauth2-*` attribute named here.
|
|
39
|
+
*/
|
|
40
|
+
export interface LinkedAccountsClassNames extends BaseClassNames {
|
|
41
|
+
/** The `<ul>` of linked accounts (`data-oauth2-linked-account-items`). */
|
|
42
|
+
list?: string;
|
|
43
|
+
/** Each `<li>` (`data-oauth2-linked-account`, whose value is the link id). */
|
|
44
|
+
item?: string;
|
|
45
|
+
/** The provider name of each account (`data-oauth2-linked-account-name`). */
|
|
46
|
+
name?: string;
|
|
47
|
+
/** The email and date line under the name (`data-oauth2-linked-account-meta`). */
|
|
48
|
+
meta?: string;
|
|
49
|
+
/** Each "Disconnect" button (`data-oauth2-unlink`). */
|
|
50
|
+
unlink?: string;
|
|
51
|
+
/**
|
|
52
|
+
* The text shown in place of "Disconnect" on an account that cannot be
|
|
53
|
+
* unlinked (`data-oauth2-last-method`).
|
|
54
|
+
*/
|
|
55
|
+
hint?: string;
|
|
56
|
+
/** The wrapper of the "Connect …" controls (`data-oauth2-connect`). */
|
|
57
|
+
connectSection?: string;
|
|
58
|
+
/** Each "Connect …" button or link (`data-oauth2-connect-button`). */
|
|
59
|
+
connectButton?: string;
|
|
60
|
+
/** The error summary shown after a failed action (`data-oauth2-error-summary`). */
|
|
61
|
+
errorSummary?: string;
|
|
62
|
+
/** The text shown when no account is linked (`data-oauth2-empty`). */
|
|
63
|
+
empty?: string;
|
|
64
|
+
}
|
|
65
|
+
/** Visible text overrides for {@link LinkedAccounts}. */
|
|
66
|
+
export interface LinkedAccountsLabels {
|
|
67
|
+
/** Prefix of the linked date. Default: `"Connected"`. */
|
|
68
|
+
linked?: string;
|
|
69
|
+
/**
|
|
70
|
+
* "Disconnect" button text. Default: `"Disconnect"`. Its accessible name adds
|
|
71
|
+
* the provider, such as "Disconnect GitHub".
|
|
72
|
+
*/
|
|
73
|
+
unlink?: string;
|
|
74
|
+
/** "Disconnect" button text while pending. Default: `"Disconnecting…"`. */
|
|
75
|
+
unlinking?: string;
|
|
76
|
+
/**
|
|
77
|
+
* Text before a provider's name on its connect control. Default:
|
|
78
|
+
* `"Connect"`, rendering "Connect GitHub".
|
|
79
|
+
*/
|
|
80
|
+
link?: string;
|
|
81
|
+
/** Connect button text while pending. Default: `"Connecting…"`. */
|
|
82
|
+
linking?: string;
|
|
83
|
+
/**
|
|
84
|
+
* Shown on an account whose `canUnlink` is `false`. Default:
|
|
85
|
+
* `"This is your only way to sign in, so it can't be disconnected."`.
|
|
86
|
+
*/
|
|
87
|
+
lastMethod?: string;
|
|
88
|
+
/** Shown when `accounts` is empty. Default: `"No accounts connected yet."`. */
|
|
89
|
+
empty?: string;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The live state {@link LinkedAccounts} hands to a render-prop `children`:
|
|
93
|
+
* the data, which action is pending, the last error, and the two actions with
|
|
94
|
+
* the component's single-flight guard applied.
|
|
95
|
+
*/
|
|
96
|
+
export interface LinkedAccountsState {
|
|
97
|
+
/** The linked accounts passed to the component. */
|
|
98
|
+
accounts: readonly LinkedAccount[];
|
|
99
|
+
/** The providers passed to the component. */
|
|
100
|
+
providers: readonly SocialProvider[];
|
|
101
|
+
/** The id of the account whose unlink is pending, else `null`. */
|
|
102
|
+
pendingAccountId: string | null;
|
|
103
|
+
/** The id of the provider whose link is pending, else `null`. */
|
|
104
|
+
pendingProviderId: string | null;
|
|
105
|
+
/** The message from the last failed action, else `null`. */
|
|
106
|
+
error: string | null;
|
|
107
|
+
/**
|
|
108
|
+
* Runs `onUnlink` for an account. Ignored while any action is pending, when
|
|
109
|
+
* `onUnlink` was not passed, or when the account's `canUnlink` is `false`.
|
|
110
|
+
*/
|
|
111
|
+
unlink(account: LinkedAccount): Promise<void>;
|
|
112
|
+
/**
|
|
113
|
+
* Runs `onLink` for a provider. Ignored while any action is pending or when
|
|
114
|
+
* `onLink` was not passed.
|
|
115
|
+
*/
|
|
116
|
+
link(provider: SocialProvider): Promise<void>;
|
|
117
|
+
}
|
|
118
|
+
/** Props for {@link LinkedAccounts}. */
|
|
119
|
+
export interface LinkedAccountsProps {
|
|
120
|
+
/** The accounts linked to this account, in the order to list them. */
|
|
121
|
+
accounts: readonly LinkedAccount[];
|
|
122
|
+
/**
|
|
123
|
+
* Disconnects one linked account. Omit it for a read-only list. Refuse an
|
|
124
|
+
* unlink that would leave no way to sign in on your server, whatever
|
|
125
|
+
* `canUnlink` says.
|
|
126
|
+
*/
|
|
127
|
+
onUnlink?: AccountActionHandler<LinkedAccount>;
|
|
128
|
+
/**
|
|
129
|
+
* Providers the account can still link. Each gets a "Connect …" control
|
|
130
|
+
* when `onLink` or `linkHref` is passed. Empty or absent renders no connect
|
|
131
|
+
* section.
|
|
132
|
+
*/
|
|
133
|
+
providers?: readonly SocialProvider[];
|
|
134
|
+
/**
|
|
135
|
+
* Starts linking a provider. Its pending label shows until the returned
|
|
136
|
+
* promise settles; a flow that navigates away can simply not resolve.
|
|
137
|
+
*/
|
|
138
|
+
onLink?: AccountActionHandler<SocialProvider>;
|
|
139
|
+
/**
|
|
140
|
+
* Builds the href that starts linking a provider, rendering links instead of
|
|
141
|
+
* buttons. Wins over `onLink` when both are passed.
|
|
142
|
+
*/
|
|
143
|
+
linkHref?: (provider: SocialProvider) => string;
|
|
144
|
+
/**
|
|
145
|
+
* Formats `linkedAt`. Defaults to the runtime's locale and time zone, which
|
|
146
|
+
* can differ between server and browser; pass a formatter with a fixed
|
|
147
|
+
* locale and `timeZone` on a server-rendered page so hydration matches.
|
|
148
|
+
*/
|
|
149
|
+
formatDate?: (date: Date) => string;
|
|
150
|
+
/**
|
|
151
|
+
* `action` for each "Disconnect" button's `<form>`. Set it on a
|
|
152
|
+
* server-rendered page so the button still posts when JavaScript never
|
|
153
|
+
* arrives, with `intent=unlink-identity` and `identityId`. Once React is
|
|
154
|
+
* running, `onUnlink` handles the submit and the native post is
|
|
155
|
+
* suppressed. The forms always use `post`. A native post cannot carry a
|
|
156
|
+
* CSRF header, so check `Origin` or `Sec-Fetch-Site` on the route that
|
|
157
|
+
* receives it. Connect controls never post: use `linkHref` for a link that
|
|
158
|
+
* works without JavaScript.
|
|
159
|
+
*/
|
|
160
|
+
action?: string;
|
|
161
|
+
/** Class for the root wrapper (merged with `classNames.root`). */
|
|
162
|
+
className?: string;
|
|
163
|
+
/** Per-slot class hooks for theming. See {@link LinkedAccountsClassNames}. */
|
|
164
|
+
classNames?: LinkedAccountsClassNames;
|
|
165
|
+
/** Text overrides. */
|
|
166
|
+
labels?: LinkedAccountsLabels;
|
|
167
|
+
/**
|
|
168
|
+
* Render-prop escape hatch. When provided, you own the markup and receive
|
|
169
|
+
* the live {@link LinkedAccountsState}; the component still owns the
|
|
170
|
+
* pending and error state.
|
|
171
|
+
*/
|
|
172
|
+
children?: (state: LinkedAccountsState) => ReactNode;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* A ready-to-use list of the social and federated accounts linked to an
|
|
176
|
+
* account. Pass the accounts your loader read and wire `onUnlink` to your
|
|
177
|
+
* server; pass `providers` with `onLink` or `linkHref` to offer the ones not
|
|
178
|
+
* yet linked. After an action succeeds, pass the updated data so the list
|
|
179
|
+
* follows.
|
|
180
|
+
*
|
|
181
|
+
* Set `canUnlink: false` on an account that is the last way to sign in. A
|
|
182
|
+
* failed action shows its message in an error summary that takes focus, and a
|
|
183
|
+
* pending button keeps focus with `aria-disabled="true"`.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```tsx
|
|
187
|
+
* import {
|
|
188
|
+
* type LinkedAccount,
|
|
189
|
+
* LinkedAccounts,
|
|
190
|
+
* } from "@udibo/oauth2/react/components";
|
|
191
|
+
*
|
|
192
|
+
* function Connected(props: { accounts: LinkedAccount[]; hasPassword: boolean }) {
|
|
193
|
+
* return (
|
|
194
|
+
* <LinkedAccounts
|
|
195
|
+
* accounts={props.accounts.map((account) => ({
|
|
196
|
+
* ...account,
|
|
197
|
+
* canUnlink: props.hasPassword || props.accounts.length > 1,
|
|
198
|
+
* }))}
|
|
199
|
+
* onUnlink={async (account) => {
|
|
200
|
+
* const response = await fetch(`/account/identities/${account.id}`, {
|
|
201
|
+
* method: "DELETE",
|
|
202
|
+
* });
|
|
203
|
+
* if (!response.ok) return { error: "Couldn't disconnect that account." };
|
|
204
|
+
* }}
|
|
205
|
+
* providers={[{ id: "github", name: "GitHub" }]}
|
|
206
|
+
* linkHref={(provider) => `/auth/link/${provider.id}`}
|
|
207
|
+
* />
|
|
208
|
+
* );
|
|
209
|
+
* }
|
|
210
|
+
* ```
|
|
211
|
+
*/
|
|
212
|
+
export declare function LinkedAccounts(props: LinkedAccountsProps): ReactNode;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { AccountActionError, ActionForm, formatAccountDate, useAccountAction, useFocusAfterRemoval, } from "./account-internal.js";
|
|
3
|
+
import { combineClassNames } from "./internal.js";
|
|
4
|
+
const LINK_KEY_PREFIX = "\u0000link:";
|
|
5
|
+
/**
|
|
6
|
+
* A ready-to-use list of the social and federated accounts linked to an
|
|
7
|
+
* account. Pass the accounts your loader read and wire `onUnlink` to your
|
|
8
|
+
* server; pass `providers` with `onLink` or `linkHref` to offer the ones not
|
|
9
|
+
* yet linked. After an action succeeds, pass the updated data so the list
|
|
10
|
+
* follows.
|
|
11
|
+
*
|
|
12
|
+
* Set `canUnlink: false` on an account that is the last way to sign in. A
|
|
13
|
+
* failed action shows its message in an error summary that takes focus, and a
|
|
14
|
+
* pending button keeps focus with `aria-disabled="true"`.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```tsx
|
|
18
|
+
* import {
|
|
19
|
+
* type LinkedAccount,
|
|
20
|
+
* LinkedAccounts,
|
|
21
|
+
* } from "@udibo/oauth2/react/components";
|
|
22
|
+
*
|
|
23
|
+
* function Connected(props: { accounts: LinkedAccount[]; hasPassword: boolean }) {
|
|
24
|
+
* return (
|
|
25
|
+
* <LinkedAccounts
|
|
26
|
+
* accounts={props.accounts.map((account) => ({
|
|
27
|
+
* ...account,
|
|
28
|
+
* canUnlink: props.hasPassword || props.accounts.length > 1,
|
|
29
|
+
* }))}
|
|
30
|
+
* onUnlink={async (account) => {
|
|
31
|
+
* const response = await fetch(`/account/identities/${account.id}`, {
|
|
32
|
+
* method: "DELETE",
|
|
33
|
+
* });
|
|
34
|
+
* if (!response.ok) return { error: "Couldn't disconnect that account." };
|
|
35
|
+
* }}
|
|
36
|
+
* providers={[{ id: "github", name: "GitHub" }]}
|
|
37
|
+
* linkHref={(provider) => `/auth/link/${provider.id}`}
|
|
38
|
+
* />
|
|
39
|
+
* );
|
|
40
|
+
* }
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export function LinkedAccounts(props) {
|
|
44
|
+
const { accounts, onUnlink, providers = [], onLink, linkHref, formatDate = formatAccountDate, action, className, classNames, labels, children, } = props;
|
|
45
|
+
const runner = useAccountAction();
|
|
46
|
+
const rootRef = useFocusAfterRemoval(runner, accounts);
|
|
47
|
+
const unlink = async (account) => {
|
|
48
|
+
if (!onUnlink || account.canUnlink === false)
|
|
49
|
+
return;
|
|
50
|
+
await runner.run(account.id, () => onUnlink(account));
|
|
51
|
+
};
|
|
52
|
+
const link = async (provider) => {
|
|
53
|
+
if (!onLink)
|
|
54
|
+
return;
|
|
55
|
+
await runner.run(LINK_KEY_PREFIX + provider.id, () => onLink(provider));
|
|
56
|
+
};
|
|
57
|
+
const pendingProviderId = runner.pendingKey?.startsWith(LINK_KEY_PREFIX)
|
|
58
|
+
? runner.pendingKey.slice(LINK_KEY_PREFIX.length)
|
|
59
|
+
: null;
|
|
60
|
+
const pendingAccountId = pendingProviderId === null ? runner.pendingKey : null;
|
|
61
|
+
if (children) {
|
|
62
|
+
return (_jsx(_Fragment, { children: children({
|
|
63
|
+
accounts,
|
|
64
|
+
providers,
|
|
65
|
+
pendingAccountId,
|
|
66
|
+
pendingProviderId,
|
|
67
|
+
error: runner.error,
|
|
68
|
+
unlink,
|
|
69
|
+
link,
|
|
70
|
+
}) }));
|
|
71
|
+
}
|
|
72
|
+
const linkText = labels?.link ?? "Connect";
|
|
73
|
+
const showConnect = providers.length > 0 && Boolean(linkHref || onLink);
|
|
74
|
+
return (_jsxs("div", { ref: rootRef, tabIndex: -1, "data-oauth2-linked-accounts": "", className: combineClassNames(className, classNames?.root), children: [_jsx(AccountActionError, { error: runner.error, className: classNames?.errorSummary }), accounts.length === 0 ? (_jsx("p", { "data-oauth2-empty": "", className: classNames?.empty, children: labels?.empty ?? "No accounts connected yet." })) : (_jsx("ul", { "data-oauth2-linked-account-items": "", className: classNames?.list, children: accounts.map((account) => {
|
|
75
|
+
const meta = [
|
|
76
|
+
account.email || null,
|
|
77
|
+
account.linkedAt
|
|
78
|
+
? `${labels?.linked ?? "Connected"} ${formatDate(account.linkedAt)}`
|
|
79
|
+
: null,
|
|
80
|
+
].filter((part) => part !== null);
|
|
81
|
+
return (_jsxs("li", { "data-oauth2-linked-account": account.id, className: classNames?.item, children: [_jsx("span", { "data-oauth2-linked-account-name": "", className: classNames?.name, children: account.providerName }), meta.length > 0 ? (_jsx("span", { "data-oauth2-linked-account-meta": "", className: classNames?.meta, children: meta.join(" · ") })) : null, onUnlink && account.canUnlink === false ? (_jsx("span", { "data-oauth2-last-method": "", className: classNames?.hint, children: labels?.lastMethod ??
|
|
82
|
+
"This is your only way to sign in, so it can't be disconnected." })) : null, onUnlink && account.canUnlink !== false ? (_jsx(ActionForm, { fields: {
|
|
83
|
+
intent: "unlink-identity",
|
|
84
|
+
identityId: account.id,
|
|
85
|
+
}, action: action, onActivate: () => {
|
|
86
|
+
void unlink(account);
|
|
87
|
+
}, pending: pendingAccountId === account.id, label: labels?.unlink ?? "Disconnect", pendingLabel: labels?.unlinking ?? "Disconnecting…", accessibleName: account.providerName, dataAttribute: "data-oauth2-unlink", dataValue: account.id, className: classNames?.unlink })) : null] }, account.id));
|
|
88
|
+
}) })), showConnect ? (_jsx("div", { "data-oauth2-connect": "", className: classNames?.connectSection, children: providers.map((provider) => {
|
|
89
|
+
const content = (_jsxs(_Fragment, { children: [provider.iconSlot ? (_jsx("span", { "data-oauth2-social-icon": "", children: provider.iconSlot })) : null, _jsx("span", { "data-oauth2-social-label": "", children: pendingProviderId === provider.id
|
|
90
|
+
? (labels?.linking ?? "Connecting…")
|
|
91
|
+
: `${linkText} ${provider.name}` })] }));
|
|
92
|
+
return linkHref ? (_jsx("a", { href: linkHref(provider), "data-oauth2-connect-button": provider.id, className: classNames?.connectButton, children: content }, provider.id)) : (_jsx("button", { type: "button", "aria-disabled": pendingProviderId === provider.id ? true : undefined, "aria-label": pendingProviderId === provider.id
|
|
93
|
+
? `${labels?.linking ?? "Connecting…"} ${provider.name}`
|
|
94
|
+
: undefined, onClick: () => {
|
|
95
|
+
void link(provider);
|
|
96
|
+
}, "data-oauth2-connect-button": provider.id, className: classNames?.connectButton, children: content }, provider.id));
|
|
97
|
+
}) })) : null] }));
|
|
98
|
+
}
|