@icp-sdk/auth 11.0.0 → 11.2.0

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 (90) hide show
  1. package/dist/esm/client/auth-client.d.ts +73 -17
  2. package/dist/esm/client/auth-client.js +155 -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 +15 -12
  12. package/dist/esm/client/index.js +12 -10
  13. package/dist/esm/client/index.js.map +1 -1
  14. package/dist/esm/client/notification-consent.d.ts +102 -0
  15. package/dist/esm/client/notification-consent.js +143 -0
  16. package/dist/esm/client/notification-consent.js.map +1 -0
  17. package/dist/esm/client/session/app-delegation-source.js.map +1 -0
  18. package/dist/esm/client/session/app-lock.js.map +1 -0
  19. package/dist/esm/client/{session-delegation.js → session/session-delegation.js} +1 -1
  20. package/dist/esm/client/session/session-delegation.js.map +1 -0
  21. package/dist/esm/client/{session-identity.d.ts → session/session-identity.d.ts} +1 -1
  22. package/dist/esm/client/session/session-identity.js.map +1 -0
  23. package/dist/esm/client/session/session-minter.js.map +1 -0
  24. package/dist/esm/client/sso.d.ts +91 -0
  25. package/dist/esm/client/sso.js +206 -0
  26. package/dist/esm/client/sso.js.map +1 -1
  27. package/dist/esm/client/{cookie-state-storage.d.ts → state/cookie-state-storage.d.ts} +11 -1
  28. package/dist/esm/client/{cookie-state-storage.js → state/cookie-state-storage.js} +25 -1
  29. package/dist/esm/client/state/cookie-state-storage.js.map +1 -0
  30. package/dist/esm/client/state/local-state-storage.d.ts +36 -0
  31. package/dist/esm/client/{state-storage.js → state/local-state-storage.js} +92 -66
  32. package/dist/esm/client/state/local-state-storage.js.map +1 -0
  33. package/dist/esm/client/state/memory-state-storage.d.ts +27 -0
  34. package/dist/esm/client/state/memory-state-storage.js +67 -0
  35. package/dist/esm/client/state/memory-state-storage.js.map +1 -0
  36. package/dist/esm/client/{state-storage.d.ts → state/state-storage.d.ts} +12 -46
  37. package/dist/esm/client/state/state-storage.js +2 -0
  38. package/dist/esm/client/state/state-storage.js.map +1 -0
  39. package/package.json +9 -9
  40. package/src/client/auth-client.ts +174 -13
  41. package/src/client/{idb-credential-storage.ts → credentials/idb-credential-storage.ts} +1 -1
  42. package/src/client/index.ts +28 -20
  43. package/src/client/notification-consent.ts +214 -0
  44. package/src/client/{session-delegation.ts → session/session-delegation.ts} +1 -1
  45. package/src/client/{session-identity.ts → session/session-identity.ts} +1 -1
  46. package/src/client/sso.ts +258 -0
  47. package/src/client/{cookie-state-storage.ts → state/cookie-state-storage.ts} +28 -1
  48. package/src/client/state/local-state-storage.ts +216 -0
  49. package/src/client/state/memory-state-storage.ts +75 -0
  50. package/src/client/state/state-storage.ts +112 -0
  51. package/dist/esm/client/app-delegation-source.js.map +0 -1
  52. package/dist/esm/client/app-lock.js.map +0 -1
  53. package/dist/esm/client/cookie-state-storage.js.map +0 -1
  54. package/dist/esm/client/credential-storage.js.map +0 -1
  55. package/dist/esm/client/idb-credential-storage.js.map +0 -1
  56. package/dist/esm/client/local-credential-storage.js.map +0 -1
  57. package/dist/esm/client/memory-credential-storage.js.map +0 -1
  58. package/dist/esm/client/session-delegation.js.map +0 -1
  59. package/dist/esm/client/session-identity.js.map +0 -1
  60. package/dist/esm/client/session-minter.js.map +0 -1
  61. package/dist/esm/client/shared-memory-credential-storage.js.map +0 -1
  62. package/dist/esm/client/sso-status.d.ts +0 -91
  63. package/dist/esm/client/sso-status.js +0 -207
  64. package/dist/esm/client/sso-status.js.map +0 -1
  65. package/dist/esm/client/state-storage.js.map +0 -1
  66. package/src/client/sso-status.ts +0 -257
  67. package/src/client/state-storage.ts +0 -284
  68. /package/dist/esm/client/{credential-storage.d.ts → credentials/credential-storage.d.ts} +0 -0
  69. /package/dist/esm/client/{credential-storage.js → credentials/credential-storage.js} +0 -0
  70. /package/dist/esm/client/{local-credential-storage.d.ts → credentials/local-credential-storage.d.ts} +0 -0
  71. /package/dist/esm/client/{local-credential-storage.js → credentials/local-credential-storage.js} +0 -0
  72. /package/dist/esm/client/{memory-credential-storage.d.ts → credentials/memory-credential-storage.d.ts} +0 -0
  73. /package/dist/esm/client/{memory-credential-storage.js → credentials/memory-credential-storage.js} +0 -0
  74. /package/dist/esm/client/{shared-memory-credential-storage.d.ts → credentials/shared-memory-credential-storage.d.ts} +0 -0
  75. /package/dist/esm/client/{shared-memory-credential-storage.js → credentials/shared-memory-credential-storage.js} +0 -0
  76. /package/dist/esm/client/{app-delegation-source.d.ts → session/app-delegation-source.d.ts} +0 -0
  77. /package/dist/esm/client/{app-delegation-source.js → session/app-delegation-source.js} +0 -0
  78. /package/dist/esm/client/{app-lock.d.ts → session/app-lock.d.ts} +0 -0
  79. /package/dist/esm/client/{app-lock.js → session/app-lock.js} +0 -0
  80. /package/dist/esm/client/{session-delegation.d.ts → session/session-delegation.d.ts} +0 -0
  81. /package/dist/esm/client/{session-identity.js → session/session-identity.js} +0 -0
  82. /package/dist/esm/client/{session-minter.d.ts → session/session-minter.d.ts} +0 -0
  83. /package/dist/esm/client/{session-minter.js → session/session-minter.js} +0 -0
  84. /package/src/client/{credential-storage.ts → credentials/credential-storage.ts} +0 -0
  85. /package/src/client/{local-credential-storage.ts → credentials/local-credential-storage.ts} +0 -0
  86. /package/src/client/{memory-credential-storage.ts → credentials/memory-credential-storage.ts} +0 -0
  87. /package/src/client/{shared-memory-credential-storage.ts → credentials/shared-memory-credential-storage.ts} +0 -0
  88. /package/src/client/{app-delegation-source.ts → session/app-delegation-source.ts} +0 -0
  89. /package/src/client/{app-lock.ts → session/app-lock.ts} +0 -0
  90. /package/src/client/{session-minter.ts → session/session-minter.ts} +0 -0
