@icp-sdk/auth 8.0.2 → 9.0.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 (85) hide show
  1. package/dist/esm/client/app-delegation-source.d.ts +65 -0
  2. package/dist/esm/client/app-delegation-source.js +58 -0
  3. package/dist/esm/client/app-delegation-source.js.map +1 -0
  4. package/dist/esm/client/app-lock.d.ts +63 -0
  5. package/dist/esm/client/app-lock.js +92 -0
  6. package/dist/esm/client/app-lock.js.map +1 -0
  7. package/dist/esm/client/auth-client.d.ts +270 -53
  8. package/dist/esm/client/auth-client.js +1017 -414
  9. package/dist/esm/client/auth-client.js.map +1 -1
  10. package/dist/esm/client/base64.d.ts +8 -0
  11. package/dist/esm/client/base64.js +28 -0
  12. package/dist/esm/client/base64.js.map +1 -0
  13. package/dist/esm/client/cookie-state-storage.d.ts +59 -0
  14. package/dist/esm/client/cookie-state-storage.js +245 -0
  15. package/dist/esm/client/cookie-state-storage.js.map +1 -0
  16. package/dist/esm/client/credential-storage.d.ts +48 -0
  17. package/dist/esm/client/credential-storage.js +2 -0
  18. package/dist/esm/client/credential-storage.js.map +1 -0
  19. package/dist/esm/client/db.d.ts +6 -1
  20. package/dist/esm/client/db.js +56 -15
  21. package/dist/esm/client/db.js.map +1 -1
  22. package/dist/esm/client/foreground-refresh.d.ts +35 -0
  23. package/dist/esm/client/foreground-refresh.js +83 -0
  24. package/dist/esm/client/foreground-refresh.js.map +1 -0
  25. package/dist/esm/client/idb-credential-storage.d.ts +25 -0
  26. package/dist/esm/client/idb-credential-storage.js +69 -0
  27. package/dist/esm/client/idb-credential-storage.js.map +1 -0
  28. package/dist/esm/client/index.d.ts +14 -3
  29. package/dist/esm/client/index.js +13 -3
  30. package/dist/esm/client/index.js.map +1 -1
  31. package/dist/esm/client/local-credential-storage.d.ts +26 -0
  32. package/dist/esm/client/local-credential-storage.js +59 -0
  33. package/dist/esm/client/local-credential-storage.js.map +1 -0
  34. package/dist/esm/client/memory-credential-storage.d.ts +22 -0
  35. package/dist/esm/client/memory-credential-storage.js +35 -0
  36. package/dist/esm/client/memory-credential-storage.js.map +1 -0
  37. package/dist/esm/client/session-delegation.d.ts +40 -0
  38. package/dist/esm/client/session-delegation.js +100 -0
  39. package/dist/esm/client/session-delegation.js.map +1 -0
  40. package/dist/esm/client/session-identity.d.ts +97 -0
  41. package/dist/esm/client/session-identity.js +392 -0
  42. package/dist/esm/client/session-identity.js.map +1 -0
  43. package/dist/esm/client/session-minter.d.ts +94 -0
  44. package/dist/esm/client/session-minter.js +185 -0
  45. package/dist/esm/client/session-minter.js.map +1 -0
  46. package/dist/esm/client/shared-memory-credential-storage.d.ts +44 -0
  47. package/dist/esm/client/shared-memory-credential-storage.js +243 -0
  48. package/dist/esm/client/shared-memory-credential-storage.js.map +1 -0
  49. package/dist/esm/client/slots.d.ts +59 -0
  50. package/dist/esm/client/slots.js +67 -0
  51. package/dist/esm/client/slots.js.map +1 -0
  52. package/dist/esm/client/sso.d.ts +33 -0
  53. package/dist/esm/client/sso.js +120 -0
  54. package/dist/esm/client/sso.js.map +1 -0
  55. package/dist/esm/client/state-storage.d.ts +135 -0
  56. package/dist/esm/client/state-storage.js +178 -0
  57. package/dist/esm/client/state-storage.js.map +1 -0
  58. package/package.json +3 -2
  59. package/src/client/app-delegation-source.ts +86 -0
  60. package/src/client/app-lock.ts +120 -0
  61. package/src/client/auth-client.ts +1300 -487
  62. package/src/client/base64.ts +28 -0
  63. package/src/client/cookie-state-storage.ts +277 -0
  64. package/src/client/credential-storage.ts +56 -0
  65. package/src/client/db.ts +56 -12
  66. package/src/client/foreground-refresh.ts +92 -0
  67. package/src/client/idb-credential-storage.ts +82 -0
  68. package/src/client/index.ts +24 -8
  69. package/src/client/local-credential-storage.ts +68 -0
  70. package/src/client/memory-credential-storage.ts +41 -0
  71. package/src/client/session-delegation.ts +138 -0
  72. package/src/client/session-identity.ts +510 -0
  73. package/src/client/session-minter.ts +286 -0
  74. package/src/client/shared-memory-credential-storage.ts +303 -0
  75. package/src/client/slots.ts +78 -0
  76. package/src/client/sso.ts +122 -0
  77. package/src/client/state-storage.ts +284 -0
  78. package/dist/esm/client/idle-manager.d.ts +0 -83
  79. package/dist/esm/client/idle-manager.js +0 -100
  80. package/dist/esm/client/idle-manager.js.map +0 -1
  81. package/dist/esm/client/storage.d.ts +0 -51
  82. package/dist/esm/client/storage.js +0 -90
  83. package/dist/esm/client/storage.js.map +0 -1
  84. package/src/client/idle-manager.ts +0 -162
  85. package/src/client/storage.ts +0 -114
