@gopherium/react-auth 0.1.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/LICENSE +202 -0
- package/README.md +45 -0
- package/dist/AuthGate.d.ts +17 -0
- package/dist/AuthGate.js +30 -0
- package/dist/admin/index.d.ts +45 -0
- package/dist/admin/index.js +95 -0
- package/dist/api.d.ts +42 -0
- package/dist/api.js +71 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/probe.d.ts +8 -0
- package/dist/probe.js +15 -0
- package/dist/queryClient.d.ts +9 -0
- package/dist/queryClient.js +27 -0
- package/dist/session.d.ts +19 -0
- package/dist/session.js +35 -0
- package/dist/testing/index.d.ts +66 -0
- package/dist/testing/index.js +101 -0
- package/dist/wpds/AccountPanel.d.ts +9 -0
- package/dist/wpds/AccountPanel.js +18 -0
- package/dist/wpds/LoginScreen.d.ts +11 -0
- package/dist/wpds/LoginScreen.js +38 -0
- package/dist/wpds/NewUserScreen.d.ts +9 -0
- package/dist/wpds/NewUserScreen.js +47 -0
- package/dist/wpds/UsersScreen.d.ts +11 -0
- package/dist/wpds/UsersScreen.js +42 -0
- package/dist/wpds/index.d.ts +5 -0
- package/dist/wpds/index.js +6 -0
- package/dist/wpds/nav.d.ts +10 -0
- package/dist/wpds/nav.js +7 -0
- package/dist/wpds/style.css +33 -0
- package/package.json +93 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# @gopherium/react-auth
|
|
2
|
+
|
|
3
|
+
Session authentication for React apps backed by gouncer's authkit.
|
|
4
|
+
|
|
5
|
+
## Entry points
|
|
6
|
+
|
|
7
|
+
- `@gopherium/react-auth` is the headless core: the auth API client,
|
|
8
|
+
`useSession`, `useLogout`, `sessionQueryKey`, the slot-based
|
|
9
|
+
`AuthGate`, `createAuthQueryClient`, and `isSessionRevoked`.
|
|
10
|
+
- `@gopherium/react-auth/admin` is the user administration API client.
|
|
11
|
+
- `@gopherium/react-auth/wpds` renders the WordPress Design System UI:
|
|
12
|
+
`LoginScreen` (brand prop), `AccountPanel`, `UsersScreen`,
|
|
13
|
+
`NewUserScreen`, and `usersNavItem`. Import
|
|
14
|
+
`@gopherium/react-auth/wpds/style.css` alongside it.
|
|
15
|
+
- `@gopherium/react-auth/testing` is the msw harness: `server`,
|
|
16
|
+
`installTestEnvironment`, `seedSession`, `defaultUser`, and canned
|
|
17
|
+
handlers for the auth endpoints.
|
|
18
|
+
|
|
19
|
+
## Mount
|
|
20
|
+
|
|
21
|
+
```tsx
|
|
22
|
+
const client = createAuthQueryClient()
|
|
23
|
+
|
|
24
|
+
<QueryClientProvider client={client}>
|
|
25
|
+
<AuthGate loginScreen={(onLogin) => <LoginScreen brand="MyApp" onLogin={onLogin} />}>
|
|
26
|
+
<App />
|
|
27
|
+
</AuthGate>
|
|
28
|
+
</QueryClientProvider>
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Consumer requirements
|
|
32
|
+
|
|
33
|
+
- `react` and `@tanstack/react-query` are peer dependencies; the app
|
|
34
|
+
must own exactly one copy of each. With workspace or linked installs,
|
|
35
|
+
add both to your bundler's dedupe list.
|
|
36
|
+
- The client calls same-origin `/api/auth/*` and `/api/users` paths. In
|
|
37
|
+
development, proxy `/api` to your backend so the `__Host-` session
|
|
38
|
+
cookie is first-party.
|
|
39
|
+
- `/wpds` needs the `@wordpress/ui` peer and, on React 19, a
|
|
40
|
+
`@wordpress/element` patch stubbing the react-dom exports React 19
|
|
41
|
+
removed. See `patches/` in this package's repository directory.
|
|
42
|
+
|
|
43
|
+
## License
|
|
44
|
+
|
|
45
|
+
Apache-2.0. Copyright © 2026 Manuel 'SirLouen' Camargo.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { User } from './api';
|
|
3
|
+
/**
|
|
4
|
+
* Guards its children behind a login session, rendering the given login
|
|
5
|
+
* screen until the user is authenticated.
|
|
6
|
+
* @param children - The application to reveal once a session is active.
|
|
7
|
+
* @param loginScreen - Renders the login UI, wired to the given login handler.
|
|
8
|
+
* @param loading - Shown while the session resolves.
|
|
9
|
+
* @param error - Shown when the session cannot be loaded.
|
|
10
|
+
* @returns The children, the login screen, or a status element.
|
|
11
|
+
*/
|
|
12
|
+
export declare function AuthGate({ children, loginScreen, loading, error, }: {
|
|
13
|
+
children: ReactNode;
|
|
14
|
+
loginScreen: (onLogin: (user: User) => void | Promise<void>) => ReactNode;
|
|
15
|
+
loading?: ReactNode;
|
|
16
|
+
error?: ReactNode;
|
|
17
|
+
}): import("react").JSX.Element;
|
package/dist/AuthGate.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
4
|
+
import { sessionQueryKey, useSession } from './session';
|
|
5
|
+
/**
|
|
6
|
+
* Guards its children behind a login session, rendering the given login
|
|
7
|
+
* screen until the user is authenticated.
|
|
8
|
+
* @param children - The application to reveal once a session is active.
|
|
9
|
+
* @param loginScreen - Renders the login UI, wired to the given login handler.
|
|
10
|
+
* @param loading - Shown while the session resolves.
|
|
11
|
+
* @param error - Shown when the session cannot be loaded.
|
|
12
|
+
* @returns The children, the login screen, or a status element.
|
|
13
|
+
*/
|
|
14
|
+
export function AuthGate({ children, loginScreen, loading = _jsx("p", { role: "status", children: "Loading\u2026" }), error = _jsx("p", { role: "alert", children: "Something went wrong." }), }) {
|
|
15
|
+
const queryClient = useQueryClient();
|
|
16
|
+
const session = useSession();
|
|
17
|
+
if (session.data === undefined) {
|
|
18
|
+
if (session.isError) {
|
|
19
|
+
return _jsx(_Fragment, { children: error });
|
|
20
|
+
}
|
|
21
|
+
return _jsx(_Fragment, { children: loading });
|
|
22
|
+
}
|
|
23
|
+
if (session.data === null) {
|
|
24
|
+
return (_jsx(_Fragment, { children: loginScreen(async (user) => {
|
|
25
|
+
await queryClient.cancelQueries({ queryKey: sessionQueryKey });
|
|
26
|
+
queryClient.setQueryData(sessionQueryKey, user);
|
|
27
|
+
}) }));
|
|
28
|
+
}
|
|
29
|
+
return _jsx(_Fragment, { children: children });
|
|
30
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const usersQueryKey: readonly ["users"];
|
|
3
|
+
declare const userSchema: z.ZodObject<{
|
|
4
|
+
id: z.ZodString;
|
|
5
|
+
email: z.ZodString;
|
|
6
|
+
name: z.ZodString;
|
|
7
|
+
disabled: z.ZodBoolean;
|
|
8
|
+
created_at: z.ZodCoercedDate<unknown>;
|
|
9
|
+
}, z.core.$strip>;
|
|
10
|
+
export type User = z.infer<typeof userSchema>;
|
|
11
|
+
export interface NewUser {
|
|
12
|
+
email: string;
|
|
13
|
+
name: string;
|
|
14
|
+
password: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* EmailTakenError is thrown when a new user's email is already in use.
|
|
18
|
+
*/
|
|
19
|
+
export declare class EmailTakenError extends Error {
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* ValidationError is thrown when the backend rejects the submitted user
|
|
23
|
+
* details; its message is the backend's human-readable explanation.
|
|
24
|
+
*/
|
|
25
|
+
export declare class ValidationError extends Error {
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Returns every user account.
|
|
29
|
+
* @param signal - Aborts the in-flight request.
|
|
30
|
+
* @returns The parsed list of users.
|
|
31
|
+
*/
|
|
32
|
+
export declare function fetchUsers(signal?: AbortSignal): Promise<User[]>;
|
|
33
|
+
/**
|
|
34
|
+
* Creates a user account and returns it.
|
|
35
|
+
* @param input - The email, name, and password of the new account.
|
|
36
|
+
* @returns The created user.
|
|
37
|
+
*/
|
|
38
|
+
export declare function createUser(input: NewUser): Promise<User>;
|
|
39
|
+
/**
|
|
40
|
+
* Sets whether a user may log in.
|
|
41
|
+
* @param id - The identifier of the user to update.
|
|
42
|
+
* @param disabled - Whether the account should be disabled.
|
|
43
|
+
*/
|
|
44
|
+
export declare function setUserDisabled(id: string, disabled: boolean): Promise<void>;
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { UnauthorizedError } from '../api';
|
|
4
|
+
export const usersQueryKey = ['users'];
|
|
5
|
+
const userSchema = z.object({
|
|
6
|
+
id: z.string(),
|
|
7
|
+
email: z.string(),
|
|
8
|
+
name: z.string(),
|
|
9
|
+
disabled: z.boolean(),
|
|
10
|
+
created_at: z.coerce.date(),
|
|
11
|
+
});
|
|
12
|
+
/**
|
|
13
|
+
* EmailTakenError is thrown when a new user's email is already in use.
|
|
14
|
+
*/
|
|
15
|
+
export class EmailTakenError extends Error {
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* ValidationError is thrown when the backend rejects the submitted user
|
|
19
|
+
* details; its message is the backend's human-readable explanation.
|
|
20
|
+
*/
|
|
21
|
+
export class ValidationError extends Error {
|
|
22
|
+
}
|
|
23
|
+
const errorSchema = z.object({ error: z.string() });
|
|
24
|
+
/**
|
|
25
|
+
* Extracts the backend's explanation from a failed response body.
|
|
26
|
+
* @param response - The failed HTTP response.
|
|
27
|
+
* @param fallback - The message to use when the body is unreadable.
|
|
28
|
+
* @returns The message explaining the failure.
|
|
29
|
+
*/
|
|
30
|
+
async function errorMessage(response, fallback) {
|
|
31
|
+
try {
|
|
32
|
+
return errorSchema.parse(await response.json()).error;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return fallback;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Returns every user account.
|
|
40
|
+
* @param signal - Aborts the in-flight request.
|
|
41
|
+
* @returns The parsed list of users.
|
|
42
|
+
*/
|
|
43
|
+
export async function fetchUsers(signal) {
|
|
44
|
+
const response = await fetch('/api/users', { signal });
|
|
45
|
+
if (response.status === 401) {
|
|
46
|
+
throw new UnauthorizedError('session expired');
|
|
47
|
+
}
|
|
48
|
+
if (!response.ok) {
|
|
49
|
+
throw new Error(`listing users failed with status ${response.status}`);
|
|
50
|
+
}
|
|
51
|
+
return z.array(userSchema).parse(await response.json());
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Creates a user account and returns it.
|
|
55
|
+
* @param input - The email, name, and password of the new account.
|
|
56
|
+
* @returns The created user.
|
|
57
|
+
*/
|
|
58
|
+
export async function createUser(input) {
|
|
59
|
+
const response = await fetch('/api/users', {
|
|
60
|
+
method: 'POST',
|
|
61
|
+
headers: { 'Content-Type': 'application/json' },
|
|
62
|
+
body: JSON.stringify(input),
|
|
63
|
+
});
|
|
64
|
+
if (response.status === 401) {
|
|
65
|
+
throw new UnauthorizedError('session expired');
|
|
66
|
+
}
|
|
67
|
+
if (response.status === 409) {
|
|
68
|
+
throw new EmailTakenError('email already in use');
|
|
69
|
+
}
|
|
70
|
+
if (response.status === 422) {
|
|
71
|
+
throw new ValidationError(await errorMessage(response, 'invalid user details'));
|
|
72
|
+
}
|
|
73
|
+
if (!response.ok) {
|
|
74
|
+
throw new Error(`creating user failed with status ${response.status}`);
|
|
75
|
+
}
|
|
76
|
+
return userSchema.parse(await response.json());
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Sets whether a user may log in.
|
|
80
|
+
* @param id - The identifier of the user to update.
|
|
81
|
+
* @param disabled - Whether the account should be disabled.
|
|
82
|
+
*/
|
|
83
|
+
export async function setUserDisabled(id, disabled) {
|
|
84
|
+
const response = await fetch(`/api/users/${id}`, {
|
|
85
|
+
method: 'PATCH',
|
|
86
|
+
headers: { 'Content-Type': 'application/json' },
|
|
87
|
+
body: JSON.stringify({ disabled }),
|
|
88
|
+
});
|
|
89
|
+
if (response.status === 401) {
|
|
90
|
+
throw new UnauthorizedError('session expired');
|
|
91
|
+
}
|
|
92
|
+
if (!response.ok) {
|
|
93
|
+
throw new Error(`updating user failed with status ${response.status}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
declare const userSchema: z.ZodObject<{
|
|
3
|
+
id: z.ZodString;
|
|
4
|
+
email: z.ZodString;
|
|
5
|
+
name: z.ZodString;
|
|
6
|
+
}, z.core.$strip>;
|
|
7
|
+
export type User = z.infer<typeof userSchema>;
|
|
8
|
+
/**
|
|
9
|
+
* InvalidCredentialsError is thrown when the backend rejects a login.
|
|
10
|
+
*/
|
|
11
|
+
export declare class InvalidCredentialsError extends Error {
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* UnauthorizedError is thrown when the backend rejects a request because
|
|
15
|
+
* the session is missing, expired, or revoked.
|
|
16
|
+
*/
|
|
17
|
+
export declare class UnauthorizedError extends Error {
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* RateLimitedError is thrown when the backend rejects a login for too many
|
|
21
|
+
* attempts.
|
|
22
|
+
*/
|
|
23
|
+
export declare class RateLimitedError extends Error {
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Returns the logged-in user, or null when no session is active.
|
|
27
|
+
* @param signal - Aborts the in-flight request.
|
|
28
|
+
* @returns The current user, or null when unauthenticated.
|
|
29
|
+
*/
|
|
30
|
+
export declare function fetchSession(signal?: AbortSignal): Promise<User | null>;
|
|
31
|
+
/**
|
|
32
|
+
* Logs in with the given credentials and returns the user.
|
|
33
|
+
* @param email - The account email address.
|
|
34
|
+
* @param password - The account password.
|
|
35
|
+
* @returns The authenticated user.
|
|
36
|
+
*/
|
|
37
|
+
export declare function login(email: string, password: string): Promise<User>;
|
|
38
|
+
/**
|
|
39
|
+
* Ends the current session.
|
|
40
|
+
*/
|
|
41
|
+
export declare function logout(): Promise<void>;
|
|
42
|
+
export {};
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
const userSchema = z.object({
|
|
4
|
+
id: z.string(),
|
|
5
|
+
email: z.string(),
|
|
6
|
+
name: z.string(),
|
|
7
|
+
});
|
|
8
|
+
/**
|
|
9
|
+
* InvalidCredentialsError is thrown when the backend rejects a login.
|
|
10
|
+
*/
|
|
11
|
+
export class InvalidCredentialsError extends Error {
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* UnauthorizedError is thrown when the backend rejects a request because
|
|
15
|
+
* the session is missing, expired, or revoked.
|
|
16
|
+
*/
|
|
17
|
+
export class UnauthorizedError extends Error {
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* RateLimitedError is thrown when the backend rejects a login for too many
|
|
21
|
+
* attempts.
|
|
22
|
+
*/
|
|
23
|
+
export class RateLimitedError extends Error {
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Returns the logged-in user, or null when no session is active.
|
|
27
|
+
* @param signal - Aborts the in-flight request.
|
|
28
|
+
* @returns The current user, or null when unauthenticated.
|
|
29
|
+
*/
|
|
30
|
+
export async function fetchSession(signal) {
|
|
31
|
+
const response = await fetch('/api/auth/session', { signal });
|
|
32
|
+
if (response.status === 401) {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
if (!response.ok) {
|
|
36
|
+
throw new Error(`loading session failed with status ${response.status}`);
|
|
37
|
+
}
|
|
38
|
+
return userSchema.parse(await response.json());
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Logs in with the given credentials and returns the user.
|
|
42
|
+
* @param email - The account email address.
|
|
43
|
+
* @param password - The account password.
|
|
44
|
+
* @returns The authenticated user.
|
|
45
|
+
*/
|
|
46
|
+
export async function login(email, password) {
|
|
47
|
+
const response = await fetch('/api/auth/login', {
|
|
48
|
+
method: 'POST',
|
|
49
|
+
headers: { 'Content-Type': 'application/json' },
|
|
50
|
+
body: JSON.stringify({ email, password }),
|
|
51
|
+
});
|
|
52
|
+
if (response.status === 401) {
|
|
53
|
+
throw new InvalidCredentialsError('invalid credentials');
|
|
54
|
+
}
|
|
55
|
+
if (response.status === 429) {
|
|
56
|
+
throw new RateLimitedError('too many login attempts');
|
|
57
|
+
}
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
throw new Error(`login failed with status ${response.status}`);
|
|
60
|
+
}
|
|
61
|
+
return userSchema.parse(await response.json());
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Ends the current session.
|
|
65
|
+
*/
|
|
66
|
+
export async function logout() {
|
|
67
|
+
const response = await fetch('/api/auth/logout', { method: 'POST' });
|
|
68
|
+
if (!response.ok) {
|
|
69
|
+
throw new Error(`logout failed with status ${response.status}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { InvalidCredentialsError, RateLimitedError, UnauthorizedError, fetchSession, login, logout, } from './api';
|
|
2
|
+
export type { User } from './api';
|
|
3
|
+
export { AuthGate } from './AuthGate';
|
|
4
|
+
export { isSessionRevoked } from './probe';
|
|
5
|
+
export { createAuthQueryClient } from './queryClient';
|
|
6
|
+
export { sessionQueryKey, useLogout, useSession } from './session';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
export { InvalidCredentialsError, RateLimitedError, UnauthorizedError, fetchSession, login, logout, } from './api';
|
|
3
|
+
export { AuthGate } from './AuthGate';
|
|
4
|
+
export { isSessionRevoked } from './probe';
|
|
5
|
+
export { createAuthQueryClient } from './queryClient';
|
|
6
|
+
export { sessionQueryKey, useLogout, useSession } from './session';
|
package/dist/probe.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reports whether the backend considers the session gone, distinguishing
|
|
3
|
+
* a revoked login from a transient outage after a stream failure.
|
|
4
|
+
* @param signal - Aborts the in-flight request.
|
|
5
|
+
* @returns True when the session is revoked, false when the backend still
|
|
6
|
+
* accepts it.
|
|
7
|
+
*/
|
|
8
|
+
export declare function isSessionRevoked(signal?: AbortSignal): Promise<boolean>;
|
package/dist/probe.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Reports whether the backend considers the session gone, distinguishing
|
|
4
|
+
* a revoked login from a transient outage after a stream failure.
|
|
5
|
+
* @param signal - Aborts the in-flight request.
|
|
6
|
+
* @returns True when the session is revoked, false when the backend still
|
|
7
|
+
* accepts it.
|
|
8
|
+
*/
|
|
9
|
+
export async function isSessionRevoked(signal) {
|
|
10
|
+
const response = await fetch('/api/auth/session', {
|
|
11
|
+
credentials: 'include',
|
|
12
|
+
signal,
|
|
13
|
+
});
|
|
14
|
+
return response.status === 401;
|
|
15
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { QueryClient } from '@tanstack/react-query';
|
|
2
|
+
import type { DefaultOptions } from '@tanstack/react-query';
|
|
3
|
+
/**
|
|
4
|
+
* Builds a query client that drops the cached session whenever a query
|
|
5
|
+
* or mutation fails with an UnauthorizedError so the login screen takes over.
|
|
6
|
+
* @param defaultOptions - Query and mutation defaults, mainly for tests.
|
|
7
|
+
* @returns The configured query client.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createAuthQueryClient(defaultOptions?: DefaultOptions): QueryClient;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { MutationCache, QueryCache, QueryClient } from '@tanstack/react-query';
|
|
3
|
+
import { UnauthorizedError } from './api';
|
|
4
|
+
import { sessionQueryKey } from './session';
|
|
5
|
+
/**
|
|
6
|
+
* Builds a query client that drops the cached session whenever a query
|
|
7
|
+
* or mutation fails with an UnauthorizedError so the login screen takes over.
|
|
8
|
+
* @param defaultOptions - Query and mutation defaults, mainly for tests.
|
|
9
|
+
* @returns The configured query client.
|
|
10
|
+
*/
|
|
11
|
+
export function createAuthQueryClient(defaultOptions) {
|
|
12
|
+
const queryClient = new QueryClient({
|
|
13
|
+
defaultOptions,
|
|
14
|
+
queryCache: new QueryCache({ onError: dropExpiredSession }),
|
|
15
|
+
mutationCache: new MutationCache({ onError: dropExpiredSession }),
|
|
16
|
+
});
|
|
17
|
+
/**
|
|
18
|
+
* Clears the cached session when the backend reports it gone.
|
|
19
|
+
* @param error - The failure reported by a query or mutation.
|
|
20
|
+
*/
|
|
21
|
+
function dropExpiredSession(error) {
|
|
22
|
+
if (error instanceof UnauthorizedError) {
|
|
23
|
+
queryClient.setQueryData(sessionQueryKey, null);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return queryClient;
|
|
27
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sessionQueryKey is the react-query key the login session is cached under.
|
|
3
|
+
*/
|
|
4
|
+
export declare const sessionQueryKey: readonly ["session"];
|
|
5
|
+
/**
|
|
6
|
+
* Loads the current session as a react-query result.
|
|
7
|
+
* @returns The session query, whose data is the user or null.
|
|
8
|
+
*/
|
|
9
|
+
export declare function useSession(): import("@tanstack/react-query").UseQueryResult<NoInfer<{
|
|
10
|
+
id: string;
|
|
11
|
+
email: string;
|
|
12
|
+
name: string;
|
|
13
|
+
} | null>, Error>;
|
|
14
|
+
/**
|
|
15
|
+
* Ends the current session and drops all cached data belonging to the
|
|
16
|
+
* signed-out user.
|
|
17
|
+
* @returns The logout mutation.
|
|
18
|
+
*/
|
|
19
|
+
export declare function useLogout(): import("@tanstack/react-query").UseMutationResult<void, Error, void, unknown>;
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { hashKey, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
3
|
+
import { fetchSession, logout } from './api';
|
|
4
|
+
/**
|
|
5
|
+
* sessionQueryKey is the react-query key the login session is cached under.
|
|
6
|
+
*/
|
|
7
|
+
export const sessionQueryKey = ['session'];
|
|
8
|
+
/**
|
|
9
|
+
* Loads the current session as a react-query result.
|
|
10
|
+
* @returns The session query, whose data is the user or null.
|
|
11
|
+
*/
|
|
12
|
+
export function useSession() {
|
|
13
|
+
return useQuery({
|
|
14
|
+
queryKey: sessionQueryKey,
|
|
15
|
+
queryFn: ({ signal }) => fetchSession(signal),
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Ends the current session and drops all cached data belonging to the
|
|
20
|
+
* signed-out user.
|
|
21
|
+
* @returns The logout mutation.
|
|
22
|
+
*/
|
|
23
|
+
export function useLogout() {
|
|
24
|
+
const queryClient = useQueryClient();
|
|
25
|
+
return useMutation({
|
|
26
|
+
mutationFn: logout,
|
|
27
|
+
onSuccess: async () => {
|
|
28
|
+
await queryClient.cancelQueries();
|
|
29
|
+
queryClient.setQueryData(sessionQueryKey, null);
|
|
30
|
+
queryClient.removeQueries({
|
|
31
|
+
predicate: (query) => query.queryHash !== hashKey(sessionQueryKey),
|
|
32
|
+
});
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import '@testing-library/jest-dom/vitest';
|
|
2
|
+
import type { QueryClient } from '@tanstack/react-query';
|
|
3
|
+
import type { User } from '../api';
|
|
4
|
+
export { http, HttpResponse } from 'msw';
|
|
5
|
+
export declare const server: import("msw/node").SetupServer;
|
|
6
|
+
/**
|
|
7
|
+
* Installs the msw server lifecycle and DOM cleanup as vitest hooks.
|
|
8
|
+
*/
|
|
9
|
+
export declare function installTestEnvironment(): void;
|
|
10
|
+
/**
|
|
11
|
+
* defaultUser is the canned account tests sign in as.
|
|
12
|
+
*/
|
|
13
|
+
export declare const defaultUser: User;
|
|
14
|
+
/**
|
|
15
|
+
* Seeds the cached session so components render signed in without a fetch.
|
|
16
|
+
* @param client - The query client under test.
|
|
17
|
+
* @param user - The signed-in user, or null for a signed-out state.
|
|
18
|
+
*/
|
|
19
|
+
export declare function seedSession(client: QueryClient, user?: User | null): void;
|
|
20
|
+
/**
|
|
21
|
+
* Answers the session endpoint with the given user.
|
|
22
|
+
* @param user - The user the session belongs to.
|
|
23
|
+
* @returns The msw handler.
|
|
24
|
+
*/
|
|
25
|
+
export declare function sessionOk(user?: User): import("msw").HttpHandler;
|
|
26
|
+
/**
|
|
27
|
+
* Answers the session endpoint as signed out.
|
|
28
|
+
* @returns The msw handler.
|
|
29
|
+
*/
|
|
30
|
+
export declare function sessionAnonymous(): import("msw").HttpHandler;
|
|
31
|
+
/**
|
|
32
|
+
* Fails the session endpoint with a server error.
|
|
33
|
+
* @returns The msw handler.
|
|
34
|
+
*/
|
|
35
|
+
export declare function sessionFailure(): import("msw").HttpHandler;
|
|
36
|
+
/**
|
|
37
|
+
* Accepts any login with the given user.
|
|
38
|
+
* @param user - The user the login authenticates.
|
|
39
|
+
* @returns The msw handler.
|
|
40
|
+
*/
|
|
41
|
+
export declare function loginOk(user?: User): import("msw").HttpHandler;
|
|
42
|
+
/**
|
|
43
|
+
* Rejects logins as invalid credentials.
|
|
44
|
+
* @returns The msw handler.
|
|
45
|
+
*/
|
|
46
|
+
export declare function loginInvalid(): import("msw").HttpHandler;
|
|
47
|
+
/**
|
|
48
|
+
* Rejects logins as rate limited.
|
|
49
|
+
* @returns The msw handler.
|
|
50
|
+
*/
|
|
51
|
+
export declare function loginRateLimited(): import("msw").HttpHandler;
|
|
52
|
+
/**
|
|
53
|
+
* Fails logins with a server error.
|
|
54
|
+
* @returns The msw handler.
|
|
55
|
+
*/
|
|
56
|
+
export declare function loginFailure(): import("msw").HttpHandler;
|
|
57
|
+
/**
|
|
58
|
+
* Accepts logouts.
|
|
59
|
+
* @returns The msw handler.
|
|
60
|
+
*/
|
|
61
|
+
export declare function logoutOk(): import("msw").HttpHandler;
|
|
62
|
+
/**
|
|
63
|
+
* Fails logouts with a server error.
|
|
64
|
+
* @returns The msw handler.
|
|
65
|
+
*/
|
|
66
|
+
export declare function logoutFailure(): import("msw").HttpHandler;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import '@testing-library/jest-dom/vitest';
|
|
3
|
+
import { cleanup } from '@testing-library/react';
|
|
4
|
+
import { HttpResponse, http } from 'msw';
|
|
5
|
+
import { setupServer } from 'msw/node';
|
|
6
|
+
import { afterAll, afterEach, beforeAll } from 'vitest';
|
|
7
|
+
import { sessionQueryKey } from '../session';
|
|
8
|
+
export { http, HttpResponse } from 'msw';
|
|
9
|
+
export const server = setupServer();
|
|
10
|
+
/**
|
|
11
|
+
* Installs the msw server lifecycle and DOM cleanup as vitest hooks.
|
|
12
|
+
*/
|
|
13
|
+
export function installTestEnvironment() {
|
|
14
|
+
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
cleanup();
|
|
17
|
+
server.resetHandlers();
|
|
18
|
+
});
|
|
19
|
+
afterAll(() => server.close());
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* defaultUser is the canned account tests sign in as.
|
|
23
|
+
*/
|
|
24
|
+
export const defaultUser = {
|
|
25
|
+
id: '0198b2f0-0000-7000-8000-000000000001',
|
|
26
|
+
email: 'grace@example.com',
|
|
27
|
+
name: 'Grace Hopper',
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Seeds the cached session so components render signed in without a fetch.
|
|
31
|
+
* @param client - The query client under test.
|
|
32
|
+
* @param user - The signed-in user, or null for a signed-out state.
|
|
33
|
+
*/
|
|
34
|
+
export function seedSession(client, user = defaultUser) {
|
|
35
|
+
client.setQueryData(sessionQueryKey, user);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Answers the session endpoint with the given user.
|
|
39
|
+
* @param user - The user the session belongs to.
|
|
40
|
+
* @returns The msw handler.
|
|
41
|
+
*/
|
|
42
|
+
export function sessionOk(user = defaultUser) {
|
|
43
|
+
return http.get('/api/auth/session', () => HttpResponse.json(user));
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Answers the session endpoint as signed out.
|
|
47
|
+
* @returns The msw handler.
|
|
48
|
+
*/
|
|
49
|
+
export function sessionAnonymous() {
|
|
50
|
+
return http.get('/api/auth/session', () => HttpResponse.json({ error: 'no session' }, { status: 401 }));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Fails the session endpoint with a server error.
|
|
54
|
+
* @returns The msw handler.
|
|
55
|
+
*/
|
|
56
|
+
export function sessionFailure() {
|
|
57
|
+
return http.get('/api/auth/session', () => HttpResponse.json({ error: 'internal error' }, { status: 500 }));
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Accepts any login with the given user.
|
|
61
|
+
* @param user - The user the login authenticates.
|
|
62
|
+
* @returns The msw handler.
|
|
63
|
+
*/
|
|
64
|
+
export function loginOk(user = defaultUser) {
|
|
65
|
+
return http.post('/api/auth/login', () => HttpResponse.json(user));
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Rejects logins as invalid credentials.
|
|
69
|
+
* @returns The msw handler.
|
|
70
|
+
*/
|
|
71
|
+
export function loginInvalid() {
|
|
72
|
+
return http.post('/api/auth/login', () => HttpResponse.json({ error: 'invalid credentials' }, { status: 401 }));
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Rejects logins as rate limited.
|
|
76
|
+
* @returns The msw handler.
|
|
77
|
+
*/
|
|
78
|
+
export function loginRateLimited() {
|
|
79
|
+
return http.post('/api/auth/login', () => HttpResponse.json({ error: 'too many login attempts' }, { status: 429 }));
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Fails logins with a server error.
|
|
83
|
+
* @returns The msw handler.
|
|
84
|
+
*/
|
|
85
|
+
export function loginFailure() {
|
|
86
|
+
return http.post('/api/auth/login', () => HttpResponse.json({ error: 'internal error' }, { status: 500 }));
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Accepts logouts.
|
|
90
|
+
* @returns The msw handler.
|
|
91
|
+
*/
|
|
92
|
+
export function logoutOk() {
|
|
93
|
+
return http.post('/api/auth/logout', () => new HttpResponse(null, { status: 204 }));
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Fails logouts with a server error.
|
|
97
|
+
* @returns The msw handler.
|
|
98
|
+
*/
|
|
99
|
+
export function logoutFailure() {
|
|
100
|
+
return http.post('/api/auth/logout', () => HttpResponse.json({ error: 'internal error' }, { status: 500 }));
|
|
101
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renders the signed-in user's identity with a logout control, or nothing
|
|
3
|
+
* without an active session.
|
|
4
|
+
* @param className - Extra class names for the surrounding stack.
|
|
5
|
+
* @returns The account panel element, or null when signed out.
|
|
6
|
+
*/
|
|
7
|
+
export declare function AccountPanel({ className }: {
|
|
8
|
+
className?: string;
|
|
9
|
+
}): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { Button, Stack, Text } from '@wordpress/ui';
|
|
4
|
+
import { useLogout, useSession } from '../session';
|
|
5
|
+
/**
|
|
6
|
+
* Renders the signed-in user's identity with a logout control, or nothing
|
|
7
|
+
* without an active session.
|
|
8
|
+
* @param className - Extra class names for the surrounding stack.
|
|
9
|
+
* @returns The account panel element, or null when signed out.
|
|
10
|
+
*/
|
|
11
|
+
export function AccountPanel({ className }) {
|
|
12
|
+
const user = useSession().data;
|
|
13
|
+
const signOut = useLogout();
|
|
14
|
+
if (!user) {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
return (_jsxs(Stack, { direction: "column", gap: "sm", className: className, children: [_jsx(Text, { children: user.name }), _jsx(Button, { variant: "outline", disabled: signOut.isPending, onClick: () => signOut.mutate(), children: "Log out" }), signOut.isError ? (_jsx(Text, { role: "alert", children: "Logout failed, please try again." })) : null] }));
|
|
18
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { User } from '../api';
|
|
2
|
+
/**
|
|
3
|
+
* Renders the login form and reports the authenticated user upward.
|
|
4
|
+
* @param brand - The product name shown above the form.
|
|
5
|
+
* @param onLogin - Called with the user after a successful login.
|
|
6
|
+
* @returns The login screen element.
|
|
7
|
+
*/
|
|
8
|
+
export declare function LoginScreen({ brand, onLogin, }: {
|
|
9
|
+
brand: string;
|
|
10
|
+
onLogin: (user: User) => void | Promise<void>;
|
|
11
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { useMutation } from '@tanstack/react-query';
|
|
4
|
+
import { Button, Card, InputControl, Stack, Text } from '@wordpress/ui';
|
|
5
|
+
import { useState } from 'react';
|
|
6
|
+
import { InvalidCredentialsError, RateLimitedError, login } from '../api';
|
|
7
|
+
/**
|
|
8
|
+
* Maps a login attempt error to the message shown to the user.
|
|
9
|
+
* @param error - The error thrown by the login attempt.
|
|
10
|
+
* @returns The message to display.
|
|
11
|
+
*/
|
|
12
|
+
function loginErrorMessage(error) {
|
|
13
|
+
if (error instanceof InvalidCredentialsError) {
|
|
14
|
+
return 'Invalid email or password.';
|
|
15
|
+
}
|
|
16
|
+
if (error instanceof RateLimitedError) {
|
|
17
|
+
return 'Too many attempts. Please wait a minute and try again.';
|
|
18
|
+
}
|
|
19
|
+
return 'Login failed, please try again.';
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Renders the login form and reports the authenticated user upward.
|
|
23
|
+
* @param brand - The product name shown above the form.
|
|
24
|
+
* @param onLogin - Called with the user after a successful login.
|
|
25
|
+
* @returns The login screen element.
|
|
26
|
+
*/
|
|
27
|
+
export function LoginScreen({ brand, onLogin, }) {
|
|
28
|
+
const [email, setEmail] = useState('');
|
|
29
|
+
const [password, setPassword] = useState('');
|
|
30
|
+
const attempt = useMutation({
|
|
31
|
+
mutationFn: () => login(email.trim(), password),
|
|
32
|
+
onSuccess: (user) => onLogin(user),
|
|
33
|
+
});
|
|
34
|
+
return (_jsx("div", { className: "gopherium-login", children: _jsx(Card.Root, { className: "gopherium-login__card", children: _jsx(Card.Content, { children: _jsx("form", { onSubmit: (event) => {
|
|
35
|
+
event.preventDefault();
|
|
36
|
+
attempt.mutate();
|
|
37
|
+
}, children: _jsxs(Stack, { direction: "column", gap: "lg", children: [_jsx(Text, { variant: "heading-lg", render: _jsx("h1", {}), children: brand }), _jsx(InputControl, { label: "Email", type: "email", value: email, onChange: (event) => setEmail(event.target.value) }), _jsx(InputControl, { label: "Password", type: "password", value: password, onChange: (event) => setPassword(event.target.value) }), _jsx(Button, { type: "submit", disabled: email.trim() === '' || password === '' || attempt.isPending, children: "Log in" }), attempt.isError ? (_jsx(Text, { role: "alert", children: loginErrorMessage(attempt.error) })) : null] }) }) }) }) }));
|
|
38
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renders the new user form, creating an account and reporting success
|
|
3
|
+
* upward, typically for the app to navigate back to its user list.
|
|
4
|
+
* @param onCreated - Called after the account is created.
|
|
5
|
+
* @returns The new user screen element.
|
|
6
|
+
*/
|
|
7
|
+
export declare function NewUserScreen({ onCreated, }: {
|
|
8
|
+
onCreated?: () => void | Promise<void>;
|
|
9
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
|
4
|
+
import { Button, InputControl, Stack, Text } from '@wordpress/ui';
|
|
5
|
+
import { useState } from 'react';
|
|
6
|
+
import { EmailTakenError, ValidationError, createUser, usersQueryKey } from '../admin';
|
|
7
|
+
/**
|
|
8
|
+
* Maps a creation failure to the message shown under the form, surfacing
|
|
9
|
+
* the backend's explanation for rejected input.
|
|
10
|
+
* @param error - The error thrown by the create mutation.
|
|
11
|
+
* @returns The human-readable failure message.
|
|
12
|
+
*/
|
|
13
|
+
function createErrorMessage(error) {
|
|
14
|
+
if (error instanceof EmailTakenError) {
|
|
15
|
+
return 'That email is already in use.';
|
|
16
|
+
}
|
|
17
|
+
if (error instanceof ValidationError) {
|
|
18
|
+
return error.message;
|
|
19
|
+
}
|
|
20
|
+
return 'The user could not be created.';
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Renders the new user form, creating an account and reporting success
|
|
24
|
+
* upward, typically for the app to navigate back to its user list.
|
|
25
|
+
* @param onCreated - Called after the account is created.
|
|
26
|
+
* @returns The new user screen element.
|
|
27
|
+
*/
|
|
28
|
+
export function NewUserScreen({ onCreated, }) {
|
|
29
|
+
const queryClient = useQueryClient();
|
|
30
|
+
const [email, setEmail] = useState('');
|
|
31
|
+
const [name, setName] = useState('');
|
|
32
|
+
const [password, setPassword] = useState('');
|
|
33
|
+
const create = useMutation({
|
|
34
|
+
mutationFn: () => createUser({ email: email.trim(), name: name.trim(), password }),
|
|
35
|
+
onSuccess: async () => {
|
|
36
|
+
await queryClient.invalidateQueries({ queryKey: usersQueryKey });
|
|
37
|
+
await onCreated?.();
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
return (_jsxs(Stack, { direction: "column", gap: "lg", children: [_jsx(Text, { variant: "heading-lg", render: _jsx("h1", {}), children: "New user" }), _jsx("form", { onSubmit: (event) => {
|
|
41
|
+
event.preventDefault();
|
|
42
|
+
create.mutate();
|
|
43
|
+
}, children: _jsxs(Stack, { direction: "column", gap: "md", children: [_jsx(InputControl, { label: "Email", type: "email", autoComplete: "off", value: email, onChange: (event) => setEmail(event.target.value) }), _jsx(InputControl, { label: "Name", autoComplete: "off", value: name, onChange: (event) => setName(event.target.value) }), _jsx(InputControl, { label: "Password", type: "password", autoComplete: "new-password", value: password, onChange: (event) => setPassword(event.target.value) }), _jsx(Button, { type: "submit", disabled: email.trim() === '' ||
|
|
44
|
+
name.trim() === '' ||
|
|
45
|
+
password === '' ||
|
|
46
|
+
create.isPending, children: "Create user" }), create.isError ? (_jsx(Text, { role: "alert", children: createErrorMessage(create.error) })) : null] }) })] }));
|
|
47
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ReactElement } from 'react';
|
|
2
|
+
/**
|
|
3
|
+
* Renders the user administration screen: the account list with status and
|
|
4
|
+
* disable controls, plus an optional control to create a new user.
|
|
5
|
+
* @param newUserRender - The navigation element the New user button renders
|
|
6
|
+
* as, typically the app router's link to its create form.
|
|
7
|
+
* @returns The users screen, or a loading or error message.
|
|
8
|
+
*/
|
|
9
|
+
export declare function UsersScreen({ newUserRender, }: {
|
|
10
|
+
newUserRender?: ReactElement<Record<string, unknown>>;
|
|
11
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
4
|
+
import { Badge, Button, Stack, Text, VisuallyHidden } from '@wordpress/ui';
|
|
5
|
+
import { fetchUsers, setUserDisabled, usersQueryKey } from '../admin';
|
|
6
|
+
import { useSession } from '../session';
|
|
7
|
+
/**
|
|
8
|
+
* Renders one user row with status and a disable toggle, hidden for the
|
|
9
|
+
* signed-in account.
|
|
10
|
+
* @param user - The user the row describes.
|
|
11
|
+
* @param isSelf - Whether the row is the signed-in account.
|
|
12
|
+
* @returns The table row element.
|
|
13
|
+
*/
|
|
14
|
+
function UserRow({ user, isSelf }) {
|
|
15
|
+
const queryClient = useQueryClient();
|
|
16
|
+
const toggle = useMutation({
|
|
17
|
+
mutationFn: () => setUserDisabled(user.id, !user.disabled),
|
|
18
|
+
onSuccess: () => queryClient.invalidateQueries({ queryKey: usersQueryKey }),
|
|
19
|
+
});
|
|
20
|
+
return (_jsxs("tr", { children: [_jsx("td", { children: user.name }), _jsx("td", { children: user.email }), _jsx("td", { children: _jsx(Badge, { intent: user.disabled ? 'draft' : 'stable', children: user.disabled ? 'Disabled' : 'Active' }) }), _jsx("td", { children: isSelf ? null : (_jsxs(Stack, { direction: "column", gap: "xs", children: [_jsx(Button, { variant: "outline", "aria-label": `${user.disabled ? 'Enable' : 'Disable'} ${user.name}`, disabled: toggle.isPending, onClick: () => toggle.mutate(), children: user.disabled ? 'Enable' : 'Disable' }), toggle.isError ? _jsx(Text, { role: "alert", children: "Update failed." }) : null] })) })] }));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Renders the user administration screen: the account list with status and
|
|
24
|
+
* disable controls, plus an optional control to create a new user.
|
|
25
|
+
* @param newUserRender - The navigation element the New user button renders
|
|
26
|
+
* as, typically the app router's link to its create form.
|
|
27
|
+
* @returns The users screen, or a loading or error message.
|
|
28
|
+
*/
|
|
29
|
+
export function UsersScreen({ newUserRender, }) {
|
|
30
|
+
const currentUserId = useSession().data?.id;
|
|
31
|
+
const users = useQuery({
|
|
32
|
+
queryKey: usersQueryKey,
|
|
33
|
+
queryFn: ({ signal }) => fetchUsers(signal),
|
|
34
|
+
});
|
|
35
|
+
if (users.isPending) {
|
|
36
|
+
return _jsx(Text, { role: "status", children: "Loading users\u2026" });
|
|
37
|
+
}
|
|
38
|
+
if (users.isError) {
|
|
39
|
+
return _jsx(Text, { role: "alert", children: "Users could not be loaded." });
|
|
40
|
+
}
|
|
41
|
+
return (_jsxs(Stack, { direction: "column", gap: "lg", children: [_jsxs(Stack, { direction: "row", align: "center", gap: "md", children: [_jsx(Text, { variant: "heading-lg", render: _jsx("h1", {}), children: "Users" }), newUserRender ? _jsx(Button, { render: newUserRender, children: "New user" }) : null] }), _jsxs("table", { className: "gopherium-users", children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "Name" }), _jsx("th", { scope: "col", children: "Email" }), _jsx("th", { scope: "col", children: "Status" }), _jsx("th", { scope: "col", children: _jsx(VisuallyHidden, { children: "Actions" }) })] }) }), _jsx("tbody", { children: users.data.map((user) => (_jsx(UserRow, { user: user, isSelf: user.id === currentUserId }, user.id))) })] })] }));
|
|
42
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
export { AccountPanel } from './AccountPanel';
|
|
3
|
+
export { LoginScreen } from './LoginScreen';
|
|
4
|
+
export { usersNavItem } from './nav';
|
|
5
|
+
export { NewUserScreen } from './NewUserScreen';
|
|
6
|
+
export { UsersScreen } from './UsersScreen';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ComponentProps, ReactElement } from 'react';
|
|
2
|
+
/**
|
|
3
|
+
* usersNavItem is the ready-made navigation entry for the user
|
|
4
|
+
* administration screen.
|
|
5
|
+
*/
|
|
6
|
+
export declare const usersNavItem: {
|
|
7
|
+
label: string;
|
|
8
|
+
to: string;
|
|
9
|
+
icon: ReactElement<ComponentProps<'svg'>>;
|
|
10
|
+
};
|
package/dist/wpds/nav.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
const usersIcon = (_jsx("svg", { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", fill: "currentColor", children: _jsx("path", { d: "M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" }) }));
|
|
3
|
+
/**
|
|
4
|
+
* usersNavItem is the ready-made navigation entry for the user
|
|
5
|
+
* administration screen.
|
|
6
|
+
*/
|
|
7
|
+
export const usersNavItem = { label: 'Users', to: '/users', icon: usersIcon };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/* SPDX-License-Identifier: Apache-2.0 */
|
|
2
|
+
|
|
3
|
+
.gopherium-login {
|
|
4
|
+
display: flex;
|
|
5
|
+
align-items: center;
|
|
6
|
+
justify-content: center;
|
|
7
|
+
min-height: 100vh;
|
|
8
|
+
padding: 24px;
|
|
9
|
+
box-sizing: border-box;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
.gopherium-login__card {
|
|
13
|
+
width: 100%;
|
|
14
|
+
max-width: 360px;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
.gopherium-users {
|
|
18
|
+
width: 100%;
|
|
19
|
+
border-collapse: collapse;
|
|
20
|
+
text-align: left;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
.gopherium-users th,
|
|
24
|
+
.gopherium-users td {
|
|
25
|
+
padding: 8px 12px;
|
|
26
|
+
border-bottom: 1px solid var(--wpds-color-stroke-surface-neutral);
|
|
27
|
+
vertical-align: middle;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
.gopherium-users th {
|
|
31
|
+
font-size: var(--wpds-typography-font-size-sm);
|
|
32
|
+
color: var(--wpds-color-foreground-content-neutral-weak);
|
|
33
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@gopherium/react-auth",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Session authentication for React apps backed by gouncer's authkit.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/gopherium/gouncer.git",
|
|
10
|
+
"directory": "react-auth"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./admin": {
|
|
21
|
+
"types": "./dist/admin/index.d.ts",
|
|
22
|
+
"default": "./dist/admin/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./wpds": {
|
|
25
|
+
"types": "./dist/wpds/index.d.ts",
|
|
26
|
+
"default": "./dist/wpds/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./wpds/style.css": "./dist/wpds/style.css",
|
|
29
|
+
"./testing": {
|
|
30
|
+
"types": "./dist/testing/index.d.ts",
|
|
31
|
+
"default": "./dist/testing/index.js"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"zod": "^4.4.3"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@tanstack/react-query": "^5.101.2",
|
|
42
|
+
"@testing-library/jest-dom": "^6.9.1",
|
|
43
|
+
"@testing-library/react": "^16.3.2",
|
|
44
|
+
"@wordpress/ui": "^0.17.0",
|
|
45
|
+
"msw": "^2.15.0",
|
|
46
|
+
"react": "^19.2.7",
|
|
47
|
+
"vitest": "^4.1.10"
|
|
48
|
+
},
|
|
49
|
+
"peerDependenciesMeta": {
|
|
50
|
+
"@testing-library/jest-dom": {
|
|
51
|
+
"optional": true
|
|
52
|
+
},
|
|
53
|
+
"@testing-library/react": {
|
|
54
|
+
"optional": true
|
|
55
|
+
},
|
|
56
|
+
"@wordpress/ui": {
|
|
57
|
+
"optional": true
|
|
58
|
+
},
|
|
59
|
+
"msw": {
|
|
60
|
+
"optional": true
|
|
61
|
+
},
|
|
62
|
+
"vitest": {
|
|
63
|
+
"optional": true
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
"devDependencies": {
|
|
67
|
+
"@tanstack/react-query": "^5.101.2",
|
|
68
|
+
"@testing-library/jest-dom": "^6.9.1",
|
|
69
|
+
"@testing-library/react": "^16.3.2",
|
|
70
|
+
"@testing-library/user-event": "^14.6.1",
|
|
71
|
+
"@types/react": "^19.2.17",
|
|
72
|
+
"@vitejs/plugin-react": "^6.0.3",
|
|
73
|
+
"@vitest/coverage-v8": "^4.1.10",
|
|
74
|
+
"@wordpress/ui": "^0.17.0",
|
|
75
|
+
"eslint": "^9.39.1",
|
|
76
|
+
"eslint-plugin-jsdoc": "^63.0.13",
|
|
77
|
+
"eslint-plugin-tsdoc": "^0.4.0",
|
|
78
|
+
"jsdom": "^29.1.1",
|
|
79
|
+
"msw": "^2.15.0",
|
|
80
|
+
"oxlint": "^1.71.0",
|
|
81
|
+
"react": "^19.2.7",
|
|
82
|
+
"react-dom": "^19.2.7",
|
|
83
|
+
"typescript": "~6.0.2",
|
|
84
|
+
"typescript-eslint": "^8.46.4",
|
|
85
|
+
"vite": "^8.1.4",
|
|
86
|
+
"vitest": "^4.1.10"
|
|
87
|
+
},
|
|
88
|
+
"scripts": {
|
|
89
|
+
"build": "tsc -p tsconfig.build.json && cp src/wpds/style.css dist/wpds/style.css",
|
|
90
|
+
"cover": "vitest run --coverage",
|
|
91
|
+
"lint": "oxlint"
|
|
92
|
+
}
|
|
93
|
+
}
|