@icp-sdk/auth 11.1.0 → 11.2.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.
Files changed (89) hide show
  1. package/dist/esm/client/auth-client.d.ts +28 -17
  2. package/dist/esm/client/auth-client.js +65 -11
  3. package/dist/esm/client/auth-client.js.map +1 -1
  4. package/dist/esm/client/credentials/credential-storage.js.map +1 -0
  5. package/dist/esm/client/{idb-credential-storage.d.ts → credentials/idb-credential-storage.d.ts} +1 -1
  6. package/dist/esm/client/{idb-credential-storage.js → credentials/idb-credential-storage.js} +1 -1
  7. package/dist/esm/client/credentials/idb-credential-storage.js.map +1 -0
  8. package/dist/esm/client/credentials/local-credential-storage.js.map +1 -0
  9. package/dist/esm/client/credentials/memory-credential-storage.js.map +1 -0
  10. package/dist/esm/client/credentials/shared-memory-credential-storage.js.map +1 -0
  11. package/dist/esm/client/index.d.ts +14 -12
  12. package/dist/esm/client/index.js +11 -10
  13. package/dist/esm/client/index.js.map +1 -1
  14. package/dist/esm/client/notification-consent.js +3 -3
  15. package/dist/esm/client/notification-consent.js.map +1 -1
  16. package/dist/esm/client/session/app-delegation-source.js.map +1 -0
  17. package/dist/esm/client/session/app-lock.js.map +1 -0
  18. package/dist/esm/client/{session-delegation.js → session/session-delegation.js} +1 -1
  19. package/dist/esm/client/session/session-delegation.js.map +1 -0
  20. package/dist/esm/client/{session-identity.d.ts → session/session-identity.d.ts} +1 -1
  21. package/dist/esm/client/session/session-identity.js.map +1 -0
  22. package/dist/esm/client/session/session-minter.js.map +1 -0
  23. package/dist/esm/client/sso.d.ts +91 -0
  24. package/dist/esm/client/sso.js +206 -0
  25. package/dist/esm/client/sso.js.map +1 -1
  26. package/dist/esm/client/{cookie-state-storage.d.ts → state/cookie-state-storage.d.ts} +11 -1
  27. package/dist/esm/client/{cookie-state-storage.js → state/cookie-state-storage.js} +25 -1
  28. package/dist/esm/client/state/cookie-state-storage.js.map +1 -0
  29. package/dist/esm/client/state/local-state-storage.d.ts +36 -0
  30. package/dist/esm/client/{state-storage.js → state/local-state-storage.js} +92 -66
  31. package/dist/esm/client/state/local-state-storage.js.map +1 -0
  32. package/dist/esm/client/state/memory-state-storage.d.ts +27 -0
  33. package/dist/esm/client/state/memory-state-storage.js +67 -0
  34. package/dist/esm/client/state/memory-state-storage.js.map +1 -0
  35. package/dist/esm/client/{state-storage.d.ts → state/state-storage.d.ts} +12 -46
  36. package/dist/esm/client/state/state-storage.js +2 -0
  37. package/dist/esm/client/state/state-storage.js.map +1 -0
  38. package/package.json +10 -10
  39. package/src/client/auth-client.ts +76 -17
  40. package/src/client/{idb-credential-storage.ts → credentials/idb-credential-storage.ts} +1 -1
  41. package/src/client/index.ts +20 -20
  42. package/src/client/notification-consent.ts +3 -3
  43. package/src/client/{session-delegation.ts → session/session-delegation.ts} +1 -1
  44. package/src/client/{session-identity.ts → session/session-identity.ts} +1 -1
  45. package/src/client/sso.ts +258 -0
  46. package/src/client/{cookie-state-storage.ts → state/cookie-state-storage.ts} +28 -1
  47. package/src/client/state/local-state-storage.ts +216 -0
  48. package/src/client/state/memory-state-storage.ts +75 -0
  49. package/src/client/state/state-storage.ts +112 -0
  50. package/dist/esm/client/app-delegation-source.js.map +0 -1
  51. package/dist/esm/client/app-lock.js.map +0 -1
  52. package/dist/esm/client/cookie-state-storage.js.map +0 -1
  53. package/dist/esm/client/credential-storage.js.map +0 -1
  54. package/dist/esm/client/idb-credential-storage.js.map +0 -1
  55. package/dist/esm/client/local-credential-storage.js.map +0 -1
  56. package/dist/esm/client/memory-credential-storage.js.map +0 -1
  57. package/dist/esm/client/session-delegation.js.map +0 -1
  58. package/dist/esm/client/session-identity.js.map +0 -1
  59. package/dist/esm/client/session-minter.js.map +0 -1
  60. package/dist/esm/client/shared-memory-credential-storage.js.map +0 -1
  61. package/dist/esm/client/sso-status.d.ts +0 -91
  62. package/dist/esm/client/sso-status.js +0 -207
  63. package/dist/esm/client/sso-status.js.map +0 -1
  64. package/dist/esm/client/state-storage.js.map +0 -1
  65. package/src/client/sso-status.ts +0 -257
  66. package/src/client/state-storage.ts +0 -284
  67. /package/dist/esm/client/{credential-storage.d.ts → credentials/credential-storage.d.ts} +0 -0
  68. /package/dist/esm/client/{credential-storage.js → credentials/credential-storage.js} +0 -0
  69. /package/dist/esm/client/{local-credential-storage.d.ts → credentials/local-credential-storage.d.ts} +0 -0
  70. /package/dist/esm/client/{local-credential-storage.js → credentials/local-credential-storage.js} +0 -0
  71. /package/dist/esm/client/{memory-credential-storage.d.ts → credentials/memory-credential-storage.d.ts} +0 -0
  72. /package/dist/esm/client/{memory-credential-storage.js → credentials/memory-credential-storage.js} +0 -0
  73. /package/dist/esm/client/{shared-memory-credential-storage.d.ts → credentials/shared-memory-credential-storage.d.ts} +0 -0
  74. /package/dist/esm/client/{shared-memory-credential-storage.js → credentials/shared-memory-credential-storage.js} +0 -0
  75. /package/dist/esm/client/{app-delegation-source.d.ts → session/app-delegation-source.d.ts} +0 -0
  76. /package/dist/esm/client/{app-delegation-source.js → session/app-delegation-source.js} +0 -0
  77. /package/dist/esm/client/{app-lock.d.ts → session/app-lock.d.ts} +0 -0
  78. /package/dist/esm/client/{app-lock.js → session/app-lock.js} +0 -0
  79. /package/dist/esm/client/{session-delegation.d.ts → session/session-delegation.d.ts} +0 -0
  80. /package/dist/esm/client/{session-identity.js → session/session-identity.js} +0 -0
  81. /package/dist/esm/client/{session-minter.d.ts → session/session-minter.d.ts} +0 -0
  82. /package/dist/esm/client/{session-minter.js → session/session-minter.js} +0 -0
  83. /package/src/client/{credential-storage.ts → credentials/credential-storage.ts} +0 -0
  84. /package/src/client/{local-credential-storage.ts → credentials/local-credential-storage.ts} +0 -0
  85. /package/src/client/{memory-credential-storage.ts → credentials/memory-credential-storage.ts} +0 -0
  86. /package/src/client/{shared-memory-credential-storage.ts → credentials/shared-memory-credential-storage.ts} +0 -0
  87. /package/src/client/{app-delegation-source.ts → session/app-delegation-source.ts} +0 -0
  88. /package/src/client/{app-lock.ts → session/app-lock.ts} +0 -0
  89. /package/src/client/{session-minter.ts → session/session-minter.ts} +0 -0
