@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
package/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# @icp-sdk/auth
|
|
2
|
+
|
|
3
|
+
Authentication library for Internet Computer web apps.
|
|
4
|
+
|
|
5
|
+
## Contributing
|
|
6
|
+
|
|
7
|
+
Contributions are welcome! Please see the [contribution guide](./CONTRIBUTING.md) for more information.
|
|
8
|
+
|
|
9
|
+
## License
|
|
10
|
+
|
|
11
|
+
This project is licensed under the [Apache-2.0](./LICENSE) license.
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { Identity, SignIdentity } from '@icp-sdk/core/agent';
|
|
2
|
+
import { DelegationChain, PartialIdentity } from '@icp-sdk/core/identity';
|
|
3
|
+
import { Principal } from '@icp-sdk/core/principal';
|
|
4
|
+
import { IdleManager, IdleManagerOptions } from './idle-manager.ts';
|
|
5
|
+
import { AuthClientStorage } from './storage.ts';
|
|
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;
|
|
9
|
+
export declare const ERROR_USER_INTERRUPT = "UserInterrupt";
|
|
10
|
+
/**
|
|
11
|
+
* List of options for creating an {@link AuthClient}.
|
|
12
|
+
*/
|
|
13
|
+
export interface AuthClientCreateOptions {
|
|
14
|
+
/**
|
|
15
|
+
* An {@link SignIdentity} or {@link PartialIdentity} to authenticate via delegation.
|
|
16
|
+
*/
|
|
17
|
+
identity?: SignIdentity | PartialIdentity;
|
|
18
|
+
/**
|
|
19
|
+
* Optional storage with get, set, and remove. Uses {@link IdbStorage} by default.
|
|
20
|
+
* @see {@link AuthClientStorage}
|
|
21
|
+
*/
|
|
22
|
+
storage?: AuthClientStorage;
|
|
23
|
+
/**
|
|
24
|
+
* Type to use for the base key.
|
|
25
|
+
*
|
|
26
|
+
* If you are using a custom storage provider that does not support CryptoKey storage,
|
|
27
|
+
* you should use `Ed25519` as the key type, as it can serialize to a string.
|
|
28
|
+
* @default 'ECDSA'
|
|
29
|
+
*/
|
|
30
|
+
keyType?: BaseKeyType;
|
|
31
|
+
/**
|
|
32
|
+
* Options to handle idle timeouts
|
|
33
|
+
* @default after 10 minutes, invalidates the identity
|
|
34
|
+
*/
|
|
35
|
+
idleOptions?: IdleOptions;
|
|
36
|
+
/**
|
|
37
|
+
* Options to handle login, passed to the login method
|
|
38
|
+
*/
|
|
39
|
+
loginOptions?: AuthClientLoginOptions;
|
|
40
|
+
}
|
|
41
|
+
export interface IdleOptions extends IdleManagerOptions {
|
|
42
|
+
/**
|
|
43
|
+
* Disables idle functionality for {@link IdleManager}
|
|
44
|
+
* @default false
|
|
45
|
+
*/
|
|
46
|
+
disableIdle?: boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Disables default idle behavior - call logout & reload window
|
|
49
|
+
* @default false
|
|
50
|
+
*/
|
|
51
|
+
disableDefaultIdleCallback?: boolean;
|
|
52
|
+
}
|
|
53
|
+
export type OnSuccessFunc = (() => void | Promise<void>) | ((message: InternetIdentityAuthResponseSuccess) => void | Promise<void>);
|
|
54
|
+
export type OnErrorFunc = (error?: string) => void | Promise<void>;
|
|
55
|
+
export interface AuthClientLoginOptions {
|
|
56
|
+
/**
|
|
57
|
+
* Identity provider
|
|
58
|
+
* @default "https://identity.internetcomputer.org"
|
|
59
|
+
*/
|
|
60
|
+
identityProvider?: string | URL;
|
|
61
|
+
/**
|
|
62
|
+
* Expiration of the authentication in nanoseconds
|
|
63
|
+
* @default BigInt(8) hours * BigInt(3_600_000_000_000) nanoseconds
|
|
64
|
+
*/
|
|
65
|
+
maxTimeToLive?: bigint;
|
|
66
|
+
/**
|
|
67
|
+
* 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).
|
|
68
|
+
*/
|
|
69
|
+
allowPinAuthentication?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* 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`.
|
|
72
|
+
* @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc
|
|
73
|
+
*/
|
|
74
|
+
derivationOrigin?: string | URL;
|
|
75
|
+
/**
|
|
76
|
+
* Auth Window feature config string
|
|
77
|
+
* @example "toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100"
|
|
78
|
+
*/
|
|
79
|
+
windowOpenerFeatures?: string;
|
|
80
|
+
/**
|
|
81
|
+
* Callback once login has completed
|
|
82
|
+
*/
|
|
83
|
+
onSuccess?: OnSuccessFunc;
|
|
84
|
+
/**
|
|
85
|
+
* Callback in case authentication fails
|
|
86
|
+
*/
|
|
87
|
+
onError?: OnErrorFunc;
|
|
88
|
+
/**
|
|
89
|
+
* Extra values to be passed in the login request during the authorize-ready phase
|
|
90
|
+
*/
|
|
91
|
+
customValues?: Record<string, unknown>;
|
|
92
|
+
}
|
|
93
|
+
export interface InternetIdentityAuthResponseSuccess {
|
|
94
|
+
kind: 'authorize-client-success';
|
|
95
|
+
delegations: {
|
|
96
|
+
delegation: {
|
|
97
|
+
pubkey: Uint8Array;
|
|
98
|
+
expiration: bigint;
|
|
99
|
+
targets?: Principal[];
|
|
100
|
+
};
|
|
101
|
+
signature: Uint8Array;
|
|
102
|
+
}[];
|
|
103
|
+
userPublicKey: Uint8Array;
|
|
104
|
+
authnMethod: 'passkey' | 'pin' | 'recovery';
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Tool to manage authentication and identity
|
|
108
|
+
* @see {@link AuthClient}
|
|
109
|
+
*/
|
|
110
|
+
export declare class AuthClient {
|
|
111
|
+
private _identity;
|
|
112
|
+
private _key;
|
|
113
|
+
private _chain;
|
|
114
|
+
private _storage;
|
|
115
|
+
idleManager: IdleManager | undefined;
|
|
116
|
+
private _createOptions;
|
|
117
|
+
private _idpWindow?;
|
|
118
|
+
private _eventHandler?;
|
|
119
|
+
/**
|
|
120
|
+
* Create an AuthClient to manage authentication and identity
|
|
121
|
+
* @param {AuthClientCreateOptions} options - Options for creating an {@link AuthClient}
|
|
122
|
+
* @see {@link AuthClientCreateOptions}
|
|
123
|
+
* @param options.identity Optional Identity to use as the base
|
|
124
|
+
* @see {@link SignIdentity}
|
|
125
|
+
* @param options.storage Storage mechanism for delegation credentials
|
|
126
|
+
* @see {@link AuthClientStorage}
|
|
127
|
+
* @param options.keyType Type of key to use for the base key
|
|
128
|
+
* @param {IdleOptions} options.idleOptions Configures an {@link IdleManager}
|
|
129
|
+
* @see {@link IdleOptions}
|
|
130
|
+
* 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.
|
|
131
|
+
* @example
|
|
132
|
+
* const authClient = await AuthClient.create({
|
|
133
|
+
* idleOptions: {
|
|
134
|
+
* disableIdle: true
|
|
135
|
+
* }
|
|
136
|
+
* })
|
|
137
|
+
*/
|
|
138
|
+
static create(options?: AuthClientCreateOptions): Promise<AuthClient>;
|
|
139
|
+
protected constructor(_identity: Identity | PartialIdentity, _key: SignIdentity | PartialIdentity, _chain: DelegationChain | null, _storage: AuthClientStorage, idleManager: IdleManager | undefined, _createOptions: AuthClientCreateOptions | undefined, _idpWindow?: Window | undefined, _eventHandler?: ((event: MessageEvent) => void) | undefined);
|
|
140
|
+
private _registerDefaultIdleCallback;
|
|
141
|
+
private _handleSuccess;
|
|
142
|
+
getIdentity(): Identity;
|
|
143
|
+
isAuthenticated(): Promise<boolean>;
|
|
144
|
+
/**
|
|
145
|
+
* AuthClient Login - Opens up a new window to authenticate with Internet Identity
|
|
146
|
+
* @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.
|
|
147
|
+
* @param options.identityProvider Identity provider
|
|
148
|
+
* @param options.maxTimeToLive Expiration of the authentication in nanoseconds
|
|
149
|
+
* @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).
|
|
150
|
+
* @param options.derivationOrigin Origin for Identity Provider to use while generating the delegated identity
|
|
151
|
+
* @param options.windowOpenerFeatures Configures the opened authentication window
|
|
152
|
+
* @param options.onSuccess Callback once login has completed
|
|
153
|
+
* @param options.onError Callback in case authentication fails
|
|
154
|
+
* @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.
|
|
155
|
+
* @example
|
|
156
|
+
* const authClient = await AuthClient.create();
|
|
157
|
+
* authClient.login({
|
|
158
|
+
* identityProvider: 'http://<canisterID>.127.0.0.1:8000',
|
|
159
|
+
* maxTimeToLive: BigInt (7) * BigInt(24) * BigInt(3_600_000_000_000), // 1 week
|
|
160
|
+
* windowOpenerFeatures: "toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100",
|
|
161
|
+
* onSuccess: () => {
|
|
162
|
+
* console.log('Login Successful!');
|
|
163
|
+
* },
|
|
164
|
+
* onError: (error) => {
|
|
165
|
+
* console.error('Login Failed: ', error);
|
|
166
|
+
* }
|
|
167
|
+
* });
|
|
168
|
+
*/
|
|
169
|
+
login(options?: AuthClientLoginOptions): Promise<void>;
|
|
170
|
+
private _getEventHandler;
|
|
171
|
+
private _handleFailure;
|
|
172
|
+
private _removeEventListener;
|
|
173
|
+
logout(options?: {
|
|
174
|
+
returnTo?: string;
|
|
175
|
+
}): Promise<void>;
|
|
176
|
+
}
|
|
177
|
+
export {};
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { AnonymousIdentity } from "@icp-sdk/core/agent";
|
|
2
|
+
import { Ed25519KeyIdentity, ECDSAKeyIdentity, DelegationChain, isDelegationValid, PartialDelegationIdentity, DelegationIdentity, Delegation } from "@icp-sdk/core/identity";
|
|
3
|
+
import { IdleManager } from "./idle-manager.js";
|
|
4
|
+
import { IdbStorage, KEY_STORAGE_KEY, LocalStorage, KEY_STORAGE_DELEGATION, KEY_VECTOR } from "./storage.js";
|
|
5
|
+
const NANOSECONDS_PER_SECOND = BigInt(1e9);
|
|
6
|
+
const SECONDS_PER_HOUR = BigInt(3600);
|
|
7
|
+
const NANOSECONDS_PER_HOUR = NANOSECONDS_PER_SECOND * SECONDS_PER_HOUR;
|
|
8
|
+
const IDENTITY_PROVIDER_DEFAULT = "https://identity.internetcomputer.org";
|
|
9
|
+
const IDENTITY_PROVIDER_ENDPOINT = "#authorize";
|
|
10
|
+
const DEFAULT_MAX_TIME_TO_LIVE = BigInt(8) * NANOSECONDS_PER_HOUR;
|
|
11
|
+
const ECDSA_KEY_LABEL = "ECDSA";
|
|
12
|
+
const ED25519_KEY_LABEL = "Ed25519";
|
|
13
|
+
const INTERRUPT_CHECK_INTERVAL = 500;
|
|
14
|
+
const ERROR_USER_INTERRUPT = "UserInterrupt";
|
|
15
|
+
class AuthClient {
|
|
16
|
+
constructor(_identity, _key, _chain, _storage, idleManager, _createOptions, _idpWindow, _eventHandler) {
|
|
17
|
+
this._identity = _identity;
|
|
18
|
+
this._key = _key;
|
|
19
|
+
this._chain = _chain;
|
|
20
|
+
this._storage = _storage;
|
|
21
|
+
this.idleManager = idleManager;
|
|
22
|
+
this._createOptions = _createOptions;
|
|
23
|
+
this._idpWindow = _idpWindow;
|
|
24
|
+
this._eventHandler = _eventHandler;
|
|
25
|
+
this._registerDefaultIdleCallback();
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Create an AuthClient to manage authentication and identity
|
|
29
|
+
* @param {AuthClientCreateOptions} options - Options for creating an {@link AuthClient}
|
|
30
|
+
* @see {@link AuthClientCreateOptions}
|
|
31
|
+
* @param options.identity Optional Identity to use as the base
|
|
32
|
+
* @see {@link SignIdentity}
|
|
33
|
+
* @param options.storage Storage mechanism for delegation credentials
|
|
34
|
+
* @see {@link AuthClientStorage}
|
|
35
|
+
* @param options.keyType Type of key to use for the base key
|
|
36
|
+
* @param {IdleOptions} options.idleOptions Configures an {@link IdleManager}
|
|
37
|
+
* @see {@link IdleOptions}
|
|
38
|
+
* 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.
|
|
39
|
+
* @example
|
|
40
|
+
* const authClient = await AuthClient.create({
|
|
41
|
+
* idleOptions: {
|
|
42
|
+
* disableIdle: true
|
|
43
|
+
* }
|
|
44
|
+
* })
|
|
45
|
+
*/
|
|
46
|
+
static async create(options = {}) {
|
|
47
|
+
const storage = options.storage ?? new IdbStorage();
|
|
48
|
+
const keyType = options.keyType ?? ECDSA_KEY_LABEL;
|
|
49
|
+
let key = null;
|
|
50
|
+
if (options.identity) {
|
|
51
|
+
key = options.identity;
|
|
52
|
+
} else {
|
|
53
|
+
let maybeIdentityStorage = await storage.get(KEY_STORAGE_KEY);
|
|
54
|
+
if (!maybeIdentityStorage) {
|
|
55
|
+
try {
|
|
56
|
+
const fallbackLocalStorage = new LocalStorage();
|
|
57
|
+
const localChain = await fallbackLocalStorage.get(KEY_STORAGE_DELEGATION);
|
|
58
|
+
const localKey = await fallbackLocalStorage.get(KEY_STORAGE_KEY);
|
|
59
|
+
if (localChain && localKey && keyType === ECDSA_KEY_LABEL) {
|
|
60
|
+
console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB");
|
|
61
|
+
await storage.set(KEY_STORAGE_DELEGATION, localChain);
|
|
62
|
+
await storage.set(KEY_STORAGE_KEY, localKey);
|
|
63
|
+
maybeIdentityStorage = localChain;
|
|
64
|
+
await fallbackLocalStorage.remove(KEY_STORAGE_DELEGATION);
|
|
65
|
+
await fallbackLocalStorage.remove(KEY_STORAGE_KEY);
|
|
66
|
+
}
|
|
67
|
+
} catch (error) {
|
|
68
|
+
console.error(`error while attempting to recover localstorage: ${error}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (maybeIdentityStorage) {
|
|
72
|
+
try {
|
|
73
|
+
if (typeof maybeIdentityStorage === "object") {
|
|
74
|
+
if (keyType === ED25519_KEY_LABEL && typeof maybeIdentityStorage === "string") {
|
|
75
|
+
key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);
|
|
76
|
+
} else {
|
|
77
|
+
key = await ECDSAKeyIdentity.fromKeyPair(maybeIdentityStorage);
|
|
78
|
+
}
|
|
79
|
+
} else if (typeof maybeIdentityStorage === "string") {
|
|
80
|
+
key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);
|
|
81
|
+
}
|
|
82
|
+
} catch {
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
let identity = new AnonymousIdentity();
|
|
87
|
+
let chain = null;
|
|
88
|
+
if (key) {
|
|
89
|
+
try {
|
|
90
|
+
const chainStorage = await storage.get(KEY_STORAGE_DELEGATION);
|
|
91
|
+
if (typeof chainStorage === "object" && chainStorage !== null) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
"Delegation chain is incorrectly stored. A delegation chain should be stored as a string."
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
if (options.identity) {
|
|
97
|
+
identity = options.identity;
|
|
98
|
+
} else if (chainStorage) {
|
|
99
|
+
chain = DelegationChain.fromJSON(chainStorage);
|
|
100
|
+
if (!isDelegationValid(chain)) {
|
|
101
|
+
await _deleteStorage(storage);
|
|
102
|
+
key = null;
|
|
103
|
+
} else {
|
|
104
|
+
if ("toDer" in key) {
|
|
105
|
+
identity = PartialDelegationIdentity.fromDelegation(key, chain);
|
|
106
|
+
} else {
|
|
107
|
+
identity = DelegationIdentity.fromDelegation(key, chain);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
} catch (e) {
|
|
112
|
+
console.error(e);
|
|
113
|
+
await _deleteStorage(storage);
|
|
114
|
+
key = null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
let idleManager;
|
|
118
|
+
if (options.idleOptions?.disableIdle) {
|
|
119
|
+
idleManager = void 0;
|
|
120
|
+
} else if (chain || options.identity) {
|
|
121
|
+
idleManager = IdleManager.create(options.idleOptions);
|
|
122
|
+
}
|
|
123
|
+
if (!key) {
|
|
124
|
+
if (keyType === ED25519_KEY_LABEL) {
|
|
125
|
+
key = Ed25519KeyIdentity.generate();
|
|
126
|
+
await storage.set(KEY_STORAGE_KEY, JSON.stringify(key.toJSON()));
|
|
127
|
+
} else {
|
|
128
|
+
if (options.storage && keyType === ECDSA_KEY_LABEL) {
|
|
129
|
+
console.warn(
|
|
130
|
+
`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`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
key = await ECDSAKeyIdentity.generate();
|
|
134
|
+
await storage.set(KEY_STORAGE_KEY, key.getKeyPair());
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return new AuthClient(identity, key, chain, storage, idleManager, options);
|
|
138
|
+
}
|
|
139
|
+
_registerDefaultIdleCallback() {
|
|
140
|
+
const idleOptions = this._createOptions?.idleOptions;
|
|
141
|
+
if (!idleOptions?.onIdle && !idleOptions?.disableDefaultIdleCallback) {
|
|
142
|
+
this.idleManager?.registerCallback(() => {
|
|
143
|
+
this.logout();
|
|
144
|
+
location.reload();
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async _handleSuccess(message, onSuccess) {
|
|
149
|
+
const delegations = message.delegations.map((signedDelegation) => {
|
|
150
|
+
return {
|
|
151
|
+
delegation: new Delegation(
|
|
152
|
+
signedDelegation.delegation.pubkey,
|
|
153
|
+
signedDelegation.delegation.expiration,
|
|
154
|
+
signedDelegation.delegation.targets
|
|
155
|
+
),
|
|
156
|
+
signature: signedDelegation.signature
|
|
157
|
+
};
|
|
158
|
+
});
|
|
159
|
+
const delegationChain = DelegationChain.fromDelegations(
|
|
160
|
+
delegations,
|
|
161
|
+
message.userPublicKey
|
|
162
|
+
);
|
|
163
|
+
const key = this._key;
|
|
164
|
+
if (!key) {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
this._chain = delegationChain;
|
|
168
|
+
if ("toDer" in key) {
|
|
169
|
+
this._identity = PartialDelegationIdentity.fromDelegation(key, this._chain);
|
|
170
|
+
} else {
|
|
171
|
+
this._identity = DelegationIdentity.fromDelegation(key, this._chain);
|
|
172
|
+
}
|
|
173
|
+
this._idpWindow?.close();
|
|
174
|
+
const idleOptions = this._createOptions?.idleOptions;
|
|
175
|
+
if (!this.idleManager && !idleOptions?.disableIdle) {
|
|
176
|
+
this.idleManager = IdleManager.create(idleOptions);
|
|
177
|
+
this._registerDefaultIdleCallback();
|
|
178
|
+
}
|
|
179
|
+
this._removeEventListener();
|
|
180
|
+
delete this._idpWindow;
|
|
181
|
+
if (this._chain) {
|
|
182
|
+
await this._storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(this._chain.toJSON()));
|
|
183
|
+
}
|
|
184
|
+
onSuccess?.(message);
|
|
185
|
+
}
|
|
186
|
+
getIdentity() {
|
|
187
|
+
return this._identity;
|
|
188
|
+
}
|
|
189
|
+
async isAuthenticated() {
|
|
190
|
+
return !this.getIdentity().getPrincipal().isAnonymous() && this._chain !== null && isDelegationValid(this._chain);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* AuthClient Login - Opens up a new window to authenticate with Internet Identity
|
|
194
|
+
* @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.
|
|
195
|
+
* @param options.identityProvider Identity provider
|
|
196
|
+
* @param options.maxTimeToLive Expiration of the authentication in nanoseconds
|
|
197
|
+
* @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).
|
|
198
|
+
* @param options.derivationOrigin Origin for Identity Provider to use while generating the delegated identity
|
|
199
|
+
* @param options.windowOpenerFeatures Configures the opened authentication window
|
|
200
|
+
* @param options.onSuccess Callback once login has completed
|
|
201
|
+
* @param options.onError Callback in case authentication fails
|
|
202
|
+
* @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.
|
|
203
|
+
* @example
|
|
204
|
+
* const authClient = await AuthClient.create();
|
|
205
|
+
* authClient.login({
|
|
206
|
+
* identityProvider: 'http://<canisterID>.127.0.0.1:8000',
|
|
207
|
+
* maxTimeToLive: BigInt (7) * BigInt(24) * BigInt(3_600_000_000_000), // 1 week
|
|
208
|
+
* windowOpenerFeatures: "toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100",
|
|
209
|
+
* onSuccess: () => {
|
|
210
|
+
* console.log('Login Successful!');
|
|
211
|
+
* },
|
|
212
|
+
* onError: (error) => {
|
|
213
|
+
* console.error('Login Failed: ', error);
|
|
214
|
+
* }
|
|
215
|
+
* });
|
|
216
|
+
*/
|
|
217
|
+
async login(options) {
|
|
218
|
+
const loginOptions = mergeLoginOptions(this._createOptions?.loginOptions, options);
|
|
219
|
+
const maxTimeToLive = loginOptions?.maxTimeToLive ?? DEFAULT_MAX_TIME_TO_LIVE;
|
|
220
|
+
const identityProviderUrl = new URL(
|
|
221
|
+
loginOptions?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT
|
|
222
|
+
);
|
|
223
|
+
identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT;
|
|
224
|
+
this._idpWindow?.close();
|
|
225
|
+
this._removeEventListener();
|
|
226
|
+
this._eventHandler = this._getEventHandler(identityProviderUrl, {
|
|
227
|
+
maxTimeToLive,
|
|
228
|
+
...loginOptions
|
|
229
|
+
});
|
|
230
|
+
window.addEventListener("message", this._eventHandler);
|
|
231
|
+
this._idpWindow = window.open(
|
|
232
|
+
identityProviderUrl.toString(),
|
|
233
|
+
"idpWindow",
|
|
234
|
+
loginOptions?.windowOpenerFeatures
|
|
235
|
+
) ?? void 0;
|
|
236
|
+
const checkInterruption = () => {
|
|
237
|
+
if (this._idpWindow) {
|
|
238
|
+
if (this._idpWindow.closed) {
|
|
239
|
+
this._handleFailure(ERROR_USER_INTERRUPT, loginOptions?.onError);
|
|
240
|
+
} else {
|
|
241
|
+
setTimeout(checkInterruption, INTERRUPT_CHECK_INTERVAL);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
checkInterruption();
|
|
246
|
+
}
|
|
247
|
+
_getEventHandler(identityProviderUrl, options) {
|
|
248
|
+
return async (event) => {
|
|
249
|
+
if (event.origin !== identityProviderUrl.origin) {
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const message = event.data;
|
|
253
|
+
switch (message.kind) {
|
|
254
|
+
case "authorize-ready": {
|
|
255
|
+
const request = {
|
|
256
|
+
kind: "authorize-client",
|
|
257
|
+
sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer()),
|
|
258
|
+
maxTimeToLive: options?.maxTimeToLive,
|
|
259
|
+
allowPinAuthentication: options?.allowPinAuthentication,
|
|
260
|
+
derivationOrigin: options?.derivationOrigin?.toString(),
|
|
261
|
+
// Pass any custom values to the IDP.
|
|
262
|
+
...options?.customValues
|
|
263
|
+
};
|
|
264
|
+
this._idpWindow?.postMessage(request, identityProviderUrl.origin);
|
|
265
|
+
break;
|
|
266
|
+
}
|
|
267
|
+
case "authorize-client-success":
|
|
268
|
+
try {
|
|
269
|
+
await this._handleSuccess(message, options?.onSuccess);
|
|
270
|
+
} catch (err) {
|
|
271
|
+
this._handleFailure(err.message, options?.onError);
|
|
272
|
+
}
|
|
273
|
+
break;
|
|
274
|
+
case "authorize-client-failure":
|
|
275
|
+
this._handleFailure(message.text, options?.onError);
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
_handleFailure(errorMessage, onError) {
|
|
281
|
+
this._idpWindow?.close();
|
|
282
|
+
onError?.(errorMessage);
|
|
283
|
+
this._removeEventListener();
|
|
284
|
+
delete this._idpWindow;
|
|
285
|
+
}
|
|
286
|
+
_removeEventListener() {
|
|
287
|
+
if (this._eventHandler) {
|
|
288
|
+
window.removeEventListener("message", this._eventHandler);
|
|
289
|
+
}
|
|
290
|
+
this._eventHandler = void 0;
|
|
291
|
+
}
|
|
292
|
+
async logout(options = {}) {
|
|
293
|
+
await _deleteStorage(this._storage);
|
|
294
|
+
this._identity = new AnonymousIdentity();
|
|
295
|
+
this._chain = null;
|
|
296
|
+
if (options.returnTo) {
|
|
297
|
+
try {
|
|
298
|
+
window.history.pushState({}, "", options.returnTo);
|
|
299
|
+
} catch {
|
|
300
|
+
window.location.href = options.returnTo;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
async function _deleteStorage(storage) {
|
|
306
|
+
await storage.remove(KEY_STORAGE_KEY);
|
|
307
|
+
await storage.remove(KEY_STORAGE_DELEGATION);
|
|
308
|
+
await storage.remove(KEY_VECTOR);
|
|
309
|
+
}
|
|
310
|
+
function mergeLoginOptions(loginOptions, otherLoginOptions) {
|
|
311
|
+
if (!loginOptions && !otherLoginOptions) {
|
|
312
|
+
return void 0;
|
|
313
|
+
}
|
|
314
|
+
const customValues = loginOptions?.customValues || otherLoginOptions?.customValues ? {
|
|
315
|
+
...loginOptions?.customValues,
|
|
316
|
+
...otherLoginOptions?.customValues
|
|
317
|
+
} : void 0;
|
|
318
|
+
return {
|
|
319
|
+
...loginOptions,
|
|
320
|
+
...otherLoginOptions,
|
|
321
|
+
customValues
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
export {
|
|
325
|
+
AuthClient,
|
|
326
|
+
ERROR_USER_INTERRUPT
|
|
327
|
+
};
|
|
328
|
+
//# sourceMappingURL=auth-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-client.js","sources":["../../../src/client/auth-client.ts"],"sourcesContent":["import {\n AnonymousIdentity,\n type DerEncodedPublicKey,\n type Identity,\n type Signature,\n type SignIdentity,\n} from '@icp-sdk/core/agent';\nimport {\n Delegation,\n DelegationChain,\n DelegationIdentity,\n ECDSAKeyIdentity,\n Ed25519KeyIdentity,\n isDelegationValid,\n PartialDelegationIdentity,\n type PartialIdentity,\n} from '@icp-sdk/core/identity';\nimport type { Principal } from '@icp-sdk/core/principal';\nimport { IdleManager, type IdleManagerOptions } from './idle-manager.ts';\nimport {\n type AuthClientStorage,\n IdbStorage,\n KEY_STORAGE_DELEGATION,\n KEY_STORAGE_KEY,\n KEY_VECTOR,\n LocalStorage,\n} from './storage.ts';\n\nconst NANOSECONDS_PER_SECOND = BigInt(1_000_000_000);\nconst SECONDS_PER_HOUR = BigInt(3_600);\nconst NANOSECONDS_PER_HOUR = NANOSECONDS_PER_SECOND * SECONDS_PER_HOUR;\n\nconst IDENTITY_PROVIDER_DEFAULT = 'https://identity.internetcomputer.org';\nconst IDENTITY_PROVIDER_ENDPOINT = '#authorize';\n\nconst DEFAULT_MAX_TIME_TO_LIVE = BigInt(8) * NANOSECONDS_PER_HOUR;\n\nconst ECDSA_KEY_LABEL = 'ECDSA';\nconst ED25519_KEY_LABEL = 'Ed25519';\ntype BaseKeyType = typeof ECDSA_KEY_LABEL | typeof ED25519_KEY_LABEL;\n\nconst INTERRUPT_CHECK_INTERVAL = 500;\n\nexport const ERROR_USER_INTERRUPT = 'UserInterrupt';\n\n/**\n * List of options for creating an {@link AuthClient}.\n */\nexport interface AuthClientCreateOptions {\n /**\n * An {@link SignIdentity} or {@link PartialIdentity} to authenticate via delegation.\n */\n identity?: SignIdentity | PartialIdentity;\n /**\n * Optional storage with get, set, and remove. Uses {@link IdbStorage} by default.\n * @see {@link AuthClientStorage}\n */\n storage?: AuthClientStorage;\n\n /**\n * Type to use for the base key.\n *\n * If you are using a custom storage provider that does not support CryptoKey storage,\n * you should use `Ed25519` as the key type, as it can serialize to a string.\n * @default 'ECDSA'\n */\n keyType?: BaseKeyType;\n\n /**\n * Options to handle idle timeouts\n * @default after 10 minutes, invalidates the identity\n */\n idleOptions?: IdleOptions;\n\n /**\n * Options to handle login, passed to the login method\n */\n loginOptions?: AuthClientLoginOptions;\n}\n\nexport interface IdleOptions extends IdleManagerOptions {\n /**\n * Disables idle functionality for {@link IdleManager}\n * @default false\n */\n disableIdle?: boolean;\n\n /**\n * Disables default idle behavior - call logout & reload window\n * @default false\n */\n disableDefaultIdleCallback?: boolean;\n}\n\nexport type OnSuccessFunc =\n | (() => void | Promise<void>)\n | ((message: InternetIdentityAuthResponseSuccess) => void | Promise<void>);\n\nexport type OnErrorFunc = (error?: string) => void | Promise<void>;\n\nexport interface AuthClientLoginOptions {\n /**\n * Identity provider\n * @default \"https://identity.internetcomputer.org\"\n */\n identityProvider?: string | URL;\n /**\n * Expiration of the authentication in nanoseconds\n * @default BigInt(8) hours * BigInt(3_600_000_000_000) nanoseconds\n */\n maxTimeToLive?: bigint;\n /**\n * 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).\n */\n allowPinAuthentication?: boolean;\n /**\n * 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`.\n * @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc\n */\n derivationOrigin?: string | URL;\n /**\n * Auth Window feature config string\n * @example \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\"\n */\n windowOpenerFeatures?: string;\n /**\n * Callback once login has completed\n */\n onSuccess?: OnSuccessFunc;\n /**\n * Callback in case authentication fails\n */\n onError?: OnErrorFunc;\n /**\n * Extra values to be passed in the login request during the authorize-ready phase\n */\n customValues?: Record<string, unknown>;\n}\n\ninterface InternetIdentityAuthRequest {\n kind: 'authorize-client';\n sessionPublicKey: Uint8Array;\n maxTimeToLive?: bigint;\n allowPinAuthentication?: boolean;\n derivationOrigin?: string;\n}\n\nexport interface InternetIdentityAuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthReadyMessage {\n kind: 'authorize-ready';\n}\n\ninterface AuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthResponseFailure {\n kind: 'authorize-client-failure';\n text: string;\n}\n\ntype IdentityServiceResponseMessage = AuthReadyMessage | AuthResponse;\ntype AuthResponse = AuthResponseSuccess | AuthResponseFailure;\n\n/**\n * Tool to manage authentication and identity\n * @see {@link AuthClient}\n */\nexport class AuthClient {\n /**\n * Create an AuthClient to manage authentication and identity\n * @param {AuthClientCreateOptions} options - Options for creating an {@link AuthClient}\n * @see {@link AuthClientCreateOptions}\n * @param options.identity Optional Identity to use as the base\n * @see {@link SignIdentity}\n * @param options.storage Storage mechanism for delegation credentials\n * @see {@link AuthClientStorage}\n * @param options.keyType Type of key to use for the base key\n * @param {IdleOptions} options.idleOptions Configures an {@link IdleManager}\n * @see {@link IdleOptions}\n * 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.\n * @example\n * const authClient = await AuthClient.create({\n * idleOptions: {\n * disableIdle: true\n * }\n * })\n */\n public static async create(options: AuthClientCreateOptions = {}): Promise<AuthClient> {\n const storage = options.storage ?? new IdbStorage();\n const keyType = options.keyType ?? ECDSA_KEY_LABEL;\n\n let key: null | SignIdentity | PartialIdentity = null;\n if (options.identity) {\n key = options.identity;\n } else {\n let maybeIdentityStorage = await storage.get(KEY_STORAGE_KEY);\n if (!maybeIdentityStorage) {\n // Attempt to migrate from localstorage\n try {\n const fallbackLocalStorage = new LocalStorage();\n const localChain = await fallbackLocalStorage.get(KEY_STORAGE_DELEGATION);\n const localKey = await fallbackLocalStorage.get(KEY_STORAGE_KEY);\n // not relevant for Ed25519\n if (localChain && localKey && keyType === ECDSA_KEY_LABEL) {\n console.log('Discovered an identity stored in localstorage. Migrating to IndexedDB');\n await storage.set(KEY_STORAGE_DELEGATION, localChain);\n await storage.set(KEY_STORAGE_KEY, localKey);\n\n maybeIdentityStorage = localChain;\n // clean up\n await fallbackLocalStorage.remove(KEY_STORAGE_DELEGATION);\n await fallbackLocalStorage.remove(KEY_STORAGE_KEY);\n }\n } catch (error) {\n console.error(`error while attempting to recover localstorage: ${error}`);\n }\n }\n if (maybeIdentityStorage) {\n try {\n if (typeof maybeIdentityStorage === 'object') {\n if (keyType === ED25519_KEY_LABEL && typeof maybeIdentityStorage === 'string') {\n key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n } else {\n key = await ECDSAKeyIdentity.fromKeyPair(maybeIdentityStorage);\n }\n } else if (typeof maybeIdentityStorage === 'string') {\n // This is a legacy identity, which is a serialized Ed25519KeyIdentity.\n key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n }\n } catch {\n // Ignore this, this means that the localStorage value isn't a valid Ed25519KeyIdentity or ECDSAKeyIdentity\n // serialization.\n }\n }\n }\n\n let identity: SignIdentity | PartialIdentity = new AnonymousIdentity() as PartialIdentity;\n let chain: null | DelegationChain = null;\n if (key) {\n try {\n const chainStorage = await storage.get(KEY_STORAGE_DELEGATION);\n if (typeof chainStorage === 'object' && chainStorage !== null) {\n throw new Error(\n 'Delegation chain is incorrectly stored. A delegation chain should be stored as a string.',\n );\n }\n\n if (options.identity) {\n identity = options.identity;\n } else if (chainStorage) {\n chain = DelegationChain.fromJSON(chainStorage);\n\n // Verify that the delegation isn't expired.\n if (!isDelegationValid(chain)) {\n await _deleteStorage(storage);\n key = null;\n } else {\n // If the key is a public key, then we create a PartialDelegationIdentity.\n if ('toDer' in key) {\n identity = PartialDelegationIdentity.fromDelegation(key, chain);\n // otherwise, we create a DelegationIdentity.\n } else {\n identity = DelegationIdentity.fromDelegation(key, chain);\n }\n }\n }\n } catch (e) {\n console.error(e);\n // If there was a problem loading the chain, delete the key.\n await _deleteStorage(storage);\n key = null;\n }\n }\n let idleManager: IdleManager | undefined;\n if (options.idleOptions?.disableIdle) {\n idleManager = undefined;\n }\n // if there is a delegation chain or provided identity, setup idleManager\n else if (chain || options.identity) {\n idleManager = IdleManager.create(options.idleOptions);\n }\n\n if (!key) {\n // Create a new key (whether or not one was in storage).\n if (keyType === ED25519_KEY_LABEL) {\n key = Ed25519KeyIdentity.generate();\n await storage.set(KEY_STORAGE_KEY, JSON.stringify((key as Ed25519KeyIdentity).toJSON()));\n } else {\n if (options.storage && keyType === ECDSA_KEY_LABEL) {\n console.warn(\n `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`,\n );\n }\n key = await ECDSAKeyIdentity.generate();\n await storage.set(KEY_STORAGE_KEY, (key as ECDSAKeyIdentity).getKeyPair());\n }\n }\n\n return new AuthClient(identity, key, chain, storage, idleManager, options);\n }\n\n protected constructor(\n private _identity: Identity | PartialIdentity,\n private _key: SignIdentity | PartialIdentity,\n private _chain: DelegationChain | null,\n private _storage: AuthClientStorage,\n public idleManager: IdleManager | undefined,\n private _createOptions: AuthClientCreateOptions | undefined,\n // A handle on the IdP window.\n private _idpWindow?: Window,\n // The event handler for processing events from the IdP.\n private _eventHandler?: (event: MessageEvent) => void,\n ) {\n this._registerDefaultIdleCallback();\n }\n\n private _registerDefaultIdleCallback() {\n const idleOptions = this._createOptions?.idleOptions;\n /**\n * Default behavior is to clear stored identity and reload the page.\n * By either setting the disableDefaultIdleCallback flag or passing in a custom idle callback, we will ignore this config\n */\n if (!idleOptions?.onIdle && !idleOptions?.disableDefaultIdleCallback) {\n this.idleManager?.registerCallback(() => {\n this.logout();\n location.reload();\n });\n }\n }\n\n private async _handleSuccess(\n message: InternetIdentityAuthResponseSuccess,\n onSuccess?: OnSuccessFunc,\n ) {\n const delegations = message.delegations.map((signedDelegation) => {\n return {\n delegation: new Delegation(\n signedDelegation.delegation.pubkey,\n signedDelegation.delegation.expiration,\n signedDelegation.delegation.targets,\n ),\n signature: signedDelegation.signature as Signature,\n };\n });\n\n const delegationChain = DelegationChain.fromDelegations(\n delegations,\n message.userPublicKey as DerEncodedPublicKey,\n );\n\n const key = this._key;\n if (!key) {\n return;\n }\n\n this._chain = delegationChain;\n\n if ('toDer' in key) {\n this._identity = PartialDelegationIdentity.fromDelegation(key, this._chain);\n } else {\n this._identity = DelegationIdentity.fromDelegation(key, this._chain);\n }\n\n this._idpWindow?.close();\n const idleOptions = this._createOptions?.idleOptions;\n // create the idle manager on a successful login if we haven't disabled it\n // and it doesn't already exist.\n if (!this.idleManager && !idleOptions?.disableIdle) {\n this.idleManager = IdleManager.create(idleOptions);\n this._registerDefaultIdleCallback();\n }\n\n this._removeEventListener();\n delete this._idpWindow;\n\n if (this._chain) {\n await this._storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(this._chain.toJSON()));\n }\n\n // onSuccess should be the last thing to do to avoid consumers\n // interfering by navigating or refreshing the page\n onSuccess?.(message);\n }\n\n public getIdentity(): Identity {\n return this._identity;\n }\n\n public async isAuthenticated(): Promise<boolean> {\n return (\n !this.getIdentity().getPrincipal().isAnonymous() &&\n this._chain !== null &&\n isDelegationValid(this._chain)\n );\n }\n\n /**\n * AuthClient Login - Opens up a new window to authenticate with Internet Identity\n * @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.\n * @param options.identityProvider Identity provider\n * @param options.maxTimeToLive Expiration of the authentication in nanoseconds\n * @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).\n * @param options.derivationOrigin Origin for Identity Provider to use while generating the delegated identity\n * @param options.windowOpenerFeatures Configures the opened authentication window\n * @param options.onSuccess Callback once login has completed\n * @param options.onError Callback in case authentication fails\n * @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.\n * @example\n * const authClient = await AuthClient.create();\n * authClient.login({\n * identityProvider: 'http://<canisterID>.127.0.0.1:8000',\n * maxTimeToLive: BigInt (7) * BigInt(24) * BigInt(3_600_000_000_000), // 1 week\n * windowOpenerFeatures: \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\",\n * onSuccess: () => {\n * console.log('Login Successful!');\n * },\n * onError: (error) => {\n * console.error('Login Failed: ', error);\n * }\n * });\n */\n public async login(options?: AuthClientLoginOptions): Promise<void> {\n // Merge the passed options with the options set during creation\n const loginOptions = mergeLoginOptions(this._createOptions?.loginOptions, options);\n\n // Set default maxTimeToLive to 8 hours\n const maxTimeToLive = loginOptions?.maxTimeToLive ?? DEFAULT_MAX_TIME_TO_LIVE;\n\n // Create the URL of the IDP. (e.g. https://XXXX/#authorize)\n const identityProviderUrl = new URL(\n loginOptions?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT,\n );\n // Set the correct hash if it isn't already set.\n identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT;\n\n // If `login` has been called previously, then close/remove any previous windows\n // and event listeners.\n this._idpWindow?.close();\n this._removeEventListener();\n\n // Add an event listener to handle responses.\n this._eventHandler = this._getEventHandler(identityProviderUrl, {\n maxTimeToLive,\n ...loginOptions,\n });\n window.addEventListener('message', this._eventHandler);\n\n // Open a new window with the IDP provider.\n this._idpWindow =\n window.open(\n identityProviderUrl.toString(),\n 'idpWindow',\n loginOptions?.windowOpenerFeatures,\n ) ?? undefined;\n\n // Check if the _idpWindow is closed by user.\n const checkInterruption = (): void => {\n // The _idpWindow is opened and not yet closed by the client\n if (this._idpWindow) {\n if (this._idpWindow.closed) {\n this._handleFailure(ERROR_USER_INTERRUPT, loginOptions?.onError);\n } else {\n setTimeout(checkInterruption, INTERRUPT_CHECK_INTERVAL);\n }\n }\n };\n checkInterruption();\n }\n\n private _getEventHandler(identityProviderUrl: URL, options?: AuthClientLoginOptions) {\n return async (event: MessageEvent) => {\n if (event.origin !== identityProviderUrl.origin) {\n // Ignore any event that is not from the identity provider\n return;\n }\n\n const message = event.data as IdentityServiceResponseMessage;\n\n switch (message.kind) {\n case 'authorize-ready': {\n // IDP is ready. Send a message to request authorization.\n const request: InternetIdentityAuthRequest = {\n kind: 'authorize-client',\n sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer()),\n maxTimeToLive: options?.maxTimeToLive,\n allowPinAuthentication: options?.allowPinAuthentication,\n derivationOrigin: options?.derivationOrigin?.toString(),\n // Pass any custom values to the IDP.\n ...options?.customValues,\n };\n this._idpWindow?.postMessage(request, identityProviderUrl.origin);\n break;\n }\n case 'authorize-client-success':\n // Create the delegation chain and store it.\n try {\n await this._handleSuccess(message, options?.onSuccess);\n } catch (err) {\n this._handleFailure((err as Error).message, options?.onError);\n }\n break;\n case 'authorize-client-failure':\n this._handleFailure(message.text, options?.onError);\n break;\n default:\n break;\n }\n };\n }\n\n private _handleFailure(errorMessage?: string, onError?: (error?: string) => void): void {\n this._idpWindow?.close();\n onError?.(errorMessage);\n this._removeEventListener();\n delete this._idpWindow;\n }\n\n private _removeEventListener() {\n if (this._eventHandler) {\n window.removeEventListener('message', this._eventHandler);\n }\n this._eventHandler = undefined;\n }\n\n public async logout(options: { returnTo?: string } = {}): Promise<void> {\n await _deleteStorage(this._storage);\n\n // Reset this auth client to a non-authenticated state.\n this._identity = new AnonymousIdentity();\n this._chain = null;\n\n if (options.returnTo) {\n try {\n window.history.pushState({}, '', options.returnTo);\n } catch {\n window.location.href = options.returnTo;\n }\n }\n }\n}\n\nasync function _deleteStorage(storage: AuthClientStorage) {\n await storage.remove(KEY_STORAGE_KEY);\n await storage.remove(KEY_STORAGE_DELEGATION);\n await storage.remove(KEY_VECTOR);\n}\n\nfunction mergeLoginOptions(\n loginOptions: AuthClientLoginOptions | undefined,\n otherLoginOptions: AuthClientLoginOptions | undefined,\n): AuthClientLoginOptions | undefined {\n if (!loginOptions && !otherLoginOptions) {\n return undefined;\n }\n\n const customValues =\n loginOptions?.customValues || otherLoginOptions?.customValues\n ? {\n ...loginOptions?.customValues,\n ...otherLoginOptions?.customValues,\n }\n : undefined;\n\n return {\n ...loginOptions,\n ...otherLoginOptions,\n customValues,\n };\n}\n"],"names":[],"mappings":";;;;AA4BA,MAAM,yBAAyB,OAAO,GAAa;AACnD,MAAM,mBAAmB,OAAO,IAAK;AACrC,MAAM,uBAAuB,yBAAyB;AAEtD,MAAM,4BAA4B;AAClC,MAAM,6BAA6B;AAEnC,MAAM,2BAA2B,OAAO,CAAC,IAAI;AAE7C,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAG1B,MAAM,2BAA2B;AAE1B,MAAM,uBAAuB;AAoJ7B,MAAM,WAAW;AAAA,EAsIZ,YACA,WACA,MACA,QACA,UACD,aACC,gBAEA,YAEA,eACR;AAVQ,SAAA,YAAA;AACA,SAAA,OAAA;AACA,SAAA,SAAA;AACA,SAAA,WAAA;AACD,SAAA,cAAA;AACC,SAAA,iBAAA;AAEA,SAAA,aAAA;AAEA,SAAA,gBAAA;AAER,SAAK,6BAAA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA/HA,aAAoB,OAAO,UAAmC,IAAyB;AACrF,UAAM,UAAU,QAAQ,WAAW,IAAI,WAAA;AACvC,UAAM,UAAU,QAAQ,WAAW;AAEnC,QAAI,MAA6C;AACjD,QAAI,QAAQ,UAAU;AACpB,YAAM,QAAQ;AAAA,IAChB,OAAO;AACL,UAAI,uBAAuB,MAAM,QAAQ,IAAI,eAAe;AAC5D,UAAI,CAAC,sBAAsB;AAEzB,YAAI;AACF,gBAAM,uBAAuB,IAAI,aAAA;AACjC,gBAAM,aAAa,MAAM,qBAA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AAQ,MAAM,SAAS,OAAO;AAClD;AAAA,MAEA;AAAA,IAEN;AAAA,EACF;AAAA,EAEQ,eAAe,cAAuB,SAA0C;AACtF,SAAK,YAAY,MAAA;AACjB,cAAU,YAAY;AACtB,SAAK,qBAAA;AACL,WAAO,KAAK;AAAA,EACd;AAAA,EAEQ,uBAAuB;AAC7B,QAAI,KAAK,eAAe;AACtB,aAAO,oBAAoB,WAAW,KAAK,aAAa;AAAA,IAC1D;AACA,SAAK,gBAAgB;AAAA,EACvB;AAAA,EAEA,MAAa,OAAO,UAAiC,IAAmB;AACtE,UAAM,eAAe,KAAK,QAAQ;AAGlC,SAAK,YAAY,IAAI,kBAAA;AACrB,SAAK,SAAS;AAEd,QAAI,QAAQ,UAAU;AACpB,UAAI;AACF,eAAO,QAAQ,UAAU,CAAA,GAAI,IAAI,QAAQ,QAAQ;AAAA,MACnD,QAAQ;AACN,eAAO,SAAS,OAAO,QAAQ;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAe,eAAe,SAA4B;AACxD,QAAM,QAAQ,OAAO,eAAe;AACpC,QAAM,QAAQ,OAAO,sBAAsB;AAC3C,QAAM,QAAQ,OAAO,UAAU;AACjC;AAEA,SAAS,kBACP,cACA,mBACoC;AACpC,MAAI,CAAC,gBAAgB,CAAC,mBAAmB;AACvC,WAAO;AAAA,EACT;AAEA,QAAM,eACJ,cAAc,gBAAgB,mBAAmB,eAC7C;AAAA,IACE,GAAG,cAAc;AAAA,IACjB,GAAG,mBAAmB;AAAA,EAAA,IAExB;AAEN,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
type IDBValidKey = string | number | Date | BufferSource | IDBValidKey[];
|
|
2
|
+
export type DBCreateOptions = {
|
|
3
|
+
dbName?: string;
|
|
4
|
+
storeName?: string;
|
|
5
|
+
version?: number;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Simple Key Value store
|
|
9
|
+
* Defaults to `'auth-client-db'` with an object store of `'ic-keyval'`
|
|
10
|
+
*/
|
|
11
|
+
export declare class IdbKeyVal {
|
|
12
|
+
private _db;
|
|
13
|
+
private _storeName;
|
|
14
|
+
/**
|
|
15
|
+
* @param {DBCreateOptions} options - DBCreateOptions
|
|
16
|
+
* @param {DBCreateOptions['dbName']} options.dbName name for the indexeddb database
|
|
17
|
+
* @default
|
|
18
|
+
* @param {DBCreateOptions['storeName']} options.storeName name for the indexeddb Data Store
|
|
19
|
+
* @default
|
|
20
|
+
* @param {DBCreateOptions['version']} options.version version of the database. Increment to safely upgrade
|
|
21
|
+
*/
|
|
22
|
+
static create(options?: DBCreateOptions): Promise<IdbKeyVal>;
|
|
23
|
+
private constructor();
|
|
24
|
+
/**
|
|
25
|
+
* Basic setter
|
|
26
|
+
* @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]
|
|
27
|
+
* @param value value to set
|
|
28
|
+
* @returns void
|
|
29
|
+
*/
|
|
30
|
+
set<T>(key: IDBValidKey, value: T): Promise<IDBValidKey>;
|
|
31
|
+
/**
|
|
32
|
+
* Basic getter
|
|
33
|
+
* Pass in a type T for type safety if you know the type the value will have if it is found
|
|
34
|
+
* @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]
|
|
35
|
+
* @returns `Promise<T | null>`
|
|
36
|
+
* @example
|
|
37
|
+
* await get<string>('exampleKey') -> 'exampleValue'
|
|
38
|
+
*/
|
|
39
|
+
get<T>(key: IDBValidKey): Promise<T | null>;
|
|
40
|
+
/**
|
|
41
|
+
* Remove a key
|
|
42
|
+
* @param key {@link IDBValidKey}
|
|
43
|
+
* @returns void
|
|
44
|
+
*/
|
|
45
|
+
remove(key: IDBValidKey): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
export {};
|