@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
@@ -1,257 +0,0 @@
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
-
5
- /**
6
- * Whether the organization domain a client was built with can be signed in with.
7
- *
8
- * - `checking`: Internet Identity has not answered yet.
9
- * - `available`: the domain resolves to a usable SSO configuration. `name` is
10
- * the label the organization publishes, for a "Continue with Acme" button.
11
- * - `invalid`: the value is not a domain, so no check is made and a retry
12
- * cannot help. The user has to change what they typed. `reason` names every
13
- * problem with it, to show as is.
14
- * - `unavailable`: the domain publishes no usable configuration, or fetching
15
- * it is failing. While `retryAfter` is in the future Internet Identity will
16
- * not fetch again, so a retry before then gets the same answer; without it,
17
- * a retry cannot help. `reason` is Internet Identity's explanation, when it
18
- * gives one, to show as is.
19
- */
20
- export type SsoStatus =
21
- | { state: 'checking' }
22
- | { state: 'available'; name?: string }
23
- | { state: 'invalid'; reason: string }
24
- | { state: 'unavailable'; retryAfter?: Date; reason?: string };
25
-
26
- type CandidSsoDomainStatus =
27
- | { Available: { name: [] | [string] } }
28
- | { Pending: null }
29
- | { Unavailable: { retry_after: [] | [bigint]; reason: [] | [string] } };
30
-
31
- /** The two Internet Identity methods an SSO domain check calls. */
32
- export interface SsoDomainService {
33
- app_sso_domain_check(domain: string): Promise<void>;
34
- app_sso_domain_status(domain: string): Promise<CandidSsoDomainStatus>;
35
- }
36
-
37
- /**
38
- * Written out for the same reason as the session methods in `session-minter.ts`:
39
- * this package carries no Internet Identity declarations.
40
- */
41
- const idlFactory: IDL.InterfaceFactory = ({ IDL }) => {
42
- const Timestamp = IDL.Nat64;
43
- const Status = IDL.Variant({
44
- Available: IDL.Record({ name: IDL.Opt(IDL.Text) }),
45
- Pending: IDL.Null,
46
- Unavailable: IDL.Record({ retry_after: IDL.Opt(Timestamp), reason: IDL.Opt(IDL.Text) }),
47
- });
48
- return IDL.Service({
49
- app_sso_domain_check: IDL.Func([IDL.Text], [], []),
50
- app_sso_domain_status: IDL.Func([IDL.Text], [Status], ['query']),
51
- });
52
- };
53
-
54
- /**
55
- * Builds the service an SSO domain check calls, as the anonymous caller: the
56
- * check runs before anyone has signed in.
57
- */
58
- export async function createSsoDomainService(options: {
59
- canisterId: Principal;
60
- agentOptions?: Omit<HttpAgentOptions, 'identity'>;
61
- }): Promise<SsoDomainService> {
62
- const agent = await HttpAgent.create({
63
- ...options.agentOptions,
64
- // Last, so no agent option can make the check call as someone.
65
- identity: new AnonymousIdentity(),
66
- });
67
- return Actor.createActor<SsoDomainService>(idlFactory, {
68
- agent,
69
- canisterId: options.canisterId,
70
- });
71
- }
72
-
73
- /** The first and the longest wait between two status reads. */
74
- export const SSO_POLL_MIN_MS = 500;
75
- export const SSO_POLL_MAX_MS = 2_000;
76
-
77
- /**
78
- * How long a check may read `Pending` before it is started again. Matches the
79
- * age at which Internet Identity treats a fetch as abandoned.
80
- */
81
- export const SSO_RECHECK_AFTER_MS = 120_000;
82
-
83
- const CHECKING: SsoStatus = Object.freeze({ state: 'checking' });
84
-
85
- const NANOS_PER_MILLI = 1_000_000n;
86
-
87
- function fromCandid(status: CandidSsoDomainStatus): SsoStatus | undefined {
88
- if ('Available' in status) {
89
- const name = status.Available.name[0];
90
- return name === undefined ? { state: 'available' } : { state: 'available', name };
91
- }
92
- if ('Unavailable' in status) {
93
- const retryAfterNs = status.Unavailable.retry_after[0];
94
- const reason = status.Unavailable.reason[0];
95
- return {
96
- state: 'unavailable',
97
- ...(retryAfterNs !== undefined && {
98
- retryAfter: new Date(Number(retryAfterNs / NANOS_PER_MILLI)),
99
- }),
100
- ...(reason !== undefined && { reason }),
101
- };
102
- }
103
- // Pending: the fetch is still running, which is what `checking` already says.
104
- return undefined;
105
- }
106
-
107
- function sameStatus(a: SsoStatus, b: SsoStatus): boolean {
108
- switch (a.state) {
109
- case 'checking':
110
- return b.state === 'checking';
111
- case 'available':
112
- return b.state === 'available' && a.name === b.name;
113
- case 'invalid':
114
- return b.state === 'invalid' && a.reason === b.reason;
115
- case 'unavailable':
116
- return (
117
- b.state === 'unavailable' &&
118
- a.retryAfter?.getTime() === b.retryAfter?.getTime() &&
119
- a.reason === b.reason
120
- );
121
- }
122
- }
123
-
124
- /**
125
- * Asks Internet Identity whether one SSO domain can be signed in with, and holds
126
- * the answer.
127
- *
128
- * One update starts the fetch, then the status is read with a query until it is
129
- * final: a query needs no consensus, so polling it is cheap where polling an
130
- * update is not. A read that fails is retried at the next interval, so a check
131
- * ends only on an answer from Internet Identity, or on {@link dispose}.
132
- */
133
- export class SsoStatusChecker {
134
- readonly #domain: string | undefined;
135
- readonly #createService: () => Promise<SsoDomainService>;
136
- readonly #onChange: () => void;
137
- #service: Promise<SsoDomainService> | undefined;
138
- #status: SsoStatus;
139
- #timer: ReturnType<typeof setTimeout> | undefined;
140
- // Bumped by every start and by dispose, so a run that was replaced drops its
141
- // late answers instead of overwriting a newer one.
142
- #run = 0;
143
- #disposed = false;
144
-
145
- /**
146
- * @param domain - The normalized domain, or, for a value that is not one, why
147
- * not: `invalid` from the start and never checked.
148
- * @param createService - Builds the service on the first call.
149
- * @param onChange - Called after the status changes.
150
- */
151
- constructor(
152
- domain: string | { invalid: string },
153
- createService: () => Promise<SsoDomainService>,
154
- onChange: () => void,
155
- ) {
156
- this.#domain = typeof domain === 'string' ? domain : undefined;
157
- this.#createService = createService;
158
- this.#onChange = onChange;
159
- this.#status =
160
- typeof domain === 'string'
161
- ? CHECKING
162
- : Object.freeze({ state: 'invalid', reason: domain.invalid });
163
- if (typeof domain === 'string') this.#start(0);
164
- }
165
-
166
- /** The current answer. The same object until it changes. */
167
- get status(): SsoStatus {
168
- return this.#status;
169
- }
170
-
171
- /** Checks again. Does nothing for an `invalid` domain, or once disposed. */
172
- refresh(): void {
173
- if (this.#domain === undefined || this.#disposed) return;
174
- this.#set(CHECKING);
175
- this.#start(0);
176
- }
177
-
178
- /** Stops checking. A call already sent is not recalled; its answer is dropped. */
179
- dispose(): void {
180
- this.#disposed = true;
181
- this.#run += 1;
182
- clearTimeout(this.#timer);
183
- this.#timer = undefined;
184
- }
185
-
186
- #start(delayMs: number): void {
187
- this.#run += 1;
188
- const run = this.#run;
189
- clearTimeout(this.#timer);
190
- this.#timer = setTimeout(() => {
191
- void this.#check(run);
192
- }, delayMs);
193
- }
194
-
195
- #isCurrent(run: number): boolean {
196
- return run === this.#run && !this.#disposed;
197
- }
198
-
199
- async #check(run: number): Promise<void> {
200
- const domain = this.#domain;
201
- if (domain === undefined || !this.#isCurrent(run)) return;
202
- const checkedAt = Date.now();
203
- try {
204
- const service = await this.#serviceFor();
205
- if (!this.#isCurrent(run)) return;
206
- await service.app_sso_domain_check(domain);
207
- } catch {
208
- // The reads below still see whatever Internet Identity has, and a check
209
- // that never started is started again after `SSO_RECHECK_AFTER_MS`.
210
- }
211
- await this.#poll(run, domain, checkedAt, SSO_POLL_MIN_MS);
212
- }
213
-
214
- async #poll(run: number, domain: string, checkedAt: number, nextDelayMs: number): Promise<void> {
215
- if (!this.#isCurrent(run)) return;
216
- let answer: SsoStatus | undefined;
217
- try {
218
- const service = await this.#serviceFor();
219
- if (!this.#isCurrent(run)) return;
220
- answer = fromCandid(await service.app_sso_domain_status(domain));
221
- } catch {
222
- answer = undefined;
223
- }
224
- if (!this.#isCurrent(run)) return;
225
- if (answer !== undefined) {
226
- this.#set(answer);
227
- return;
228
- }
229
- if (Date.now() - checkedAt >= SSO_RECHECK_AFTER_MS) {
230
- this.#timer = setTimeout(() => {
231
- void this.#check(run);
232
- }, nextDelayMs);
233
- return;
234
- }
235
- this.#timer = setTimeout(() => {
236
- void this.#poll(run, domain, checkedAt, Math.min(nextDelayMs * 2, SSO_POLL_MAX_MS));
237
- }, nextDelayMs);
238
- }
239
-
240
- #serviceFor(): Promise<SsoDomainService> {
241
- if (this.#service === undefined) {
242
- const created = this.#createService();
243
- this.#service = created;
244
- // A service that could not be built is built again on the next call.
245
- created.catch(() => {
246
- if (this.#service === created) this.#service = undefined;
247
- });
248
- }
249
- return this.#service;
250
- }
251
-
252
- #set(next: SsoStatus): void {
253
- if (sameStatus(this.#status, next)) return;
254
- this.#status = next;
255
- this.#onChange();
256
- }
257
- }
@@ -1,284 +0,0 @@
1
- import { Principal } from '@icp-sdk/core/principal';
2
-
3
- /**
4
- * What a client knows about its sign-in without holding a credential: which
5
- * account is signed in here, and when that ends.
6
- *
7
- * Both fields are public. The principal is what an application's canisters see
8
- * as the caller, and the expiration is what the identity provider granted, so
9
- * neither is a secret and both can live somewhere a page reads synchronously.
10
- */
11
- export interface SessionState {
12
- principal: Principal;
13
-
14
- /** Nanoseconds since the epoch, matching `Delegation.expiration`. */
15
- expiration: bigint;
16
-
17
- /**
18
- * Whether this origin holds a credential for that account, or only knows the
19
- * sign-in exists.
20
- *
21
- * Derived on read and never published: where the record reaches further than
22
- * one origin, the record itself cannot carry a per-origin fact. A sibling
23
- * subdomain that has not acquired its own credential reads the sign-in with
24
- * `held: false`, which is what tells it to acquire one.
25
- */
26
- held: boolean;
27
- }
28
-
29
- /**
30
- * Holds the state of a sign-in.
31
- *
32
- * This is what decides whether this origin is signed in and as whom. It is a
33
- * store of its own because it has to be readable without awaiting, which a
34
- * credential store does not.
35
- *
36
- * A record can be stale — a session revoked at the canister still reads as
37
- * signed in until something calls and is refused — so it is the state as this
38
- * browser knows it rather than an authority against the network.
39
- */
40
- export interface StateStorage {
41
- /** The state, or `null` where nothing is signed in within this store's reach. */
42
- get(key: string): SessionState | null;
43
-
44
- set(key: string, state: Omit<SessionState, 'held'>): void;
45
-
46
- /**
47
- * Removes the state, and anything this store publishes beyond this origin.
48
- *
49
- * What signing out does: the user ended the sign-in, so a sibling reading a
50
- * shared record must stop seeing one.
51
- */
52
- remove(key: string): void;
53
-
54
- /**
55
- * Removes what this origin holds, leaving anything shared alone.
56
- *
57
- * What finding out does, which is a different act. An origin whose chain turns
58
- * out to be dead cannot tell whether the session was revoked or replaced by a
59
- * sibling signing in — and in the second case the shared record was written by
60
- * that sibling a moment ago, so retracting it would tell it that the session it
61
- * just obtained is gone.
62
- *
63
- * A store that publishes nothing beyond this origin answers it with
64
- * {@link remove}, which is one line and the right answer.
65
- */
66
- discard(key: string): void;
67
-
68
- /**
69
- * Whether a sign-in kept in this store may be resumed without a ceremony.
70
- *
71
- * True only where the record reaches past this origin, because that is the
72
- * case a silent re-issue exists for: a sibling reads the sign-in, holds no
73
- * credential of its own, and needs the identity provider to remember the
74
- * session it can extend. A store the origin keeps to itself has nothing to
75
- * gain and would only be asking the provider to persist a sign-in on a device
76
- * where nothing wanted one kept.
77
- *
78
- * Absent means false, which is the answer for a store that never considered
79
- * the question.
80
- */
81
- readonly resumable?: boolean;
82
-
83
- /**
84
- * Registers a listener fired when the state under `key` changes, including
85
- * when something other than this client changed it. Returns a function that
86
- * unregisters it.
87
- *
88
- * Required rather than optional: two clients can share one store, even a
89
- * store with no medium behind it, and a client that cannot be told the record
90
- * changed under it goes on answering for a sign-in that is no longer there.
91
- */
92
- subscribe(key: string, listener: () => void): () => void;
93
- }
94
-
95
- /**
96
- * State held for the lifetime of the instance and shared with nothing.
97
- *
98
- * For tests and for environments with no `localStorage`, where a client is
99
- * alone and a reload starts from nothing.
100
- * @see implements {@link StateStorage}
101
- */
102
- export class MemoryStateStorage implements StateStorage {
103
- #state = new Map<string, Omit<SessionState, 'held'>>();
104
- #subscribers = new Map<string, Set<() => void>>();
105
-
106
- public get(key: string): SessionState | null {
107
- // Nothing reaches past this instance, so a record here is always one it holds.
108
- const state = this.#state.get(key);
109
- return state === undefined ? null : { ...state, held: true };
110
- }
111
-
112
- public set(key: string, state: Omit<SessionState, 'held'>): void {
113
- this.#state.set(key, state);
114
- this.#fire(key);
115
- }
116
-
117
- public remove(key: string): void {
118
- this.#state.delete(key);
119
- this.#fire(key);
120
- }
121
-
122
- /** The same as {@link remove}: this store publishes nothing at all. */
123
- public discard(key: string): void {
124
- this.remove(key);
125
- }
126
-
127
- /**
128
- * Fires when the state changes, which here means when something writes to
129
- * this instance.
130
- *
131
- * Nothing outside the process can reach a `Map`, so a medium is not what makes
132
- * this worth having: two clients can be handed the same instance, and this is
133
- * how the one that did not write finds out. Each listener is told only when the
134
- * record actually changed since it was last told, so a client's own writes do
135
- * not come back to it as news.
136
- */
137
- public subscribe(key: string, listener: () => void): () => void {
138
- let last = this.#raw(key);
139
- const check = (): void => {
140
- const now = this.#raw(key);
141
- if (now !== last) {
142
- last = now;
143
- listener();
144
- }
145
- };
146
- const listeners = this.#subscribers.get(key) ?? new Set();
147
- listeners.add(check);
148
- this.#subscribers.set(key, listeners);
149
-
150
- return () => {
151
- listeners.delete(check);
152
- };
153
- }
154
-
155
- #fire(key: string): void {
156
- for (const check of [...(this.#subscribers.get(key) ?? [])]) check();
157
- }
158
-
159
- // The same shape `LocalStateStorage` keeps, so "changed" means the same thing
160
- // in both: a record is one string, and comparing strings needs no field walk.
161
- #raw(key: string): string | null {
162
- const state = this.#state.get(key);
163
- return state === undefined
164
- ? null
165
- : `${state.principal.toText()}|${state.expiration.toString()}`;
166
- }
167
- }
168
-
169
- /**
170
- * State in `localStorage`, so every tab of an origin agrees on it and it
171
- * survives a reload.
172
- *
173
- * The two fields are written as `<principal>|<expiration>` rather than JSON,
174
- * because an expiration is a `bigint` and JSON has no way to carry one.
175
- * @see implements {@link StateStorage}
176
- */
177
- export class LocalStateStorage implements StateStorage {
178
- // Fired on a same-tab write: `storage` reaches the other tabs of an origin and
179
- // deliberately not the one that wrote. Per key, because one store answers for
180
- // whatever key it is handed.
181
- #subscribers = new Map<string, Set<() => void>>();
182
-
183
- public get(key: string): SessionState | null {
184
- const raw = this.#localStorage().getItem(key);
185
- if (raw === null) return null;
186
-
187
- const [principalText, expiration] = raw.split('|');
188
- if (principalText === undefined || expiration === undefined) return null;
189
- try {
190
- return {
191
- principal: Principal.fromText(principalText),
192
- expiration: BigInt(expiration),
193
- // This record is written by this origin and read by no other, so having
194
- // one and holding a credential for it are the same thing.
195
- held: true,
196
- };
197
- } catch {
198
- return null;
199
- }
200
- }
201
-
202
- public set(key: string, state: Omit<SessionState, 'held'>): void {
203
- this.#localStorage().setItem(key, `${state.principal.toText()}|${state.expiration.toString()}`);
204
- this.#fire(key);
205
- }
206
-
207
- public remove(key: string): void {
208
- this.#localStorage().removeItem(key);
209
- this.#fire(key);
210
- }
211
-
212
- /** The same as {@link remove}: this store publishes nothing beyond the origin. */
213
- public discard(key: string): void {
214
- this.remove(key);
215
- }
216
-
217
- /**
218
- * Fires when the state changes, here or in another tab of this origin.
219
- *
220
- * `localStorage` raises `storage` in every tab except the one that wrote, so
221
- * that event carries a change between tabs and a same-tab write is announced
222
- * directly. Either way the record is readable before it is announced, so a
223
- * listener asking who is signed in sees what it was told about.
224
- */
225
- public subscribe(key: string, listener: () => void): () => void {
226
- let last = this.#raw(key);
227
- const check = (): void => {
228
- const now = this.#raw(key);
229
- if (now !== last) {
230
- last = now;
231
- listener();
232
- }
233
- };
234
- const listeners = this.#subscribers.get(key) ?? new Set();
235
- listeners.add(check);
236
- this.#subscribers.set(key, listeners);
237
-
238
- const onStorage = (event: StorageEvent): void => {
239
- // `key` is null when a tab cleared the whole store, which changes this too.
240
- if (event.key === key || event.key === null) check();
241
- };
242
- globalThis.addEventListener('storage', onStorage);
243
-
244
- // `storage` is the only notice this store gets, and a page restored from the
245
- // back-forward cache was not listening while it was frozen. So the record is
246
- // re-read when the page is shown or its window regains focus, which is when
247
- // somebody is about to act on the answer.
248
- const onVisible = (): void => {
249
- if (document.visibilityState === 'visible') check();
250
- };
251
- const hooked = typeof document !== 'undefined';
252
- if (hooked) {
253
- document.addEventListener('visibilitychange', onVisible);
254
- globalThis.addEventListener('pageshow', check);
255
- globalThis.addEventListener('focus', check);
256
- }
257
-
258
- return () => {
259
- listeners.delete(check);
260
- globalThis.removeEventListener('storage', onStorage);
261
- if (hooked) {
262
- document.removeEventListener('visibilitychange', onVisible);
263
- globalThis.removeEventListener('pageshow', check);
264
- globalThis.removeEventListener('focus', check);
265
- }
266
- };
267
- }
268
-
269
- #fire(key: string): void {
270
- for (const check of [...(this.#subscribers.get(key) ?? [])]) check();
271
- }
272
-
273
- #raw(key: string): string | null {
274
- return this.#localStorage().getItem(key);
275
- }
276
-
277
- #localStorage(): Storage {
278
- const ls = globalThis.localStorage;
279
- if (!ls) {
280
- throw new Error('Could not find local storage.');
281
- }
282
- return ls;
283
- }
284
- }
File without changes