@@ -2,18 +2,17 @@
2
2
  * @module api/client
3
3
  */
4
4
 
5
- export { type AppDelegationSource, SessionGoneError } from './app-delegation-source.js';
6
5
  export * from './auth-client.js';
6
+ export type { Credential, CredentialStorage } from './credentials/credential-storage.js';
7
+ export { IdbCredentialStorage } from './credentials/idb-credential-storage.js';
8
+ export { LocalCredentialStorage } from './credentials/local-credential-storage.js';
9
+ export { MemoryCredentialStorage } from './credentials/memory-credential-storage.js';
7
10
  export {
8
- CookieStateStorage,
9
- type CookieStateStorageOptions,
10
- } from './cookie-state-storage.js';
11
- export type { Credential, CredentialStorage } from './credential-storage.js';
11
+ DEFAULT_SHARED_MEMORY_NAME,
12
+ SharedMemoryCredentialStorage,
13
+ } from './credentials/shared-memory-credential-storage.js';
12
14
  export { DB_VERSION, type DBCreateOptions, IdbKeyVal } from './db.js';
13
15
  export { watchActivity, watchForeground } from './foreground-refresh.js';
14
- export { IdbCredentialStorage } from './idb-credential-storage.js';
15
- export { LocalCredentialStorage } from './local-credential-storage.js';
16
- export { MemoryCredentialStorage } from './memory-credential-storage.js';
17
16
  export {
18
17
  NotificationConsent,
19
18
  type NotificationConsentOptions,
@@ -22,17 +21,18 @@ export {
22
21
  NotificationsUnsupportedError,
23
22
  requestNotificationConsent,
24
23
  } from './notification-consent.js';
25
- export { InteractionRequiredError, requestSessionDelegation } from './session-delegation.js';
26
- export { SessionIdentity, type SessionIdentityOptions } from './session-identity.js';
27
- export { SessionMinter, type SessionMinterOptions } from './session-minter.js';
24
+ export { type AppDelegationSource, SessionGoneError } from './session/app-delegation-source.js';
28
25
  export {
29
- DEFAULT_SHARED_MEMORY_NAME,
30
- SharedMemoryCredentialStorage,
31
- } from './shared-memory-credential-storage.js';
32
- export type { SsoStatus } from './sso-status.js';
26
+ InteractionRequiredError,
27
+ requestSessionDelegation,
28
+ } from './session/session-delegation.js';
29
+ export { SessionIdentity, type SessionIdentityOptions } from './session/session-identity.js';
30
+ export { SessionMinter, type SessionMinterOptions } from './session/session-minter.js';
31
+ export type { SsoStatus } from './sso.js';
33
32
  export {
34
- LocalStateStorage,
35
- MemoryStateStorage,
36
- type SessionState,
37
- type StateStorage,
38
- } from './state-storage.js';
33
+ CookieStateStorage,
34
+ type CookieStateStorageOptions,
35
+ } from './state/cookie-state-storage.js';
36
+ export { LocalStateStorage } from './state/local-state-storage.js';
37
+ export { MemoryStateStorage } from './state/memory-state-storage.js';
38
+ export type { SessionState, StateStorage } from './state/state-storage.js';
@@ -3,9 +3,9 @@ import type { IDL } from '@icp-sdk/core/candid';
3
3
  import { type DelegationChain, DelegationIdentity } from '@icp-sdk/core/identity';
