@icp-sdk/auth 5.0.0-beta.2 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,25 +40,37 @@ Here's a simple example of how to use the `@icp-sdk/auth` package to authenticat
40
40
  ```typescript
41
41
  import { AuthClient } from '@icp-sdk/auth/client';
42
42
 
43
- const identityProvider = 'https://id.ai/';
43
+ const authClient = new AuthClient();
44
44
 
45
- const authClient = await AuthClient.create();
46
- const identity = authClient.getIdentity(); // At this point, you'll get a Principal.anonymous()
47
-
48
- async function onSuccess() {
49
- console.log('Login successful');
45
+ // Check for an existing session (synchronous)
46
+ if (authClient.isAuthenticated()) {
47
+ const identity = await authClient.getIdentity();
48
+ console.log('Restored session:', identity.getPrincipal().toString());
49
+ }
50
50
 
51
- const identity = authClient.getIdentity(); // At this point, you'll get an authenticated identity
52
- console.log(authClient.isAuthenticated()); // true
51
+ // Log in
52
+ try {
53
+ await authClient.login();
54
+ const identity = await authClient.getIdentity();
55
+ console.log('Logged in:', identity.getPrincipal().toString());
56
+ } catch (error) {
57
+ console.error('Login failed:', error);
53
58
  }
54
59
 
55
- await authClient.login({
56
- identityProvider,
57
- onSuccess,
60
+ // Log out
61
+ await authClient.logout();
62
+ ```
63
+
64
+ ### One-Click OpenID Sign-In
65
+
66
+ Skip the Internet Identity authentication method screen and offer sign-in options like Google directly in your app:
67
+
68
+ ```typescript
69
+ const authClient = new AuthClient({
70
+ openIdProvider: 'google', // or 'apple' or 'microsoft'
58
71
  });
59
72
 
60
- // later in your app
61
- await authClient.logout();
73
+ await authClient.login();
62
74
  ```
63
75
 
