@icp-sdk/auth 4.0.0-beta.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.
- package/README.md +11 -0
- package/dist/esm/client/auth-client.d.ts +177 -0
- package/dist/esm/client/auth-client.js +328 -0
- package/dist/esm/client/auth-client.js.map +1 -0
- package/dist/esm/client/db.d.ts +47 -0
- package/dist/esm/client/db.js +83 -0
- package/dist/esm/client/db.js.map +1 -0
- package/dist/esm/client/idle-manager.d.ts +81 -0
- package/dist/esm/client/idle-manager.js +81 -0
- package/dist/esm/client/idle-manager.js.map +1 -0
- package/dist/esm/client/index.d.ts +4 -0
- package/dist/esm/client/index.js +15 -0
- package/dist/esm/client/index.js.map +1 -0
- package/dist/esm/client/storage.d.ts +51 -0
- package/dist/esm/client/storage.js +83 -0
- package/dist/esm/client/storage.js.map +1 -0
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/index.js.map +1 -0
- package/package.json +62 -0
- package/src/client/auth-client.ts +593 -0
- package/src/client/db.ts +114 -0
- package/src/client/idle-manager.ts +144 -0
- package/src/client/index.ts +10 -0
- package/src/client/storage.ts +112 -0
- package/src/index.ts +3 -0
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AnonymousIdentity,
|
|
3
|
+
type DerEncodedPublicKey,
|
|
4
|
+
type Identity,
|
|
5
|
+
type Signature,
|
|
6
|
+
type SignIdentity,
|
|
7
|
+
} from '@icp-sdk/core/agent';
|
|
8
|
+
import {
|
|
9
|
+
Delegation,
|
|
10
|
+
DelegationChain,
|
|
11
|
+
DelegationIdentity,
|
|
12
|
+
ECDSAKeyIdentity,
|
|
13
|
+
Ed25519KeyIdentity,
|
|
14
|
+
isDelegationValid,
|
|
15
|
+
PartialDelegationIdentity,
|
|
16
|
+
type PartialIdentity,
|
|
17
|
+
} from '@icp-sdk/core/identity';
|
|
18
|
+
import type { Principal } from '@icp-sdk/core/principal';
|
|
19
|
+
import { IdleManager, type IdleManagerOptions } from './idle-manager.ts';
|
|
20
|
+
import {
|
|
21
|
+
type AuthClientStorage,
|
|
22
|
+
IdbStorage,
|
|
23
|
+
KEY_STORAGE_DELEGATION,
|
|
24
|
+
KEY_STORAGE_KEY,
|
|
25
|
+
KEY_VECTOR,
|
|
26
|
+
LocalStorage,
|
|
27
|
+
} from './storage.ts';
|
|
28
|
+
|
|
29
|
+
const NANOSECONDS_PER_SECOND = BigInt(1_000_000_000);
|
|
30
|
+
const SECONDS_PER_HOUR = BigInt(3_600);
|
|
31
|
+
const NANOSECONDS_PER_HOUR = NANOSECONDS_PER_SECOND * SECONDS_PER_HOUR;
|
|
32
|
+
|
|
33
|
+
const IDENTITY_PROVIDER_DEFAULT = 'https://identity.internetcomputer.org';
|
|
34
|
+
const IDENTITY_PROVIDER_ENDPOINT = '#authorize';
|
|
35
|
+
|
|
36
|
+
const DEFAULT_MAX_TIME_TO_LIVE = BigInt(8) * NANOSECONDS_PER_HOUR;
|
|
37
|
+
|
|
38
|
+
const ECDSA_KEY_LABEL = 'ECDSA';
|
|
39
|
+
const ED25519_KEY_LABEL = 'Ed25519';
|
|
40
|
+
type BaseKeyType = typeof ECDSA_KEY_LABEL | typeof ED25519_KEY_LABEL;
|
|
41
|
+
|
|
42
|
+
const INTERRUPT_CHECK_INTERVAL = 500;
|
|
43
|
+
|
|
44
|
+
export const ERROR_USER_INTERRUPT = 'UserInterrupt';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* List of options for creating an {@link AuthClient}.
|
|
48
|
+
*/
|
|
49
|
+
export interface AuthClientCreateOptions {
|
|
50
|
+
/**
|
|
51
|
+
* An {@link SignIdentity} or {@link PartialIdentity} to authenticate via delegation.
|
|
52
|
+
*/
|
|
53
|
+
identity?: SignIdentity | PartialIdentity;
|
|
54
|
+
/**
|
|
55
|
+
* Optional storage with get, set, and remove. Uses {@link IdbStorage} by default.
|
|
56
|
+
* @see {@link AuthClientStorage}
|
|
57
|
+
*/
|
|
58
|
+
storage?: AuthClientStorage;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Type to use for the base key.
|
|
62
|
+
*
|
|
63
|
+
* If you are using a custom storage provider that does not support CryptoKey storage,
|
|
64
|
+
* you should use `Ed25519` as the key type, as it can serialize to a string.
|
|
65
|
+
* @default 'ECDSA'
|
|
66
|
+
*/
|
|
67
|
+
keyType?: BaseKeyType;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Options to handle idle timeouts
|
|
71
|
+
* @default after 10 minutes, invalidates the identity
|
|
72
|
+
*/
|
|
73
|
+
idleOptions?: IdleOptions;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Options to handle login, passed to the login method
|
|
77
|
+
*/
|
|
78
|
+
loginOptions?: AuthClientLoginOptions;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface IdleOptions extends IdleManagerOptions {
|
|
82
|
+
/**
|
|
83
|
+
* Disables idle functionality for {@link IdleManager}
|
|
84
|
+
* @default false
|
|
85
|
+
*/
|
|
86
|
+
disableIdle?: boolean;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Disables default idle behavior - call logout & reload window
|
|
90
|
+
* @default false
|
|
91
|
+
*/
|
|
92
|
+
disableDefaultIdleCallback?: boolean;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export type OnSuccessFunc =
|
|
96
|
+
| (() => void | Promise<void>)
|
|
97
|
+
| ((message: InternetIdentityAuthResponseSuccess) => void | Promise<void>);
|
|
98
|
+
|
|
99
|
+
export type OnErrorFunc = (error?: string) => void | Promise<void>;
|
|
100
|
+
|
|
101
|
+
export interface AuthClientLoginOptions {
|
|
102
|
+
/**
|
|
103
|
+
* Identity provider
|
|
104
|
+
* @default "https://identity.internetcomputer.org"
|
|
105
|
+
*/
|
|
106
|
+
identityProvider?: string | URL;
|
|
107
|
+
/**
|
|
108
|
+
* Expiration of the authentication in nanoseconds
|
|
109
|
+
* @default BigInt(8) hours * BigInt(3_600_000_000_000) nanoseconds
|
|
110
|
+
*/
|
|
111
|
+
maxTimeToLive?: bigint;
|
|
112
|
+
/**
|
|
113
|
+
* If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).
|
|
114
|
+
*/
|
|
115
|
+
allowPinAuthentication?: boolean;
|
|
116
|
+
/**
|
|
117
|
+
* Origin for Identity Provider to use while generating the delegated identity. For II, the derivation origin must authorize this origin by setting a record at `<derivation-origin>/.well-known/ii-alternative-origins`.
|
|
118
|
+
* @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc
|
|
119
|
+
*/
|
|
120
|
+
derivationOrigin?: string | URL;
|
|
121
|
+
/**
|
|
122
|
+
* Auth Window feature config string
|
|
123
|
+
* @example "toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100"
|
|
124
|
+
*/
|
|
125
|
+
windowOpenerFeatures?: string;
|
|
126
|
+
/**
|
|
127
|
+
* Callback once login has completed
|
|
128
|
+
*/
|
|
129
|
+
onSuccess?: OnSuccessFunc;
|
|
130
|
+
/**
|
|
131
|
+
* Callback in case authentication fails
|
|
132
|
+
*/
|
|
133
|
+
onError?: OnErrorFunc;
|
|
134
|
+
/**
|
|
135
|
+
* Extra values to be passed in the login request during the authorize-ready phase
|
|
136
|
+
*/
|
|
137
|
+
customValues?: Record<string, unknown>;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
interface InternetIdentityAuthRequest {
|
|
141
|
+
kind: 'authorize-client';
|
|
142
|
+
sessionPublicKey: Uint8Array;
|
|
143
|
+
maxTimeToLive?: bigint;
|
|
144
|
+
allowPinAuthentication?: boolean;
|
|
145
|
+
derivationOrigin?: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface InternetIdentityAuthResponseSuccess {
|
|
149
|
+
kind: 'authorize-client-success';
|
|
150
|
+
delegations: {
|
|
151
|
+
delegation: {
|
|
152
|
+
pubkey: Uint8Array;
|
|
153
|
+
expiration: bigint;
|
|
154
|
+
targets?: Principal[];
|
|
155
|
+
};
|
|
156
|
+
signature: Uint8Array;
|
|
157
|
+
}[];
|
|
158
|
+
userPublicKey: Uint8Array;
|
|
159
|
+
authnMethod: 'passkey' | 'pin' | 'recovery';
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
interface AuthReadyMessage {
|
|
163
|
+
kind: 'authorize-ready';
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
interface AuthResponseSuccess {
|
|
167
|
+
kind: 'authorize-client-success';
|
|
168
|
+
delegations: {
|
|
169
|
+
delegation: {
|
|
170
|
+
pubkey: Uint8Array;
|
|
171
|
+
expiration: bigint;
|
|
172
|
+
targets?: Principal[];
|
|
173
|
+
};
|
|
174
|
+
signature: Uint8Array;
|
|
175
|
+
}[];
|
|
176
|
+
userPublicKey: Uint8Array;
|
|
177
|
+
authnMethod: 'passkey' | 'pin' | 'recovery';
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
interface AuthResponseFailure {
|
|
181
|
+
kind: 'authorize-client-failure';
|
|
182
|
+
text: string;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
type IdentityServiceResponseMessage = AuthReadyMessage | AuthResponse;
|
|
186
|
+
type AuthResponse = AuthResponseSuccess | AuthResponseFailure;
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Tool to manage authentication and identity
|
|
190
|
+
* @see {@link AuthClient}
|
|
191
|
+
*/
|
|
192
|
+
export class AuthClient {
|
|
193
|
+
/**
|
|
194
|
+
* Create an AuthClient to manage authentication and identity
|
|
195
|
+
* @param {AuthClientCreateOptions} options - Options for creating an {@link AuthClient}
|
|
196
|
+
* @see {@link AuthClientCreateOptions}
|
|
197
|
+
* @param options.identity Optional Identity to use as the base
|
|
198
|
+
* @see {@link SignIdentity}
|
|
199
|
+
* @param options.storage Storage mechanism for delegation credentials
|
|
200
|
+
* @see {@link AuthClientStorage}
|
|
201
|
+
* @param options.keyType Type of key to use for the base key
|
|
202
|
+
* @param {IdleOptions} options.idleOptions Configures an {@link IdleManager}
|
|
203
|
+
* @see {@link IdleOptions}
|
|
204
|
+
* Default behavior is to clear stored identity and reload the page when a user goes idle, unless you set the disableDefaultIdleCallback flag or pass in a custom idle callback.
|
|
205
|
+
* @example
|
|
206
|
+
* const authClient = await AuthClient.create({
|
|
207
|
+
* idleOptions: {
|
|
208
|
+
* disableIdle: true
|
|
209
|
+
* }
|
|
210
|
+
* })
|
|
211
|
+
*/
|
|
212
|
+
public static async create(options: AuthClientCreateOptions = {}): Promise<AuthClient> {
|
|
213
|
+
const storage = options.storage ?? new IdbStorage();
|
|
214
|
+
const keyType = options.keyType ?? ECDSA_KEY_LABEL;
|
|
215
|
+
|
|
216
|
+
let key: null | SignIdentity | PartialIdentity = null;
|
|
217
|
+
if (options.identity) {
|
|
218
|
+
key = options.identity;
|
|
219
|
+
} else {
|
|
220
|
+
let maybeIdentityStorage = await storage.get(KEY_STORAGE_KEY);
|
|
221
|
+
if (!maybeIdentityStorage) {
|
|
222
|
+
// Attempt to migrate from localstorage
|
|
223
|
+
try {
|
|
224
|
+
const fallbackLocalStorage = new LocalStorage();
|
|
225
|
+
const localChain = await fallbackLocalStorage.get(KEY_STORAGE_DELEGATION);
|
|
226
|
+
const localKey = await fallbackLocalStorage.get(KEY_STORAGE_KEY);
|
|
227
|
+
// not relevant for Ed25519
|
|
228
|
+
if (localChain && localKey && keyType === ECDSA_KEY_LABEL) {
|
|
229
|
+
console.log('Discovered an identity stored in localstorage. Migrating to IndexedDB');
|
|
230
|
+
await storage.set(KEY_STORAGE_DELEGATION, localChain);
|
|
231
|
+
await storage.set(KEY_STORAGE_KEY, localKey);
|
|
232
|
+
|
|
233
|
+
maybeIdentityStorage = localChain;
|
|
234
|
+
// clean up
|
|
235
|
+
await fallbackLocalStorage.remove(KEY_STORAGE_DELEGATION);
|
|
236
|
+
await fallbackLocalStorage.remove(KEY_STORAGE_KEY);
|
|
237
|
+
}
|
|
238
|
+
} catch (error) {
|
|
239
|
+
console.error(`error while attempting to recover localstorage: ${error}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (maybeIdentityStorage) {
|
|
243
|
+
try {
|
|
244
|
+
if (typeof maybeIdentityStorage === 'object') {
|
|
245
|
+
if (keyType === ED25519_KEY_LABEL && typeof maybeIdentityStorage === 'string') {
|
|
246
|
+
key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);
|
|
247
|
+
} else {
|
|
248
|
+
key = await ECDSAKeyIdentity.fromKeyPair(maybeIdentityStorage);
|
|
249
|
+
}
|
|
250
|
+
} else if (typeof maybeIdentityStorage === 'string') {
|
|
251
|
+
// This is a legacy identity, which is a serialized Ed25519KeyIdentity.
|
|
252
|
+
key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);
|
|
253
|
+
}
|
|
254
|
+
} catch {
|
|
255
|
+
// Ignore this, this means that the localStorage value isn't a valid Ed25519KeyIdentity or ECDSAKeyIdentity
|
|
256
|
+
// serialization.
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
let identity: SignIdentity | PartialIdentity = new AnonymousIdentity() as PartialIdentity;
|
|
262
|
+
let chain: null | DelegationChain = null;
|
|
263
|
+
if (key) {
|
|
264
|
+
try {
|
|
265
|
+
const chainStorage = await storage.get(KEY_STORAGE_DELEGATION);
|
|
266
|
+
if (typeof chainStorage === 'object' && chainStorage !== null) {
|
|
267
|
+
throw new Error(
|
|
268
|
+
'Delegation chain is incorrectly stored. A delegation chain should be stored as a string.',
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (options.identity) {
|
|
273
|
+
identity = options.identity;
|
|
274
|
+
} else if (chainStorage) {
|
|
275
|
+
chain = DelegationChain.fromJSON(chainStorage);
|
|
276
|
+
|
|
277
|
+
// Verify that the delegation isn't expired.
|
|
278
|
+
if (!isDelegationValid(chain)) {
|
|
279
|
+
await _deleteStorage(storage);
|
|
280
|
+
key = null;
|
|
281
|
+
} else {
|
|
282
|
+
// If the key is a public key, then we create a PartialDelegationIdentity.
|
|
283
|
+
if ('toDer' in key) {
|
|
284
|
+
identity = PartialDelegationIdentity.fromDelegation(key, chain);
|
|
285
|
+
// otherwise, we create a DelegationIdentity.
|
|
286
|
+
} else {
|
|
287
|
+
identity = DelegationIdentity.fromDelegation(key, chain);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
} catch (e) {
|
|
292
|
+
console.error(e);
|
|
293
|
+
// If there was a problem loading the chain, delete the key.
|
|
294
|
+
await _deleteStorage(storage);
|
|
295
|
+
key = null;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
let idleManager: IdleManager | undefined;
|
|
299
|
+
if (options.idleOptions?.disableIdle) {
|
|
300
|
+
idleManager = undefined;
|
|
301
|
+
}
|
|
302
|
+
// if there is a delegation chain or provided identity, setup idleManager
|
|
303
|
+
else if (chain || options.identity) {
|
|
304
|
+
idleManager = IdleManager.create(options.idleOptions);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (!key) {
|
|
308
|
+
// Create a new key (whether or not one was in storage).
|
|
309
|
+
if (keyType === ED25519_KEY_LABEL) {
|
|
310
|
+
key = Ed25519KeyIdentity.generate();
|
|
311
|
+
await storage.set(KEY_STORAGE_KEY, JSON.stringify((key as Ed25519KeyIdentity).toJSON()));
|
|
312
|
+
} else {
|
|
313
|
+
if (options.storage && keyType === ECDSA_KEY_LABEL) {
|
|
314
|
+
console.warn(
|
|
315
|
+
`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${ED25519_KEY_LABEL}' as the key type, as it can serialize to a string`,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
key = await ECDSAKeyIdentity.generate();
|
|
319
|
+
await storage.set(KEY_STORAGE_KEY, (key as ECDSAKeyIdentity).getKeyPair());
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
return new AuthClient(identity, key, chain, storage, idleManager, options);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
protected constructor(
|
|
327
|
+
private _identity: Identity | PartialIdentity,
|
|
328
|
+
private _key: SignIdentity | PartialIdentity,
|
|
329
|
+
private _chain: DelegationChain | null,
|
|
330
|
+
private _storage: AuthClientStorage,
|
|
331
|
+
public idleManager: IdleManager | undefined,
|
|
332
|
+
private _createOptions: AuthClientCreateOptions | undefined,
|
|
333
|
+
// A handle on the IdP window.
|
|
334
|
+
private _idpWindow?: Window,
|
|
335
|
+
// The event handler for processing events from the IdP.
|
|
336
|
+
private _eventHandler?: (event: MessageEvent) => void,
|
|
337
|
+
) {
|
|
338
|
+
this._registerDefaultIdleCallback();
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
private _registerDefaultIdleCallback() {
|
|
342
|
+
const idleOptions = this._createOptions?.idleOptions;
|
|
343
|
+
/**
|
|
344
|
+
* Default behavior is to clear stored identity and reload the page.
|
|
345
|
+
* By either setting the disableDefaultIdleCallback flag or passing in a custom idle callback, we will ignore this config
|
|
346
|
+
*/
|
|
347
|
+
if (!idleOptions?.onIdle && !idleOptions?.disableDefaultIdleCallback) {
|
|
348
|
+
this.idleManager?.registerCallback(() => {
|
|
349
|
+
this.logout();
|
|
350
|
+
location.reload();
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
private async _handleSuccess(
|
|
356
|
+
message: InternetIdentityAuthResponseSuccess,
|
|
357
|
+
onSuccess?: OnSuccessFunc,
|
|
358
|
+
) {
|
|
359
|
+
const delegations = message.delegations.map((signedDelegation) => {
|
|
360
|
+
return {
|
|
361
|
+
delegation: new Delegation(
|
|
362
|
+
signedDelegation.delegation.pubkey,
|
|
363
|
+
signedDelegation.delegation.expiration,
|
|
364
|
+
signedDelegation.delegation.targets,
|
|
365
|
+
),
|
|
366
|
+
signature: signedDelegation.signature as Signature,
|
|
367
|
+
};
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
const delegationChain = DelegationChain.fromDelegations(
|
|
371
|
+
delegations,
|
|
372
|
+
message.userPublicKey as DerEncodedPublicKey,
|
|
373
|
+
);
|
|
374
|
+
|
|
375
|
+
const key = this._key;
|
|
376
|
+
if (!key) {
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
this._chain = delegationChain;
|
|
381
|
+
|
|
382
|
+
if ('toDer' in key) {
|
|
383
|
+
this._identity = PartialDelegationIdentity.fromDelegation(key, this._chain);
|
|
384
|
+
} else {
|
|
385
|
+
this._identity = DelegationIdentity.fromDelegation(key, this._chain);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
this._idpWindow?.close();
|
|
389
|
+
const idleOptions = this._createOptions?.idleOptions;
|
|
390
|
+
// create the idle manager on a successful login if we haven't disabled it
|
|
391
|
+
// and it doesn't already exist.
|
|
392
|
+
if (!this.idleManager && !idleOptions?.disableIdle) {
|
|
393
|
+
this.idleManager = IdleManager.create(idleOptions);
|
|
394
|
+
this._registerDefaultIdleCallback();
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
this._removeEventListener();
|
|
398
|
+
delete this._idpWindow;
|
|
399
|
+
|
|
400
|
+
if (this._chain) {
|
|
401
|
+
await this._storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(this._chain.toJSON()));
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// onSuccess should be the last thing to do to avoid consumers
|
|
405
|
+
// interfering by navigating or refreshing the page
|
|
406
|
+
onSuccess?.(message);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
public getIdentity(): Identity {
|
|
410
|
+
return this._identity;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
public async isAuthenticated(): Promise<boolean> {
|
|
414
|
+
return (
|
|
415
|
+
!this.getIdentity().getPrincipal().isAnonymous() &&
|
|
416
|
+
this._chain !== null &&
|
|
417
|
+
isDelegationValid(this._chain)
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* AuthClient Login - Opens up a new window to authenticate with Internet Identity
|
|
423
|
+
* @param {AuthClientLoginOptions} options - Options for logging in, merged with the options set during creation if any. Note: we only perform a shallow merge for the `customValues` property.
|
|
424
|
+
* @param options.identityProvider Identity provider
|
|
425
|
+
* @param options.maxTimeToLive Expiration of the authentication in nanoseconds
|
|
426
|
+
* @param options.allowPinAuthentication If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).
|
|
427
|
+
* @param options.derivationOrigin Origin for Identity Provider to use while generating the delegated identity
|
|
428
|
+
* @param options.windowOpenerFeatures Configures the opened authentication window
|
|
429
|
+
* @param options.onSuccess Callback once login has completed
|
|
430
|
+
* @param options.onError Callback in case authentication fails
|
|
431
|
+
* @param options.customValues Extra values to be passed in the login request during the authorize-ready phase. Note: we only perform a shallow merge for the `customValues` property.
|
|
432
|
+
* @example
|
|
433
|
+
* const authClient = await AuthClient.create();
|
|
434
|
+
* authClient.login({
|
|
435
|
+
* identityProvider: 'http://<canisterID>.127.0.0.1:8000',
|
|
436
|
+
* maxTimeToLive: BigInt (7) * BigInt(24) * BigInt(3_600_000_000_000), // 1 week
|
|
437
|
+
* windowOpenerFeatures: "toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100",
|
|
438
|
+
* onSuccess: () => {
|
|
439
|
+
* console.log('Login Successful!');
|
|
440
|
+
* },
|
|
441
|
+
* onError: (error) => {
|
|
442
|
+
* console.error('Login Failed: ', error);
|
|
443
|
+
* }
|
|
444
|
+
* });
|
|
445
|
+
*/
|
|
446
|
+
public async login(options?: AuthClientLoginOptions): Promise<void> {
|
|
447
|
+
// Merge the passed options with the options set during creation
|
|
448
|
+
const loginOptions = mergeLoginOptions(this._createOptions?.loginOptions, options);
|
|
449
|
+
|
|
450
|
+
// Set default maxTimeToLive to 8 hours
|
|
451
|
+
const maxTimeToLive = loginOptions?.maxTimeToLive ?? DEFAULT_MAX_TIME_TO_LIVE;
|
|
452
|
+
|
|
453
|
+
// Create the URL of the IDP. (e.g. https://XXXX/#authorize)
|
|
454
|
+
const identityProviderUrl = new URL(
|
|
455
|
+
loginOptions?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT,
|
|
456
|
+
);
|
|
457
|
+
// Set the correct hash if it isn't already set.
|
|
458
|
+
identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT;
|
|
459
|
+
|
|
460
|
+
// If `login` has been called previously, then close/remove any previous windows
|
|
461
|
+
// and event listeners.
|
|
462
|
+
this._idpWindow?.close();
|
|
463
|
+
this._removeEventListener();
|
|
464
|
+
|
|
465
|
+
// Add an event listener to handle responses.
|
|
466
|
+
this._eventHandler = this._getEventHandler(identityProviderUrl, {
|
|
467
|
+
maxTimeToLive,
|
|
468
|
+
...loginOptions,
|
|
469
|
+
});
|
|
470
|
+
window.addEventListener('message', this._eventHandler);
|
|
471
|
+
|
|
472
|
+
// Open a new window with the IDP provider.
|
|
473
|
+
this._idpWindow =
|
|
474
|
+
window.open(
|
|
475
|
+
identityProviderUrl.toString(),
|
|
476
|
+
'idpWindow',
|
|
477
|
+
loginOptions?.windowOpenerFeatures,
|
|
478
|
+
) ?? undefined;
|
|
479
|
+
|
|
480
|
+
// Check if the _idpWindow is closed by user.
|
|
481
|
+
const checkInterruption = (): void => {
|
|
482
|
+
// The _idpWindow is opened and not yet closed by the client
|
|
483
|
+
if (this._idpWindow) {
|
|
484
|
+
if (this._idpWindow.closed) {
|
|
485
|
+
this._handleFailure(ERROR_USER_INTERRUPT, loginOptions?.onError);
|
|
486
|
+
} else {
|
|
487
|
+
setTimeout(checkInterruption, INTERRUPT_CHECK_INTERVAL);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
checkInterruption();
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
private _getEventHandler(identityProviderUrl: URL, options?: AuthClientLoginOptions) {
|
|
495
|
+
return async (event: MessageEvent) => {
|
|
496
|
+
if (event.origin !== identityProviderUrl.origin) {
|
|
497
|
+
// Ignore any event that is not from the identity provider
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const message = event.data as IdentityServiceResponseMessage;
|
|
502
|
+
|
|
503
|
+
switch (message.kind) {
|
|
504
|
+
case 'authorize-ready': {
|
|
505
|
+
// IDP is ready. Send a message to request authorization.
|
|
506
|
+
const request: InternetIdentityAuthRequest = {
|
|
507
|
+
kind: 'authorize-client',
|
|
508
|
+
sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer()),
|
|
509
|
+
maxTimeToLive: options?.maxTimeToLive,
|
|
510
|
+
allowPinAuthentication: options?.allowPinAuthentication,
|
|
511
|
+
derivationOrigin: options?.derivationOrigin?.toString(),
|
|
512
|
+
// Pass any custom values to the IDP.
|
|
513
|
+
...options?.customValues,
|
|
514
|
+
};
|
|
515
|
+
this._idpWindow?.postMessage(request, identityProviderUrl.origin);
|
|
516
|
+
break;
|
|
517
|
+
}
|
|
518
|
+
case 'authorize-client-success':
|
|
519
|
+
// Create the delegation chain and store it.
|
|
520
|
+
try {
|
|
521
|
+
await this._handleSuccess(message, options?.onSuccess);
|
|
522
|
+
} catch (err) {
|
|
523
|
+
this._handleFailure((err as Error).message, options?.onError);
|
|
524
|
+
}
|
|
525
|
+
break;
|
|
526
|
+
case 'authorize-client-failure':
|
|
527
|
+
this._handleFailure(message.text, options?.onError);
|
|
528
|
+
break;
|
|
529
|
+
default:
|
|
530
|
+
break;
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
private _handleFailure(errorMessage?: string, onError?: (error?: string) => void): void {
|
|
536
|
+
this._idpWindow?.close();
|
|
537
|
+
onError?.(errorMessage);
|
|
538
|
+
this._removeEventListener();
|
|
539
|
+
delete this._idpWindow;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
private _removeEventListener() {
|
|
543
|
+
if (this._eventHandler) {
|
|
544
|
+
window.removeEventListener('message', this._eventHandler);
|
|
545
|
+
}
|
|
546
|
+
this._eventHandler = undefined;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
public async logout(options: { returnTo?: string } = {}): Promise<void> {
|
|
550
|
+
await _deleteStorage(this._storage);
|
|
551
|
+
|
|
552
|
+
// Reset this auth client to a non-authenticated state.
|
|
553
|
+
this._identity = new AnonymousIdentity();
|
|
554
|
+
this._chain = null;
|
|
555
|
+
|
|
556
|
+
if (options.returnTo) {
|
|
557
|
+
try {
|
|
558
|
+
window.history.pushState({}, '', options.returnTo);
|
|
559
|
+
} catch {
|
|
560
|
+
window.location.href = options.returnTo;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
async function _deleteStorage(storage: AuthClientStorage) {
|
|
567
|
+
await storage.remove(KEY_STORAGE_KEY);
|
|
568
|
+
await storage.remove(KEY_STORAGE_DELEGATION);
|
|
569
|
+
await storage.remove(KEY_VECTOR);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function mergeLoginOptions(
|
|
573
|
+
loginOptions: AuthClientLoginOptions | undefined,
|
|
574
|
+
otherLoginOptions: AuthClientLoginOptions | undefined,
|
|
575
|
+
): AuthClientLoginOptions | undefined {
|
|
576
|
+
if (!loginOptions && !otherLoginOptions) {
|
|
577
|
+
return undefined;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const customValues =
|
|
581
|
+
loginOptions?.customValues || otherLoginOptions?.customValues
|
|
582
|
+
? {
|
|
583
|
+
...loginOptions?.customValues,
|
|
584
|
+
...otherLoginOptions?.customValues,
|
|
585
|
+
}
|
|
586
|
+
: undefined;
|
|
587
|
+
|
|
588
|
+
return {
|
|
589
|
+
...loginOptions,
|
|
590
|
+
...otherLoginOptions,
|
|
591
|
+
customValues,
|
|
592
|
+
};
|
|
593
|
+
}
|
package/src/client/db.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { type IDBPDatabase, openDB } from 'idb';
|
|
2
|
+
import { DB_VERSION, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage.ts';
|
|
3
|
+
|
|
4
|
+
type Database = IDBPDatabase<unknown>;
|
|
5
|
+
type IDBValidKey = string | number | Date | BufferSource | IDBValidKey[];
|
|
6
|
+
const AUTH_DB_NAME = 'auth-client-db';
|
|
7
|
+
const OBJECT_STORE_NAME = 'ic-keyval';
|
|
8
|
+
|
|
9
|
+
const _openDbStore = async (
|
|
10
|
+
dbName = AUTH_DB_NAME,
|
|
11
|
+
storeName = OBJECT_STORE_NAME,
|
|
12
|
+
version: number,
|
|
13
|
+
) => {
|
|
14
|
+
// Clear legacy stored delegations
|
|
15
|
+
if (localStorage?.getItem(KEY_STORAGE_DELEGATION)) {
|
|
16
|
+
localStorage.removeItem(KEY_STORAGE_DELEGATION);
|
|
17
|
+
localStorage.removeItem(KEY_STORAGE_KEY);
|
|
18
|
+
}
|
|
19
|
+
return await openDB(dbName, version, {
|
|
20
|
+
upgrade: (database) => {
|
|
21
|
+
if (database.objectStoreNames.contains(storeName)) {
|
|
22
|
+
database.clear(storeName);
|
|
23
|
+
}
|
|
24
|
+
database.createObjectStore(storeName);
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
async function _getValue<T>(
|
|
30
|
+
db: Database,
|
|
31
|
+
storeName: string,
|
|
32
|
+
key: IDBValidKey,
|
|
33
|
+
): Promise<T | undefined> {
|
|
34
|
+
return await db.get(storeName, key);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function _setValue<T>(
|
|
38
|
+
db: Database,
|
|
39
|
+
storeName: string,
|
|
40
|
+
key: IDBValidKey,
|
|
41
|
+
value: T,
|
|
42
|
+
): Promise<IDBValidKey> {
|
|
43
|
+
return await db.put(storeName, value, key);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function _removeValue(db: Database, storeName: string, key: IDBValidKey): Promise<void> {
|
|
47
|
+
return await db.delete(storeName, key);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type DBCreateOptions = {
|
|
51
|
+
dbName?: string;
|
|
52
|
+
storeName?: string;
|
|
53
|
+
version?: number;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Simple Key Value store
|
|
58
|
+
* Defaults to `'auth-client-db'` with an object store of `'ic-keyval'`
|
|
59
|
+
*/
|
|
60
|
+
export class IdbKeyVal {
|
|
61
|
+
/**
|
|
62
|
+
* @param {DBCreateOptions} options - DBCreateOptions
|
|
63
|
+
* @param {DBCreateOptions['dbName']} options.dbName name for the indexeddb database
|
|
64
|
+
* @default
|
|
65
|
+
* @param {DBCreateOptions['storeName']} options.storeName name for the indexeddb Data Store
|
|
66
|
+
* @default
|
|
67
|
+
* @param {DBCreateOptions['version']} options.version version of the database. Increment to safely upgrade
|
|
68
|
+
*/
|
|
69
|
+
public static async create(options?: DBCreateOptions): Promise<IdbKeyVal> {
|
|
70
|
+
const {
|
|
71
|
+
dbName = AUTH_DB_NAME,
|
|
72
|
+
storeName = OBJECT_STORE_NAME,
|
|
73
|
+
version = DB_VERSION,
|
|
74
|
+
} = options ?? {};
|
|
75
|
+
const db = await _openDbStore(dbName, storeName, version);
|
|
76
|
+
return new IdbKeyVal(db, storeName);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Do not use - instead prefer create
|
|
80
|
+
private constructor(
|
|
81
|
+
private _db: Database,
|
|
82
|
+
private _storeName: string,
|
|
83
|
+
) {}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Basic setter
|
|
87
|
+
* @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]
|
|
88
|
+
* @param value value to set
|
|
89
|
+
* @returns void
|
|
90
|
+
*/
|
|
91
|
+
public async set<T>(key: IDBValidKey, value: T) {
|
|
92
|
+
return await _setValue<T>(this._db, this._storeName, key, value);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Basic getter
|
|
96
|
+
* Pass in a type T for type safety if you know the type the value will have if it is found
|
|
97
|
+
* @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]
|
|
98
|
+
* @returns `Promise<T | null>`
|
|
99
|
+
* @example
|
|
100
|
+
* await get<string>('exampleKey') -> 'exampleValue'
|
|
101
|
+
*/
|
|
102
|
+
public async get<T>(key: IDBValidKey): Promise<T | null> {
|
|
103
|
+
return (await _getValue<T>(this._db, this._storeName, key)) ?? null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Remove a key
|
|
108
|
+
* @param key {@link IDBValidKey}
|
|
109
|
+
* @returns void
|
|
110
|
+
*/
|
|
111
|
+
public async remove(key: IDBValidKey) {
|
|
112
|
+
return await _removeValue(this._db, this._storeName, key);
|
|
113
|
+
}
|
|
114
|
+
}
|