4
4
  import type { Principal } from '@icp-sdk/core/principal';
5
5
  import type { Signer } from '@icp-sdk/signer';
6
- import { SessionGoneError } from './app-delegation-source.js';
7
- import { InteractionRequiredError } from './session-delegation.js';
8
- import { assertChainReaches } from './session-minter.js';
6
+ import { SessionGoneError } from './session/app-delegation-source.js';
7
+ import { InteractionRequiredError } from './session/session-delegation.js';
8
+ import { assertChainReaches } from './session/session-minter.js';
9
9
 
10
10
  /**
11
11
  * The method Internet Identity answers with the user's decision about being
@@ -2,7 +2,7 @@ import type { DerEncodedPublicKey } from '@icp-sdk/core/agent';
2
2
  import { Delegation, DelegationChain } from '@icp-sdk/core/identity';
3
3
  import { Principal } from '@icp-sdk/core/principal';
4
4
  import type { Signer } from '@icp-sdk/signer';
5
- import { fromBase64, toBase64 } from './base64.js';
5
+ import { fromBase64, toBase64 } from '../base64.js';
6
6
 
7
7
  /**
8
8
  * The method Internet Identity answers with a session rather than a long-lived
@@ -1,6 +1,7 @@
1
1
  import type { DerEncodedPublicKey, HttpAgentRequest } from '@icp-sdk/core/agent';
2
2
  import { DelegationChain, DelegationIdentity } from '@icp-sdk/core/identity';
3
3
  import { Principal } from '@icp-sdk/core/principal';
4
+ import type { Credential, CredentialStorage } from '../credentials/credential-storage.js';
4
5
  import {
5
6
  AccountMismatchError,
6
7
  type AppDelegationSource,
@@ -9,7 +10,6 @@ import {
9
10
  SessionUnsupportedError,
10
11
  } from './app-delegation-source.js';
11
12
  import { withMintLock } from './app-lock.js';
12
- import type { Credential, CredentialStorage } from './credential-storage.js';
13
13
 
14
14
  /**
15
15
  * How much life a delegation needs left to be handed to a caller. Covers a
package/src/client/sso.ts CHANGED
@@ -1,3 +1,7 @@
1
+ import { Actor, AnonymousIdentity, HttpAgent, type HttpAgentOptions } from '@icp-sdk/core/agent';
2
+ import type { IDL } from '@icp-sdk/core/candid';
3
+ import type { Principal } from '@icp-sdk/core/principal';
4
+
1
5
  // The identity provider's cap on the domain it will fetch.
2
6
  const MAX_AUTHORITY_LENGTH = 255;
3
7
 
@@ -105,3 +109,257 @@ export function normalizeSsoDomain(domain: string): string {
105
109
  }
106
110
  return host;
107
111
  }
112
+
113
+ /**
114
+ * Whether the organization domain a client was built with can be signed in with.
115
+ *
116
+ * - `checking`: Internet Identity has not answered yet.
117
+ * - `available`: the domain resolves to a usable SSO configuration. `name` is
118
+ * the label the organization publishes, for a "Continue with Acme" button.
119
+ * - `invalid`: the value is not a domain, so no check is made and a retry
120
+ * cannot help. The user has to change what they typed. `reason` names every
121
+ * problem with it, to show as is.
122
+ * - `unavailable`: the domain publishes no usable configuration, or fetching
123
+ * it is failing. While `retryAfter` is in the future Internet Identity will
124
+ * not fetch again, so a retry before then gets the same answer; without it,
125
+ * a retry cannot help. `reason` is Internet Identity's explanation, when it
126
+ * gives one, to show as is.
127
+ */
128
+ export type SsoStatus =
129
+ | { state: 'checking' }
130
+ | { state: 'available'; name?: string }
131
+ | { state: 'invalid'; reason: string }
132
+ | { state: 'unavailable'; retryAfter?: Date; reason?: string };
133
+
134
+ type CandidSsoDomainStatus =
135
+ | { Available: { name: [] | [string] } }
136
+ | { Pending: null }
137
+ | { Unavailable: { retry_after: [] | [bigint]; reason: [] | [string] } };
138
+
139
+ /** The two Internet Identity methods an SSO domain check calls. */
140
+ export interface SsoDomainService {
141
+ app_sso_domain_check(domain: string): Promise<void>;
142
+ app_sso_domain_status(domain: string): Promise<CandidSsoDomainStatus>;
143
+ }
144
+
145
+ /**
146
+ * Written out for the same reason as the session methods in `session-minter.ts`:
147
+ * this package carries no Internet Identity declarations.
148
+ */
149
+ const idlFactory: IDL.InterfaceFactory = ({ IDL }) => {
150
+ const Timestamp = IDL.Nat64;
151
+ const Status = IDL.Variant({
152
+ Available: IDL.Record({ name: IDL.Opt(IDL.Text) }),
153
+ Pending: IDL.Null,
154
+ Unavailable: IDL.Record({ retry_after: IDL.Opt(Timestamp), reason: IDL.Opt(IDL.Text) }),
155
+ });
156
+ return IDL.Service({
157
+ app_sso_domain_check: IDL.Func([IDL.Text], [], []),
158
+ app_sso_domain_status: IDL.Func([IDL.Text], [Status], ['query']),
159
+ });
160
+ };
161
+
162
+ /**
163
+ * Builds the service an SSO domain check calls, as the anonymous caller: the
164
+ * check runs before anyone has signed in.
165
+ */
166
+ export async function createSsoDomainService(options: {
167
+ canisterId: Principal;
168
+ agentOptions?: Omit<HttpAgentOptions, 'identity'>;
169
+ }): Promise<SsoDomainService> {
170
+ const agent = await HttpAgent.create({
171
+ ...options.agentOptions,
172
+ // Last, so no agent option can make the check call as someone.
173
+ identity: new AnonymousIdentity(),
174
+ });
175
+ return Actor.createActor<SsoDomainService>(idlFactory, {
176
+ agent,
177
+ canisterId: options.canisterId,
178
+ });
179
+ }
180
+
181
+ /** The first and the longest wait between two status reads. */
182
+ export const SSO_POLL_MIN_MS = 500;
183
+ export const SSO_POLL_MAX_MS = 2_000;
184
+
185
+ /**
186
+ * How long a check may read `Pending` before it is started again. Matches the
187
+ * age at which Internet Identity treats a fetch as abandoned.
188
+ */
189
+ export const SSO_RECHECK_AFTER_MS = 120_000;
190
+
191
+ const CHECKING: SsoStatus = Object.freeze({ state: 'checking' });
192
+
193
+ const NANOS_PER_MILLI = 1_000_000n;
194
+
195
+ function fromCandid(status: CandidSsoDomainStatus): SsoStatus | undefined {
196
+ if ('Available' in status) {
197
+ const name = status.Available.name[0];
198
+ return name === undefined ? { state: 'available' } : { state: 'available', name };
199
+ }
200
+ if ('Unavailable' in status) {
201
+ const retryAfterNs = status.Unavailable.retry_after[0];
202
+ const reason = status.Unavailable.reason[0];
203
+ return {
204
+ state: 'unavailable',
205
+ ...(retryAfterNs !== undefined && {
206
+ retryAfter: new Date(Number(retryAfterNs / NANOS_PER_MILLI)),
207
+ }),
208
+ ...(reason !== undefined && { reason }),
209
+ };
210
+ }
211
+ // Pending: the fetch is still running, which is what `checking` already says.
212
+ return undefined;
213
+ }
214
+
215
+ function sameStatus(a: SsoStatus, b: SsoStatus): boolean {
216
+ switch (a.state) {
217
+ case 'checking':
218
+ return b.state === 'checking';
219
+ case 'available':
220
+ return b.state === 'available' && a.name === b.name;
221
+ case 'invalid':
222
+ return b.state === 'invalid' && a.reason === b.reason;
223
+ case 'unavailable':
224
+ return (
225
+ b.state === 'unavailable' &&
226
+ a.retryAfter?.getTime() === b.retryAfter?.getTime() &&
227
+ a.reason === b.reason
228
+ );
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Asks Internet Identity whether one SSO domain can be signed in with, and holds
234
+ * the answer.
235
+ *
236
+ * One update starts the fetch, then the status is read with a query until it is
237
+ * final: a query needs no consensus, so polling it is cheap where polling an
238
+ * update is not. A read that fails is retried at the next interval, so a check
239
+ * ends only on an answer from Internet Identity, or on {@link dispose}.
240
+ */
241
+ export class SsoStatusChecker {
242
+ readonly #domain: string | undefined;
243
+ readonly #createService: () => Promise<SsoDomainService>;
244
+ readonly #onChange: () => void;
245
+ #service: Promise<SsoDomainService> | undefined;
246
+ #status: SsoStatus;
247
+ #timer: ReturnType<typeof setTimeout> | undefined;
248
+ // Bumped by every start and by dispose, so a run that was replaced drops its
249
+ // late answers instead of overwriting a newer one.
250
+ #run = 0;
251
+ #disposed = false;
252
+
253
+ /**
254
+ * @param domain - The normalized domain, or, for a value that is not one, why
255
+ * not: `invalid` from the start and never checked.
256
+ * @param createService - Builds the service on the first call.
257
+ * @param onChange - Called after the status changes.
258
+ */
259
+ constructor(
260
+ domain: string | { invalid: string },
261
+ createService: () => Promise<SsoDomainService>,
262
+ onChange: () => void,
263
+ ) {
264
+ this.#domain = typeof domain === 'string' ? domain : undefined;
265
+ this.#createService = createService;
266
+ this.#onChange = onChange;
267
+ this.#status =
268
+ typeof domain === 'string'
269
+ ? CHECKING
270
+ : Object.freeze({ state: 'invalid', reason: domain.invalid });
271
+ if (typeof domain === 'string') this.#start(0);
272
+ }
273
+
274
+ /** The current answer. The same object until it changes. */
275
+ get status(): SsoStatus {
276
+ return this.#status;
277
+ }
278
+
279
+ /** Checks again. Does nothing for an `invalid` domain, or once disposed. */
280
+ refresh(): void {
281
+ if (this.#domain === undefined || this.#disposed) return;
282
+ this.#set(CHECKING);
283
+ this.#start(0);
284
+ }
285
+
286
+ /** Stops checking. A call already sent is not recalled; its answer is dropped. */
287
+ dispose(): void {
288
+ this.#disposed = true;
289
+ this.#run += 1;
290
+ clearTimeout(this.#timer);
291
+ this.#timer = undefined;
292
+ }
293
+
294
+ #start(delayMs: number): void {
295
+ this.#run += 1;
296
+ const run = this.#run;
297
+ clearTimeout(this.#timer);
298
+ this.#timer = setTimeout(() => {
299
+ void this.#check(run);
300
+ }, delayMs);
301
+ }
302
+
303
+ #isCurrent(run: number): boolean {
304
+ return run === this.#run && !this.#disposed;
305
+ }
306
+
307
+ async #check(run: number): Promise<void> {
308
+ const domain = this.#domain;
309
+ if (domain === undefined || !this.#isCurrent(run)) return;
310
+ const checkedAt = Date.now();
311
+ try {
312
+ const service = await this.#serviceFor();
313
+ if (!this.#isCurrent(run)) return;
314
+ await service.app_sso_domain_check(domain);
315
+ } catch {
316
+ // The reads below still see whatever Internet Identity has, and a check
317
+ // that never started is started again after `SSO_RECHECK_AFTER_MS`.
318
+ }
319
+ await this.#poll(run, domain, checkedAt, SSO_POLL_MIN_MS);
320
+ }
321
+
322
+ async #poll(run: number, domain: string, checkedAt: number, nextDelayMs: number): Promise<void> {
323
+ if (!this.#isCurrent(run)) return;
324
+ let answer: SsoStatus | undefined;
325
+ try {
326
+ const service = await this.#serviceFor();
327
+ if (!this.#isCurrent(run)) return;
328
+ answer = fromCandid(await service.app_sso_domain_status(domain));
329
+ } catch {
330
+ answer = undefined;
331
+ }
332
+ if (!this.#isCurrent(run)) return;
333
+ if (answer !== undefined) {
334
+ this.#set(answer);
335
+ return;
336
+ }
337
+ if (Date.now() - checkedAt >= SSO_RECHECK_AFTER_MS) {
338
+ this.#timer = setTimeout(() => {
339
+ void this.#check(run);
340
+ }, nextDelayMs);
341
+ return;
342
+ }
343
+ this.#timer = setTimeout(() => {
344
+ void this.#poll(run, domain, checkedAt, Math.min(nextDelayMs * 2, SSO_POLL_MAX_MS));
345
+ }, nextDelayMs);
346
+ }
347
+
348
+ #serviceFor(): Promise<SsoDomainService> {
349
+ if (this.#service === undefined) {
350
+ const created = this.#createService();
351
+ this.#service = created;
352
+ // A service that could not be built is built again on the next call.
353
+ created.catch(() => {
354
+ if (this.#service === created) this.#service = undefined;
355
+ });
356
+ }
357
+ return this.#service;
358
+ }
359
+
360
+ #set(next: SsoStatus): void {
361
+ if (sameStatus(this.#status, next)) return;
362
+ this.#status = next;
363
+ this.#onChange();
364
+ }
365
+ }
@@ -1,5 +1,6 @@
1
1
  import { Principal } from '@icp-sdk/core/principal';
2
- import { LocalStateStorage, type SessionState, type StateStorage } from './state-storage.js';
2
+ import { LocalStateStorage } from './local-state-storage.js';
3
+ import type { SessionState, StateStorage } from './state-storage.js';
3
4
 
4
5
  /**
5
6
  * How long the browser keeps the record, which is not how long the sign-in
@@ -47,6 +48,12 @@ export interface CookieStateStorageOptions {
47
48
  * removing it is what tells a sibling the sign-in is over. It carries no chain
48
49
  * and no key, so a sibling acting on it asks the identity provider to re-issue
49
50
  * rather than treating it as proof.
51
+ *
52
+ * Workers cannot read cookies, and only ever act with this origin's own
53
+ * credentials, so a worker reads this origin's claim, which the
54
+ * {@link LocalStateStorage} below mirrors to it. A sign-in this origin holds no
55
+ * credentials for reads as signed out there. A worker only reads: signing in and
56
+ * out happens in a page.
50
57
  * @see implements {@link StateStorage}
51
58
  */
52
59
  export class CookieStateStorage implements StateStorage {
@@ -70,6 +77,16 @@ export class CookieStateStorage implements StateStorage {
70
77
  // composed in on read, under the same key the cookie uses.
71
78
  readonly #local = new LocalStateStorage();
72
79
 
80
+ /** True in a worker, which reads this origin's claim and changes nothing. */
81
+ public get isReadOnly(): boolean {
82
+ return this.#local.isReadOnly;
83
+ }
84
+
85
+ /** Resolves once a worker has loaded this origin's claim. */
86
+ public ready(): Promise<void> {
87
+ return this.#local.ready();
88
+ }
89
+
73
90
  constructor(options: CookieStateStorageOptions) {
74
91
  // Both sides, because this decides whether to skip the check below and drop
75
92
  // the `Domain` attribute. Taken from the configured domain alone, a
@@ -133,6 +150,7 @@ export class CookieStateStorage implements StateStorage {
133
150
  }
134
151
 
135
152
  public get(key: string): SessionState | null {
153
+ if (this.isReadOnly) return this.#local.get(key);
136
154
  const raw = readCookie(key);
137
155
  if (raw === null) return null;
138
156
 
@@ -218,6 +236,15 @@ export class CookieStateStorage implements StateStorage {
218
236
  listeners.add(check);
219
237
  this.#subscribers.set(key, listeners);
220
238
 
239
+ // A worker hears of a change through this origin's claim.
240
+ if (this.isReadOnly) {
241
+ const unwatchClaim = this.#local.subscribe(key, check);
242
+ return () => {
243
+ listeners.delete(check);
244
+ unwatchClaim();
245
+ };
246
+ }
247
+
221
248
  const onVisible = (): void => {
222
249
  if (document.visibilityState === 'visible') check();
223
250
  };
@@ -0,0 +1,216 @@
1
+ import { Principal } from '@icp-sdk/core/principal';
2
+ import { IdbKeyVal } from '../db.js';
3
+ import type { SessionState, StateStorage } from './state-storage.js';
4
+
5
+ /** Where tabs mirror their `localStorage` records for workers, which cannot read it. */
6
+ const MIRROR_DB = { dbName: 'auth-client-state-db', storeName: 'ic-keyval' };
7
+
8
+ /** The channel a tab announces a mirrored record on, carrying only its key. */
9
+ const MIRROR_CHANNEL = 'ic-session-state';
10
+
11
+ /** What a store throws when asked to change the sign-in where it can only read it. */
12
+ export const readOnlyError = (): Error =>
13
+ new Error(
14
+ 'The sign-in state is read-only in a worker: sign in and sign out from a page of this origin.',
15
+ );
16
+
17
+ const hasLocalStorage = (): boolean => {
18
+ try {
19
+ return globalThis.localStorage !== undefined && globalThis.localStorage !== null;
20
+ } catch {
21
+ // Reading `localStorage` throws where the browser blocks storage for the page.
22
+ return false;
23
+ }
24
+ };
25
+
26
+ /**
27
+ * State in `localStorage`, so every tab of an origin agrees on it and it
28
+ * survives a reload.
29
+ *
30
+ * Workers cannot read `localStorage`, so a tab mirrors each record it writes or
31
+ * subscribes to into IndexedDB and announces it, and a worker loads the mirror
32
+ * into memory. A worker changes nothing: signing in and out happens in a page.
33
+ *
34
+ * The two fields are written as `<principal>|<expiration>` rather than JSON,
35
+ * because an expiration is a `bigint` and JSON has no way to carry one.
36
+ * @see implements {@link StateStorage}
37
+ */
38
+ export class LocalStateStorage implements StateStorage {
39
+ // Fired on a same-tab write: `storage` reaches the other tabs of an origin and
40
+ // deliberately not the one that wrote. Per key, because one store answers for
41
+ // whatever key it is handed.
42
+ #subscribers = new Map<string, Set<() => void>>();
43
+
44
+ /** True in a worker, which reads what its tabs mirror and changes nothing. */
45
+ public readonly isReadOnly = !hasLocalStorage();
46
+
47
+ // In a worker: the mirrored records, and the loads that fill them, one after
48
+ // another so a later load always lands last.
49
+ readonly #mirrored = new Map<string, string | null>();
50
+ #loads: Promise<void> = Promise.resolve();
51
+
52
+ /** Resolves once a worker has loaded the keys subscribed to so far, and every load queued meanwhile. */
53
+ public async ready(): Promise<void> {
54
+ let loads: Promise<void>;
55
+ do {
56
+ loads = this.#loads;
57
+ await loads;
58
+ } while (loads !== this.#loads);
59
+ }
60
+
61
+ public get(key: string): SessionState | null {
62
+ const raw = this.#raw(key);
63
+ if (raw === null) return null;
64
+
65
+ const [principalText, expiration] = raw.split('|');
66
+ if (principalText === undefined || expiration === undefined) return null;
67
+ try {
68
+ return {
69
+ principal: Principal.fromText(principalText),
70
+ expiration: BigInt(expiration),
71
+ // This record is written by this origin and read by no other, so having
72
+ // one and holding a credential for it are the same thing.
73
+ held: true,
74
+ };
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+
80
+ public set(key: string, state: Omit<SessionState, 'held'>): void {
81
+ if (this.isReadOnly) throw readOnlyError();
82
+ this.#localStorage().setItem(key, `${state.principal.toText()}|${state.expiration.toString()}`);
83
+ this.#fire(key);
84
+ void this.#mirror(key);
85
+ }
86
+
87
+ public remove(key: string): void {
88
+ if (this.isReadOnly) throw readOnlyError();
89
+ this.#localStorage().removeItem(key);
90
+ this.#fire(key);
91
+ void this.#mirror(key);
92
+ }
93
+
94
+ /** The same as {@link remove}: this store publishes nothing beyond the origin. */
95
+ public discard(key: string): void {
96
+ this.remove(key);
97
+ }
98
+
99
+ /**
100
+ * Fires when the state changes, here or in another tab of this origin.
101
+ *
102
+ * `localStorage` raises `storage` in every tab except the one that wrote, so
103
+ * that event carries a change between tabs and a same-tab write is announced
104
+ * directly. Either way the record is readable before it is announced, so a
105
+ * listener asking who is signed in sees what it was told about.
106
+ */
107
+ public subscribe(key: string, listener: () => void): () => void {
108
+ let last = this.#raw(key);
109
+ const check = (): void => {
110
+ const now = this.#raw(key);
111
+ if (now !== last) {
112
+ last = now;
113
+ listener();
114
+ }
115
+ };
116
+ const listeners = this.#subscribers.get(key) ?? new Set();
117
+ listeners.add(check);
118
+ this.#subscribers.set(key, listeners);
119
+
120
+ // A tab mirrors what it holds now, which also repairs a mirror an earlier
121
+ // version or a closing page left behind; a worker loads it. Afterwards each
122
+ // announcement is a write in some tab: a worker loads it, and a tab re-checks,
123
+ // because a write by another store in this tab raises no `storage` event.
124
+ if (this.isReadOnly) {
125
+ this.#load(key);
126
+ } else {
127
+ void this.#mirror(key);
128
+ }
129
+ const channel =
130
+ typeof BroadcastChannel === 'undefined' ? undefined : new BroadcastChannel(MIRROR_CHANNEL);
131
+ channel?.addEventListener('message', (event: MessageEvent<unknown>) => {
132
+ if (event.data !== key) return;
133
+ if (this.isReadOnly) {
134
+ this.#load(key);
135
+ } else {
136
+ check();
137
+ }
138
+ });
139
+
140
+ const onStorage = (event: StorageEvent): void => {
141
+ // `key` is null when a tab cleared the whole store, which changes this too.
142
+ if (event.key === key || event.key === null) check();
143
+ };
144
+ globalThis.addEventListener('storage', onStorage);
145
+
146
+ // `storage` is the only notice this store gets, and a page restored from the
147
+ // back-forward cache was not listening while it was frozen. So the record is
148
+ // re-read when the page is shown or its window regains focus, which is when
149
+ // somebody is about to act on the answer.
150
+ const onVisible = (): void => {
151
+ if (document.visibilityState === 'visible') check();
152
+ };
153
+ const hooked = typeof document !== 'undefined';
154
+ if (hooked) {
155
+ document.addEventListener('visibilitychange', onVisible);
156
+ globalThis.addEventListener('pageshow', check);
157
+ globalThis.addEventListener('focus', check);
158
+ }
159
+
160
+ return () => {
161
+ listeners.delete(check);
162
+ channel?.close();
163
+ globalThis.removeEventListener('storage', onStorage);
164
+ if (hooked) {
165
+ document.removeEventListener('visibilitychange', onVisible);
166
+ globalThis.removeEventListener('pageshow', check);
167
+ globalThis.removeEventListener('focus', check);
168
+ }
169
+ };
170
+ }
171
+
172
+ #fire(key: string): void {
173
+ for (const check of [...(this.#subscribers.get(key) ?? [])]) check();
174
+ }
175
+
176
+ #raw(key: string): string | null {
177
+ if (this.isReadOnly) return this.#mirrored.get(key) ?? null;
178
+ return this.#localStorage().getItem(key);
179
+ }
180
+
181
+ /** Writes what `localStorage` holds under `key` to the mirror, and announces it. */
182
+ async #mirror(key: string): Promise<void> {
183
+ try {
184
+ const db = await IdbKeyVal.create(MIRROR_DB);
185
+ // Read after the await and right before the write: IndexedDB applies writes
186
+ // in the order they are made, so the last to land holds what is current.
187
+ await db.set(key, { raw: this.#raw(key) });
188
+ const channel = new BroadcastChannel(MIRROR_CHANNEL);
189
+ channel.postMessage(key);
190
+ channel.close();
191
+ } catch {
192
+ // No IndexedDB or no channel here: workers keep what they have until the
193
+ // next write reaches them.
194
+ }
195
+ }
196
+
197
+ #load(key: string): void {
198
+ this.#loads = this.#loads.then(async () => {
199
+ try {
200
+ const db = await IdbKeyVal.create(MIRROR_DB);
201
+ this.#mirrored.set(key, (await db.get<{ raw: string | null }>(key))?.raw ?? null);
202
+ } catch {
203
+ // No IndexedDB here: the worker reads as signed out.
204
+ }
205
+ this.#fire(key);
206
+ });
207
+ }
208
+
209
+ #localStorage(): Storage {
210
+ const ls = globalThis.localStorage;
211
+ if (!ls) {
212
+ throw new Error('Could not find local storage.');
213
+ }
214
+ return ls;
215
+ }
216
+ }