-
Notifications
You must be signed in to change notification settings - Fork 86
/
index.ts
384 lines (330 loc) · 11 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import {
AnonymousIdentity,
DerEncodedPublicKey,
Identity,
Signature,
SignIdentity,
} from '@dfinity/agent';
import { isDelegationValid } from '@dfinity/authentication';
import {
Delegation,
DelegationChain,
DelegationIdentity,
Ed25519KeyIdentity,
} from '@dfinity/identity';
import { Principal } from '@dfinity/principal';
const KEY_LOCALSTORAGE_KEY = 'identity';
const KEY_LOCALSTORAGE_DELEGATION = 'delegation';
const IDENTITY_PROVIDER_DEFAULT = 'https://identity.ic0.app';
const IDENTITY_PROVIDER_ENDPOINT = '#authorize';
const INTERRUPT_CHECK_INTERVAL = 500;
export const ERROR_USER_INTERRUPT = 'UserInterrupt';
/**
* List of options for creating an {@link AuthClient}.
*/
export interface AuthClientCreateOptions {
/**
* An identity to use as the base
*/
identity?: SignIdentity;
/**
* Optional storage with get, set, and remove. Uses LocalStorage by default
*/
storage?: AuthClientStorage;
}
export interface AuthClientLoginOptions {
/**
* Identity provider. By default, use the identity service.
*/
identityProvider?: string | URL;
/**
* Expiration of the authentication in nanoseconds
*/
maxTimeToLive?: bigint;
/**
* Callback once login has completed
*/
onSuccess?: (() => void) | (() => Promise<void>);
/**
* Callback in case authentication fails
*/
onError?: ((error?: string) => void) | ((error?: string) => Promise<void>);
}
/**
* Interface for persisting user authentication data
*/
export interface AuthClientStorage {
get(key: string): Promise<string | null>;
set(key: string, value: string): Promise<void>;
remove(key: string): Promise<void>;
}
interface InternetIdentityAuthRequest {
kind: 'authorize-client';
sessionPublicKey: Uint8Array;
maxTimeToLive?: bigint;
}
interface InternetIdentityAuthResponseSuccess {
kind: 'authorize-client-success';
delegations: {
delegation: {
pubkey: Uint8Array;
expiration: bigint;
targets?: Principal[];
};
signature: Uint8Array;
}[];
userPublicKey: Uint8Array;
}
async function _deleteStorage(storage: AuthClientStorage) {
await storage.remove(KEY_LOCALSTORAGE_KEY);
await storage.remove(KEY_LOCALSTORAGE_DELEGATION);
}
export class LocalStorage implements AuthClientStorage {
constructor(public readonly prefix = 'ic-', private readonly _localStorage?: Storage) {}
public get(key: string): Promise<string | null> {
return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key));
}
public set(key: string, value: string): Promise<void> {
this._getLocalStorage().setItem(this.prefix + key, value);
return Promise.resolve();
}
public remove(key: string): Promise<void> {
this._getLocalStorage().removeItem(this.prefix + key);
return Promise.resolve();
}
private _getLocalStorage() {
if (this._localStorage) {
return this._localStorage;
}
const ls =
typeof window === 'undefined'
? typeof global === 'undefined'
? typeof self === 'undefined'
? undefined
: self.localStorage
: global.localStorage
: window.localStorage;
if (!ls) {
throw new Error('Could not find local storage.');
}
return ls;
}
}
interface AuthReadyMessage {
kind: 'authorize-ready';
}
interface AuthResponseSuccess {
kind: 'authorize-client-success';
delegations: {
delegation: {
pubkey: Uint8Array;
expiration: bigint;
targets?: Principal[];
};
signature: Uint8Array;
}[];
userPublicKey: Uint8Array;
}
interface AuthResponseFailure {
kind: 'authorize-client-failure';
text: string;
}
type IdentityServiceResponseMessage = AuthReadyMessage | AuthResponse;
type AuthResponse = AuthResponseSuccess | AuthResponseFailure;
export class AuthClient {
public static async create(options: AuthClientCreateOptions = {}): Promise<AuthClient> {
const storage = options.storage ?? new LocalStorage('ic-');
let key: null | SignIdentity = null;
if (options.identity) {
key = options.identity;
} else {
const maybeIdentityStorage = await storage.get(KEY_LOCALSTORAGE_KEY);
if (maybeIdentityStorage) {
try {
key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);
} catch (e) {
// Ignore this, this means that the localStorage value isn't a valid Ed25519KeyIdentity
// serialization.
}
}
}
let identity = new AnonymousIdentity();
let chain: null | DelegationChain = null;
if (key) {
try {
const chainStorage = await storage.get(KEY_LOCALSTORAGE_DELEGATION);
if (options.identity) {
identity = options.identity;
} else if (chainStorage) {
chain = DelegationChain.fromJSON(chainStorage);
// Verify that the delegation isn't expired.
if (!isDelegationValid(chain)) {
await _deleteStorage(storage);
key = null;
} else {
identity = DelegationIdentity.fromDelegation(key, chain);
}
}
} catch (e) {
console.error(e);
// If there was a problem loading the chain, delete the key.
await _deleteStorage(storage);
key = null;
}
}
return new this(identity, key, chain, storage);
}
protected constructor(
private _identity: Identity,
private _key: SignIdentity | null,
private _chain: DelegationChain | null,
private _storage: AuthClientStorage,
// A handle on the IdP window.
private _idpWindow?: Window,
// The event handler for processing events from the IdP.
private _eventHandler?: (event: MessageEvent) => void,
) {}
private _handleSuccess(message: InternetIdentityAuthResponseSuccess, onSuccess?: () => void) {
const delegations = message.delegations.map(signedDelegation => {
return {
delegation: new Delegation(
signedDelegation.delegation.pubkey,
signedDelegation.delegation.expiration,
signedDelegation.delegation.targets,
),
signature: signedDelegation.signature.buffer as Signature,
};
});
const delegationChain = DelegationChain.fromDelegations(
delegations,
message.userPublicKey.buffer as DerEncodedPublicKey,
);
const key = this._key;
if (!key) {
return;
}
this._chain = delegationChain;
this._identity = DelegationIdentity.fromDelegation(key, this._chain);
this._idpWindow?.close();
onSuccess?.();
this._removeEventListener();
delete this._idpWindow;
}
public getIdentity(): Identity {
return this._identity;
}
public async isAuthenticated(): Promise<boolean> {
return !this.getIdentity().getPrincipal().isAnonymous() && this._chain !== null;
}
public async login(options?: AuthClientLoginOptions): Promise<void> {
let key = this._key;
if (!key) {
// Create a new key (whether or not one was in storage).
key = Ed25519KeyIdentity.generate();
this._key = key;
await this._storage.set(KEY_LOCALSTORAGE_KEY, JSON.stringify(key));
}
// Set default maxTimeToLive to 1 day
const defaultTimeToLive =
/* days */ BigInt(1) * /* hours */ BigInt(24) * /* nanoseconds */ BigInt(3600000000000);
// Create the URL of the IDP. (e.g. https://XXXX/#authorize)
const identityProviderUrl = new URL(
options?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT,
);
// Set the correct hash if it isn't already set.
identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT;
// If `login` has been called previously, then close/remove any previous windows
// and event listeners.
this._idpWindow?.close();
this._removeEventListener();
// Add an event listener to handle responses.
this._eventHandler = this._getEventHandler(identityProviderUrl, {
maxTimeToLive: defaultTimeToLive,
...options,
});
window.addEventListener('message', this._eventHandler);
// Open a new window with the IDP provider.
this._idpWindow = window.open(identityProviderUrl.toString(), 'idpWindow') ?? undefined;
// Check if the _idpWindow is closed by user.
const checkInterruption = (): void => {
// The _idpWindow is opened and not yet closed by the client
if (this._idpWindow) {
if (this._idpWindow.closed) {
this._handleFailure(ERROR_USER_INTERRUPT, options?.onError);
} else {
setTimeout(checkInterruption, INTERRUPT_CHECK_INTERVAL);
}
}
};
checkInterruption();
}
private _getEventHandler(identityProviderUrl: URL, options?: AuthClientLoginOptions) {
return async (event: MessageEvent) => {
if (event.origin !== identityProviderUrl.origin) {
console.warn(`WARNING: expected origin '${identityProviderUrl.origin}', got '${event.origin}' (ignoring)`);
return;
}
const message = event.data as IdentityServiceResponseMessage;
switch (message.kind) {
case 'authorize-ready': {
// IDP is ready. Send a message to request authorization.
const request: InternetIdentityAuthRequest = {
kind: 'authorize-client',
sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer() as ArrayBuffer),
maxTimeToLive: options?.maxTimeToLive,
};
this._idpWindow?.postMessage(request, identityProviderUrl.origin);
break;
}
case 'authorize-client-success':
// Create the delegation chain and store it.
try {
this._handleSuccess(message, options?.onSuccess);
// Setting the storage is moved out of _handleSuccess to make
// it a sync function. Having _handleSuccess as an async function
// messes up the jest tests for some reason.
if (this._chain) {
await this._storage.set(
KEY_LOCALSTORAGE_DELEGATION,
JSON.stringify(this._chain.toJSON()),
);
}
} catch (err) {
this._handleFailure((err as Error).message, options?.onError);
}
break;
case 'authorize-client-failure':
this._handleFailure(message.text, options?.onError);
break;
default:
break;
}
};
}
private _handleFailure(errorMessage?: string, onError?: (error?: string) => void): void {
this._idpWindow?.close();
onError?.(errorMessage);
this._removeEventListener();
delete this._idpWindow;
}
private _removeEventListener() {
if (this._eventHandler) {
window.removeEventListener('message', this._eventHandler);
}
this._eventHandler = undefined;
}
public async logout(options: { returnTo?: string } = {}): Promise<void> {
_deleteStorage(this._storage);
// Reset this auth client to a non-authenticated state.
this._identity = new AnonymousIdentity();
this._key = null;
this._chain = null;
if (options.returnTo) {
try {
window.history.pushState({}, '', options.returnTo);
} catch (e) {
window.location.href = options.returnTo;
}
}
}
}