@venizia/ardor-kernel 0.4.8-16 → 0.4.8-17
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/README.md +2 -2
- package/dist/base/applications/abstract.d.ts +41 -14
- package/dist/base/applications/abstract.js +139 -32
- package/dist/base/applications/app-info.d.ts +8 -0
- package/dist/base/applications/app-info.js +38 -0
- package/dist/base/metadata/index.d.ts +1 -0
- package/dist/base/metadata/index.js +1 -0
- package/dist/base/metadata/provide-option.d.ts +28 -0
- package/dist/base/metadata/provide-option.js +30 -0
- package/dist/base/providers/index.d.ts +1 -0
- package/dist/base/providers/index.js +1 -0
- package/dist/base/providers/role-permission.d.ts +59 -0
- package/dist/base/providers/role-permission.js +118 -0
- package/dist/base/services/auth.d.ts +50 -4
- package/dist/base/services/auth.js +153 -15
- package/dist/base/services/network-request.d.ts +48 -2
- package/dist/base/services/network-request.js +201 -15
- package/dist/common/keys.d.ts +44 -8
- package/dist/common/keys.js +21 -6
- package/dist/common/types.d.ts +61 -28
- package/dist/helpers/auth-token-store.d.ts +6 -2
- package/dist/helpers/auth-token-store.js +6 -3
- package/dist/helpers/networks/auth-recovery.d.ts +10 -3
- package/dist/helpers/networks/auth-recovery.js +17 -6
- package/dist/helpers/networks/response-reader.d.ts +2 -0
- package/dist/helpers/networks/response-reader.js +14 -5
- package/dist/utilities/runtime-config.d.ts +40 -14
- package/dist/utilities/runtime-config.js +45 -8
- package/package.json +7 -7
|
@@ -1,18 +1,33 @@
|
|
|
1
1
|
import { getError } from '@venizia/ignis-inversion';
|
|
2
|
+
import { HTTP } from '@venizia/ignis-helpers/common';
|
|
2
3
|
import { NodeFetchNetworkRequest } from '@venizia/ignis-helpers/core';
|
|
3
4
|
import { UuidV4Generator } from '@venizia/ignis-helpers/uuid';
|
|
4
5
|
import { HttpExtraRequest } from '@venizia/ignis-kernel/repository';
|
|
5
6
|
import { App, HeaderConstants, LocalStorageKeys, RequestChannel, RequestCountData, RequestMethods, RequestTypes, } from '../../common/index.js';
|
|
6
7
|
import { AuthRecovery, AuthTokenStore, NetworkHeaders, RequestBodyEncoder, ResponseReader, } from '../../helpers/index.js';
|
|
7
8
|
import { BaseService } from './base.js';
|
|
9
|
+
/** The `normalized.code` of the 401 that answers a request whose session is gone: the user who sent it signed out or another user signed in while it was in flight. */
|
|
10
|
+
export const SESSION_CHANGED_CODE = 'ardor.network.session_changed';
|
|
11
|
+
/** The `normalized.code` of the 504 a request rejects with when it outlives the configured `timeout`. */
|
|
12
|
+
export const NETWORK_TIMEOUT_CODE = 'ardor.network.timeout';
|
|
8
13
|
/**
|
|
14
|
+
* Sends the requests of the data provider with its own sender. The repositories of
|
|
15
|
+
* `@venizia/ardor/repository` send through IGNIS's `HttpDataSource`, from the optional peer
|
|
16
|
+
* `@venizia/ignis-connectors`, which this service cannot import without making that peer required:
|
|
17
|
+
* until IGNIS's transport core is in a required peer, two clients exist, and `getDataSourceAuth`
|
|
18
|
+
* gives the second the session of the first.
|
|
19
|
+
*
|
|
9
20
|
* The options hold data (the base URL, headers, the no-auth lists, the refresh path); behaviour is
|
|
10
21
|
* in the protected hooks, each taking one `opts` object, which a subclass overrides.
|
|
11
22
|
*/
|
|
12
23
|
export class DefaultNetworkRequestService extends BaseService {
|
|
13
24
|
constructor(opts) {
|
|
14
25
|
super({ scope: DefaultNetworkRequestService.name });
|
|
15
|
-
|
|
26
|
+
/** The session each data source request was sent under, keyed by the context object IGNIS hands to both hooks. */
|
|
27
|
+
this.sentSessions = new WeakMap();
|
|
28
|
+
const { name, baseUrl = '', headers = {}, noAuthPaths, noAuthPathRegex, authRecovery, authService, timeout = { use: false }, } = opts;
|
|
29
|
+
DefaultNetworkRequestService.assertTimeout({ timeout });
|
|
30
|
+
this.timeout = timeout;
|
|
16
31
|
this.headers = NetworkHeaders.toRecord({ headers });
|
|
17
32
|
this.noAuthPaths = noAuthPaths;
|
|
18
33
|
this.noAuthPathRegexes = this.compileNoAuthPathRegex({ input: noAuthPathRegex });
|
|
@@ -54,6 +69,19 @@ export class DefaultNetworkRequestService extends BaseService {
|
|
|
54
69
|
const { token: key } = LocalStorageKeys.scoped({ id: opts.id });
|
|
55
70
|
return () => AuthTokenStore.read({ key });
|
|
56
71
|
}
|
|
72
|
+
/** Throws unless a timeout that is on has a positive integer `milliseconds`. */
|
|
73
|
+
static assertTimeout(opts) {
|
|
74
|
+
const { timeout } = opts;
|
|
75
|
+
if (!timeout?.use) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const { milliseconds } = timeout;
|
|
79
|
+
if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {
|
|
80
|
+
throw getError({
|
|
81
|
+
message: `[DefaultNetworkRequestService] timeout.milliseconds must be a positive integer, got ${milliseconds}`,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
57
85
|
// --- Hooks -----------------------------------------------------------------------------------
|
|
58
86
|
/**
|
|
59
87
|
* The token this service sends. The one way to supply a token: override it to read another
|
|
@@ -217,7 +245,79 @@ export class DefaultNetworkRequestService extends BaseService {
|
|
|
217
245
|
* Also what `DefaultAuthProvider.refreshToken` calls, so a refresh is made in one place.
|
|
218
246
|
*/
|
|
219
247
|
refresh() {
|
|
220
|
-
|
|
248
|
+
const { userId, token } = this.readSession();
|
|
249
|
+
return this.recovery.refresh({ key: `${userId}|${token}` });
|
|
250
|
+
}
|
|
251
|
+
/** The session signed in now: who, and with which token. */
|
|
252
|
+
readSession() {
|
|
253
|
+
const userId = this.authService?.getUser().userId;
|
|
254
|
+
return {
|
|
255
|
+
userId: userId === undefined ? undefined : `${userId}`,
|
|
256
|
+
token: this.resolveAuthToken()?.value,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
/** The 401 that answers a request whose session is gone: `DefaultAuthProvider.checkError` leaves the signed-in session alone for it. */
|
|
260
|
+
sessionChangedError() {
|
|
261
|
+
return getError({
|
|
262
|
+
statusCode: 401,
|
|
263
|
+
messageCode: SESSION_CHANGED_CODE,
|
|
264
|
+
message: '[doRequest] The session that sent this request ended while it was in flight',
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* How the session changed since `sent`: `undefined` when it did not, `true` when the same user holds
|
|
269
|
+
* another token now (the request can be sent again with it), `false` when the user who sent is gone. When
|
|
270
|
+
* nobody can tell who sent, another token is a switch: it is never read as the same user's.
|
|
271
|
+
*/
|
|
272
|
+
readSessionChange(opts) {
|
|
273
|
+
const { sent } = opts;
|
|
274
|
+
const now = this.readSession();
|
|
275
|
+
if (now.userId === sent.userId && now.token === sent.token) {
|
|
276
|
+
return undefined;
|
|
277
|
+
}
|
|
278
|
+
return sent.userId !== undefined && now.userId === sent.userId && !!now.token;
|
|
279
|
+
}
|
|
280
|
+
/** `task` settles as it does, or the wait rejects with the reason of `signal` once it aborts; the task itself is not cancelled. */
|
|
281
|
+
static async untilAborted(opts) {
|
|
282
|
+
const { task, signal } = opts;
|
|
283
|
+
if (!signal) {
|
|
284
|
+
return task;
|
|
285
|
+
}
|
|
286
|
+
let onAbort;
|
|
287
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
288
|
+
onAbort = () => reject(signal.reason);
|
|
289
|
+
if (signal.aborted) {
|
|
290
|
+
onAbort();
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
294
|
+
});
|
|
295
|
+
try {
|
|
296
|
+
const settled = await Promise.race([task, aborted]);
|
|
297
|
+
return settled;
|
|
298
|
+
}
|
|
299
|
+
finally {
|
|
300
|
+
if (onAbort) {
|
|
301
|
+
signal.removeEventListener('abort', onAbort);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Whether the 401 of a request that `sent` is a session change for the caller: the user who sent is gone and
|
|
307
|
+
* either the request was sent again since (`isRetried`) or another session is signed in now. A refresh that
|
|
308
|
+
* failed and ended the session itself leaves nobody to protect, and its 401 stands.
|
|
309
|
+
*/
|
|
310
|
+
isSessionTaken(opts) {
|
|
311
|
+
// With no user to compare, the token that follows a refresh this service ran is that refresh's.
|
|
312
|
+
if (opts.sent.userId === undefined && opts.isRetried) {
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
// A user switch in progress (a token stored for another user than the identity) is someone signing in: it
|
|
316
|
+
// reads no token, but it is not a sign-out.
|
|
317
|
+
return (this.readSessionChange({ sent: opts.sent }) === false &&
|
|
318
|
+
(opts.isRetried ||
|
|
319
|
+
this.readSession().token !== undefined ||
|
|
320
|
+
this.authService?.isSwitching() === true));
|
|
221
321
|
}
|
|
222
322
|
// --- Requests --------------------------------------------------------------------------------
|
|
223
323
|
/**
|
|
@@ -227,18 +327,46 @@ export class DefaultNetworkRequestService extends BaseService {
|
|
|
227
327
|
*/
|
|
228
328
|
getDataSourceAuth(opts) {
|
|
229
329
|
return {
|
|
230
|
-
authTokenResolver: (
|
|
231
|
-
|
|
330
|
+
authTokenResolver: (context) => {
|
|
331
|
+
const { paths } = context;
|
|
332
|
+
const sent = this.sentSessions.get(context);
|
|
333
|
+
// The retry of a request whose user has gone must not carry the token of whoever signed in since.
|
|
334
|
+
if (sent && this.readSessionChange({ sent }) === false) {
|
|
335
|
+
return undefined;
|
|
336
|
+
}
|
|
337
|
+
const token = this.isNoAuthPath({ resource: paths[0], paths })
|
|
232
338
|
? undefined
|
|
233
339
|
: this.resolveAuthToken();
|
|
340
|
+
// Both hooks receive this very object, and a retry sends again under the session of that moment.
|
|
341
|
+
this.sentSessions.set(context, { userId: this.readSession().userId, token: token?.value });
|
|
342
|
+
return token;
|
|
234
343
|
},
|
|
235
344
|
headersResolver: () => {
|
|
236
345
|
return NetworkHeaders.merge({
|
|
237
346
|
sources: [this.getSessionHeaders(), opts ? this.getTracingHeaders(opts) : {}],
|
|
238
347
|
});
|
|
239
348
|
},
|
|
240
|
-
onUnauthorized: (
|
|
241
|
-
|
|
349
|
+
onUnauthorized: (context) => {
|
|
350
|
+
if (!this.recovery.canRecover({ paths: context.paths })) {
|
|
351
|
+
return Promise.resolve(false);
|
|
352
|
+
}
|
|
353
|
+
const sent = this.sentSessions.get(context);
|
|
354
|
+
const change = sent ? this.readSessionChange({ sent }) : undefined;
|
|
355
|
+
if (change === false) {
|
|
356
|
+
return Promise.reject(this.sessionChangedError());
|
|
357
|
+
}
|
|
358
|
+
if (change === true) {
|
|
359
|
+
return Promise.resolve(true);
|
|
360
|
+
}
|
|
361
|
+
return this.refresh().then((isRefreshed) => {
|
|
362
|
+
// The retry sends again under the session of this refresh.
|
|
363
|
+
if (sent && sent.userId === undefined && isRefreshed) {
|
|
364
|
+
this.sentSessions.set(context, this.readSession());
|
|
365
|
+
}
|
|
366
|
+
return sent && this.isSessionTaken({ sent, isRetried: isRefreshed })
|
|
367
|
+
? Promise.reject(this.sessionChangedError())
|
|
368
|
+
: isRefreshed;
|
|
369
|
+
});
|
|
242
370
|
},
|
|
243
371
|
errorRootKey: ResponseReader.ERROR_ROOT_KEY,
|
|
244
372
|
};
|
|
@@ -376,10 +504,11 @@ export class DefaultNetworkRequestService extends BaseService {
|
|
|
376
504
|
* Sends the request and reads the response by `type`. Throws when `baseUrl` (the option, else the
|
|
377
505
|
* service's) is empty. A 401 on a path that can recover triggers `refresh` and, if it refreshed,
|
|
378
506
|
* one retry with the new token. Any other non-2xx response, or a retry that still fails, throws
|
|
379
|
-
* the error read from the response.
|
|
507
|
+
* the error read from the response. An aborted `signal` rejects with its reason, and a request
|
|
508
|
+
* that outlives the service's `timeout` rejects with a 504 coded `NETWORK_TIMEOUT_CODE`.
|
|
380
509
|
*/
|
|
381
510
|
async doRequest(opts) {
|
|
382
|
-
const { baseUrl = this.baseUrl,
|
|
511
|
+
const { baseUrl = this.baseUrl, paths, signal } = opts;
|
|
383
512
|
if (!baseUrl) {
|
|
384
513
|
throw getError({
|
|
385
514
|
message: '[doRequest] Invalid baseUrl to send request!',
|
|
@@ -389,6 +518,33 @@ export class DefaultNetworkRequestService extends BaseService {
|
|
|
389
518
|
if (!DefaultNetworkRequestService.isUnderBase({ baseUrl, paths, url })) {
|
|
390
519
|
throw getError({ message: '[doRequest] Invalid path to send request!' });
|
|
391
520
|
}
|
|
521
|
+
const timeoutSignal = this.timeout.use
|
|
522
|
+
? AbortSignal.timeout(this.timeout.milliseconds)
|
|
523
|
+
: undefined;
|
|
524
|
+
const sendSignal = timeoutSignal && signal
|
|
525
|
+
? AbortSignal.any([signal, timeoutSignal])
|
|
526
|
+
: (timeoutSignal ?? signal);
|
|
527
|
+
try {
|
|
528
|
+
const response = await this.sendAndRead({ ...opts, url, signal: sendSignal });
|
|
529
|
+
return response;
|
|
530
|
+
}
|
|
531
|
+
catch (error) {
|
|
532
|
+
// The combined signal keeps the reason of whichever source aborted first.
|
|
533
|
+
if (this.timeout.use &&
|
|
534
|
+
timeoutSignal?.aborted &&
|
|
535
|
+
sendSignal?.reason === timeoutSignal.reason) {
|
|
536
|
+
throw getError({
|
|
537
|
+
statusCode: HTTP.ResultCodes.RS_5.GatewayTimeout,
|
|
538
|
+
messageCode: NETWORK_TIMEOUT_CODE,
|
|
539
|
+
message: `[doRequest] The request to ${paths.join('/')} did not answer within ${this.timeout.milliseconds} ms`,
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
throw error;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/** `doRequest` once the URL is checked: the send, the refresh and retry after a 401, then the read. */
|
|
546
|
+
async sendAndRead(opts) {
|
|
547
|
+
const { url, type, method, paths, body, headers, query, requestCountData, signal } = opts;
|
|
392
548
|
const sendOnce = (sendHeaders) => {
|
|
393
549
|
return this.networkRequest.getNetworkService().send({
|
|
394
550
|
url,
|
|
@@ -396,15 +552,33 @@ export class DefaultNetworkRequestService extends BaseService {
|
|
|
396
552
|
params: query,
|
|
397
553
|
body: method === RequestMethods.GET ? undefined : body,
|
|
398
554
|
headers: sendHeaders,
|
|
555
|
+
signal,
|
|
399
556
|
}, this.logger);
|
|
400
557
|
};
|
|
401
|
-
|
|
402
|
-
|
|
558
|
+
const sent = this.readSession();
|
|
559
|
+
let isRetried = false;
|
|
403
560
|
let fetched = await sendOnce(headers);
|
|
404
|
-
if (fetched.status === 401 &&
|
|
405
|
-
|
|
406
|
-
this.
|
|
407
|
-
|
|
561
|
+
if (fetched.status === 401 && this.recovery.canRecover({ paths })) {
|
|
562
|
+
// A 401 that arrives after the session changed is not the new session's to refresh or to end.
|
|
563
|
+
const change = this.readSessionChange({ sent });
|
|
564
|
+
if (change === false) {
|
|
565
|
+
throw this.sessionChangedError();
|
|
566
|
+
}
|
|
567
|
+
let isRefreshed = change === true;
|
|
568
|
+
if (change === undefined) {
|
|
569
|
+
// The wait ends with this request's abort; the refresh itself keeps running for the others.
|
|
570
|
+
const refreshed = await DefaultNetworkRequestService.untilAborted({
|
|
571
|
+
task: this.refresh(),
|
|
572
|
+
signal,
|
|
573
|
+
});
|
|
574
|
+
isRefreshed = refreshed;
|
|
575
|
+
}
|
|
576
|
+
// The session may have moved on while the refresh was in flight, or inside a `refreshToken` override.
|
|
577
|
+
if (this.isSessionTaken({ sent, isRetried: isRefreshed })) {
|
|
578
|
+
throw this.sessionChangedError();
|
|
579
|
+
}
|
|
580
|
+
// The shared refresh is never aborted for one request: this request stops when it returns.
|
|
581
|
+
signal?.throwIfAborted();
|
|
408
582
|
if (isRefreshed) {
|
|
409
583
|
const authHeader = this.getRequestAuthorizationHeader();
|
|
410
584
|
const retryHeaders = NetworkHeaders.merge({
|
|
@@ -418,14 +592,26 @@ export class DefaultNetworkRequestService extends BaseService {
|
|
|
418
592
|
});
|
|
419
593
|
const result = await sendOnce(retryHeaders);
|
|
420
594
|
fetched = result;
|
|
595
|
+
isRetried = true;
|
|
421
596
|
}
|
|
422
597
|
}
|
|
423
598
|
const status = fetched.status;
|
|
599
|
+
// The retry may have been answered 401 after the user who sent it had gone too.
|
|
600
|
+
if (status === 401 &&
|
|
601
|
+
this.recovery.canRecover({ paths }) &&
|
|
602
|
+
this.isSessionTaken({ sent, isRetried })) {
|
|
603
|
+
throw this.sessionChangedError();
|
|
604
|
+
}
|
|
424
605
|
if (status < 200 || status >= 300) {
|
|
425
606
|
const result2 = await ResponseReader.toError({ response: fetched });
|
|
426
607
|
throw result2;
|
|
427
608
|
}
|
|
428
|
-
|
|
609
|
+
const response = await ResponseReader.read({
|
|
610
|
+
response: fetched,
|
|
611
|
+
type,
|
|
612
|
+
requestCountData,
|
|
613
|
+
});
|
|
614
|
+
return response;
|
|
429
615
|
}
|
|
430
616
|
}
|
|
431
617
|
//# sourceMappingURL=network-request.js.map
|
package/dist/common/keys.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { IRestDataProviderOptions, IRolePermissionProviderOptions, TAuthProviderOptions } from './types.js';
|
|
1
2
|
/** The container keys the kernel binds and reads. */
|
|
2
3
|
export declare class CoreBindings {
|
|
3
4
|
/** The application itself, bound by `preConfigure`. */
|
|
@@ -10,35 +11,69 @@ export declare class CoreBindings {
|
|
|
10
11
|
static readonly DEFAULT_I18N_PROVIDER = "@app/application/i18n/default";
|
|
11
12
|
/** The REST data provider. */
|
|
12
13
|
static readonly DEFAULT_REST_DATA_PROVIDER = "@app/application/data/rest/default";
|
|
13
|
-
/** The `
|
|
14
|
+
/** The `TAuthProviderOptions`: `{ use: true }` turns sign-in on; unbound means `{ use: false }`. */
|
|
14
15
|
static readonly AUTH_PROVIDER_OPTIONS = "@app/application/options/auth";
|
|
15
16
|
/** The `DefaultAuthService`. */
|
|
16
17
|
static readonly DEFAULT_AUTH_SERVICE = "@app/application/service/auth/default";
|
|
17
18
|
/** The `IRestDataProviderOptions`. */
|
|
18
19
|
static readonly REST_DATA_PROVIDER_OPTIONS = "@app/application/options/rest/data";
|
|
19
|
-
/** The options of the i18n provider. */
|
|
20
|
+
/** The options of the i18n provider; unbound means English only. */
|
|
20
21
|
static readonly I18N_PROVIDER_OPTIONS = "@app/application/options/i18n";
|
|
21
22
|
/** The `features()` an application mounts, bound by `preConfigure()`. */
|
|
22
23
|
static readonly FEATURES = "@app/application/features";
|
|
23
24
|
/** An `IPermissionProvider`, bound by the application; unbound means every check passes. */
|
|
24
25
|
static readonly PERMISSION_PROVIDER = "@app/application/permission/provider";
|
|
26
|
+
/** The `IRolePermissionProviderOptions` that `RolePermissionProvider` reads. */
|
|
27
|
+
static readonly PERMISSION_PROVIDER_OPTIONS = "@app/application/options/permission";
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The options type of each options key of `CoreBindings`, which `provideOption` checks a method
|
|
31
|
+
* against. A package that owns an options type declares it with `declare module '@venizia/ardor-kernel'`:
|
|
32
|
+
* `@venizia/ardor-admin` adds `CoreBindings.I18N_PROVIDER_OPTIONS`.
|
|
33
|
+
*/
|
|
34
|
+
export interface ICoreOptionTypes {
|
|
35
|
+
[CoreBindings.AUTH_PROVIDER_OPTIONS]: TAuthProviderOptions;
|
|
36
|
+
[CoreBindings.REST_DATA_PROVIDER_OPTIONS]: IRestDataProviderOptions;
|
|
37
|
+
[CoreBindings.PERMISSION_PROVIDER_OPTIONS]: IRolePermissionProviderOptions;
|
|
25
38
|
}
|
|
26
39
|
/** The session keys and the store prefix of one application, from `LocalStorageKeys.scoped`. */
|
|
27
40
|
export interface IScopedKeys {
|
|
28
|
-
/**
|
|
41
|
+
/**
|
|
42
|
+
* The prefix of this application's session keys: `DefaultAuthService.cleanUp` removes them. Without
|
|
43
|
+
* an application `id` it is also the start of every scoped session, and `cleanUp` skips those.
|
|
44
|
+
*/
|
|
29
45
|
authPrefix: string;
|
|
30
|
-
/**
|
|
46
|
+
/**
|
|
47
|
+
* The data of this application's signed-in user; sign-out removes every key that starts with it.
|
|
48
|
+
* Without an application `id` it is `@app/store/`, the start of every scoped store prefix, so an
|
|
49
|
+
* application without an `id` removes the data of the applications with one: every application on
|
|
50
|
+
* an origin sets an `id`.
|
|
51
|
+
*/
|
|
31
52
|
storePrefix: string;
|
|
53
|
+
/** The preferences of this application's user: they outlive a sign-out. */
|
|
54
|
+
prefsPrefix: string;
|
|
55
|
+
/** The stored locale of the i18n provider. */
|
|
56
|
+
locale: string;
|
|
32
57
|
token: string;
|
|
33
58
|
identity: string;
|
|
34
59
|
permission: string;
|
|
35
60
|
}
|
|
36
61
|
/** The `localStorage` keys the kernel owns. */
|
|
37
62
|
export declare class LocalStorageKeys {
|
|
38
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* The session keys of an application with no `id`: `DefaultAuthService.cleanUp` removes them, and
|
|
65
|
+
* skips the keys of applications with an `id`, which are `@app/auth/<id>/...`.
|
|
66
|
+
*/
|
|
39
67
|
static readonly PREFIX_AUTH = "@app/auth/";
|
|
40
|
-
/**
|
|
68
|
+
/**
|
|
69
|
+
* The data of the signed-in user: sign-out removes every key that starts with the store prefix of
|
|
70
|
+
* the application. This one is the start of every scoped store prefix (`@app/store/<id>/`), so
|
|
71
|
+
* applications that share an origin must all set an `id`. Preferences that outlive a sign-out go
|
|
72
|
+
* under `@app/prefs/`.
|
|
73
|
+
*/
|
|
41
74
|
static readonly PREFIX_STORE = "@app/store/";
|
|
75
|
+
/** Preferences that outlive a sign-out, such as the chosen language: nothing sweeps them. */
|
|
76
|
+
static readonly PREFIX_PREFS = "@app/prefs/";
|
|
42
77
|
/** The stored `IAuthTokenRecord`, as JSON. */
|
|
43
78
|
static readonly KEY_AUTH_TOKEN = "@app/auth/token";
|
|
44
79
|
/** The stored identity (`userId`, `username`, `referenceId`, `provider`), as JSON. */
|
|
@@ -50,9 +85,10 @@ export declare class LocalStorageKeys {
|
|
|
50
85
|
/**
|
|
51
86
|
* The keys of one application. With no `id` they are the constants above, so an application that is
|
|
52
87
|
* alone on its origin changes nothing. With an `id` (`IApplicationInfo.id`) the session sits under
|
|
53
|
-
* `@app/auth/<id>/` and the
|
|
88
|
+
* `@app/auth/<id>/`, the store under `@app/store/<id>/` and the preferences under `@app/prefs/<id>/`, so two applications on one origin share
|
|
54
89
|
* no session and no sign-out sweeps the other's data. The `id` is letters, digits, `.`, `_` and `-`,
|
|
55
|
-
* and is not made of dots only.
|
|
90
|
+
* and is not made of dots only. Applications on one origin must ALL set an `id`: the store prefix
|
|
91
|
+
* without one is a prefix of every scoped store prefix, so its sign-out removes their data too.
|
|
56
92
|
*/
|
|
57
93
|
static scoped(opts?: {
|
|
58
94
|
id?: string;
|
package/dist/common/keys.js
CHANGED
|
@@ -11,25 +11,37 @@ export class CoreBindings {
|
|
|
11
11
|
static { this.DEFAULT_I18N_PROVIDER = '@app/application/i18n/default'; }
|
|
12
12
|
/** The REST data provider. */
|
|
13
13
|
static { this.DEFAULT_REST_DATA_PROVIDER = '@app/application/data/rest/default'; }
|
|
14
|
-
/** The `
|
|
14
|
+
/** The `TAuthProviderOptions`: `{ use: true }` turns sign-in on; unbound means `{ use: false }`. */
|
|
15
15
|
static { this.AUTH_PROVIDER_OPTIONS = '@app/application/options/auth'; }
|
|
16
16
|
/** The `DefaultAuthService`. */
|
|
17
17
|
static { this.DEFAULT_AUTH_SERVICE = '@app/application/service/auth/default'; }
|
|
18
18
|
/** The `IRestDataProviderOptions`. */
|
|
19
19
|
static { this.REST_DATA_PROVIDER_OPTIONS = '@app/application/options/rest/data'; }
|
|
20
|
-
/** The options of the i18n provider. */
|
|
20
|
+
/** The options of the i18n provider; unbound means English only. */
|
|
21
21
|
static { this.I18N_PROVIDER_OPTIONS = '@app/application/options/i18n'; }
|
|
22
22
|
/** The `features()` an application mounts, bound by `preConfigure()`. */
|
|
23
23
|
static { this.FEATURES = '@app/application/features'; }
|
|
24
24
|
/** An `IPermissionProvider`, bound by the application; unbound means every check passes. */
|
|
25
25
|
static { this.PERMISSION_PROVIDER = '@app/application/permission/provider'; }
|
|
26
|
+
/** The `IRolePermissionProviderOptions` that `RolePermissionProvider` reads. */
|
|
27
|
+
static { this.PERMISSION_PROVIDER_OPTIONS = '@app/application/options/permission'; }
|
|
26
28
|
}
|
|
27
29
|
/** The `localStorage` keys the kernel owns. */
|
|
28
30
|
export class LocalStorageKeys {
|
|
29
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* The session keys of an application with no `id`: `DefaultAuthService.cleanUp` removes them, and
|
|
33
|
+
* skips the keys of applications with an `id`, which are `@app/auth/<id>/...`.
|
|
34
|
+
*/
|
|
30
35
|
static { this.PREFIX_AUTH = '@app/auth/'; }
|
|
31
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* The data of the signed-in user: sign-out removes every key that starts with the store prefix of
|
|
38
|
+
* the application. This one is the start of every scoped store prefix (`@app/store/<id>/`), so
|
|
39
|
+
* applications that share an origin must all set an `id`. Preferences that outlive a sign-out go
|
|
40
|
+
* under `@app/prefs/`.
|
|
41
|
+
*/
|
|
32
42
|
static { this.PREFIX_STORE = '@app/store/'; }
|
|
43
|
+
/** Preferences that outlive a sign-out, such as the chosen language: nothing sweeps them. */
|
|
44
|
+
static { this.PREFIX_PREFS = '@app/prefs/'; }
|
|
33
45
|
/** The stored `IAuthTokenRecord`, as JSON. */
|
|
34
46
|
static { this.KEY_AUTH_TOKEN = '@app/auth/token'; }
|
|
35
47
|
/** The stored identity (`userId`, `username`, `referenceId`, `provider`), as JSON. */
|
|
@@ -45,9 +57,10 @@ export class LocalStorageKeys {
|
|
|
45
57
|
/**
|
|
46
58
|
* The keys of one application. With no `id` they are the constants above, so an application that is
|
|
47
59
|
* alone on its origin changes nothing. With an `id` (`IApplicationInfo.id`) the session sits under
|
|
48
|
-
* `@app/auth/<id>/` and the
|
|
60
|
+
* `@app/auth/<id>/`, the store under `@app/store/<id>/` and the preferences under `@app/prefs/<id>/`, so two applications on one origin share
|
|
49
61
|
* no session and no sign-out sweeps the other's data. The `id` is letters, digits, `.`, `_` and `-`,
|
|
50
|
-
* and is not made of dots only.
|
|
62
|
+
* and is not made of dots only. Applications on one origin must ALL set an `id`: the store prefix
|
|
63
|
+
* without one is a prefix of every scoped store prefix, so its sign-out removes their data too.
|
|
51
64
|
*/
|
|
52
65
|
static scoped(opts = {}) {
|
|
53
66
|
const { id } = opts;
|
|
@@ -60,6 +73,8 @@ export class LocalStorageKeys {
|
|
|
60
73
|
return {
|
|
61
74
|
authPrefix: `${this.PREFIX_AUTH}${scope}`,
|
|
62
75
|
storePrefix: `${this.PREFIX_STORE}${scope}`,
|
|
76
|
+
prefsPrefix: `${this.PREFIX_PREFS}${scope}`,
|
|
77
|
+
locale: `${this.PREFIX_PREFS}${scope}locale`,
|
|
63
78
|
token: `${this.PREFIX_AUTH}${scope}token`,
|
|
64
79
|
identity: `${this.PREFIX_AUTH}${scope}identity`,
|
|
65
80
|
permission: `${this.PREFIX_AUTH}${scope}permission`,
|
package/dist/common/types.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { TConstValue, TNumberConstValue, TPrettify, TStringConstValue, Valu
|
|
|
2
2
|
import type { TBuildInfoRecord } from '@venizia/ignis-helpers/core';
|
|
3
3
|
import type { TClass } from '@venizia/ignis-inversion';
|
|
4
4
|
import type { TExtraRequest } from '@venizia/ignis-kernel/repository';
|
|
5
|
+
import type { AbstractArdorApplication } from '../base/applications/abstract.js';
|
|
5
6
|
import type { Environments, RequestBodyTypes, RequestCountData, RequestMethods, RequestTypes, StorageAreas } from './constants.js';
|
|
6
7
|
/** A record id: a string or a number. */
|
|
7
8
|
export type IdType = string | number;
|
|
@@ -30,7 +31,19 @@ export interface ISendParams {
|
|
|
30
31
|
requestCountData?: TConstValue<typeof RequestCountData>;
|
|
31
32
|
/** The list extras to ask the route for, sent in `x-request-extra`. */
|
|
32
33
|
extra?: TExtraRequest;
|
|
34
|
+
/** Aborts the request; it then rejects with the signal's reason. */
|
|
35
|
+
signal?: AbortSignal;
|
|
33
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* How long a request may take before it is aborted and rejects with `NETWORK_TIMEOUT_CODE`.
|
|
39
|
+
* `milliseconds` is a positive integer.
|
|
40
|
+
*/
|
|
41
|
+
export type TRequestTimeoutOptions = {
|
|
42
|
+
use: false;
|
|
43
|
+
} | {
|
|
44
|
+
use: true;
|
|
45
|
+
milliseconds: number;
|
|
46
|
+
};
|
|
34
47
|
/** One of the `RequestBodyTypes` values. */
|
|
35
48
|
export type TRequestBodyType = TStringConstValue<typeof RequestBodyTypes>;
|
|
36
49
|
/** One of the `StorageAreas` values. */
|
|
@@ -93,7 +106,10 @@ export interface ISignInSession {
|
|
|
93
106
|
};
|
|
94
107
|
roles: Array<string>;
|
|
95
108
|
}
|
|
96
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* Data only: where the auth provider talks to, the `use: true` half of `TAuthProviderOptions`.
|
|
111
|
+
* Behaviour is in `DefaultAuthProvider`'s protected hooks.
|
|
112
|
+
*/
|
|
97
113
|
export interface IAuthProviderOptions {
|
|
98
114
|
paths?: {
|
|
99
115
|
/**
|
|
@@ -111,6 +127,16 @@ export interface IAuthProviderOptions {
|
|
|
111
127
|
afterLogin?: string | false;
|
|
112
128
|
};
|
|
113
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* What `CoreBindings.AUTH_PROVIDER_OPTIONS` holds: sign-in on with its `paths`, or off. Unbound means
|
|
132
|
+
* `{ use: false }`: `ApplicationProviders.resolve` then hands react-admin no auth provider, and
|
|
133
|
+
* every page is public.
|
|
134
|
+
*/
|
|
135
|
+
export type TAuthProviderOptions = {
|
|
136
|
+
use: false;
|
|
137
|
+
} | ({
|
|
138
|
+
use: true;
|
|
139
|
+
} & IAuthProviderOptions);
|
|
114
140
|
/** How a request recovers from a 401. */
|
|
115
141
|
export interface IAuthRecoveryOptions {
|
|
116
142
|
/**
|
|
@@ -167,6 +193,12 @@ export interface IRestDataProviderOptions extends INoAuthOptions {
|
|
|
167
193
|
headers?: HeadersInit;
|
|
168
194
|
/** Enables the refresh-and-retry after a 401. */
|
|
169
195
|
authRecovery?: IAuthRecoveryOptions;
|
|
196
|
+
/**
|
|
197
|
+
* Aborts a request that has not answered within `milliseconds`; it rejects with a 504 whose
|
|
198
|
+
* `normalized.code` is `NETWORK_TIMEOUT_CODE`. An invalid `milliseconds` throws when the provider is built.
|
|
199
|
+
* @default { use: false }
|
|
200
|
+
*/
|
|
201
|
+
timeout?: TRequestTimeoutOptions;
|
|
170
202
|
}
|
|
171
203
|
/** The token an application is signed in with. */
|
|
172
204
|
export interface IAuthTokenRecord {
|
|
@@ -174,6 +206,8 @@ export interface IAuthTokenRecord {
|
|
|
174
206
|
type?: string;
|
|
175
207
|
value: string;
|
|
176
208
|
provider?: string;
|
|
209
|
+
/** The user the token was issued to, stored by `saveAuth`; absent on a token stored without it. */
|
|
210
|
+
userId?: IdType;
|
|
177
211
|
}
|
|
178
212
|
/** What an `HttpDataSource` hook reads from the request it is asked about. */
|
|
179
213
|
export interface IDataSourceRequestContext {
|
|
@@ -217,7 +251,18 @@ export interface IFeatureBase {
|
|
|
217
251
|
* @default []
|
|
218
252
|
*/
|
|
219
253
|
configurations?: Array<TClass<unknown>>;
|
|
220
|
-
/**
|
|
254
|
+
/**
|
|
255
|
+
* The feature's own stereotyped classes, by value, in the shape of the application's
|
|
256
|
+
* `artifacts()` index. Importing the feature module imports them, so discovery binds them, and
|
|
257
|
+
* `start()` checks each was discovered.
|
|
258
|
+
* @default {}
|
|
259
|
+
*/
|
|
260
|
+
artifacts?: IArtifactIndex;
|
|
261
|
+
/**
|
|
262
|
+
* The permission names the feature's pages use, in the application's vocabulary: metadata for a
|
|
263
|
+
* role editor to list. Descriptive only, it enforces nothing; `access` on a route or a menu entry
|
|
264
|
+
* is what asks `canAccess`.
|
|
265
|
+
*/
|
|
221
266
|
permissions?: Array<string>;
|
|
222
267
|
}
|
|
223
268
|
/**
|
|
@@ -245,32 +290,20 @@ export interface IPermissionProvider {
|
|
|
245
290
|
record?: unknown;
|
|
246
291
|
}): Promise<boolean>;
|
|
247
292
|
}
|
|
248
|
-
/** The
|
|
249
|
-
export interface
|
|
250
|
-
/**
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
/** Binds `value` under `<scope>.<ClassName>` as a singleton. */
|
|
263
|
-
injectable<T>(scope: string, value: TClass<T>, tags?: Array<string>): void;
|
|
264
|
-
/** Binds `value` in the service namespace. */
|
|
265
|
-
service<T>(value: TClass<T>): unknown;
|
|
266
|
-
/** Binds `value` in the repository namespace. */
|
|
267
|
-
repository<T>(value: TClass<T>): unknown;
|
|
268
|
-
/** Binds `value` in the data source namespace. */
|
|
269
|
-
dataSource<T>(value: TClass<T>): unknown;
|
|
270
|
-
/** Binds `value` in the component namespace. */
|
|
271
|
-
component<T>(value: TClass<T>): unknown;
|
|
272
|
-
/** Runs the whole startup: resolves the indexes, then `preConfigure`, then `postConfigure`. */
|
|
273
|
-
start(): ValueOrPromise<void>;
|
|
293
|
+
/** The options of `RolePermissionProvider`, bound under `CoreBindings.PERMISSION_PROVIDER_OPTIONS`. */
|
|
294
|
+
export interface IRolePermissionProviderOptions {
|
|
295
|
+
/**
|
|
296
|
+
* Role name to grant patterns. A pattern is `'<resource>.<action>'`, `'<resource>.*'`, `'*.<action>'`
|
|
297
|
+
* or `'*'`; anything else throws when the provider is built. A pattern has one `.`, so a resource whose
|
|
298
|
+
* name contains a `.` cannot be named exactly: grant it with `'*.<action>'` or `'*'`, or give it a name without one.
|
|
299
|
+
*/
|
|
300
|
+
grants: Record<string, ReadonlyArray<string>>;
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* The contract of an application: lifecycle hooks, registration of artifacts, and `start`. Picked
|
|
304
|
+
* from `AbstractArdorApplication`, so its signatures are the class's own.
|
|
305
|
+
*/
|
|
306
|
+
export interface IArdorApplication extends Pick<AbstractArdorApplication, 'preConfigure' | 'postConfigure' | 'bindContext' | 'bindingList' | 'features' | 'artifacts' | 'service' | 'repository' | 'dataSource' | 'component' | 'start'> {
|
|
274
307
|
}
|
|
275
308
|
type TDeepPath = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
|
276
309
|
/** Values a path stops at: their members are not state. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type IAuthTokenRecord } from '../common/index.js';
|
|
1
|
+
import { type IAuthTokenRecord, type IdType } from '../common/index.js';
|
|
2
2
|
/** The one place that reads and writes the stored auth token, with the browser guard. */
|
|
3
3
|
export declare class AuthTokenStore {
|
|
4
4
|
private static readonly logger;
|
|
@@ -6,13 +6,17 @@ export declare class AuthTokenStore {
|
|
|
6
6
|
static read(opts?: {
|
|
7
7
|
key?: string;
|
|
8
8
|
}): IAuthTokenRecord | undefined;
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* Stores the token with its `provider`, and the `userId` it was issued to when given, under `key`
|
|
11
|
+
* (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available.
|
|
12
|
+
*/
|
|
10
13
|
static write(opts: {
|
|
11
14
|
token: {
|
|
12
15
|
value: string;
|
|
13
16
|
type: string;
|
|
14
17
|
};
|
|
15
18
|
provider: string;
|
|
19
|
+
userId?: IdType;
|
|
16
20
|
key?: string;
|
|
17
21
|
}): void;
|
|
18
22
|
}
|
|
@@ -23,14 +23,17 @@ export class AuthTokenStore {
|
|
|
23
23
|
return undefined;
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* Stores the token with its `provider`, and the `userId` it was issued to when given, under `key`
|
|
28
|
+
* (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available.
|
|
29
|
+
*/
|
|
27
30
|
static write(opts) {
|
|
28
31
|
// Not a silent skip: a sign-in that is not kept would look like it worked.
|
|
29
32
|
if (typeof localStorage === 'undefined') {
|
|
30
33
|
throw getError({ message: '[write] localStorage is not available' });
|
|
31
34
|
}
|
|
32
|
-
const { token, provider } = opts;
|
|
33
|
-
localStorage.setItem(opts.key ?? LocalStorageKeys.KEY_AUTH_TOKEN, JSON.stringify(Object.assign({}, token, { provider })));
|
|
35
|
+
const { token, provider, userId } = opts;
|
|
36
|
+
localStorage.setItem(opts.key ?? LocalStorageKeys.KEY_AUTH_TOKEN, JSON.stringify(Object.assign({}, token, { provider }, userId === undefined ? {} : { userId })));
|
|
34
37
|
}
|
|
35
38
|
}
|
|
36
39
|
//# sourceMappingURL=auth-token-store.js.map
|