@@ -0,0 +1,214 @@
1
+ import { Actor, HttpAgent, type HttpAgentOptions, type SignIdentity } from '@icp-sdk/core/agent';
2
+ import type { IDL } from '@icp-sdk/core/candid';
3
+ import { type DelegationChain, DelegationIdentity } from '@icp-sdk/core/identity';
4
+ import type { Principal } from '@icp-sdk/core/principal';
5
+ import type { Signer } from '@icp-sdk/signer';
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
+
10
+ /**
11
+ * The method Internet Identity answers with the user's decision about being
12
+ * notified. Named for its provider because a JSON-RPC method travels over a
13
+ * transport shared with other signers, unlike a canister method.
14
+ */
15
+ const NOTIFICATION_CONSENT_METHOD = 'ii_notification_consent';
16
+
17
+ /** The code Internet Identity denies a `prompt: 'none'` request with. */
18
+ const INTERACTION_REQUIRED_CODE = 3002;
19
+
20
+ /** JSON-RPC's own code for a method the receiver does not implement. */
21
+ const METHOD_NOT_FOUND_CODE = -32601;
22
+
23
+ /**
24
+ * Whether the user has allowed this application to notify them.
25
+ *
26
+ * A record rather than a bare boolean, mirroring what the canister answers: a
27
+ * second fact about the decision can then be reported without a breaking change
28
+ * to anything that already reads `granted`.
29
+ */
30
+ export interface NotificationConsentStatus {
31
+ granted: boolean;
32
+ }
33
+
34
+ /**
35
+ * Thrown where the identity provider does not send notifications at all.
36
+ *
37
+ * Its own error because its remedy is its own: there is nothing to retry and no
38
+ * ceremony to run, so an application hides the control rather than reporting a
39
+ * failure to the user. A deployment either carries the feature or does not.
40
+ */
41
+ export class NotificationsUnsupportedError extends Error {
42
+ constructor(message = 'This Internet Identity does not send notifications') {
43
+ super(message);
44
+ this.name = 'NotificationsUnsupportedError';
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Asks the user, through the identity provider, whether this application may
50
+ * notify them, and registers the browser for delivery where they agree.
51
+ *
52
+ * A refusal is an answer: it comes back as `granted: false` rather than as an
53
+ * error, because the user decided and the application has something to render.
54
+ *
55
+ * @param signer - The channel to the identity provider.
56
+ * @param derivationOrigin - The origin the account is derived for, where the
57
+ * application signs in under one other than its own.
58
+ * @returns What the provider recorded, read back rather than reported from the
59
+ * screen.
60
+ * @throws {InteractionRequiredError} Where the request asked not to render.
61
+ * @throws {NotificationsUnsupportedError} Where the provider does not notify.
62
+ */
63
+ export async function requestNotificationConsent(
64
+ signer: Signer,
65
+ derivationOrigin?: string,
66
+ ): Promise<NotificationConsentStatus> {
67
+ const response = await signer.sendRequest({
68
+ jsonrpc: '2.0' as const,
69
+ id: globalThis.crypto.randomUUID(),
70
+ method: NOTIFICATION_CONSENT_METHOD,
71
+ // Every member is optional, so an application with nothing to pass sends an
72
+ // empty object rather than no `params` at all.
73
+ params: derivationOrigin === undefined ? {} : { icrc95DerivationOrigin: derivationOrigin },
74
+ });
75
+
76
+ if ('error' in response) {
77
+ if (response.error.code === METHOD_NOT_FOUND_CODE) {
78
+ throw new NotificationsUnsupportedError(response.error.message);
79
+ }
80
+ if (response.error.code === INTERACTION_REQUIRED_CODE) {
81
+ throw new InteractionRequiredError(response.error.message);
82
+ }
83
+ throw new Error(response.error.message);
84
+ }
85
+
86
+ const result = response.result as Record<string, unknown> | undefined;
87
+ if (typeof result?.granted !== 'boolean') {
88
+ throw new Error('Invalid response: missing granted');
89
+ }
90
+ return { granted: result.granted };
91
+ }
92
+
93
+ /** What the canister answers either consent call with. */
94
+ type NotificationConsentError = { NoSuchSession: null } | { InternalCanisterError: string };
95
+ type Result<T> = { Ok: T } | { Err: NotificationConsentError };
96
+
97
+ /** The two Internet Identity methods an application makes about its own consent. */
98
+ export interface NotificationConsentService {
99
+ app_notification_consent_status(): Promise<Result<{ is_granted: boolean }>>;
100
+ app_revoke_notification_consent(): Promise<Result<null>>;
101
+ }
102
+
103
+ /**
104
+ * Written out for the same reason as the session methods in `session-minter.ts`:
105
+ * this package carries no Internet Identity declarations.
106
+ */
107
+ const idlFactory: IDL.InterfaceFactory = ({ IDL }) => {
108
+ const ConsentError = IDL.Variant({
109
+ NoSuchSession: IDL.Null,
110
+ InternalCanisterError: IDL.Text,
111
+ });
112
+ const Status = IDL.Record({ is_granted: IDL.Bool });
113
+ return IDL.Service({
114
+ app_notification_consent_status: IDL.Func(
115
+ [],
116
+ [IDL.Variant({ Ok: Status, Err: ConsentError })],
117
+ ['query'],
118
+ ),
119
+ app_revoke_notification_consent: IDL.Func(
120
+ [],
121
+ [IDL.Variant({ Ok: IDL.Null, Err: ConsentError })],
122
+ [],
123
+ ),
124
+ });
125
+ };
126
+
127
+ /**
128
+ * Unwraps a canister result, turning the one terminal error into
129
+ * {@link SessionGoneError} and the other into a plain failure.
130
+ */
131
+ const unwrap = <T>(result: Result<T>, failed: string): T => {
132
+ if ('Ok' in result) return result.Ok;
133
+ if ('NoSuchSession' in result.Err) throw new SessionGoneError();
134
+ // A candid variant, so interpolating it directly renders "[object Object]" and
135
+ // throws away the canister's own explanation of what went wrong.
136
+ const detail = result.Err.InternalCanisterError;
137
+ throw new Error(`${failed}${detail === '' ? '' : `: ${detail}`}`);
138
+ };
139
+
140
+ export interface NotificationConsentOptions {
141
+ /** The key the session chain delegates to. Signs the calls made here. */
142
+ sessionKey: SignIdentity;
143
+
144
+ /** The chain proving those calls come from the session. Restricted to II. */
145
+ sessionChain: DelegationChain;
146
+
147
+ /** The canister these calls go to. */
148
+ canisterId: Principal;
149
+
150
+ /**
151
+ * Options for the agent making them. `identity` is not among them: the agent
152
+ * signs as the session, which is what both calls are authorised by.
153
+ */
154
+ agentOptions?: Omit<HttpAgentOptions, 'identity'>;
155
+ }
156
+
157
+ /** Reads and withdraws an application's consent, at the Internet Identity canister. */
158
+ export class NotificationConsent {
159
+ readonly #service: NotificationConsentService;
160
+
161
+ private constructor(service: NotificationConsentService) {
162
+ this.#service = service;
163
+ }
164
+
165
+ /**
166
+ * Builds the calls as the session.
167
+ *
168
+ * As the session and not as the application: Internet Identity authorises both
169
+ * methods by the principal the session signs with, which is the one that mints
170
+ * app delegations rather than any of the ones minted from it.
171
+ */
172
+ static async create(options: NotificationConsentOptions): Promise<NotificationConsent> {
173
+ const { canisterId } = options;
174
+ assertChainReaches(options.sessionChain, canisterId);
175
+ const agent = await HttpAgent.create({
176
+ ...options.agentOptions,
177
+ // Last, so no agent option can replace the session these calls are made as.
178
+ identity: DelegationIdentity.fromDelegation(options.sessionKey, options.sessionChain),
179
+ });
180
+ return new NotificationConsent(
181
+ Actor.createActor<NotificationConsentService>(idlFactory, { agent, canisterId }),
182
+ );
183
+ }
184
+
185
+ /**
186
+ * Whether this application may notify the signed-in user.
187
+ *
188
+ * A query, so the answer is uncertified: it is what a control is painted from,
189
+ * not something to rest a decision on.
190
+ */
191
+ async status(): Promise<NotificationConsentStatus> {
192
+ const status = unwrap(
193
+ await this.#service.app_notification_consent_status(),
194
+ 'Internet Identity could not report this notification consent',
195
+ );
196
+ return { granted: status.is_granted };
197
+ }
198
+
199
+ /**
200
+ * Withdraws this application's consent to notify the signed-in user.
201
+ *
202
+ * Idempotent at the canister: consent that is already withdrawn is `Ok`, because
203
+ * the caller wanted it gone and it is gone. What comes back as an error is the
204
+ * canister failing to write, and it is raised rather than dropped — an
205
+ * application that told a user it had turned notifications off should be able to
206
+ * find out that it had not.
207
+ */
208
+ async revoke(): Promise<void> {
209
+ unwrap(
210
+ await this.#service.app_revoke_notification_consent(),
211
+ 'Internet Identity could not withdraw this notification consent',
212
+ );
213
+ }
214
+ }
@@ -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
  };