@udibo/oauth2 0.54.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 +1 -1
- 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/package.json +1 -1
package/SECURITY.md
CHANGED
|
@@ -13,7 +13,7 @@ reports seriously and value the time of security researchers.
|
|
|
13
13
|
|
|
14
14
|
Pre-1.0, security fixes land on the latest release only. From 1.0 on, the latest
|
|
15
15
|
minor of the current major receives fixes, and the final minor of the previous
|
|
16
|
-
major receives critical fixes for 6 months after a new major ships.
|
|
16
|
+
major receives critical fixes for 6 months after a new major ships. Security fixes are announced through a GitHub security advisory or by deprecating affected versions on npm, so a pinned release that a fix affects can be found.
|
|
17
17
|
|
|
18
18
|
## Reporting a vulnerability
|
|
19
19
|
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type ReactNode, type RefObject } from "react";
|
|
2
|
+
import type { AccountActionResult } from "./types.ts";
|
|
3
|
+
export interface AccountActionRunner {
|
|
4
|
+
pendingKey: string | null;
|
|
5
|
+
error: string | null;
|
|
6
|
+
successCount: number;
|
|
7
|
+
/** The element that had focus when the last action started. */
|
|
8
|
+
focusedAtStart: RefObject<Element | null>;
|
|
9
|
+
run(key: string, action: () => Promise<AccountActionResult | void> | AccountActionResult | void): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* One in-flight action at a time across a list's buttons: a second activation
|
|
13
|
+
* while one is pending is ignored, and a returned `error` or a throw becomes
|
|
14
|
+
* the list's error message.
|
|
15
|
+
*/
|
|
16
|
+
export declare function useAccountAction(): AccountActionRunner;
|
|
17
|
+
/**
|
|
18
|
+
* Moves focus to the list root when the control that had focus as a
|
|
19
|
+
* successful action started leaves the page (a removed row's button drops
|
|
20
|
+
* focus to `<body>`). It stops watching once focus moves away from that
|
|
21
|
+
* control, and never moves focus that is somewhere else on the page.
|
|
22
|
+
*/
|
|
23
|
+
export declare function useFocusAfterRemoval(runner: AccountActionRunner, items: unknown): RefObject<HTMLDivElement | null>;
|
|
24
|
+
export declare function AccountActionError(props: {
|
|
25
|
+
error: string | null;
|
|
26
|
+
className: string | undefined;
|
|
27
|
+
}): ReactNode;
|
|
28
|
+
/**
|
|
29
|
+
* A one-button `<form>`: its hidden `fields` post natively to `action` before
|
|
30
|
+
* JavaScript runs, and `onActivate` handles the submit once it does. Always
|
|
31
|
+
* `post`, so a pre-hydration submit never puts the fields in a URL.
|
|
32
|
+
*/
|
|
33
|
+
export declare function ActionForm(props: {
|
|
34
|
+
fields: Record<string, string>;
|
|
35
|
+
action: string | undefined;
|
|
36
|
+
onActivate: () => void;
|
|
37
|
+
pending: boolean;
|
|
38
|
+
label: string;
|
|
39
|
+
pendingLabel: string;
|
|
40
|
+
accessibleName?: string;
|
|
41
|
+
dataAttribute: `data-oauth2-${string}`;
|
|
42
|
+
dataValue?: string;
|
|
43
|
+
className: string | undefined;
|
|
44
|
+
}): ReactNode;
|
|
45
|
+
export declare function formatAccountDate(date: Date): string;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useCallback, useEffect, useRef, useState, } from "react";
|
|
3
|
+
/**
|
|
4
|
+
* One in-flight action at a time across a list's buttons: a second activation
|
|
5
|
+
* while one is pending is ignored, and a returned `error` or a throw becomes
|
|
6
|
+
* the list's error message.
|
|
7
|
+
*/
|
|
8
|
+
export function useAccountAction() {
|
|
9
|
+
const [pendingKey, setPendingKey] = useState(null);
|
|
10
|
+
const [error, setError] = useState(null);
|
|
11
|
+
const [successCount, setSuccessCount] = useState(0);
|
|
12
|
+
const runningRef = useRef(false);
|
|
13
|
+
const focusedAtStart = useRef(null);
|
|
14
|
+
const run = useCallback(async (key, action) => {
|
|
15
|
+
if (runningRef.current)
|
|
16
|
+
return;
|
|
17
|
+
runningRef.current = true;
|
|
18
|
+
focusedAtStart.current =
|
|
19
|
+
typeof document === "undefined" ? null : document.activeElement;
|
|
20
|
+
setPendingKey(key);
|
|
21
|
+
setError(null);
|
|
22
|
+
let message = null;
|
|
23
|
+
try {
|
|
24
|
+
const result = await action();
|
|
25
|
+
if (result?.error)
|
|
26
|
+
message = result.error;
|
|
27
|
+
}
|
|
28
|
+
catch (thrown) {
|
|
29
|
+
message =
|
|
30
|
+
thrown instanceof Error ? thrown.message : "Something went wrong.";
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
runningRef.current = false;
|
|
34
|
+
setPendingKey(null);
|
|
35
|
+
}
|
|
36
|
+
if (message)
|
|
37
|
+
setError(message);
|
|
38
|
+
else
|
|
39
|
+
setSuccessCount((count) => count + 1);
|
|
40
|
+
}, []);
|
|
41
|
+
return { pendingKey, error, successCount, focusedAtStart, run };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Moves focus to the list root when the control that had focus as a
|
|
45
|
+
* successful action started leaves the page (a removed row's button drops
|
|
46
|
+
* focus to `<body>`). It stops watching once focus moves away from that
|
|
47
|
+
* control, and never moves focus that is somewhere else on the page.
|
|
48
|
+
*/
|
|
49
|
+
export function useFocusAfterRemoval(runner, items) {
|
|
50
|
+
const rootRef = useRef(null);
|
|
51
|
+
const handled = useRef(0);
|
|
52
|
+
const watched = useRef(null);
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
if (typeof document === "undefined")
|
|
55
|
+
return;
|
|
56
|
+
if (runner.successCount !== handled.current) {
|
|
57
|
+
handled.current = runner.successCount;
|
|
58
|
+
const control = runner.focusedAtStart.current;
|
|
59
|
+
watched.current =
|
|
60
|
+
control === null || control === document.body ? null : control;
|
|
61
|
+
}
|
|
62
|
+
const control = watched.current;
|
|
63
|
+
if (!control)
|
|
64
|
+
return;
|
|
65
|
+
const active = document.activeElement;
|
|
66
|
+
if (!control.isConnected) {
|
|
67
|
+
watched.current = null;
|
|
68
|
+
if (active === null || active === document.body) {
|
|
69
|
+
rootRef.current?.focus({ preventScroll: true });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
else if (active !== control) {
|
|
73
|
+
watched.current = null;
|
|
74
|
+
}
|
|
75
|
+
}, [runner.successCount, items, runner.focusedAtStart]);
|
|
76
|
+
return rootRef;
|
|
77
|
+
}
|
|
78
|
+
export function AccountActionError(props) {
|
|
79
|
+
const { error, className } = props;
|
|
80
|
+
const ref = useRef(null);
|
|
81
|
+
useEffect(() => {
|
|
82
|
+
if (error)
|
|
83
|
+
ref.current?.focus();
|
|
84
|
+
}, [error]);
|
|
85
|
+
if (!error)
|
|
86
|
+
return null;
|
|
87
|
+
return (_jsx("div", { ref: ref, tabIndex: -1, "data-oauth2-error-summary": "", className: className, children: _jsx("span", { role: "alert", "data-oauth2-error-summary-message": "", children: error }) }));
|
|
88
|
+
}
|
|
89
|
+
function ignoreActivation(event) {
|
|
90
|
+
event.preventDefault();
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* A one-button `<form>`: its hidden `fields` post natively to `action` before
|
|
94
|
+
* JavaScript runs, and `onActivate` handles the submit once it does. Always
|
|
95
|
+
* `post`, so a pre-hydration submit never puts the fields in a URL.
|
|
96
|
+
*/
|
|
97
|
+
export function ActionForm(props) {
|
|
98
|
+
const { fields, action, onActivate, pending, label, pendingLabel, accessibleName, dataAttribute, dataValue = "", className, } = props;
|
|
99
|
+
const onSubmit = (event) => {
|
|
100
|
+
event.preventDefault();
|
|
101
|
+
onActivate();
|
|
102
|
+
};
|
|
103
|
+
const text = pending ? pendingLabel : label;
|
|
104
|
+
return (_jsxs("form", { onSubmit: onSubmit, action: action, method: "post", "data-oauth2-action-form": "", children: [Object.entries(fields).map(([name, value]) => (_jsx("input", { type: "hidden", name: name, value: value }, name))), _jsx("button", { type: "submit", "aria-disabled": pending ? true : undefined, "aria-label": accessibleName ? `${text} ${accessibleName}` : undefined, onClick: pending ? ignoreActivation : undefined, [dataAttribute]: dataValue, className: className, children: text })] }));
|
|
105
|
+
}
|
|
106
|
+
export function formatAccountDate(date) {
|
|
107
|
+
return date.toLocaleString(undefined, {
|
|
108
|
+
dateStyle: "medium",
|
|
109
|
+
timeStyle: "short",
|
|
110
|
+
});
|
|
111
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -16,6 +16,11 @@
|
|
|
16
16
|
* {@link RequestPasswordResetForm}, {@link ResetPasswordForm},
|
|
17
17
|
* {@link MfaEnrollmentForm}, {@link MfaChallengeForm}, {@link UserMenu} —
|
|
18
18
|
* render accessible markup with class hooks.
|
|
19
|
+
* - **Account components** — {@link SessionList}, {@link LinkedAccounts} and
|
|
20
|
+
* {@link ChangePasswordForm} — the signed-in half: the sessions and linked
|
|
21
|
+
* accounts come in as props, and each action goes out through a callback
|
|
22
|
+
* ({@link AccountActionHandler}) or `onSubmit`. They are a small set for an
|
|
23
|
+
* account page you build, not a profile page of their own.
|
|
19
24
|
* - **Headless** — {@link useAuthForm} owns values, errors, and the submit
|
|
20
25
|
* lifecycle with no markup. Every default component is built on it; "eject"
|
|
21
26
|
* by using the hook directly, or by passing a function as a component's
|
|
@@ -85,7 +90,7 @@
|
|
|
85
90
|
*/
|
|
86
91
|
export { useAuthForm } from "./use-auth-form.ts";
|
|
87
92
|
export type { AuthFieldProps, AuthFormState, AuthFormStatus, UseAuthFormOptions, } from "./use-auth-form.ts";
|
|
88
|
-
export type { AuthFormClassNames, AuthFormErrors, AuthFormResult, AuthFormValues, AuthSubmitHandler, BaseAuthFormProps, BaseClassNames, PasskeyOption, SocialProvider, SocialProvidersProps, } from "./types.ts";
|
|
93
|
+
export type { AccountActionHandler, AccountActionResult, AuthFormClassNames, AuthFormErrors, AuthFormResult, AuthFormValues, AuthSubmitHandler, BaseAuthFormProps, BaseClassNames, PasskeyOption, SocialProvider, SocialProvidersProps, } from "./types.ts";
|
|
89
94
|
export { AuthFormClassNamesProvider, useAuthFormClassNames, } from "./class-names.tsx";
|
|
90
95
|
export type { AuthFormClassNamesProviderProps } from "./class-names.tsx";
|
|
91
96
|
export { SignInForm } from "./sign-in-form.tsx";
|
|
@@ -102,3 +107,9 @@ export { MfaChallengeForm } from "./mfa-challenge-form.tsx";
|
|
|
102
107
|
export type { MfaChallengeFormProps, MfaChallengeLabels, MfaChallengeMethod, MfaChallengeValues, } from "./mfa-challenge-form.tsx";
|
|
103
108
|
export { UserMenu } from "./user-menu.tsx";
|
|
104
109
|
export type { UserMenuClassNames, UserMenuLabels, UserMenuProps, } from "./user-menu.tsx";
|
|
110
|
+
export { SessionList } from "./session-list.tsx";
|
|
111
|
+
export type { SessionListClassNames, SessionListItem, SessionListLabels, SessionListProps, SessionListState, } from "./session-list.tsx";
|
|
112
|
+
export { LinkedAccounts } from "./linked-accounts.tsx";
|
|
113
|
+
export type { LinkedAccount, LinkedAccountsClassNames, LinkedAccountsLabels, LinkedAccountsProps, LinkedAccountsState, } from "./linked-accounts.tsx";
|
|
114
|
+
export { ChangePasswordForm } from "./change-password-form.tsx";
|
|
115
|
+
export type { ChangePasswordFormProps, ChangePasswordLabels, ChangePasswordValues, } from "./change-password-form.tsx";
|
|
@@ -16,6 +16,11 @@
|
|
|
16
16
|
* {@link RequestPasswordResetForm}, {@link ResetPasswordForm},
|
|
17
17
|
* {@link MfaEnrollmentForm}, {@link MfaChallengeForm}, {@link UserMenu} —
|
|
18
18
|
* render accessible markup with class hooks.
|
|
19
|
+
* - **Account components** — {@link SessionList}, {@link LinkedAccounts} and
|
|
20
|
+
* {@link ChangePasswordForm} — the signed-in half: the sessions and linked
|
|
21
|
+
* accounts come in as props, and each action goes out through a callback
|
|
22
|
+
* ({@link AccountActionHandler}) or `onSubmit`. They are a small set for an
|
|
23
|
+
* account page you build, not a profile page of their own.
|
|
19
24
|
* - **Headless** — {@link useAuthForm} owns values, errors, and the submit
|
|
20
25
|
* lifecycle with no markup. Every default component is built on it; "eject"
|
|
21
26
|
* by using the hook directly, or by passing a function as a component's
|
|
@@ -92,3 +97,6 @@ export { ResetPasswordForm } from "./reset-password-form.js";
|
|
|
92
97
|
export { MfaEnrollmentForm } from "./mfa-enrollment-form.js";
|
|
93
98
|
export { MfaChallengeForm } from "./mfa-challenge-form.js";
|
|
94
99
|
export { UserMenu } from "./user-menu.js";
|
|
100
|
+
export { SessionList } from "./session-list.js";
|
|
101
|
+
export { LinkedAccounts } from "./linked-accounts.js";
|
|
102
|
+
export { ChangePasswordForm } from "./change-password-form.js";
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* {@link SessionList} — a default, accessible, unstyled list of the places an
|
|
3
|
+
* account is signed in, with "Sign out" on each other session and "Sign out
|
|
4
|
+
* everywhere else". The sessions come in as data and each action goes out
|
|
5
|
+
* through a callback; the component never loads or revokes anything itself.
|
|
6
|
+
*
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
import type { ReactNode } from "react";
|
|
10
|
+
import type { AccountActionHandler, AccountActionResult, BaseClassNames } from "./types.ts";
|
|
11
|
+
/** One signed-in session, as {@link SessionList} renders it. */
|
|
12
|
+
export interface SessionListItem {
|
|
13
|
+
/**
|
|
14
|
+
* The session's identifier: an opaque, non-secret id such as a public row
|
|
15
|
+
* id, **never the session token or cookie value**. It is handed back to
|
|
16
|
+
* `onRevoke`, and although it is not displayed as text, it is written into
|
|
17
|
+
* the page — `data-oauth2-*` attributes and the hidden `sessionId` input a
|
|
18
|
+
* no-JavaScript submit posts.
|
|
19
|
+
*/
|
|
20
|
+
id: string;
|
|
21
|
+
/**
|
|
22
|
+
* `true` for the session making this request. It is badged, listed with the
|
|
23
|
+
* others, and never offered a "Sign out" button: signing yourself out is
|
|
24
|
+
* the sign-out action's job.
|
|
25
|
+
*/
|
|
26
|
+
current?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* What the person recognizes the session by, such as `"Firefox on Linux"`.
|
|
29
|
+
* Summarize the user agent on your server; the component shows this text as
|
|
30
|
+
* given, or the `unknownDevice` label when it is absent.
|
|
31
|
+
*/
|
|
32
|
+
device?: string | null;
|
|
33
|
+
/** The IP address the session was last seen from. */
|
|
34
|
+
ipAddress?: string | null;
|
|
35
|
+
/** When the session signed in. */
|
|
36
|
+
createdAt?: Date;
|
|
37
|
+
/** When the session was last used. */
|
|
38
|
+
lastActiveAt?: Date;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Per-slot class hooks for {@link SessionList}: the shared
|
|
42
|
+
* {@link BaseClassNames} `root` plus the list's own slots. Each element also
|
|
43
|
+
* carries the stable `data-oauth2-*` attribute named here.
|
|
44
|
+
*/
|
|
45
|
+
export interface SessionListClassNames extends BaseClassNames {
|
|
46
|
+
/** The `<ul>` of sessions (`data-oauth2-session-items`). */
|
|
47
|
+
list?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Each `<li>` (`data-oauth2-session`, whose value is the session id; the
|
|
50
|
+
* current session also carries `data-oauth2-current-session`).
|
|
51
|
+
*/
|
|
52
|
+
item?: string;
|
|
53
|
+
/** The device text of each session (`data-oauth2-session-device`). */
|
|
54
|
+
device?: string;
|
|
55
|
+
/** The current-session badge (`data-oauth2-session-badge`). */
|
|
56
|
+
badge?: string;
|
|
57
|
+
/** The IP and time line under the device (`data-oauth2-session-meta`). */
|
|
58
|
+
meta?: string;
|
|
59
|
+
/** Each per-session "Sign out" button (`data-oauth2-revoke-session`). */
|
|
60
|
+
revoke?: string;
|
|
61
|
+
/** The wrapper of the "Sign out everywhere else" form (`data-oauth2-actions`). */
|
|
62
|
+
actions?: string;
|
|
63
|
+
/**
|
|
64
|
+
* The "Sign out everywhere else" button
|
|
65
|
+
* (`data-oauth2-revoke-other-sessions`).
|
|
66
|
+
*/
|
|
67
|
+
revokeOthers?: string;
|
|
68
|
+
/** The error summary shown after a failed action (`data-oauth2-error-summary`). */
|
|
69
|
+
errorSummary?: string;
|
|
70
|
+
/** The text shown when there are no sessions (`data-oauth2-empty`). */
|
|
71
|
+
empty?: string;
|
|
72
|
+
}
|
|
73
|
+
/** Visible text overrides for {@link SessionList}. */
|
|
74
|
+
export interface SessionListLabels {
|
|
75
|
+
/** Badge on the current session. Default: `"Current session"`. */
|
|
76
|
+
current?: string;
|
|
77
|
+
/** Device text when a session has none. Default: `"Unknown device"`. */
|
|
78
|
+
unknownDevice?: string;
|
|
79
|
+
/** Prefix of the sign-in time. Default: `"Signed in"`. */
|
|
80
|
+
signedIn?: string;
|
|
81
|
+
/** Prefix of the last-used time. Default: `"Last active"`. */
|
|
82
|
+
lastActive?: string;
|
|
83
|
+
/**
|
|
84
|
+
* Per-session button text. Default: `"Sign out"`. Its accessible name adds
|
|
85
|
+
* the session's device, such as "Sign out Firefox on Linux".
|
|
86
|
+
*/
|
|
87
|
+
revoke?: string;
|
|
88
|
+
/** Per-session button text while pending. Default: `"Signing out…"`. */
|
|
89
|
+
revoking?: string;
|
|
90
|
+
/** Text of the button for every other session. Default: `"Sign out everywhere else"`. */
|
|
91
|
+
revokeOthers?: string;
|
|
92
|
+
/** That button's text while pending. Default: `"Signing out…"`. */
|
|
93
|
+
revokingOthers?: string;
|
|
94
|
+
/** Shown when `sessions` is empty. Default: `"No active sessions."`. */
|
|
95
|
+
empty?: string;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The live state {@link SessionList} hands to a render-prop `children`: the
|
|
99
|
+
* sessions, which action is pending, the last error, and the two actions with
|
|
100
|
+
* the component's single-flight guard applied.
|
|
101
|
+
*/
|
|
102
|
+
export interface SessionListState {
|
|
103
|
+
/** The sessions passed to the component. */
|
|
104
|
+
sessions: readonly SessionListItem[];
|
|
105
|
+
/** The id of the session whose sign-out is pending, else `null`. */
|
|
106
|
+
pendingSessionId: string | null;
|
|
107
|
+
/** `true` while "Sign out everywhere else" is pending. */
|
|
108
|
+
revokingOthers: boolean;
|
|
109
|
+
/** The message from the last failed action, else `null`. */
|
|
110
|
+
error: string | null;
|
|
111
|
+
/**
|
|
112
|
+
* Runs `onRevoke` for a session. Ignored while any action is pending or
|
|
113
|
+
* when `onRevoke` was not passed.
|
|
114
|
+
*/
|
|
115
|
+
revoke(session: SessionListItem): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Runs `onRevokeOthers`. Ignored while any action is pending or when
|
|
118
|
+
* `onRevokeOthers` was not passed.
|
|
119
|
+
*/
|
|
120
|
+
revokeOthers(): Promise<void>;
|
|
121
|
+
}
|
|
122
|
+
/** Props for {@link SessionList}. */
|
|
123
|
+
export interface SessionListProps {
|
|
124
|
+
/** The account's live sessions, in the order to list them. */
|
|
125
|
+
sessions: readonly SessionListItem[];
|
|
126
|
+
/**
|
|
127
|
+
* Signs out one session other than the current one. Omit it, with
|
|
128
|
+
* `onRevokeOthers`, for a read-only list — for example while an
|
|
129
|
+
* administrator views someone else's account.
|
|
130
|
+
*/
|
|
131
|
+
onRevoke?: AccountActionHandler<SessionListItem>;
|
|
132
|
+
/**
|
|
133
|
+
* Signs out every session except the current one. The button shows only
|
|
134
|
+
* when this is passed and at least one other session is listed.
|
|
135
|
+
*/
|
|
136
|
+
onRevokeOthers?: () => Promise<AccountActionResult | void> | AccountActionResult | void;
|
|
137
|
+
/**
|
|
138
|
+
* Formats `createdAt` and `lastActiveAt`. Defaults to the runtime's locale
|
|
139
|
+
* and time zone, which can differ between server and browser; pass a
|
|
140
|
+
* formatter with a fixed locale and `timeZone` on a server-rendered page so
|
|
141
|
+
* hydration matches.
|
|
142
|
+
*/
|
|
143
|
+
formatDate?: (date: Date) => string;
|
|
144
|
+
/**
|
|
145
|
+
* `action` for each button's `<form>`. Set it on a server-rendered page so
|
|
146
|
+
* the buttons still post when JavaScript never arrives: a session's
|
|
147
|
+
* "Sign out" posts `intent=revoke-session` and `sessionId`, and "Sign out
|
|
148
|
+
* everywhere else" posts `intent=revoke-other-sessions`. Once React is
|
|
149
|
+
* running, the callbacks handle the submit and the native post is
|
|
150
|
+
* suppressed. The forms always use `post`. A native post cannot carry a
|
|
151
|
+
* CSRF header, so check `Origin` or `Sec-Fetch-Site` on the route that
|
|
152
|
+
* receives it.
|
|
153
|
+
*/
|
|
154
|
+
action?: string;
|
|
155
|
+
/** Class for the root wrapper (merged with `classNames.root`). */
|
|
156
|
+
className?: string;
|
|
157
|
+
/** Per-slot class hooks for theming. See {@link SessionListClassNames}. */
|
|
158
|
+
classNames?: SessionListClassNames;
|
|
159
|
+
/** Text overrides. */
|
|
160
|
+
labels?: SessionListLabels;
|
|
161
|
+
/**
|
|
162
|
+
* Render-prop escape hatch. When provided, you own the markup and receive
|
|
163
|
+
* the live {@link SessionListState}; the component still owns the pending
|
|
164
|
+
* and error state.
|
|
165
|
+
*/
|
|
166
|
+
children?: (state: SessionListState) => ReactNode;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* A ready-to-use list of an account's signed-in sessions. Pass the sessions
|
|
170
|
+
* your loader read and wire `onRevoke` / `onRevokeOthers` to your server;
|
|
171
|
+
* after an action succeeds, pass the updated `sessions` so the list follows.
|
|
172
|
+
*
|
|
173
|
+
* Each session shows its device, the current-session badge, its IP address
|
|
174
|
+
* and its sign-in and last-active times. A failed action shows its message in
|
|
175
|
+
* an error summary that takes focus, and a pending button keeps focus with
|
|
176
|
+
* `aria-disabled="true"`.
|
|
177
|
+
*
|
|
178
|
+
* @example
|
|
179
|
+
* ```tsx
|
|
180
|
+
* import {
|
|
181
|
+
* SessionList,
|
|
182
|
+
* type SessionListItem,
|
|
183
|
+
* } from "@udibo/oauth2/react/components";
|
|
184
|
+
*
|
|
185
|
+
* function Sessions(props: { sessions: SessionListItem[] }) {
|
|
186
|
+
* return (
|
|
187
|
+
* <SessionList
|
|
188
|
+
* sessions={props.sessions}
|
|
189
|
+
* onRevoke={async (session) => {
|
|
190
|
+
* const response = await fetch(`/account/sessions/${session.id}`, {
|
|
191
|
+
* method: "DELETE",
|
|
192
|
+
* });
|
|
193
|
+
* if (!response.ok) return { error: "Couldn't sign out that session." };
|
|
194
|
+
* }}
|
|
195
|
+
* onRevokeOthers={async () => {
|
|
196
|
+
* const response = await fetch("/account/sessions", { method: "DELETE" });
|
|
197
|
+
* if (!response.ok) return { error: "Couldn't sign out other sessions." };
|
|
198
|
+
* }}
|
|
199
|
+
* />
|
|
200
|
+
* );
|
|
201
|
+
* }
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
export declare function SessionList(props: SessionListProps): ReactNode;
|
|
@@ -0,0 +1,86 @@
|
|
|
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 OTHERS_KEY = "\u0000revoke-other-sessions";
|
|
5
|
+
/**
|
|
6
|
+
* A ready-to-use list of an account's signed-in sessions. Pass the sessions
|
|
7
|
+
* your loader read and wire `onRevoke` / `onRevokeOthers` to your server;
|
|
8
|
+
* after an action succeeds, pass the updated `sessions` so the list follows.
|
|
9
|
+
*
|
|
10
|
+
* Each session shows its device, the current-session badge, its IP address
|
|
11
|
+
* and its sign-in and last-active times. A failed action shows its message in
|
|
12
|
+
* an error summary that takes focus, and a pending button keeps focus with
|
|
13
|
+
* `aria-disabled="true"`.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```tsx
|
|
17
|
+
* import {
|
|
18
|
+
* SessionList,
|
|
19
|
+
* type SessionListItem,
|
|
20
|
+
* } from "@udibo/oauth2/react/components";
|
|
21
|
+
*
|
|
22
|
+
* function Sessions(props: { sessions: SessionListItem[] }) {
|
|
23
|
+
* return (
|
|
24
|
+
* <SessionList
|
|
25
|
+
* sessions={props.sessions}
|
|
26
|
+
* onRevoke={async (session) => {
|
|
27
|
+
* const response = await fetch(`/account/sessions/${session.id}`, {
|
|
28
|
+
* method: "DELETE",
|
|
29
|
+
* });
|
|
30
|
+
* if (!response.ok) return { error: "Couldn't sign out that session." };
|
|
31
|
+
* }}
|
|
32
|
+
* onRevokeOthers={async () => {
|
|
33
|
+
* const response = await fetch("/account/sessions", { method: "DELETE" });
|
|
34
|
+
* if (!response.ok) return { error: "Couldn't sign out other sessions." };
|
|
35
|
+
* }}
|
|
36
|
+
* />
|
|
37
|
+
* );
|
|
38
|
+
* }
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export function SessionList(props) {
|
|
42
|
+
const { sessions, onRevoke, onRevokeOthers, formatDate = formatAccountDate, action, className, classNames, labels, children, } = props;
|
|
43
|
+
const runner = useAccountAction();
|
|
44
|
+
const rootRef = useFocusAfterRemoval(runner, sessions);
|
|
45
|
+
const revoke = async (session) => {
|
|
46
|
+
if (!onRevoke || session.current)
|
|
47
|
+
return;
|
|
48
|
+
await runner.run(session.id, () => onRevoke(session));
|
|
49
|
+
};
|
|
50
|
+
const revokeOthers = async () => {
|
|
51
|
+
if (!onRevokeOthers)
|
|
52
|
+
return;
|
|
53
|
+
await runner.run(OTHERS_KEY, () => onRevokeOthers());
|
|
54
|
+
};
|
|
55
|
+
if (children) {
|
|
56
|
+
return (_jsx(_Fragment, { children: children({
|
|
57
|
+
sessions,
|
|
58
|
+
pendingSessionId: runner.pendingKey === OTHERS_KEY ? null : runner.pendingKey,
|
|
59
|
+
revokingOthers: runner.pendingKey === OTHERS_KEY,
|
|
60
|
+
error: runner.error,
|
|
61
|
+
revoke,
|
|
62
|
+
revokeOthers,
|
|
63
|
+
}) }));
|
|
64
|
+
}
|
|
65
|
+
const otherCount = sessions.filter((session) => !session.current).length;
|
|
66
|
+
const deviceOf = (session) => session.device || (labels?.unknownDevice ?? "Unknown device");
|
|
67
|
+
return (_jsxs("div", { ref: rootRef, tabIndex: -1, "data-oauth2-session-list": "", className: combineClassNames(className, classNames?.root), children: [_jsx(AccountActionError, { error: runner.error, className: classNames?.errorSummary }), sessions.length === 0 ? (_jsx("p", { "data-oauth2-empty": "", className: classNames?.empty, children: labels?.empty ?? "No active sessions." })) : (_jsx("ul", { "data-oauth2-session-items": "", className: classNames?.list, children: sessions.map((session) => {
|
|
68
|
+
const device = deviceOf(session);
|
|
69
|
+
const meta = [
|
|
70
|
+
session.ipAddress || null,
|
|
71
|
+
session.createdAt
|
|
72
|
+
? `${labels?.signedIn ?? "Signed in"} ${formatDate(session.createdAt)}`
|
|
73
|
+
: null,
|
|
74
|
+
session.lastActiveAt
|
|
75
|
+
? `${labels?.lastActive ?? "Last active"} ${formatDate(session.lastActiveAt)}`
|
|
76
|
+
: null,
|
|
77
|
+
].filter((part) => part !== null);
|
|
78
|
+
return (_jsxs("li", { "data-oauth2-session": session.id, ...(session.current
|
|
79
|
+
? { "data-oauth2-current-session": "" }
|
|
80
|
+
: {}), className: classNames?.item, children: [_jsx("span", { "data-oauth2-session-device": "", className: classNames?.device, children: device }), session.current ? (_jsx("span", { "data-oauth2-session-badge": "", className: classNames?.badge, children: labels?.current ?? "Current session" })) : null, meta.length > 0 ? (_jsx("span", { "data-oauth2-session-meta": "", className: classNames?.meta, children: meta.join(" · ") })) : null, onRevoke && !session.current ? (_jsx(ActionForm, { fields: { intent: "revoke-session", sessionId: session.id }, action: action, onActivate: () => {
|
|
81
|
+
void revoke(session);
|
|
82
|
+
}, pending: runner.pendingKey === session.id, label: labels?.revoke ?? "Sign out", pendingLabel: labels?.revoking ?? "Signing out…", accessibleName: device, dataAttribute: "data-oauth2-revoke-session", dataValue: session.id, className: classNames?.revoke })) : null] }, session.id));
|
|
83
|
+
}) })), onRevokeOthers && otherCount > 0 ? (_jsx("div", { "data-oauth2-actions": "", className: classNames?.actions, children: _jsx(ActionForm, { fields: { intent: "revoke-other-sessions" }, action: action, onActivate: () => {
|
|
84
|
+
void revokeOthers();
|
|
85
|
+
}, pending: runner.pendingKey === OTHERS_KEY, label: labels?.revokeOthers ?? "Sign out everywhere else", pendingLabel: labels?.revokingOthers ?? "Signing out…", dataAttribute: "data-oauth2-revoke-other-sessions", className: classNames?.revokeOthers }) })) : null] }));
|
|
86
|
+
}
|
|
@@ -42,6 +42,24 @@ export interface AuthFormResult {
|
|
|
42
42
|
* {@link AuthFormResult} (or throw) to report the outcome.
|
|
43
43
|
*/
|
|
44
44
|
export type AuthSubmitHandler<V extends AuthFormValues> = (values: V) => Promise<AuthFormResult | void> | AuthFormResult | void;
|
|
45
|
+
/**
|
|
46
|
+
* The result an account action — signing out a session, disconnecting a linked
|
|
47
|
+
* account — may return. Return nothing to signal success; return `error` to
|
|
48
|
+
* show a message in the component's error summary, which takes focus. A thrown
|
|
49
|
+
* error is shown the same way, using its message.
|
|
50
|
+
*/
|
|
51
|
+
export interface AccountActionResult {
|
|
52
|
+
/** The message shown in the component's error summary. */
|
|
53
|
+
error?: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The app-provided function an account component calls for one of its row
|
|
57
|
+
* actions, with the item the person acted on. Resolve to nothing on success;
|
|
58
|
+
* the component shows its pending label until the returned promise settles.
|
|
59
|
+
* Update the data you pass the component yourself, for example by
|
|
60
|
+
* revalidating, so the row disappears.
|
|
61
|
+
*/
|
|
62
|
+
export type AccountActionHandler<T> = (item: T) => Promise<AccountActionResult | void> | AccountActionResult | void;
|
|
45
63
|
/**
|
|
46
64
|
* A social / federated identity provider to render a "Continue with …" button
|
|
47
65
|
* for. Supply an array of these to a sign-in or sign-up component and the
|
|
@@ -84,14 +102,16 @@ export interface PasskeyOption {
|
|
|
84
102
|
}
|
|
85
103
|
/**
|
|
86
104
|
* The class hook every prebuilt component shares. Component-specific class-name
|
|
87
|
-
* maps ({@link AuthFormClassNames}, `UserMenuClassNames
|
|
105
|
+
* maps ({@link AuthFormClassNames}, `UserMenuClassNames`,
|
|
106
|
+
* `SessionListClassNames`, `LinkedAccountsClassNames`) extend this, so `root`
|
|
88
107
|
* means the same thing everywhere.
|
|
89
108
|
*/
|
|
90
109
|
export interface BaseClassNames {
|
|
91
110
|
/**
|
|
92
111
|
* The component's outermost element — the one carrying its
|
|
93
|
-
* `data-oauth2-form
|
|
94
|
-
*
|
|
112
|
+
* `data-oauth2-form`, `data-oauth2-user-menu`, `data-oauth2-session-list` or
|
|
113
|
+
* `data-oauth2-linked-accounts` marker. Merged with the component's
|
|
114
|
+
* top-level `className` prop.
|
|
95
115
|
*/
|
|
96
116
|
root?: string;
|
|
97
117
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@udibo/oauth2",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.55.0",
|
|
4
4
|
"description": "A flexible OAuth2 toolkit: framework-agnostic authorization & resource servers, a typed client, Hono adapters (including a backend-for-frontend), Express adapters, and React bindings.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"authorization-server",
|