@@ -1,11 +1,7 @@
1
- import { type Identity, type SignIdentity } from '@icp-sdk/core/agent';
2
- import { type PartialIdentity } from '@icp-sdk/core/identity';
3
- import type { Principal } from '@icp-sdk/core/principal';
4
- import { IdleManager, type IdleManagerOptions } from './idle-manager.js';
5
- import { type AuthClientStorage } from './storage.js';
6
- declare const ECDSA_KEY_LABEL = "ECDSA";
7
- declare const ED25519_KEY_LABEL = "Ed25519";
8
- type BaseKeyType = typeof ECDSA_KEY_LABEL | typeof ED25519_KEY_LABEL;
1
+ import { type HttpAgentOptions, type Identity } from '@icp-sdk/core/agent';
2
+ import { Principal } from '@icp-sdk/core/principal';
3
+ import type { CredentialStorage } from './credential-storage.js';
4
+ import { type StateStorage } from './state-storage.js';
9
5
  export type OpenIdProvider = 'google' | 'apple' | 'microsoft';
10
6
  export declare const OPENID_PROVIDER_URLS: {
11
7
  readonly google: "https://accounts.google.com";
@@ -13,36 +9,72 @@ export declare const OPENID_PROVIDER_URLS: {
13
9
  readonly microsoft: "https://login.microsoftonline.com/{tid}/v2.0";
14
10
  };
15
11
  declare const DEFAULT_OPENID_SCOPE_KEYS: readonly ["name", "email", "verified_email"];
12
+ declare const DEFAULT_SSO_SCOPE_KEYS: readonly ["name", "email"];
16
13
  /**
17
- * Options for creating an {@link AuthClient}.
14
+ * Options for creating an {@link AuthClient}, other than the one-click sign-in
15
+ * entry point. See {@link AuthClientCreateOptions}.
18
16
  */
19
- export interface AuthClientCreateOptions {
17
+ export interface AuthClientBaseOptions {
18
+ /**
19
+ * Where credentials are kept. Defaults to IndexedDB.
20
+ */
21
+ credentialStorage?: CredentialStorage;
20
22
  /**
21
- * An identity to authenticate via delegation.
23
+ * Prefix for every slot this client writes under.
24
+ *
25
+ * Slots are assigned in one place rather than defaulted by each store, and this
26
+ * moves all of them at once — so an application running two clients under one
27
+ * origin separates them with a single string and cannot rename some while
28
+ * missing others.
29
+ *
30
+ * Leave it unset unless a second client shares this origin.
22
31
  */
23
- identity?: SignIdentity | PartialIdentity;
32
+ namespace?: string;
24
33
  /**
25
- * Persistent storage backend. Defaults to IndexedDB.
26
- * @default IdbStorage
34
+ * Where the state of the sign-in is kept: which account is signed in here,
35
+ * and until when. Defaults to `localStorage`.
27
36
  */
28
- storage?: AuthClientStorage;
37
+ stateStorage?: StateStorage;
29
38
  /**
30
- * Type of session key to generate on each sign-in.
39
+ * Stops this client from watching the browser for signs that somebody is here.
31
40
  *
32
- * Use `'Ed25519'` when your storage provider does not support `CryptoKey`.
33
- * @default 'ECDSA'
41
+ * All of them together, because they make one claim: the page being shown, the
42
+ * window regaining focus, a pointer or a key. A backgrounded tab has its timers
43
+ * throttled, so its delegation can lapse while nobody is looking and the first
44
+ * click after coming back waits for a mint; returning to the tab is early
45
+ * enough to hide that.
46
+ *
47
+ * Nothing is hooked where there is no DOM, so a client outside a browser needs
48
+ * no option. Setting it makes requests the only thing that says this session is
49
+ * in use — including to the identity provider, which ends a session nothing
50
+ * has minted from for long enough. An application whose users read more than
51
+ * they click should leave it alone.
52
+ * @default false
34
53
  */
35
- keyType?: BaseKeyType;
54
+ disableBrowserActivity?: boolean;
36
55
  /**
37
- * Idle timeout configuration.
38
- * @default after 10 minutes, invalidates the identity
56
+ * Where the identity provider is, as two values rather than one.
57
+ *
58
+ * A ceremony is rendered at a URL and delegations are minted by a canister,
59
+ * and they are not the same address: a custom domain can front the mainnet
60
+ * canister, and a local deployment changes both. Nothing is derived from the
61
+ * URL — the origin of one is not a promise about which canister answers
62
+ * there — so a deployment is named by both or by neither. Omit the option and
63
+ * both are mainnet's.
39
64
  */
40
- idleOptions?: IdleOptions;
65
+ identityProvider?: {
66
+ /** The authorize URL a ceremony is rendered at. */
67
+ authorizeUrl: string | URL;
68
+ /** The canister that mints and revokes this application's delegations. */
69
+ canisterId: Principal | string;
70
+ };
41
71
  /**
42
- * Identity provider URL.
43
- * @default "https://id.ai/authorize"
72
+ * Options for the agent that makes the mint and revoke calls.
73
+ *
74
+ * `identity` is not among them: the agent signs as the session, which is what
75
+ * those calls rest on.
44
76
  */
45
- identityProvider?: string | URL;
77
+ agentOptions?: Omit<HttpAgentOptions, 'identity'>;
46
78
  /**
47
79
  * Derivation origin for the identity provider.
48
80
  * @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc
@@ -76,38 +108,103 @@ export interface AuthClientCreateOptions {
76
108
  * @see https://github.com/dfinity/wg-identity-authentication/blob/main/topics/icrc_167_browser_url_transport.md
77
109
  */
78
110
  transport?: 'window' | 'redirect';
111
+ /**
112
+ * Whether Internet Identity may answer without user interaction.
113
+ *
114
+ * - `'login'` (the effect of omitting it): run a normal sign-in ceremony.
115
+ * - `'none'`: Internet Identity answers from a session it already holds for
116
+ * this app and returns without rendering anything, or fails with an
117
+ * `interaction_required` error if it cannot. Pair with {@link hint} to name
118
+ * which account to re-issue for. Use it on a page load where the state names
119
+ * an account this origin has no credentials for — a sibling subdomain signed
120
+ * in — so this origin acquires its own without a ceremony.
121
+ *
122
+ * Sent as a `prompt` query param on the authorize URL. An Internet Identity
123
+ * extension inspired by OpenID Connect's `prompt`, and not part of any ICRC
124
+ * standard — which is why it travels on the URL rather than in the request.
125
+ */
126
+ prompt?: 'none' | 'login';
127
+ /**
128
+ * The account to re-issue for, which is the principal the state names.
129
+ *
130
+ * Sent as text in a `hint` query param on the authorize URL; Internet Identity
131
+ * uses it to pick which session a {@link prompt} `'none'` request resolves to
132
+ * when the user has more than one for this app. Inspired by OpenID Connect's
133
+ * `login_hint`.
134
+ */
135
+ hint?: Principal;
136
+ /**
137
+ * Whether Internet Identity may keep this sign-in so that a later
138
+ * {@link prompt} `'none'` request can be answered from it.
139
+ *
140
+ * Defaults to what {@link AuthClientCreateOptions.stateStorage} says, which is
141
+ * `true` only for {@link CookieStateStorage}: an application declares this
142
+ * intent by choosing a store whose record reaches its siblings, and making it
143
+ * say so a second time would be noise. Set it here for a cross-origin
144
+ * arrangement that is not sibling subdomains, or to force it off for siblings
145
+ * that should each sign in properly.
146
+ *
147
+ * Off means the provider keeps no session for this app on this device, so
148
+ * there is nothing for a silent request to find. It says nothing about how
149
+ * long a session lasts: {@link AuthClientSignInOptions.maxTimeToIdle} applies
150
+ * either way.
151
+ *
152
+ * Sent as a `resumable` query param on the authorize URL, for the same reason
153
+ * {@link prompt} is: the URL is assembled once, here.
154
+ */
155
+ resumable?: boolean;
156
+ }
157
+ /**
158
+ * Options for creating an {@link AuthClient}.
159
+ *
160
+ * At most one one-click sign-in entry point may be set: `openIdProvider` for a
161
+ * hardcoded provider, or `ssoDomain` for an organization's own SSO.
162
+ */
163
+ export type AuthClientCreateOptions = AuthClientBaseOptions & ({
79
164
  /**
80
165
  * OpenID provider for one-click sign-in. When set, the identity provider
81
166
  * URL includes an `openid` search param so the user authenticates via
82
167
  * the chosen provider (e.g. Google) instead of seeing Internet Identity directly.
83
168
  */
84
169
  openIdProvider?: OpenIdProvider;
85
- }
86
- export interface IdleOptions extends IdleManagerOptions {
87
- /**
88
- * Disables idle functionality entirely.
89
- * @default false
90
- */
91
- disableIdle?: boolean;
170
+ ssoDomain?: never;
171
+ } | {
172
+ openIdProvider?: never;
92
173
  /**
93
- * Disables the default idle callback (sign-out & reload).
94
- * @default false
174
+ * Organization domain for one-click SSO sign-in, e.g. `'dfinity.org'`.
175
+ * When set, the identity provider URL includes an `sso` search param so
176
+ * the user authenticates via that organization's own provider.
177
+ *
178
+ * A value that is not a domain with an optional port throws. Use
179
+ * {@link isValidSsoDomain} to check a domain the user typed.
95
180
  */
96
- disableDefaultIdleCallback?: boolean;
97
- }
181
+ ssoDomain?: string;
182
+ });
98
183
  /**
99
184
  * Options for {@link AuthClient.signIn}.
100
185
  */
101
186
  export interface AuthClientSignInOptions {
102
187
  /**
103
- * Maximum lifetime of the delegation in nanoseconds.
104
- * @default 8 hours
188
+ * The longest the session may last, in nanoseconds.
189
+ * @default the identity provider's, currently 30 days
105
190
  */
106
191
  maxTimeToLive?: bigint;
107
192
  /**
108
- * Restrict the delegation to specific canisters.
193
+ * How long a signed-in user may be idle before the sign-in ends, in nanoseconds.
194
+ * @default the identity provider's, currently 7 days
195
+ */
196
+ maxTimeToIdle?: bigint;
197
+ /**
198
+ * Where to go once the sign-in completes, ignored unless it is a same-origin
199
+ * `http(s)` target.
200
+ *
201
+ * For the flow that leaves the page: a redirect sign-in comes back to whatever
202
+ * URL the ceremony was started from, which is rarely where the user was. It is
203
+ * journaled, so it survives the round trip, and the navigation replaces the
204
+ * current history entry rather than adding one — the sign-in page and the
205
+ * redirect chain are not somewhere a back button should return to.
109
206
  */
110
- targets?: Principal[];
207
+ returnTo?: string;
111
208
  }
112
209
  export interface SignedAttributes {
113
210
  data: Uint8Array;
@@ -123,9 +220,70 @@ export interface SignedAttributes {
123
220
  * ? await authClient.getIdentity()
124
221
  * : await authClient.signIn();
125
222
  */
223
+ /**
224
+ * Who is signed in for this origin, and until when.
225
+ *
226
+ * `principal` and `expiresAtMs` are present in every case where a record
227
+ * exists, so an application can name the account and count down to the end of a
228
+ * sign-in without reading the store itself.
229
+ */
230
+ export type SessionStatus = {
231
+ state: 'signed-in';
232
+ principal: Principal;
233
+ expiresAtMs: number;
234
+ }
235
+ /**
236
+ * Someone is signed in on this domain, but this origin holds no credential
237
+ * for them, so it cannot act yet. Acquire one silently, or ask the user.
238
+ */
239
+ | {
240
+ state: 'signed-in-elsewhere';
241
+ principal: Principal;
242
+ expiresAtMs: number;
243
+ } | {
244
+ state: 'expired';
245
+ principal: Principal;
246
+ expiresAtMs: number;
247
+ } | {
248
+ state: 'signed-out';
249
+ };
250
+ /**
251
+ * Thrown when a sign-in exists within the state store's reach but this origin
252
+ * holds no credential for it.
253
+ *
254
+ * A sibling subdomain reads the shared record on its first load and is in exactly
255
+ * this position: someone is signed in, and it has nothing to act with until it
256
+ * acquires its own. Catching this is where a silent re-issue belongs.
257
+ */
258
+ export declare class SessionNotHeldError extends Error {
259
+ constructor(message?: string);
260
+ }
261
+ /**
262
+ * Manages authentication and identity for Internet Computer web apps.
263
+ *
264
+ * `getStatus()`, `isAuthenticated()` and `getPrincipal()` are synchronous, so a
265
+ * page renders on them; `getIdentity()` is what an agent signs with.
266
+ *
267
+ * @example
268
+ * const authClient = new AuthClient();
269
+ *
270
+ * const identity = authClient.isAuthenticated()
271
+ * ? await authClient.getIdentity()
272
+ * : await authClient.signIn();
273
+ */
274
+ /**
275
+ * Thrown when a later sign-in or sign-out took over from this one.
276
+ *
277
+ * Not a failure of the operation so much as a change of mind: an origin has one
278
+ * signer window and one sign-in, so the newer intent is the one honoured, and
279
+ * the earlier one reports this rather than writing what it had assembled. A
280
+ * caller may usually ignore it — the user is getting what they asked for second.
281
+ */
282
+ export declare class SupersededError extends Error {
283
+ constructor(message?: string);
284
+ }
126
285
  export declare class AuthClient {
127
286
  #private;
128
- idleManager: IdleManager | undefined;
129
287
  constructor(options?: AuthClientCreateOptions);
130
288
  /**
131
289
  * Returns the current identity, restoring a previous session if available.
@@ -136,21 +294,59 @@ export declare class AuthClient {
136
294
  */
137
295
  isAuthenticated(): boolean;
138
296
  /**
139
- * Opens the identity provider, requests a delegation, and returns the authenticated identity.
297
+ * Who this origin can act as, or `undefined` where it cannot act.
298
+ *
299
+ * The same question {@link isAuthenticated} answers, returning who rather than
300
+ * whether — so the two never disagree. Synchronous, and read from the state
301
+ * rather than from whatever material happens to be held, so a page renders on
302
+ * it without opening a store and without waiting for a mint. That is the
303
+ * difference from `(await getIdentity()).getPrincipal()`, which is asynchronous
304
+ * and, on a load with no delegation worth adopting, waits for one to be minted.
305
+ *
306
+ * A principal here means calls made as it will be accepted, so an expired
307
+ * record answers `undefined` even though it still names an account, and so does
308
+ * a record naming an account this origin holds nothing for. Returning one
309
+ * anyway would have an application acting on a session that has ended: the
310
+ * check most reach for is `if (getPrincipal())`, and it has to mean what it
311
+ * looks like it means.
312
+ *
313
+ * {@link getStatus} is where those cases are readable, and it carries the
314
+ * account principal in each of them — so nothing is lost by this being narrow,
315
+ * and an application wanting to say whose session ended asks there.
316
+ */
317
+ getPrincipal(): Principal | undefined;
318
+ /**
319
+ * Who is signed in for this origin right now.
320
+ *
321
+ * Synchronous, so a page can render on it without opening a store.
322
+ */
323
+ getStatus(): SessionStatus;
324
+ /**
325
+ * Watches who is signed in here, and returns a function that stops watching.
140
326
  *
141
- * @param options - Sign-in options.
142
- * @param options.maxTimeToLive - Maximum lifetime of the delegation in nanoseconds.
143
- * @param options.targets - Restrict the delegation to specific canisters.
144
- * @returns The authenticated identity.
145
- * @throws When authentication fails.
327
+ * `getStatus()` and the predicates beside it are snapshots, so an application
328
+ * rendering on them needs to be told when to read again. The record changes
329
+ * for reasons that are nothing to do with this client — another tab signing
330
+ * out, a sibling subdomain publishing a sign-in, a peer client on this page
331
+ * re-issuing silently — and this is how those arrive.
146
332
  *
147
- * @example
148
- * try {
149
- * const identity = await authClient.signIn();
150
- * } catch (error) {
151
- * console.error('Sign-in failed:', error);
152
- * }
333
+ * Fired once the record is readable, so a listener asking who is signed in
334
+ * sees what it was told about. It says that something changed and not what: a
335
+ * listener reads the answer it wants, which for most is `getStatus()`.
336
+ *
337
+ * What it does not cover is the identity being replaced under an application
338
+ * that holds one — an app delegation rotating is deliberately invisible, and
339
+ * nothing about who is signed in has changed when it does.
340
+ * @param listener - Called after the record changes.
341
+ * @returns A function that unregisters it.
342
+ */
343
+ subscribe(listener: () => void): () => void;
344
+ /**
345
+ * Releases what this client hooked: the browser listeners, the state
346
+ * subscription, and the refresh the identity has scheduled. Call it when
347
+ * discarding a client, so nothing it registered outlives it.
153
348
  */
349
+ dispose(): void;
154
350
  signIn(options?: AuthClientSignInOptions): Promise<Identity>;
155
351
  /**
156
352
  * Requests signed identity attributes from the identity provider.
@@ -244,6 +440,27 @@ export declare class AuthClient {
244
440
  */
245
441
  export declare function scopedKeys<P extends keyof typeof OPENID_PROVIDER_URLS, K extends string = (typeof DEFAULT_OPENID_SCOPE_KEYS)[number]>(params: {
246
442
  openIdProvider: P;
443
+ ssoDomain?: never;
247
444
  keys?: readonly K[];
248
445
  }): `openid:${(typeof OPENID_PROVIDER_URLS)[P]}:${K}`[];
446
+ /**
447
+ * Scopes attribute keys to an organization's SSO.
448
+ *
449
+ * When using one-click SSO sign-in, attributes can be scoped to the same
450
+ * organization so the user grants access in a single step.
451
+ *
452
+ * @param params.ssoDomain - The organization domain the keys should be scoped to.
453
+ * @param params.keys - The attribute keys to scope. Defaults to `['name', 'email']`;
454
+ * `verified_email` is not available for an organization SSO.
455
+ * @returns The scoped attribute keys as `sso:<domain>:<key>`.
456
+ *
457
+ * @example
458
+ * scopedKeys({ ssoDomain: 'dfinity.org', keys: ['email'] });
459
+ * // ['sso:dfinity.org:email']
460
+ */
461
+ export declare function scopedKeys<D extends string, K extends string = (typeof DEFAULT_SSO_SCOPE_KEYS)[number]>(params: {
462
+ ssoDomain: D;
463
+ openIdProvider?: never;
464
+ keys?: readonly K[];
465
+ }): `sso:${Lowercase<D>}:${K}`[];
249
466
  export {};