@orsetra/shared-ui 1.11.10 → 1.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/auth/index.ts +29 -0
- package/auth/session-controller.ts +316 -0
- package/auth/session-provider.tsx +135 -0
- package/auth/session.ts +99 -0
- package/components/ui/confirmation-dialog.tsx +13 -0
- package/lib/http-client.ts +3 -0
- package/package.json +16 -2
package/auth/index.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The session of the console applications. Kept out of the root index: it needs
|
|
2
|
+
// oidc-client-ts and react-oidc-context, which only the applications that sign users in carry.
|
|
3
|
+
export {
|
|
4
|
+
SessionController,
|
|
5
|
+
SessionExpiredError,
|
|
6
|
+
isSessionExpiredError,
|
|
7
|
+
isDefinitiveRenewError,
|
|
8
|
+
PRE_AUTH_URL_KEY,
|
|
9
|
+
type SessionSnapshot,
|
|
10
|
+
type SessionStatus,
|
|
11
|
+
type SessionUser,
|
|
12
|
+
type SessionUserManager,
|
|
13
|
+
} from './session-controller';
|
|
14
|
+
export {
|
|
15
|
+
configureSession,
|
|
16
|
+
getSession,
|
|
17
|
+
getSessionUserManager,
|
|
18
|
+
sessionAuthHeaders,
|
|
19
|
+
startSession,
|
|
20
|
+
type SessionSettings,
|
|
21
|
+
} from './session';
|
|
22
|
+
export {
|
|
23
|
+
SessionProvider,
|
|
24
|
+
SessionGate,
|
|
25
|
+
SessionExpiredScreen,
|
|
26
|
+
useSession,
|
|
27
|
+
type Session,
|
|
28
|
+
type SessionExpiredControls,
|
|
29
|
+
} from './session-provider';
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The state of the user's session, for every application of the console.
|
|
3
|
+
*
|
|
4
|
+
* react-oidc-context computes `isAuthenticated` when an event reaches it, never when the access
|
|
5
|
+
* token runs out: a page stays displayed with an expired token and every call answers 401. This
|
|
6
|
+
* controller is the single owner of that question. It renews the token, retries a renewal that
|
|
7
|
+
* failed for a passing reason, and says when the session is over.
|
|
8
|
+
*
|
|
9
|
+
* It knows nothing of React nor of oidc-client-ts: it talks to the few methods of a UserManager
|
|
10
|
+
* listed in SessionUserManager, which keeps it testable.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export type SessionStatus =
|
|
14
|
+
/** Not known yet: the stored user is being read. */
|
|
15
|
+
| 'loading'
|
|
16
|
+
/** A user with an access token that has not expired. */
|
|
17
|
+
| 'valid'
|
|
18
|
+
/** No user: nobody signed in on this page yet. */
|
|
19
|
+
| 'anonymous'
|
|
20
|
+
/** There was a valid session on this page, and it could not be renewed. */
|
|
21
|
+
| 'expired'
|
|
22
|
+
/** The user asked to sign out; the page is leaving. */
|
|
23
|
+
| 'signing-out';
|
|
24
|
+
|
|
25
|
+
export interface SessionUser {
|
|
26
|
+
access_token: string;
|
|
27
|
+
/** Seconds since the epoch. */
|
|
28
|
+
expires_at?: number;
|
|
29
|
+
profile?: unknown;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** What the controller needs of an oidc-client-ts UserManager. */
|
|
33
|
+
export interface SessionUserManager {
|
|
34
|
+
getUser(): Promise<SessionUser | null>;
|
|
35
|
+
signinSilent(): Promise<SessionUser | null>;
|
|
36
|
+
signinRedirect(args?: { prompt?: string }): Promise<void>;
|
|
37
|
+
signoutRedirect(): Promise<void>;
|
|
38
|
+
events: {
|
|
39
|
+
addUserLoaded(callback: (user: SessionUser) => void): unknown;
|
|
40
|
+
addUserUnloaded(callback: () => void): unknown;
|
|
41
|
+
addAccessTokenExpiring(callback: () => void): unknown;
|
|
42
|
+
addAccessTokenExpired(callback: () => void): unknown;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface SessionSnapshot {
|
|
47
|
+
status: SessionStatus;
|
|
48
|
+
user: SessionUser | null;
|
|
49
|
+
/** A redirect to the sign-in page is on its way. */
|
|
50
|
+
pending: boolean;
|
|
51
|
+
/** Why the last redirect to the sign-in page failed. */
|
|
52
|
+
error: string | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface SessionControllerOptions {
|
|
56
|
+
userManager: SessionUserManager;
|
|
57
|
+
/** Milliseconds since the epoch. */
|
|
58
|
+
now?: () => number;
|
|
59
|
+
sleep?: (ms: number) => Promise<void>;
|
|
60
|
+
/** Wait before each renewal attempt, in milliseconds; its length is the number of attempts. */
|
|
61
|
+
retryDelays?: number[];
|
|
62
|
+
/** After a renewal, a 401 within this time is not a session problem. */
|
|
63
|
+
unauthorizedGraceMs?: number;
|
|
64
|
+
/** Where the page to come back to is kept across the redirect. */
|
|
65
|
+
storage?: Pick<Storage, 'setItem'>;
|
|
66
|
+
location?: () => { pathname: string; search: string };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export const PRE_AUTH_URL_KEY = 'pre_auth_url';
|
|
70
|
+
|
|
71
|
+
/** Thrown instead of sending a request without a token. */
|
|
72
|
+
export class SessionExpiredError extends Error {
|
|
73
|
+
constructor(message = 'The session has expired') {
|
|
74
|
+
super(message);
|
|
75
|
+
this.name = 'SessionExpiredError';
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function isSessionExpiredError(error: unknown): boolean {
|
|
80
|
+
return (error as { name?: unknown } | null)?.name === 'SessionExpiredError';
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* An answer of the identity provider (invalid_grant, login_required…) will not change by asking
|
|
85
|
+
* again; a network error or a timeout may.
|
|
86
|
+
*/
|
|
87
|
+
export function isDefinitiveRenewError(error: unknown): boolean {
|
|
88
|
+
return typeof (error as { error?: unknown } | null)?.error === 'string';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const messageOf = (error: unknown): string =>
|
|
92
|
+
error instanceof Error && error.message ? error.message : 'The sign-in page could not be reached';
|
|
93
|
+
|
|
94
|
+
export class SessionController {
|
|
95
|
+
private readonly userManager: SessionUserManager;
|
|
96
|
+
private readonly now: () => number;
|
|
97
|
+
private readonly sleep: (ms: number) => Promise<void>;
|
|
98
|
+
private readonly retryDelays: number[];
|
|
99
|
+
private readonly unauthorizedGraceMs: number;
|
|
100
|
+
private readonly storage?: Pick<Storage, 'setItem'>;
|
|
101
|
+
private readonly location?: () => { pathname: string; search: string };
|
|
102
|
+
|
|
103
|
+
private snapshot: SessionSnapshot = { status: 'loading', user: null, pending: false, error: null };
|
|
104
|
+
private readonly listeners = new Set<() => void>();
|
|
105
|
+
private starting: Promise<void> | null = null;
|
|
106
|
+
private renewing: Promise<SessionUser | null> | null = null;
|
|
107
|
+
private redirecting: Promise<boolean> | null = null;
|
|
108
|
+
/** A session was valid on this page: losing it is an expiry, not a first visit. */
|
|
109
|
+
private wasValid = false;
|
|
110
|
+
private lastRenewAt = 0;
|
|
111
|
+
private lastRenewWasRefused = false;
|
|
112
|
+
|
|
113
|
+
constructor(options: SessionControllerOptions) {
|
|
114
|
+
this.userManager = options.userManager;
|
|
115
|
+
this.now = options.now ?? (() => Date.now());
|
|
116
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
117
|
+
this.retryDelays = options.retryDelays ?? [0, 2000, 5000];
|
|
118
|
+
this.unauthorizedGraceMs = options.unauthorizedGraceMs ?? 30_000;
|
|
119
|
+
this.storage = options.storage;
|
|
120
|
+
this.location = options.location;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
getSnapshot = (): SessionSnapshot => this.snapshot;
|
|
124
|
+
|
|
125
|
+
subscribe = (listener: () => void): (() => void) => {
|
|
126
|
+
this.listeners.add(listener);
|
|
127
|
+
return () => {
|
|
128
|
+
this.listeners.delete(listener);
|
|
129
|
+
};
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/** Reads the stored user and starts listening to the UserManager. Safe to call again. */
|
|
133
|
+
start(): Promise<void> {
|
|
134
|
+
if (!this.starting) {
|
|
135
|
+
const { events } = this.userManager;
|
|
136
|
+
events.addUserLoaded((user) => this.onUserLoaded(user));
|
|
137
|
+
events.addUserUnloaded(() => this.onUserUnloaded());
|
|
138
|
+
// The UserManager raises this a minute before the token expires.
|
|
139
|
+
events.addAccessTokenExpiring(() => {
|
|
140
|
+
void this.renew();
|
|
141
|
+
});
|
|
142
|
+
events.addAccessTokenExpired(() => {
|
|
143
|
+
void this.recheck();
|
|
144
|
+
});
|
|
145
|
+
this.starting = this.recheck();
|
|
146
|
+
}
|
|
147
|
+
return this.starting;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Compares the session with the stored user: on start, when the token expires, when the page
|
|
152
|
+
* comes back to the front or the network comes back.
|
|
153
|
+
*/
|
|
154
|
+
async recheck(): Promise<void> {
|
|
155
|
+
if (this.snapshot.status === 'signing-out') return;
|
|
156
|
+
const user = await this.readUser();
|
|
157
|
+
if (user && !this.isExpired(user)) {
|
|
158
|
+
this.setValid(user);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (user && !this.lastRenewWasRefused) {
|
|
162
|
+
if (await this.renew()) return;
|
|
163
|
+
}
|
|
164
|
+
this.setLost();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The access token to send with a request. An expired token is renewed first, once for all the
|
|
169
|
+
* requests that wait; when it cannot be, the request is refused here rather than sent without
|
|
170
|
+
* a token.
|
|
171
|
+
*/
|
|
172
|
+
async getAccessToken(): Promise<string> {
|
|
173
|
+
await this.start();
|
|
174
|
+
const user = await this.readUser();
|
|
175
|
+
if (user && !this.isExpired(user)) return user.access_token;
|
|
176
|
+
if (user) {
|
|
177
|
+
const renewed = await this.renew();
|
|
178
|
+
if (renewed) return renewed.access_token;
|
|
179
|
+
}
|
|
180
|
+
this.setLost();
|
|
181
|
+
throw new SessionExpiredError();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* A request was answered 401. The token is renewed; a refusal of the identity provider means
|
|
186
|
+
* the session is over even though the token has not reached its expiry.
|
|
187
|
+
*/
|
|
188
|
+
async handleUnauthorized(): Promise<void> {
|
|
189
|
+
if (this.snapshot.status !== 'valid') return;
|
|
190
|
+
if (this.lastRenewAt > 0 && this.now() - this.lastRenewAt < this.unauthorizedGraceMs) return;
|
|
191
|
+
const renewed = await this.renew();
|
|
192
|
+
if (!renewed && this.lastRenewWasRefused) this.setLost();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** One renewal at a time: every caller waits for the same one. */
|
|
196
|
+
renew(): Promise<SessionUser | null> {
|
|
197
|
+
if (!this.renewing) {
|
|
198
|
+
this.renewing = this.attemptRenew().finally(() => {
|
|
199
|
+
this.renewing = null;
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
return this.renewing;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Sends the user to the sign-in page. Resolves false when the redirect could not start; the
|
|
207
|
+
* session then stays as it is, with the reason in `error`, so that the screen that asked can
|
|
208
|
+
* offer to try again.
|
|
209
|
+
*/
|
|
210
|
+
signIn(options: { forceLogin?: boolean } = {}): Promise<boolean> {
|
|
211
|
+
if (!this.redirecting) {
|
|
212
|
+
this.redirecting = this.redirectToSignIn(options).finally(() => {
|
|
213
|
+
this.redirecting = null;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
return this.redirecting;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async signOut(): Promise<void> {
|
|
220
|
+
this.update({ status: 'signing-out', pending: false, error: null });
|
|
221
|
+
try {
|
|
222
|
+
await this.userManager.signoutRedirect();
|
|
223
|
+
} catch (error) {
|
|
224
|
+
this.wasValid = false;
|
|
225
|
+
this.update({ status: 'anonymous', user: null, error: messageOf(error) });
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
private async attemptRenew(): Promise<SessionUser | null> {
|
|
230
|
+
for (const delay of this.retryDelays) {
|
|
231
|
+
if (delay > 0) await this.sleep(delay);
|
|
232
|
+
try {
|
|
233
|
+
const user = await this.userManager.signinSilent();
|
|
234
|
+
if (user && !this.isExpired(user)) {
|
|
235
|
+
this.lastRenewAt = this.now();
|
|
236
|
+
this.lastRenewWasRefused = false;
|
|
237
|
+
this.setValid(user);
|
|
238
|
+
return user;
|
|
239
|
+
}
|
|
240
|
+
this.lastRenewWasRefused = true;
|
|
241
|
+
return null;
|
|
242
|
+
} catch (error) {
|
|
243
|
+
this.lastRenewWasRefused = isDefinitiveRenewError(error);
|
|
244
|
+
if (this.lastRenewWasRefused) return null;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
private async redirectToSignIn({ forceLogin }: { forceLogin?: boolean }): Promise<boolean> {
|
|
251
|
+
this.update({ pending: true, error: null });
|
|
252
|
+
try {
|
|
253
|
+
this.rememberPage();
|
|
254
|
+
await this.userManager.signinRedirect(forceLogin ? { prompt: 'login' } : undefined);
|
|
255
|
+
// The page is leaving: `pending` stays on until it does.
|
|
256
|
+
return true;
|
|
257
|
+
} catch (error) {
|
|
258
|
+
this.update({ pending: false, error: messageOf(error) });
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private rememberPage(): void {
|
|
264
|
+
if (!this.storage || !this.location) return;
|
|
265
|
+
const { pathname, search } = this.location();
|
|
266
|
+
if (pathname === '/') return;
|
|
267
|
+
try {
|
|
268
|
+
this.storage.setItem(PRE_AUTH_URL_KEY, pathname + search);
|
|
269
|
+
} catch {
|
|
270
|
+
// Without storage the user lands on the home page after signing in.
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private async readUser(): Promise<SessionUser | null> {
|
|
275
|
+
try {
|
|
276
|
+
return await this.userManager.getUser();
|
|
277
|
+
} catch {
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
private isExpired(user: SessionUser): boolean {
|
|
283
|
+
return user.expires_at !== undefined && user.expires_at * 1000 <= this.now();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
private onUserLoaded(user: SessionUser): void {
|
|
287
|
+
if (this.snapshot.status === 'signing-out') return;
|
|
288
|
+
if (this.isExpired(user)) return;
|
|
289
|
+
// A user just signed in or renewed: a 401 right after is not a session problem.
|
|
290
|
+
this.lastRenewAt = this.now();
|
|
291
|
+
this.lastRenewWasRefused = false;
|
|
292
|
+
this.setValid(user);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
private onUserUnloaded(): void {
|
|
296
|
+
if (this.snapshot.status === 'signing-out') return;
|
|
297
|
+
this.setLost();
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private setValid(user: SessionUser): void {
|
|
301
|
+
this.wasValid = true;
|
|
302
|
+
if (this.snapshot.status === 'valid' && this.snapshot.user?.access_token === user.access_token) return;
|
|
303
|
+
this.update({ status: 'valid', user, pending: false, error: null });
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private setLost(): void {
|
|
307
|
+
const status: SessionStatus = this.wasValid ? 'expired' : 'anonymous';
|
|
308
|
+
if (this.snapshot.status === status && this.snapshot.user === null) return;
|
|
309
|
+
this.update({ status, user: null });
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
private update(change: Partial<SessionSnapshot>): void {
|
|
313
|
+
this.snapshot = { ...this.snapshot, ...change };
|
|
314
|
+
for (const listener of [...this.listeners]) listener();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import * as React from 'react';
|
|
4
|
+
import { AuthProvider, type AuthProviderProps } from 'react-oidc-context';
|
|
5
|
+
import { Button } from '../components/ui/button';
|
|
6
|
+
import { getSession, getSessionUserManager, sessionStore, startSession } from './session';
|
|
7
|
+
import type { SessionSnapshot } from './session-controller';
|
|
8
|
+
|
|
9
|
+
interface SessionProviderProps {
|
|
10
|
+
children: React.ReactNode;
|
|
11
|
+
/** Called once the redirect back from the sign-in page has been processed. */
|
|
12
|
+
onSigninCallback?: AuthProviderProps['onSigninCallback'];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Gives the React tree the session of the page. It wraps react-oidc-context's AuthProvider on
|
|
17
|
+
* the session's own UserManager, so that `useAuth()` keeps working where it reads the profile,
|
|
18
|
+
* and starts the controller that decides whether the session is valid.
|
|
19
|
+
*
|
|
20
|
+
* configureSession() must have been called before the first render in the browser.
|
|
21
|
+
*/
|
|
22
|
+
export function SessionProvider({ children, onSigninCallback }: SessionProviderProps) {
|
|
23
|
+
React.useEffect(() => startSession(), []);
|
|
24
|
+
|
|
25
|
+
// No UserManager while rendering on the server: AuthProvider builds none there either.
|
|
26
|
+
const props = (typeof window === 'undefined'
|
|
27
|
+
? { authority: '', client_id: '', redirect_uri: '' }
|
|
28
|
+
: { userManager: getSessionUserManager() }) as AuthProviderProps;
|
|
29
|
+
|
|
30
|
+
return (
|
|
31
|
+
<AuthProvider {...props} onSigninCallback={onSigninCallback}>
|
|
32
|
+
{children}
|
|
33
|
+
</AuthProvider>
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface Session extends SessionSnapshot {
|
|
38
|
+
/** Sends the user to the sign-in page; false when the redirect could not start. */
|
|
39
|
+
signIn: (options?: { forceLogin?: boolean }) => Promise<boolean>;
|
|
40
|
+
signOut: () => Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const signIn: Session['signIn'] = (options) => getSession().signIn(options);
|
|
44
|
+
const signOut: Session['signOut'] = () => getSession().signOut();
|
|
45
|
+
|
|
46
|
+
export function useSession(): Session {
|
|
47
|
+
const snapshot = React.useSyncExternalStore(
|
|
48
|
+
sessionStore.subscribe,
|
|
49
|
+
sessionStore.getSnapshot,
|
|
50
|
+
sessionStore.getServerSnapshot,
|
|
51
|
+
);
|
|
52
|
+
return React.useMemo(() => ({ ...snapshot, signIn, signOut }), [snapshot]);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface SessionExpiredControls {
|
|
56
|
+
/** Sends the user to the sign-in page. */
|
|
57
|
+
signIn: () => void;
|
|
58
|
+
pending: boolean;
|
|
59
|
+
/** Why the last attempt failed, when it did. */
|
|
60
|
+
error: string | null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface SessionGateProps {
|
|
64
|
+
children: React.ReactNode;
|
|
65
|
+
/** Shown while the session is read, and while the page leaves for the sign-in page. */
|
|
66
|
+
loading: React.ReactNode;
|
|
67
|
+
/** Shown in place of the pages once the session is over. */
|
|
68
|
+
expired: (controls: SessionExpiredControls) => React.ReactNode;
|
|
69
|
+
/**
|
|
70
|
+
* After a session ended, the button asks for the credentials again (prompt=login) even when
|
|
71
|
+
* the identity provider still has a session. On by default: the screen says the session has
|
|
72
|
+
* expired. A first visit, or a new tab, still signs in silently, which is what single sign-on
|
|
73
|
+
* is for. This is ergonomics, not a control: how long a user stays signed in is decided by
|
|
74
|
+
* the lifetimes set in the identity provider.
|
|
75
|
+
*/
|
|
76
|
+
forceLoginAfterExpiry?: boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Renders the pages only while the session is valid.
|
|
81
|
+
*
|
|
82
|
+
* - No user yet: the page leaves for the sign-in page by itself.
|
|
83
|
+
* - A session that ended: the pages are replaced, not covered, by the `expired` screen. Nothing
|
|
84
|
+
* stays displayed that would call the API without a token.
|
|
85
|
+
*/
|
|
86
|
+
export function SessionGate({ children, loading, expired, forceLoginAfterExpiry = true }: SessionGateProps) {
|
|
87
|
+
const session = useSession();
|
|
88
|
+
const { status, pending, error } = session;
|
|
89
|
+
|
|
90
|
+
React.useEffect(() => {
|
|
91
|
+
if (status === 'anonymous' && !pending && !error) void session.signIn();
|
|
92
|
+
}, [status, pending, error, session]);
|
|
93
|
+
|
|
94
|
+
if (status === 'valid') return <>{children}</>;
|
|
95
|
+
|
|
96
|
+
const controls: SessionExpiredControls = {
|
|
97
|
+
signIn: () => {
|
|
98
|
+
void session.signIn({ forceLogin: status === 'expired' && forceLoginAfterExpiry });
|
|
99
|
+
},
|
|
100
|
+
pending,
|
|
101
|
+
error,
|
|
102
|
+
};
|
|
103
|
+
if (status === 'expired') return <>{expired(controls)}</>;
|
|
104
|
+
// The redirect to the sign-in page could not start: say so instead of an endless spinner.
|
|
105
|
+
if (status === 'anonymous' && error) return <>{expired(controls)}</>;
|
|
106
|
+
return <>{loading}</>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
interface SessionExpiredScreenProps extends SessionExpiredControls {
|
|
110
|
+
title: string;
|
|
111
|
+
description: string;
|
|
112
|
+
actionLabel: string;
|
|
113
|
+
/** Shown above the button when the sign-in page could not be reached. */
|
|
114
|
+
errorLabel?: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The screen that replaces the pages once the session is over. Texts come from the application. */
|
|
118
|
+
export function SessionExpiredScreen({
|
|
119
|
+
title, description, actionLabel, errorLabel, signIn: onSignIn, pending, error,
|
|
120
|
+
}: SessionExpiredScreenProps) {
|
|
121
|
+
return (
|
|
122
|
+
<div className="min-h-screen flex items-center justify-center bg-ibm-gray-10 px-4" role="alertdialog" aria-labelledby="session-expired-title" aria-describedby="session-expired-description">
|
|
123
|
+
<div className="bg-white border border-ui-border max-w-md w-full p-6 text-center">
|
|
124
|
+
<h2 id="session-expired-title" className="text-xl font-semibold text-ibm-gray-100 mb-2">{title}</h2>
|
|
125
|
+
<p id="session-expired-description" className="text-ibm-gray-70 mb-6">{description}</p>
|
|
126
|
+
{error && errorLabel && (
|
|
127
|
+
<p className="text-sm text-red-700 bg-red-50 border border-red-200 p-3 mb-4" role="alert">{errorLabel}</p>
|
|
128
|
+
)}
|
|
129
|
+
<Button variant="primary" size="md" className="w-full" onClick={onSignIn} disabled={pending}>
|
|
130
|
+
{actionLabel}
|
|
131
|
+
</Button>
|
|
132
|
+
</div>
|
|
133
|
+
</div>
|
|
134
|
+
);
|
|
135
|
+
}
|
package/auth/session.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session of the page: one UserManager and one SessionController, shared by the React tree
|
|
3
|
+
* (SessionProvider) and by the services that send requests (sessionAuthHeaders).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { UserManager, type UserManagerSettings } from 'oidc-client-ts';
|
|
7
|
+
import {
|
|
8
|
+
SessionController,
|
|
9
|
+
type SessionSnapshot,
|
|
10
|
+
type SessionUserManager,
|
|
11
|
+
} from './session-controller';
|
|
12
|
+
|
|
13
|
+
export type SessionSettings = UserManagerSettings;
|
|
14
|
+
|
|
15
|
+
let settingsFactory: (() => SessionSettings) | null = null;
|
|
16
|
+
let userManager: UserManager | null = null;
|
|
17
|
+
let controller: SessionController | null = null;
|
|
18
|
+
|
|
19
|
+
const isBrowser = () => typeof window !== 'undefined';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Says how to reach the identity provider. Given as a function, called in the browser only:
|
|
23
|
+
* the redirect address is built from the origin of the page. The first call wins, so that a
|
|
24
|
+
* module imported twice cannot give the page two sessions.
|
|
25
|
+
*/
|
|
26
|
+
export function configureSession(factory: () => SessionSettings): void {
|
|
27
|
+
if (!settingsFactory) settingsFactory = factory;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function getSessionUserManager(): UserManager {
|
|
31
|
+
if (!isBrowser()) throw new Error('The session exists in the browser only');
|
|
32
|
+
if (!userManager) {
|
|
33
|
+
if (!settingsFactory) throw new Error('configureSession() has not been called');
|
|
34
|
+
userManager = new UserManager({
|
|
35
|
+
...settingsFactory(),
|
|
36
|
+
// Renewals are the controller's: two owners would spend the same refresh token twice.
|
|
37
|
+
automaticSilentRenew: false,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return userManager;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function getSession(): SessionController {
|
|
44
|
+
if (!controller) {
|
|
45
|
+
controller = new SessionController({
|
|
46
|
+
userManager: getSessionUserManager() as unknown as SessionUserManager,
|
|
47
|
+
storage: window.sessionStorage,
|
|
48
|
+
location: () => window.location,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return controller;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const SERVER_SNAPSHOT: SessionSnapshot = { status: 'loading', user: null, pending: false, error: null };
|
|
55
|
+
|
|
56
|
+
/** For useSyncExternalStore: nothing to read nor to listen to while rendering on the server. */
|
|
57
|
+
export const sessionStore = {
|
|
58
|
+
subscribe: (listener: () => void): (() => void) => (isBrowser() ? getSession().subscribe(listener) : () => {}),
|
|
59
|
+
getSnapshot: (): SessionSnapshot => (isBrowser() ? getSession().getSnapshot() : SERVER_SNAPSHOT),
|
|
60
|
+
getServerSnapshot: (): SessionSnapshot => SERVER_SNAPSHOT,
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The headers of an authenticated request, for BaseService and HttpClient. Rejects with a
|
|
65
|
+
* SessionExpiredError rather than letting a request leave without a token.
|
|
66
|
+
*/
|
|
67
|
+
export async function sessionAuthHeaders(): Promise<Record<string, string>> {
|
|
68
|
+
const token = await getSession().getAccessToken();
|
|
69
|
+
return { Authorization: `Bearer ${token}` };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Starts the session and wires it to what the page hears: a request answered 401 (the event
|
|
74
|
+
* the HTTP client of this package raises), the page coming back to the front, the network
|
|
75
|
+
* coming back. Returns what removes the listeners.
|
|
76
|
+
*/
|
|
77
|
+
export function startSession(): () => void {
|
|
78
|
+
const session = getSession();
|
|
79
|
+
void session.start();
|
|
80
|
+
|
|
81
|
+
const onUnauthorized = () => {
|
|
82
|
+
void session.handleUnauthorized();
|
|
83
|
+
};
|
|
84
|
+
const onBack = () => {
|
|
85
|
+
if (document.visibilityState === 'visible') void session.recheck();
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
window.addEventListener('http-unauthorized', onUnauthorized);
|
|
89
|
+
window.addEventListener('online', onBack);
|
|
90
|
+
window.addEventListener('focus', onBack);
|
|
91
|
+
document.addEventListener('visibilitychange', onBack);
|
|
92
|
+
|
|
93
|
+
return () => {
|
|
94
|
+
window.removeEventListener('http-unauthorized', onUnauthorized);
|
|
95
|
+
window.removeEventListener('online', onBack);
|
|
96
|
+
window.removeEventListener('focus', onBack);
|
|
97
|
+
document.removeEventListener('visibilitychange', onBack);
|
|
98
|
+
};
|
|
99
|
+
}
|
|
@@ -33,6 +33,14 @@ export interface ConfirmationDialogProps {
|
|
|
33
33
|
}
|
|
34
34
|
open?: boolean
|
|
35
35
|
onOpenChange?: (open: boolean) => void
|
|
36
|
+
/**
|
|
37
|
+
* Keeps the confirm button disabled whatever is typed: the action is blocked by a
|
|
38
|
+
* precondition that is checked once the dialog is open, or is still being checked. Say why
|
|
39
|
+
* in `children`.
|
|
40
|
+
*/
|
|
41
|
+
confirmDisabled?: boolean
|
|
42
|
+
/** Shown under the description: what stands in the way of the action, or what it implies. */
|
|
43
|
+
children?: ReactNode
|
|
36
44
|
}
|
|
37
45
|
|
|
38
46
|
export function ConfirmationDialog({
|
|
@@ -47,6 +55,8 @@ export function ConfirmationDialog({
|
|
|
47
55
|
requireTextConfirmation,
|
|
48
56
|
open: controlledOpen,
|
|
49
57
|
onOpenChange: controlledOnOpenChange,
|
|
58
|
+
confirmDisabled = false,
|
|
59
|
+
children,
|
|
50
60
|
}: ConfirmationDialogProps) {
|
|
51
61
|
const { alert, showSuccess, showError, hideAlert } = useAlertBanner()
|
|
52
62
|
const [loading, setLoading] = useState(false)
|
|
@@ -59,6 +69,7 @@ export function ConfirmationDialog({
|
|
|
59
69
|
|
|
60
70
|
const isConfirmDisabled =
|
|
61
71
|
loading ||
|
|
72
|
+
confirmDisabled ||
|
|
62
73
|
(requireTextConfirmation &&
|
|
63
74
|
confirmationText !== requireTextConfirmation.expectedText)
|
|
64
75
|
|
|
@@ -109,6 +120,8 @@ export function ConfirmationDialog({
|
|
|
109
120
|
/>
|
|
110
121
|
)}
|
|
111
122
|
|
|
123
|
+
{children}
|
|
124
|
+
|
|
112
125
|
{requireTextConfirmation && (
|
|
113
126
|
<div className="space-y-2">
|
|
114
127
|
<Label htmlFor="confirmation-input">
|
package/lib/http-client.ts
CHANGED
|
@@ -88,6 +88,9 @@ class HttpClient {
|
|
|
88
88
|
const authHeaders = await this.authHeadersProvider();
|
|
89
89
|
Object.assign(headers, authHeaders);
|
|
90
90
|
} catch (error: unknown) {
|
|
91
|
+
// The session is over: the request is refused here, not sent without a token to come
|
|
92
|
+
// back 401. The name is compared, not the class, so that this file needs no auth code.
|
|
93
|
+
if ((error as { name?: unknown } | null)?.name === 'SessionExpiredError') throw error;
|
|
91
94
|
console.warn('Failed to get auth headers:', error);
|
|
92
95
|
}
|
|
93
96
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orsetra/shared-ui",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.1",
|
|
4
4
|
"description": "Shared UI components for Orsetra platform",
|
|
5
5
|
"main": "./index.ts",
|
|
6
6
|
"types": "./index.ts",
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
"./components/ui": "./components/ui/index.ts",
|
|
10
10
|
"./components/layout": "./components/layout/index.ts",
|
|
11
11
|
"./hooks": "./hooks/index.ts",
|
|
12
|
+
"./auth": "./auth/index.ts",
|
|
12
13
|
"./lib/*": "./lib/*.ts"
|
|
13
14
|
},
|
|
14
15
|
"files": [
|
|
@@ -16,6 +17,7 @@
|
|
|
16
17
|
"components",
|
|
17
18
|
"hooks",
|
|
18
19
|
"lib",
|
|
20
|
+
"auth",
|
|
19
21
|
"api",
|
|
20
22
|
"context",
|
|
21
23
|
"utils",
|
|
@@ -43,7 +45,17 @@
|
|
|
43
45
|
"peerDependencies": {
|
|
44
46
|
"next": "^14.0.0 || ^15.0.0",
|
|
45
47
|
"react": "^18.0.0 || ^19.0.0",
|
|
46
|
-
"react-dom": "^18.0.0 || ^19.0.0"
|
|
48
|
+
"react-dom": "^18.0.0 || ^19.0.0",
|
|
49
|
+
"oidc-client-ts": "^3.4.0",
|
|
50
|
+
"react-oidc-context": "^3.3.0"
|
|
51
|
+
},
|
|
52
|
+
"peerDependenciesMeta": {
|
|
53
|
+
"oidc-client-ts": {
|
|
54
|
+
"optional": true
|
|
55
|
+
},
|
|
56
|
+
"react-oidc-context": {
|
|
57
|
+
"optional": true
|
|
58
|
+
}
|
|
47
59
|
},
|
|
48
60
|
"dependencies": {
|
|
49
61
|
"@hookform/resolvers": "^3.9.1",
|
|
@@ -113,6 +125,8 @@
|
|
|
113
125
|
"jest": "^30.5.2",
|
|
114
126
|
"jest-environment-node": "^30.5.2",
|
|
115
127
|
"next": "^16.0.7",
|
|
128
|
+
"oidc-client-ts": "^3.4.1",
|
|
129
|
+
"react-oidc-context": "^3.3.1",
|
|
116
130
|
"typescript": "^5"
|
|
117
131
|
},
|
|
118
132
|
"scripts": {
|