@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.
@@ -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`) extend this, so `root`
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` / `data-oauth2-user-menu` marker. Merged with the
94
- * component's top-level `className` prop.
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
  }
@@ -8,8 +8,8 @@
8
8
  * guess for every attempt sharing it: the brute-force floor the lockout is
9
9
  * meant to be moves up by however many attempts an attacker can land at once.
10
10
  *
11
- * The optional `lock` cases run when the store implements it and are skipped,
12
- * with a note naming the gap, when it does not.
11
+ * The optional `lock` and `release` cases run when the store implements the
12
+ * method and are skipped, with a note naming the gap, when it does not.
13
13
  *
14
14
  * @example Verify a database-backed store
15
15
  * ```ts
@@ -53,6 +53,13 @@ export interface LockoutStoreContractOptions {
53
53
  * it does not.
54
54
  */
55
55
  lock?: boolean;
56
+ /**
57
+ * Set to `true` to require the optional {@link LockoutStore.release}: the
58
+ * suite then fails a store that does not implement it. Left unset, the
59
+ * `release` cases run when the store implements it and are skipped with a
60
+ * note when it does not.
61
+ */
62
+ release?: boolean;
56
63
  /**
57
64
  * Overrides the name passed to the outer `describe` block. Defaults to
58
65
  * `"LockoutStore contract"`.
@@ -8,8 +8,8 @@
8
8
  * guess for every attempt sharing it: the brute-force floor the lockout is
9
9
  * meant to be moves up by however many attempts an attacker can land at once.
10
10
  *
11
- * The optional `lock` cases run when the store implements it and are skipped,
12
- * with a note naming the gap, when it does not.
11
+ * The optional `lock` and `release` cases run when the store implements the
12
+ * method and are skipped, with a note naming the gap, when it does not.
13
13
  *
14
14
  * @example Verify a database-backed store
15
15
  * ```ts
@@ -169,6 +169,101 @@ export function runLockoutStoreContractTests(options) {
169
169
  expect((await store.get(OTHER_USER))?.lockedUntil).toBe(undefined);
170
170
  });
171
171
  });
