@venizia/ardor-kernel 0.4.8-8 → 0.4.8

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.
@@ -1,19 +1,47 @@
1
- import { type AnyType, type IApplicationInfo, type IAuthTokenRecord, type IdType, type IScopedKeys } from '../../common/index.js';
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
- /** `listener` runs after every `saveAuth` and `cleanUp`, so after any change of the session this service makes. */
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;
@@ -23,14 +51,24 @@ export declare class DefaultAuthService extends BaseService {
23
51
  */
24
52
  private parseStored;
25
53
  /** The stored identity; `{}` when nothing usable is stored, also outside a browser. */
26
- getUser(): AnyType;
54
+ getUser(): IAuthUser;
55
+ /** A stored identity is data from the browser: an object whose known fields, when present, have their type. */
56
+ private isAuthUser;
27
57
  /**
28
58
  * The stored roles; empty when nothing usable is stored, also outside a browser. They are data in
29
59
  * the browser, so whoever controls the browser can change them: use them to show or hide interface,
30
60
  * never to decide what a user may do. The backend must check every permission on every request.
31
61
  */
32
62
  getRoles(): Set<string>;
33
- /** The stored token, `null` for every visitor who has not signed in. */
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
+ */
34
72
  getAuth(): IAuthTokenRecord | null;
35
73
  /**
36
74
  * Stores the token and identity, then notifies the subscribers. Throws when `localStorage` is
@@ -54,7 +92,17 @@ export declare class DefaultAuthService extends BaseService {
54
92
  */
55
93
  roles?: ReadonlyArray<string>;
56
94
  }): void;
57
- /** Removes every key under `keys.authPrefix`, then notifies the subscribers; does nothing outside a browser. */
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
+ */
58
106
  cleanUp(): void;
59
107
  }
60
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
- /** `listener` runs after every `saveAuth` and `cleanUp`, so after any change of the session this service makes. */
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;
98
+ };
99
+ }
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);
34
124
  };
35
125
  }
36
- notify() {
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);
@@ -70,8 +175,20 @@ let DefaultAuthService = DefaultAuthService_1 = class DefaultAuthService extends
70
175
  key: this.keys.identity,
71
176
  method: 'getUser',
72
177
  });
73
- const isRecord = typeof identity === 'object' && identity !== null && !Array.isArray(identity);
74
- return isRecord ? identity : {};
178
+ return this.isAuthUser(identity) ? identity : {};
179
+ }
180
+ /** A stored identity is data from the browser: an object whose known fields, when present, have their type. */
181
+ isAuthUser(value) {
182
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
183
+ return false;
184
+ }
185
+ const userId = 'userId' in value ? value.userId : undefined;
186
+ const username = 'username' in value ? value.username : undefined;
187
+ const referenceId = 'referenceId' in value ? value.referenceId : undefined;
188
+ const provider = 'provider' in value ? value.provider : undefined;
189
+ const isId = (field) => field === undefined || ['string', 'number'].includes(typeof field);
190
+ const isText = (field) => field === undefined || typeof field === 'string';
191
+ return isId(userId) && isText(username) && isId(referenceId) && isText(provider);
75
192
  }
76
193
  /**
77
194
  * The stored roles; empty when nothing usable is stored, also outside a browser. They are data in
@@ -86,9 +203,21 @@ let DefaultAuthService = DefaultAuthService_1 = class DefaultAuthService extends
86
203
  const roles = Array.isArray(stored) ? stored.filter((role) => typeof role === 'string') : [];
87
204
  return new Set(roles);
88
205
  }
89
- /** The stored token, `null` for every visitor who has not signed in. */
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
+ */
90
218
  getAuth() {
91
- return AuthTokenStore.read({ key: this.keys.token }) ?? null;
219
+ const token = AuthTokenStore.read({ key: this.keys.token });
220
+ return token && this.isSessionWhole({ token }) ? token : null;
92
221
  }
93
222
  /**
94
223
  * Stores the token and identity, then notifies the subscribers. Throws when `localStorage` is
@@ -102,25 +231,46 @@ let DefaultAuthService = DefaultAuthService_1 = class DefaultAuthService extends
102
231
  });
103
232
  }
104
233
  const { token, userId, username = '', provider = '', referenceId = '', roles } = opts;
105
- AuthTokenStore.write({ token, provider, key: this.keys.token });
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.
106
235
  localStorage.setItem(this.keys.identity, JSON.stringify({ userId, username, referenceId, provider }));
107
236
  if (roles) {
108
237
  localStorage.setItem(this.keys.permission, JSON.stringify(roles));
109
238
  }
110
- this.notify();
239
+ AuthTokenStore.write({ token, provider, userId, key: this.keys.token });
240
+ this.notify({ isExternal: false });
241
+ }
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('/'));
111
254
  }
112
- /** Removes every key under `keys.authPrefix`, then notifies the subscribers; does nothing outside a browser. */
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
+ */
113
260
  cleanUp() {
114
261
  if (typeof localStorage === 'undefined') {
115
262
  return;
116
263
  }
117
- Object.keys(localStorage).forEach((key) => {
118
- if (!key.startsWith(this.keys.authPrefix)) {
119
- return;
120
- }
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) {
121
271
  localStorage.removeItem(key);
122
- });
123
- this.notify();
272
+ }
273
+ this.notify({ isExternal: false });
124
274
  }
125
275
  };
126
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,16 +207,21 @@ 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 */
173
215
  baseUrl?: string;
174
- query?: any;
216
+ query?: Record<string, unknown>;
175
217
  type: TRequestType;
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