@venizia/ardor-kernel 0.4.8-16 → 0.4.8-18
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 +8 -8
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
var RolePermissionProvider_1;
|
|
14
|
+
import { BaseHelper } from '@venizia/ignis-helpers/core';
|
|
15
|
+
import { getError, inject } from '@venizia/ignis-inversion';
|
|
16
|
+
import { CoreBindings, } from '../../common/index.js';
|
|
17
|
+
class GrantPattern {
|
|
18
|
+
static { this.WILDCARD = '*'; }
|
|
19
|
+
static { this.SEPARATOR = '.'; }
|
|
20
|
+
/** Splits a grant pattern into its resource and action; throws, naming the role and the pattern, when it is not one. */
|
|
21
|
+
static parse(opts) {
|
|
22
|
+
const { role, pattern } = opts;
|
|
23
|
+
if (typeof pattern === 'string') {
|
|
24
|
+
if (pattern === this.WILDCARD) {
|
|
25
|
+
return { resource: this.WILDCARD, action: this.WILDCARD };
|
|
26
|
+
}
|
|
27
|
+
const parts = pattern.split(this.SEPARATOR);
|
|
28
|
+
const [resource, action] = parts;
|
|
29
|
+
if (parts.length === 2 && resource && action) {
|
|
30
|
+
return { resource, action };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
throw getError({
|
|
34
|
+
message: `[RolePermissionProvider] Invalid grant ${JSON.stringify(pattern)} for role '${role}': use '<resource>.<action>', '<resource>.*', '*.<action>' or '*'`,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
static matches(opts) {
|
|
38
|
+
const { grant, resource, action } = opts;
|
|
39
|
+
return ((grant.resource === this.WILDCARD || grant.resource === resource) &&
|
|
40
|
+
(grant.action === this.WILDCARD || grant.action === action));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* An `IPermissionProvider` over a table the application writes: each role name holds grant patterns,
|
|
45
|
+
* and a user may do what any of the roles from `DefaultAuthService.getRoles` grants. Nothing else is
|
|
46
|
+
* allowed: no signed-in user, no roles, or a role without an entry is denied. The roles are read at
|
|
47
|
+
* every call and are the ones stored at sign-in; a token refresh keeps them.
|
|
48
|
+
*
|
|
49
|
+
* It is opt-in: ARDOR binds none, and unbound means every check passes. An application with other
|
|
50
|
+
* needs writes its own `IPermissionProvider` and binds that under `CoreBindings.PERMISSION_PROVIDER`.
|
|
51
|
+
* The roles are data in the browser: this decides what the interface shows, never what a user may
|
|
52
|
+
* do, and the backend must check every request.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```ts
|
|
56
|
+
* import { BindingScopes } from '@venizia/ignis-inversion';
|
|
57
|
+
* import {
|
|
58
|
+
* BaseArdorApplication,
|
|
59
|
+
* configuration,
|
|
60
|
+
* CoreBindings,
|
|
61
|
+
* provideOption,
|
|
62
|
+
* RolePermissionProvider,
|
|
63
|
+
* type IApplicationInfo,
|
|
64
|
+
* type IRolePermissionProviderOptions,
|
|
65
|
+
* } from '@venizia/ardor';
|
|
66
|
+
*
|
|
67
|
+
* @configuration()
|
|
68
|
+
* export class PermissionConfiguration {
|
|
69
|
+
* @provideOption({ key: CoreBindings.PERMISSION_PROVIDER_OPTIONS })
|
|
70
|
+
* permissionOptions(): IRolePermissionProviderOptions {
|
|
71
|
+
* return { grants: { admin: ['*'], editor: ['orders.*', 'stocks.list'] } };
|
|
72
|
+
* }
|
|
73
|
+
* }
|
|
74
|
+
*
|
|
75
|
+
* export class Application extends BaseArdorApplication {
|
|
76
|
+
* getAppInfo(): IApplicationInfo {
|
|
77
|
+
* return { name: 'shop', version: '1.0.0', description: 'A shop back office' };
|
|
78
|
+
* }
|
|
79
|
+
*
|
|
80
|
+
* bindContext(): void {
|
|
81
|
+
* this.bind({ key: CoreBindings.PERMISSION_PROVIDER })
|
|
82
|
+
* .toClass(RolePermissionProvider)
|
|
83
|
+
* .setScope(BindingScopes.SINGLETON);
|
|
84
|
+
* }
|
|
85
|
+
* }
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
let RolePermissionProvider = RolePermissionProvider_1 = class RolePermissionProvider extends BaseHelper {
|
|
89
|
+
constructor(authService, options) {
|
|
90
|
+
super({ scope: RolePermissionProvider_1.name });
|
|
91
|
+
this.authService = authService;
|
|
92
|
+
this.grants = new Map();
|
|
93
|
+
for (const [role, patterns] of Object.entries(options.grants)) {
|
|
94
|
+
this.grants.set(role, patterns.map((pattern) => GrantPattern.parse({ role, pattern })));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
async canAccess(opts) {
|
|
98
|
+
const { resource, action } = opts;
|
|
99
|
+
// Roles can outlive the token (another tab, a corrupt key): without a token no one is signed in.
|
|
100
|
+
if (!this.authService.getAuth()?.value) {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
for (const role of this.authService.getRoles()) {
|
|
104
|
+
const grants = this.grants.get(role) ?? [];
|
|
105
|
+
if (grants.some((grant) => GrantPattern.matches({ grant, resource, action }))) {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
RolePermissionProvider = RolePermissionProvider_1 = __decorate([
|
|
113
|
+
__param(0, inject({ key: CoreBindings.DEFAULT_AUTH_SERVICE })),
|
|
114
|
+
__param(1, inject({ key: CoreBindings.PERMISSION_PROVIDER_OPTIONS })),
|
|
115
|
+
__metadata("design:paramtypes", [Function, Object])
|
|
116
|
+
], RolePermissionProvider);
|
|
117
|
+
export { RolePermissionProvider };
|
|
118
|
+
//# sourceMappingURL=role-permission.js.map
|
|
@@ -1,19 +1,47 @@
|
|
|
1
1
|
import { type IApplicationInfo, type IAuthTokenRecord, type IAuthUser, type IdType, type IScopedKeys } from '../../common/index.js';
|
|
2
2
|
import { BaseService } from './base.js';
|
|
3
|
+
/** What a subscriber of `DefaultAuthService` is told: `isExternal` is a change another tab of the application made. */
|
|
4
|
+
export interface IAuthChange {
|
|
5
|
+
isExternal: boolean;
|
|
6
|
+
}
|
|
3
7
|
/**
|
|
4
8
|
* Keeps the signed-in session (token, identity, roles) in `localStorage`, everything under
|
|
5
9
|
* `keys.authPrefix`: `LocalStorageKeys.PREFIX_AUTH`, or `@app/auth/<id>/` when the application has an `id`.
|
|
6
10
|
*/
|
|
7
11
|
export declare class DefaultAuthService extends BaseService {
|
|
8
12
|
private readonly listeners;
|
|
13
|
+
private stopExternalSync?;
|
|
14
|
+
private snapshot;
|
|
9
15
|
/** The keys of this application's session and store: the application's `id` scopes them. */
|
|
10
16
|
readonly keys: IScopedKeys;
|
|
11
17
|
/** A subclass with its own constructor passes `info` on to `super(info)`; otherwise its keys are the unscoped ones. */
|
|
12
18
|
constructor(info?: IApplicationInfo);
|
|
13
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* `listener` runs after every `saveAuth` and `cleanUp`, so after any change of the session this service makes,
|
|
21
|
+
* and after a sign-in, sign-out or user switch in another tab of the browser: the first
|
|
22
|
+
* subscriber starts listening to the `storage` event of the token and identity keys, the last one to leave stops. The
|
|
23
|
+
* listener also runs when a page comes back from the back-forward cache or a tab becomes visible and the
|
|
24
|
+
* session changed meanwhile. A change of another tab calls the listener once, when the stored token and
|
|
25
|
+
* identity belong to one user, and writes nothing; a service never subscribed to listens to nothing, and
|
|
26
|
+
* outside a browser nothing is listened to.
|
|
27
|
+
*/
|
|
14
28
|
subscribe(opts: {
|
|
15
|
-
listener: () => void;
|
|
29
|
+
listener: (change: IAuthChange) => void;
|
|
16
30
|
}): () => void;
|
|
31
|
+
/** What is stored for the session now, as one text: two reads of it are equal when nothing of the session changed. */
|
|
32
|
+
private readSnapshot;
|
|
33
|
+
private startExternalSync;
|
|
34
|
+
/**
|
|
35
|
+
* Runs `listener` when the page comes back from the back-forward cache (`pageshow`, persisted) or its tab
|
|
36
|
+
* becomes visible: no `storage` event reaches a page in either state. Returns how to stop; does nothing
|
|
37
|
+
* without a window.
|
|
38
|
+
*/
|
|
39
|
+
private onPageReturn;
|
|
40
|
+
/**
|
|
41
|
+
* Whether the stored `token` and the stored identity belong to one user. A token stored without a `userId`
|
|
42
|
+
* (before `saveAuth` wrote it) counts as whole; so does a session with no token.
|
|
43
|
+
*/
|
|
44
|
+
private isSessionWhole;
|
|
17
45
|
private notify;
|
|
18
46
|
/** What is stored under the key, or `null` when nothing is, also outside a browser. */
|
|
19
47
|
private readStored;
|
|
@@ -32,7 +60,15 @@ export declare class DefaultAuthService extends BaseService {
|
|
|
32
60
|
* never to decide what a user may do. The backend must check every permission on every request.
|
|
33
61
|
*/
|
|
34
62
|
getRoles(): Set<string>;
|
|
35
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* Whether another tab is in the middle of a user switch: a token is stored, but it belongs to another user
|
|
65
|
+
* than the stored identity. `getAuth` answers `null` meanwhile, which is not a sign-out: someone is signing in.
|
|
66
|
+
*/
|
|
67
|
+
isSwitching(): boolean;
|
|
68
|
+
/**
|
|
69
|
+
* The stored token, `null` for every visitor who has not signed in, and while the stored token belongs to
|
|
70
|
+
* another user than the stored identity (another tab is switching users and has not finished writing).
|
|
71
|
+
*/
|
|
36
72
|
getAuth(): IAuthTokenRecord | null;
|
|
37
73
|
/**
|
|
38
74
|
* Stores the token and identity, then notifies the subscribers. Throws when `localStorage` is
|
|
@@ -56,7 +92,17 @@ export declare class DefaultAuthService extends BaseService {
|
|
|
56
92
|
*/
|
|
57
93
|
roles?: ReadonlyArray<string>;
|
|
58
94
|
}): void;
|
|
59
|
-
/**
|
|
95
|
+
/**
|
|
96
|
+
* Whether `key` is a key of this service's session. Without an application `id` the prefix is
|
|
97
|
+
* `LocalStorageKeys.PREFIX_AUTH`, which is also the start of every scoped session, so a key with a
|
|
98
|
+
* `/` after the prefix belongs to an application that has an `id`.
|
|
99
|
+
*/
|
|
100
|
+
private isSessionKey;
|
|
101
|
+
/**
|
|
102
|
+
* Removes the session keys under `keys.authPrefix`, then notifies the subscribers; does nothing
|
|
103
|
+
* outside a browser. A service without an application `id` leaves the sessions of applications with
|
|
104
|
+
* an `id` alone.
|
|
105
|
+
*/
|
|
60
106
|
cleanUp(): void;
|
|
61
107
|
}
|
|
62
108
|
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -12,8 +12,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
12
12
|
};
|
|
13
13
|
var DefaultAuthService_1;
|
|
14
14
|
import { getError, inject } from '@venizia/ignis-inversion';
|
|
15
|
-
import { CoreBindings, LocalStorageKeys, } from '../../common/index.js';
|
|
15
|
+
import { CoreBindings, LocalStorageKeys, StorageAreas, } from '../../common/index.js';
|
|
16
16
|
import { AuthTokenStore } from '../../helpers/index.js';
|
|
17
|
+
import { BrowserStorage, StorageCodecs } from '../../utilities/index.js';
|
|
17
18
|
import { BaseService } from './base.js';
|
|
18
19
|
/**
|
|
19
20
|
* Keeps the signed-in session (token, identity, roles) in `localStorage`, everything under
|
|
@@ -24,19 +25,123 @@ let DefaultAuthService = DefaultAuthService_1 = class DefaultAuthService extends
|
|
|
24
25
|
constructor(info) {
|
|
25
26
|
super({ scope: DefaultAuthService_1.name });
|
|
26
27
|
this.listeners = new Set();
|
|
28
|
+
this.snapshot = '';
|
|
27
29
|
this.keys = LocalStorageKeys.scoped({ id: info?.id });
|
|
28
30
|
}
|
|
29
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* `listener` runs after every `saveAuth` and `cleanUp`, so after any change of the session this service makes,
|
|
33
|
+
* and after a sign-in, sign-out or user switch in another tab of the browser: the first
|
|
34
|
+
* subscriber starts listening to the `storage` event of the token and identity keys, the last one to leave stops. The
|
|
35
|
+
* listener also runs when a page comes back from the back-forward cache or a tab becomes visible and the
|
|
36
|
+
* session changed meanwhile. A change of another tab calls the listener once, when the stored token and
|
|
37
|
+
* identity belong to one user, and writes nothing; a service never subscribed to listens to nothing, and
|
|
38
|
+
* outside a browser nothing is listened to.
|
|
39
|
+
*/
|
|
30
40
|
subscribe(opts) {
|
|
31
41
|
this.listeners.add(opts.listener);
|
|
42
|
+
this.startExternalSync();
|
|
32
43
|
return () => {
|
|
33
44
|
this.listeners.delete(opts.listener);
|
|
45
|
+
if (this.listeners.size === 0) {
|
|
46
|
+
this.stopExternalSync?.();
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** What is stored for the session now, as one text: two reads of it are equal when nothing of the session changed. */
|
|
51
|
+
readSnapshot() {
|
|
52
|
+
return [this.keys.token, this.keys.identity, this.keys.permission]
|
|
53
|
+
.map((key) => {
|
|
54
|
+
return BrowserStorage.get({
|
|
55
|
+
key,
|
|
56
|
+
fallback: null,
|
|
57
|
+
storage: StorageAreas.LOCAL,
|
|
58
|
+
codec: StorageCodecs.text(),
|
|
59
|
+
});
|
|
60
|
+
})
|
|
61
|
+
.join('\u0000');
|
|
62
|
+
}
|
|
63
|
+
startExternalSync() {
|
|
64
|
+
if (this.stopExternalSync) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
this.snapshot = this.readSnapshot();
|
|
68
|
+
// A write of this tab announced itself; an event it caused must not announce it again. A token that belongs
|
|
69
|
+
// to another user than the stored identity is a pair still being written by another tab, or a view of
|
|
70
|
+
// storage that is ahead of the event: the event of the token that completes the pair announces it.
|
|
71
|
+
const announce = () => {
|
|
72
|
+
if (this.isSessionWhole({ token: AuthTokenStore.read({ key: this.keys.token }) }) &&
|
|
73
|
+
this.readSnapshot() !== this.snapshot) {
|
|
74
|
+
this.notify({ isExternal: true });
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
// `saveAuth` writes the token last and `cleanUp` removes it first, so the token key completes a session. The
|
|
78
|
+
// identity key is heard too: a tab on older code writes the token first, and its identity comes after. Half a
|
|
79
|
+
// pair is never announced, so hearing both is safe.
|
|
80
|
+
const stops = [this.keys.token, this.keys.identity]
|
|
81
|
+
.map((key) => {
|
|
82
|
+
return BrowserStorage.subscribe({
|
|
83
|
+
key,
|
|
84
|
+
storage: StorageAreas.LOCAL,
|
|
85
|
+
listener: ({ isExternal }) => {
|
|
86
|
+
if (isExternal) {
|
|
87
|
+
announce();
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
})
|
|
92
|
+
.concat(this.onPageReturn({ listener: announce }));
|
|
93
|
+
this.stopExternalSync = () => {
|
|
94
|
+
for (const stop of stops) {
|
|
95
|
+
stop();
|
|
96
|
+
}
|
|
97
|
+
this.stopExternalSync = undefined;
|
|
34
98
|
};
|
|
35
99
|
}
|
|
36
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Runs `listener` when the page comes back from the back-forward cache (`pageshow`, persisted) or its tab
|
|
102
|
+
* becomes visible: no `storage` event reaches a page in either state. Returns how to stop; does nothing
|
|
103
|
+
* without a window.
|
|
104
|
+
*/
|
|
105
|
+
onPageReturn(opts) {
|
|
106
|
+
if (typeof globalThis.addEventListener !== 'function') {
|
|
107
|
+
return () => { };
|
|
108
|
+
}
|
|
109
|
+
const onShow = (event) => {
|
|
110
|
+
if (Reflect.get(event, 'persisted') === true) {
|
|
111
|
+
opts.listener();
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const onVisible = () => {
|
|
115
|
+
if (globalThis.document?.visibilityState === 'visible') {
|
|
116
|
+
opts.listener();
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
globalThis.addEventListener('pageshow', onShow);
|
|
120
|
+
globalThis.document?.addEventListener('visibilitychange', onVisible);
|
|
121
|
+
return () => {
|
|
122
|
+
globalThis.removeEventListener('pageshow', onShow);
|
|
123
|
+
globalThis.document?.removeEventListener('visibilitychange', onVisible);
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Whether the stored `token` and the stored identity belong to one user. A token stored without a `userId`
|
|
128
|
+
* (before `saveAuth` wrote it) counts as whole; so does a session with no token.
|
|
129
|
+
*/
|
|
130
|
+
isSessionWhole(opts) {
|
|
131
|
+
const { token } = opts;
|
|
132
|
+
if (token?.userId === undefined) {
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
const { userId } = this.getUser();
|
|
136
|
+
return userId !== undefined && String(userId) === String(token.userId);
|
|
137
|
+
}
|
|
138
|
+
notify(change) {
|
|
139
|
+
if (this.stopExternalSync) {
|
|
140
|
+
this.snapshot = this.readSnapshot();
|
|
141
|
+
}
|
|
37
142
|
for (const listener of this.listeners) {
|
|
38
143
|
try {
|
|
39
|
-
listener();
|
|
144
|
+
listener(change);
|
|
40
145
|
}
|
|
41
146
|
catch (error) {
|
|
42
147
|
this.logger.error('[notify] A listener failed | error: %o', error);
|
|
@@ -98,9 +203,21 @@ let DefaultAuthService = DefaultAuthService_1 = class DefaultAuthService extends
|
|
|
98
203
|
const roles = Array.isArray(stored) ? stored.filter((role) => typeof role === 'string') : [];
|
|
99
204
|
return new Set(roles);
|
|
100
205
|
}
|
|
101
|
-
/**
|
|
206
|
+
/**
|
|
207
|
+
* Whether another tab is in the middle of a user switch: a token is stored, but it belongs to another user
|
|
208
|
+
* than the stored identity. `getAuth` answers `null` meanwhile, which is not a sign-out: someone is signing in.
|
|
209
|
+
*/
|
|
210
|
+
isSwitching() {
|
|
211
|
+
const token = AuthTokenStore.read({ key: this.keys.token });
|
|
212
|
+
return token !== undefined && !this.isSessionWhole({ token });
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* The stored token, `null` for every visitor who has not signed in, and while the stored token belongs to
|
|
216
|
+
* another user than the stored identity (another tab is switching users and has not finished writing).
|
|
217
|
+
*/
|
|
102
218
|
getAuth() {
|
|
103
|
-
|
|
219
|
+
const token = AuthTokenStore.read({ key: this.keys.token });
|
|
220
|
+
return token && this.isSessionWhole({ token }) ? token : null;
|
|
104
221
|
}
|
|
105
222
|
/**
|
|
106
223
|
* Stores the token and identity, then notifies the subscribers. Throws when `localStorage` is
|
|
@@ -114,25 +231,46 @@ let DefaultAuthService = DefaultAuthService_1 = class DefaultAuthService extends
|
|
|
114
231
|
});
|
|
115
232
|
}
|
|
116
233
|
const { token, userId, username = '', provider = '', referenceId = '', roles } = opts;
|
|
117
|
-
|
|
234
|
+
// The identity and the roles first and the token last: another tab that reads between the writes sees another user's identity with the old token, never the old user's with the new token, and it acts on the token's event only, when the session is whole.
|
|
118
235
|
localStorage.setItem(this.keys.identity, JSON.stringify({ userId, username, referenceId, provider }));
|
|
119
236
|
if (roles) {
|
|
120
237
|
localStorage.setItem(this.keys.permission, JSON.stringify(roles));
|
|
121
238
|
}
|
|
122
|
-
this.
|
|
239
|
+
AuthTokenStore.write({ token, provider, userId, key: this.keys.token });
|
|
240
|
+
this.notify({ isExternal: false });
|
|
123
241
|
}
|
|
124
|
-
/**
|
|
242
|
+
/**
|
|
243
|
+
* Whether `key` is a key of this service's session. Without an application `id` the prefix is
|
|
244
|
+
* `LocalStorageKeys.PREFIX_AUTH`, which is also the start of every scoped session, so a key with a
|
|
245
|
+
* `/` after the prefix belongs to an application that has an `id`.
|
|
246
|
+
*/
|
|
247
|
+
isSessionKey(opts) {
|
|
248
|
+
const { key } = opts;
|
|
249
|
+
if (!key.startsWith(this.keys.authPrefix)) {
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
return (this.keys.authPrefix !== LocalStorageKeys.PREFIX_AUTH ||
|
|
253
|
+
!key.slice(this.keys.authPrefix.length).includes('/'));
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Removes the session keys under `keys.authPrefix`, then notifies the subscribers; does nothing
|
|
257
|
+
* outside a browser. A service without an application `id` leaves the sessions of applications with
|
|
258
|
+
* an `id` alone.
|
|
259
|
+
*/
|
|
125
260
|
cleanUp() {
|
|
126
261
|
if (typeof localStorage === 'undefined') {
|
|
127
262
|
return;
|
|
128
263
|
}
|
|
129
|
-
Object.keys(localStorage).
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
264
|
+
const sessionKeys = Object.keys(localStorage).filter((key) => this.isSessionKey({ key }));
|
|
265
|
+
// The token first: another tab acts on its event, and then finds no session, not an identity without a token.
|
|
266
|
+
const ordered = [
|
|
267
|
+
...sessionKeys.filter((key) => key === this.keys.token),
|
|
268
|
+
...sessionKeys.filter((key) => key !== this.keys.token),
|
|
269
|
+
];
|
|
270
|
+
for (const key of ordered) {
|
|
133
271
|
localStorage.removeItem(key);
|
|
134
|
-
}
|
|
135
|
-
this.notify();
|
|
272
|
+
}
|
|
273
|
+
this.notify({ isExternal: false });
|
|
136
274
|
}
|
|
137
275
|
};
|
|
138
276
|
DefaultAuthService = DefaultAuthService_1 = __decorate([
|
|
@@ -1,9 +1,19 @@
|
|
|
1
1
|
import { NodeFetchNetworkRequest } from '@venizia/ignis-helpers/core';
|
|
2
|
-
import { type IApplicationInfo, type IAuthTokenRecord, type IAuthRecoveryOptions, type IDataSourceAuth, type IGetRequestPropsParams, type IGetRequestPropsResult, type INetworkResponse, type INoAuthOptions, RequestCountData, type TConstValue, type TNoAuthPathRegex, type TRequestMethod, type TRequestType } from '../../common/index.js';
|
|
2
|
+
import { type IApplicationInfo, type IAuthTokenRecord, type IAuthRecoveryOptions, type IDataSourceAuth, type IGetRequestPropsParams, type IGetRequestPropsResult, type INetworkResponse, type INoAuthOptions, RequestCountData, type TConstValue, type TNoAuthPathRegex, type TRequestMethod, type TRequestTimeoutOptions, type TRequestType } from '../../common/index.js';
|
|
3
3
|
import { type IEncodedBody, ResponseReader } from '../../helpers/index.js';
|
|
4
4
|
import type { DefaultAuthService } from './auth.js';
|
|
5
5
|
import { BaseService } from './base.js';
|
|
6
|
+
/** 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. */
|
|
7
|
+
export declare const SESSION_CHANGED_CODE = "ardor.network.session_changed";
|
|
8
|
+
/** The `normalized.code` of the 504 a request rejects with when it outlives the configured `timeout`. */
|
|
9
|
+
export declare const NETWORK_TIMEOUT_CODE = "ardor.network.timeout";
|
|
6
10
|
/**
|
|
11
|
+
* Sends the requests of the data provider with its own sender. The repositories of
|
|
12
|
+
* `@venizia/ardor/repository` send through IGNIS's `HttpDataSource`, from the optional peer
|
|
13
|
+
* `@venizia/ignis-connectors`, which this service cannot import without making that peer required:
|
|
14
|
+
* until IGNIS's transport core is in a required peer, two clients exist, and `getDataSourceAuth`
|
|
15
|
+
* gives the second the session of the first.
|
|
16
|
+
*
|
|
7
17
|
* The options hold data (the base URL, headers, the no-auth lists, the refresh path); behaviour is
|
|
8
18
|
* in the protected hooks, each taking one `opts` object, which a subclass overrides.
|
|
9
19
|
*/
|
|
@@ -19,7 +29,11 @@ export declare class DefaultNetworkRequestService extends BaseService {
|
|
|
19
29
|
protected baseUrl: string;
|
|
20
30
|
protected authRecovery?: IAuthRecoveryOptions;
|
|
21
31
|
protected authService?: DefaultAuthService;
|
|
32
|
+
/** How long a request may take; see `IRestDataProviderOptions.timeout`. */
|
|
33
|
+
protected timeout: TRequestTimeoutOptions;
|
|
22
34
|
private readonly recovery;
|
|
35
|
+
/** The session each data source request was sent under, keyed by the context object IGNIS hands to both hooks. */
|
|
36
|
+
private readonly sentSessions;
|
|
23
37
|
constructor(opts: INoAuthOptions & {
|
|
24
38
|
/** The name of the underlying network request helper. */
|
|
25
39
|
name: string;
|
|
@@ -37,6 +51,11 @@ export declare class DefaultNetworkRequestService extends BaseService {
|
|
|
37
51
|
authRecovery?: IAuthRecoveryOptions;
|
|
38
52
|
/** What the default `refreshToken` saves the new token through. */
|
|
39
53
|
authService?: DefaultAuthService;
|
|
54
|
+
/**
|
|
55
|
+
* Aborts each request that has not answered in time. Throws here for an invalid `milliseconds`.
|
|
56
|
+
* @default { use: false }
|
|
57
|
+
*/
|
|
58
|
+
timeout?: TRequestTimeoutOptions;
|
|
40
59
|
});
|
|
41
60
|
/**
|
|
42
61
|
* The token under the unscoped session key (`AuthTokenStore.read`), `undefined` outside a browser, for an
|
|
@@ -57,6 +76,10 @@ export declare class DefaultNetworkRequestService extends BaseService {
|
|
|
57
76
|
static createAuthTokenReader(opts?: {
|
|
58
77
|
id?: string;
|
|
59
78
|
}): () => IAuthTokenRecord | undefined;
|
|
79
|
+
/** Throws unless a timeout that is on has a positive integer `milliseconds`. */
|
|
80
|
+
static assertTimeout(opts: {
|
|
81
|
+
timeout?: TRequestTimeoutOptions;
|
|
82
|
+
}): void;
|
|
60
83
|
/**
|
|
61
84
|
* The token this service sends. The one way to supply a token: override it to read another
|
|
62
85
|
* store, or to hold the token in memory.
|
|
@@ -107,6 +130,24 @@ export declare class DefaultNetworkRequestService extends BaseService {
|
|
|
107
130
|
* Also what `DefaultAuthProvider.refreshToken` calls, so a refresh is made in one place.
|
|
108
131
|
*/
|
|
109
132
|
refresh(): Promise<boolean>;
|
|
133
|
+
/** The session signed in now: who, and with which token. */
|
|
134
|
+
private readSession;
|
|
135
|
+
/** The 401 that answers a request whose session is gone: `DefaultAuthProvider.checkError` leaves the signed-in session alone for it. */
|
|
136
|
+
private sessionChangedError;
|
|
137
|
+
/**
|
|
138
|
+
* How the session changed since `sent`: `undefined` when it did not, `true` when the same user holds
|
|
139
|
+
* another token now (the request can be sent again with it), `false` when the user who sent is gone. When
|
|
140
|
+
* nobody can tell who sent, another token is a switch: it is never read as the same user's.
|
|
141
|
+
*/
|
|
142
|
+
private readSessionChange;
|
|
143
|
+
/** `task` settles as it does, or the wait rejects with the reason of `signal` once it aborts; the task itself is not cancelled. */
|
|
144
|
+
private static untilAborted;
|
|
145
|
+
/**
|
|
146
|
+
* Whether the 401 of a request that `sent` is a session change for the caller: the user who sent is gone and
|
|
147
|
+
* either the request was sent again since (`isRetried`) or another session is signed in now. A refresh that
|
|
148
|
+
* failed and ended the session itself leaves nobody to protect, and its 401 stands.
|
|
149
|
+
*/
|
|
150
|
+
private isSessionTaken;
|
|
110
151
|
/**
|
|
111
152
|
* Spread into an `HttpDataSource`'s settings, so its requests carry the session headers and the
|
|
112
153
|
* timezone as read at send time (and the channel and tracing id, given the data provider's
|
|
@@ -166,7 +207,8 @@ export declare class DefaultNetworkRequestService extends BaseService {
|
|
|
166
207
|
* Sends the request and reads the response by `type`. Throws when `baseUrl` (the option, else the
|
|
167
208
|
* service's) is empty. A 401 on a path that can recover triggers `refresh` and, if it refreshed,
|
|
168
209
|
* one retry with the new token. Any other non-2xx response, or a retry that still fails, throws
|
|
169
|
-
* the error read from the response.
|
|
210
|
+
* the error read from the response. An aborted `signal` rejects with its reason, and a request
|
|
211
|
+
* that outlives the service's `timeout` rejects with a 504 coded `NETWORK_TIMEOUT_CODE`.
|
|
170
212
|
*/
|
|
171
213
|
doRequest<TResult = unknown>(opts: IGetRequestPropsResult & {
|
|
172
214
|
/** @default this.baseUrl */
|
|
@@ -176,6 +218,10 @@ export declare class DefaultNetworkRequestService extends BaseService {
|
|
|
176
218
|
method: TRequestMethod;
|
|
177
219
|
paths: string[];
|
|
178
220
|
requestCountData?: TConstValue<typeof RequestCountData>;
|
|
221
|
+
/** Aborts this request only: a refresh its 401 started runs on for the other requests. */
|
|
222
|
+
signal?: AbortSignal;
|
|
179
223
|
}): Promise<INetworkResponse<TResult>>;
|
|
224
|
+
/** `doRequest` once the URL is checked: the send, the refresh and retry after a 401, then the read. */
|
|
225
|
+
private sendAndRead;
|
|
180
226
|
}
|
|
181
227
|
//# sourceMappingURL=network-request.d.ts.map
|