172
+ describe("release (optional)", () => {
173
+ const NOT_IMPLEMENTED = "release is not implemented — an attempt whose password was never " +
174
+ "checked stays counted toward the lockout";
175
+ const MAX_ATTEMPTS = 3;
176
+ if (options.release) {
177
+ it("is implemented", () => {
178
+ assert(typeof store.release === "function", `${NOT_IMPLEMENTED}. Implement it, or drop \`release: true\`.`);
179
+ });
180
+ }
181
+ it("takes back one counted attempt", async ({ skip }) => {
182
+ if (!store.release)
183
+ return skip(NOT_IMPLEMENTED);
184
+ await store.increment(USER, now);
185
+ await store.increment(USER, now);
186
+ await store.release(USER, MAX_ATTEMPTS, now);
187
+ expect((await store.get(USER, now))?.failures).toStrictEqual(1);
188
+ expect((await store.increment(USER, now)).failures).toStrictEqual(2);
189
+ });
190
+ it("leaves no count behind for the last attempt", async ({ skip }) => {
191
+ if (!store.release)
192
+ return skip(NOT_IMPLEMENTED);
193
+ await store.increment(USER, now);
194
+ await store.release(USER, MAX_ATTEMPTS, now);
195
+ expect((await store.get(USER, now))?.failures ?? 0).toStrictEqual(0);
196
+ expect((await store.increment(USER, now)).failures).toStrictEqual(1);
197
+ });
198
+ it("never takes the count below zero", async ({ skip }) => {
199
+ if (!store.release)
200
+ return skip(NOT_IMPLEMENTED);
201
+ await store.release(USER, MAX_ATTEMPTS, now);
202
+ await store.release(USER, MAX_ATTEMPTS, now);
203
+ expect((await store.get(USER, now))?.failures ?? 0).toStrictEqual(0);
204
+ expect((await store.increment(USER, now)).failures).toStrictEqual(1);
205
+ });
206
+ it("drops the lock once the count falls below maxAttempts", async ({ skip, }) => {
207
+ if (!store.release)
208
+ return skip(NOT_IMPLEMENTED);
209
+ await store.set(USER, {
210
+ failures: MAX_ATTEMPTS,
211
+ lockedUntil: now + 60_000,
212
+ });
213
+ await store.release(USER, MAX_ATTEMPTS, now);
214
+ const record = await store.get(USER, now);
215
+ expect(record?.failures).toStrictEqual(MAX_ATTEMPTS - 1);
216
+ expect(record?.lockedUntil, "a lock the counted attempts no longer reach must not stand").toBe(undefined);
217
+ });
218
+ it("keeps the lock while the count still reaches maxAttempts", async ({ skip, }) => {
219
+ if (!store.release)
220
+ return skip(NOT_IMPLEMENTED);
221
+ const lockedUntil = now + 60_000;
222
+ await store.set(USER, { failures: MAX_ATTEMPTS + 1, lockedUntil });
223
+ await store.release(USER, MAX_ATTEMPTS, now);
224
+ const record = await store.get(USER, now);
225
+ expect(record?.failures).toStrictEqual(MAX_ATTEMPTS);
226
+ expect(record?.lockedUntil).toBe(lockedUntil);
227
+ });
228
+ it("takes back exactly one attempt per release among concurrent attempts", async ({ skip, }) => {
229
+ if (!store.release)
230
+ return skip(NOT_IMPLEMENTED);
231
+ for (let i = 0; i < 5; i++)
232
+ await store.increment(USER, now);
233
+ const release = store.release.bind(store);
234
+ await Promise.all([
235
+ ...Array.from({ length: 3 }, () => release(USER, 100, now)),
236
+ ...Array.from({ length: 3 }, () => store.increment(USER, now)),
237
+ ]);
238
+ expect((await store.get(USER, now))?.failures, "a read-modify-write lets a release overwrite a concurrent " +
239
+ "attempt's count").toStrictEqual(5);
240
+ });
241
+ it("takes back one attempt per concurrent release", async ({ skip }) => {
242
+ if (!store.release)
243
+ return skip(NOT_IMPLEMENTED);
244
+ for (let i = 0; i < 5; i++)
245
+ await store.increment(USER, now);
246
+ const release = store.release.bind(store);
247
+ await Promise.all(Array.from({ length: 3 }, () => release(USER, 100, now)));
248
+ expect((await store.get(USER, now))?.failures, "a read-modify-write lets concurrent releases share one decrement").toStrictEqual(2);
249
+ });
250
+ it("leaves a record whose lock has expired as it is", async ({ skip, }) => {
251
+ if (!store.release)
252
+ return skip(NOT_IMPLEMENTED);
253
+ await store.set(USER, { failures: MAX_ATTEMPTS, lockedUntil: now - 1 });
254
+ await store.release(USER, MAX_ATTEMPTS, now);
255
+ expect((await store.increment(USER, now)).failures, "the expired lock's window is over, so the next attempt starts a " +
256
+ "fresh count").toStrictEqual(1);
257
+ });
258
+ it("releases only the account it is given", async ({ skip }) => {
259
+ if (!store.release)
260
+ return skip(NOT_IMPLEMENTED);
261
+ await store.increment(USER, now);
262
+ await store.increment(OTHER_USER, now);
263
+ await store.release(USER, MAX_ATTEMPTS, now);
264
+ expect((await store.get(OTHER_USER, now))?.failures).toStrictEqual(1);
265
+ });
266
+ });
172
267
  describe("clear", () => {
173
268
  it("drops the account's failures and lock", async () => {
174
269
  await store.set(USER, { failures: 10, lockedUntil: now + 60_000 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@udibo/oauth2",
3
- "version": "0.53.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",