64
76
  Additional documentation can be found [here](https://js.icp.build/auth/latest/).
@@ -1,175 +1,145 @@
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';
1
+ import { type Identity, type SignIdentity } from '@icp-sdk/core/agent';
2
+ import { type PartialIdentity } from '@icp-sdk/core/identity';
3
+ import type { Principal } from '@icp-sdk/core/principal';
4
+ import { IdleManager, type IdleManagerOptions } from './idle-manager.js';
5
+ import { type AuthClientStorage } from './storage.js';
6
6
  declare const ECDSA_KEY_LABEL = "ECDSA";
7
7
  declare const ED25519_KEY_LABEL = "Ed25519";
8
8
  type BaseKeyType = typeof ECDSA_KEY_LABEL | typeof ED25519_KEY_LABEL;
9
- export declare const ERROR_USER_INTERRUPT = "UserInterrupt";
9
+ export type OpenIdProvider = 'google' | 'apple' | 'microsoft';
10
10
  /**
11
- * List of options for creating an {@link AuthClient}.
11
+ * Options for creating an {@link AuthClient}.
12
12
  */
13
13
  export interface AuthClientCreateOptions {
14
14
  /**
15
- * An {@link SignIdentity} or {@link PartialIdentity} to authenticate via delegation.
15
+ * An identity to authenticate via delegation.
16
16
  */
17
17
  identity?: SignIdentity | PartialIdentity;
18
18
  /**
19
- * Optional storage with get, set, and remove. Uses {@link IdbStorage} by default.
20
- * @see {@link AuthClientStorage}
19
+ * Persistent storage backend. Defaults to IndexedDB.
20
+ * @default IdbStorage
21
21
  */
22
22
  storage?: AuthClientStorage;
23
23
  /**
24
- * Type to use for the base key.
24
+ * Type of session key to generate on each login.
25
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.
26
+ * Use `'Ed25519'` when your storage provider does not support `CryptoKey`.
28
27
  * @default 'ECDSA'
29
28
  */
30
29
  keyType?: BaseKeyType;
31
30
  /**
32
- * Options to handle idle timeouts
31
+ * Idle timeout configuration.
33
32
  * @default after 10 minutes, invalidates the identity
34
33
  */
35
34
  idleOptions?: IdleOptions;
36
35
  /**
37
- * Options to handle login, passed to the login method
36
+ * Identity provider URL.
37
+ * @default "https://id.ai/authorize"
38
38
  */
39
- loginOptions?: AuthClientLoginOptions;
39
+ identityProvider?: string | URL;
40
+ /**
41
+ * Derivation origin for the identity provider.
42
+ * @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc
43
+ */
44
+ derivationOrigin?: string | URL;
45
+ /**
46
+ * Window features string for the authentication popup.
47
+ * @example "toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100"
48
+ */
49
+ windowOpenerFeatures?: string;
50
+ /**
51
+ * OpenID provider for one-click sign-in. When set, the identity provider
52
+ * URL includes an `openid` search param so the user authenticates via
53
+ * the chosen provider (e.g. Google) instead of seeing Internet Identity directly.
54
+ */
55
+ openIdProvider?: OpenIdProvider;
40
56
  }
41
57
  export interface IdleOptions extends IdleManagerOptions {
42
58
  /**
43
- * Disables idle functionality for {@link IdleManager}
59
+ * Disables idle functionality entirely.
44
60
  * @default false
45
61
  */
46
62
  disableIdle?: boolean;
47
63
  /**
48
- * Disables default idle behavior - call logout & reload window
64
+ * Disables the default idle callback (logout & reload).
49
65
  * @default false
50
66
  */
51
67
  disableDefaultIdleCallback?: boolean;
52
68
  }
53
- export type OnSuccessFunc = (() => void | Promise<void>) | ((message: InternetIdentityAuthResponseSuccess) => void | Promise<void>);
69
+ export type OnSuccessFunc = () => void | Promise<void>;
54
70
  export type OnErrorFunc = (error?: string) => void | Promise<void>;
71
+ /**
72
+ * Options for {@link AuthClient.login}.
73
+ */
55
74
  export interface AuthClientLoginOptions {
56
75
  /**
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
76
+ * Maximum lifetime of the delegation in nanoseconds.
77
+ * @default 8 hours
64
78
  */
65
79
  maxTimeToLive?: bigint;
66
80
  /**
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"
81
+ * Restrict the delegation to specific canisters.
78
82
  */
79
- windowOpenerFeatures?: string;
83
+ targets?: Principal[];
80
84
  /**
81
- * Callback once login has completed
85
+ * Called after a successful login.
82
86
  */
83
87
  onSuccess?: OnSuccessFunc;
84
88
  /**
85
- * Callback in case authentication fails
89
+ * Called when login fails. When provided the error is **not** re-thrown,
90
+ * allowing the caller to handle it via this callback instead.
86
91
  */
87
92
  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
93
  }
106
94
  /**
107
- * Tool to manage authentication and identity
108
- * @see {@link AuthClient}
95
+ * Manages authentication and identity for Internet Computer web apps.
96
+ *
97
+ * @example
98
+ * const authClient = new AuthClient();
99
+ *
100
+ * if (authClient.isAuthenticated()) {
101
+ * const identity = await authClient.getIdentity();
102
+ * }
103
+ *
104
+ * await authClient.login({
105
+ * onSuccess: () => console.log('Logged in!'),
106
+ * });
109
107
  */
110
108
  export declare class AuthClient {
111
- private _identity;
112
- private _key;
113
- private _chain;
114
- private _storage;
109
+ #private;
115
110
  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.
111
+ constructor(options?: AuthClientCreateOptions);
112
+ /**
113
+ * Returns the current identity, restoring a previous session if available.
114
+ */
115
+ getIdentity(): Promise<Identity>;
116
+ /**
117
+ * Checks whether the user has an active, non-expired session.
118
+ */
119
+ isAuthenticated(): boolean;
120
+ /**
121
+ * Opens the identity provider and requests a delegation.
122
+ *
123
+ * @param options - Login options.
124
+ * @param options.maxTimeToLive - Maximum lifetime of the delegation in nanoseconds.
125
+ * @param options.targets - Restrict the delegation to specific canisters.
126
+ * @param options.onSuccess - Called after a successful login.
127
+ * @param options.onError - Called when login fails. When provided the error is not re-thrown.
128
+ * @throws When authentication fails and no `onError` callback is provided.
129
+ *
155
130
  * @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
- * }
131
+ * await authClient.login({
132
+ * onSuccess: () => console.log('Logged in!'),
133
+ * onError: (err) => console.error(err),
167
134
  * });
168
135
  */
169
136
  login(options?: AuthClientLoginOptions): Promise<void>;
170
- private _getEventHandler;
171
- private _handleFailure;
172
- private _removeEventListener;
137
+ /**
138
+ * Clears the stored session and resets the client to an anonymous state.
139
+ *
140
+ * @param options - Logout options.
141
+ * @param options.returnTo - URL to navigate to after logout.
142
+ */
173
143
  logout(options?: {
174
144
  returnTo?: string;
175
145
  }): Promise<void>;