@account-kit/signer 4.16.1-alpha.3 → 4.18.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/esm/base.d.ts +16 -32
  2. package/dist/esm/base.js +127 -122
  3. package/dist/esm/base.js.map +1 -1
  4. package/dist/esm/client/base.d.ts +3 -36
  5. package/dist/esm/client/base.js +15 -20
  6. package/dist/esm/client/base.js.map +1 -1
  7. package/dist/esm/client/index.d.ts +27 -40
  8. package/dist/esm/client/index.js +41 -164
  9. package/dist/esm/client/index.js.map +1 -1
  10. package/dist/esm/client/types.d.ts +27 -65
  11. package/dist/esm/client/types.js.map +1 -1
  12. package/dist/esm/errors.d.ts +0 -6
  13. package/dist/esm/errors.js +0 -18
  14. package/dist/esm/errors.js.map +1 -1
  15. package/dist/esm/index.d.ts +1 -1
  16. package/dist/esm/index.js +1 -1
  17. package/dist/esm/index.js.map +1 -1
  18. package/dist/esm/metrics.d.ts +3 -0
  19. package/dist/esm/metrics.js.map +1 -1
  20. package/dist/esm/oauth.d.ts +5 -4
  21. package/dist/esm/oauth.js +16 -6
  22. package/dist/esm/oauth.js.map +1 -1
  23. package/dist/esm/session/manager.d.ts +0 -1
  24. package/dist/esm/session/manager.js +4 -0
  25. package/dist/esm/session/manager.js.map +1 -1
  26. package/dist/esm/session/types.d.ts +1 -1
  27. package/dist/esm/session/types.js.map +1 -1
  28. package/dist/esm/signer.d.ts +8 -5
  29. package/dist/esm/signer.js.map +1 -1
  30. package/dist/esm/types.d.ts +2 -9
  31. package/dist/esm/types.js +1 -5
  32. package/dist/esm/types.js.map +1 -1
  33. package/dist/esm/version.d.ts +1 -1
  34. package/dist/esm/version.js +1 -1
  35. package/dist/esm/version.js.map +1 -1
  36. package/dist/types/base.d.ts +16 -32
  37. package/dist/types/base.d.ts.map +1 -1
  38. package/dist/types/client/base.d.ts +3 -36
  39. package/dist/types/client/base.d.ts.map +1 -1
  40. package/dist/types/client/index.d.ts +27 -40
  41. package/dist/types/client/index.d.ts.map +1 -1
  42. package/dist/types/client/types.d.ts +27 -65
  43. package/dist/types/client/types.d.ts.map +1 -1
  44. package/dist/types/errors.d.ts +0 -6
  45. package/dist/types/errors.d.ts.map +1 -1
  46. package/dist/types/index.d.ts +1 -1
  47. package/dist/types/index.d.ts.map +1 -1
  48. package/dist/types/metrics.d.ts +3 -0
  49. package/dist/types/metrics.d.ts.map +1 -1
  50. package/dist/types/oauth.d.ts +5 -4
  51. package/dist/types/oauth.d.ts.map +1 -1
  52. package/dist/types/session/manager.d.ts +0 -1
  53. package/dist/types/session/manager.d.ts.map +1 -1
  54. package/dist/types/session/types.d.ts +1 -1
  55. package/dist/types/session/types.d.ts.map +1 -1
  56. package/dist/types/signer.d.ts +8 -5
  57. package/dist/types/signer.d.ts.map +1 -1
  58. package/dist/types/types.d.ts +2 -9
  59. package/dist/types/types.d.ts.map +1 -1
  60. package/dist/types/version.d.ts +1 -1
  61. package/package.json +4 -4
  62. package/src/base.ts +120 -166
  63. package/src/client/base.ts +26 -65
  64. package/src/client/index.ts +46 -174
  65. package/src/client/types.ts +31 -75
  66. package/src/errors.ts +1 -11
  67. package/src/index.ts +1 -5
  68. package/src/metrics.ts +2 -1
  69. package/src/oauth.ts +22 -8
  70. package/src/session/manager.ts +8 -7
  71. package/src/session/types.ts +1 -1
  72. package/src/signer.ts +13 -7
  73. package/src/types.ts +1 -9
  74. package/src/version.ts +1 -1
  75. package/dist/esm/utils/parseMfaError.d.ts +0 -2
  76. package/dist/esm/utils/parseMfaError.js +0 -15
  77. package/dist/esm/utils/parseMfaError.js.map +0 -1
  78. package/dist/types/utils/parseMfaError.d.ts +0 -3
  79. package/dist/types/utils/parseMfaError.d.ts.map +0 -1
  80. package/src/utils/parseMfaError.ts +0 -15
@@ -22,6 +22,7 @@ export type ExportWalletParams = {
22
22
  export type CreateAccountParams = {
23
23
  type: "email";
24
24
  email: string;
25
+ /** @deprecated This option will be overriden by dashboard settings. Please use the dashboard settings instead. This option will be removed in a future release. */
25
26
  emailMode?: EmailType;
26
27
  expirationSeconds?: number;
27
28
  redirectParams?: URLSearchParams;
@@ -37,11 +38,11 @@ export type CreateAccountParams = {
37
38
  export type EmailType = "magicLink" | "otp";
38
39
  export type EmailAuthParams = {
39
40
  email: string;
41
+ /** @deprecated This option will be overriden by dashboard settings. Please use the dashboard settings instead. This option will be removed in a future release. */
40
42
  emailMode?: EmailType;
41
43
  expirationSeconds?: number;
42
44
  targetPublicKey: string;
43
45
  redirectParams?: URLSearchParams;
44
- multiFactors?: VerifyMfaParams[];
45
46
  };
46
47
  export type OauthParams = Extract<AuthParams, {
47
48
  type: "oauth";
@@ -54,7 +55,16 @@ export type OtpParams = {
54
55
  otpCode: string;
55
56
  targetPublicKey: string;
56
57
  expirationSeconds?: number;
57
- multiFactors?: VerifyMfaParams[];
58
+ };
59
+ export type JwtParams = {
60
+ jwt: string;
61
+ targetPublicKey: string;
62
+ authProvider: string;
63
+ };
64
+ export type JwtResponse = {
65
+ isSignUp: boolean;
66
+ orgId: string;
67
+ credentialBundle: string;
58
68
  };
59
69
  export type SignupResponse = {
60
70
  orgId: string;
@@ -67,6 +77,12 @@ export type OauthConfig = {
67
77
  requestKey: string;
68
78
  authProviders: AuthProviderConfig[];
69
79
  };
80
+ export type EmailConfig = {
81
+ mode?: "MAGIC_LINK" | "OTP";
82
+ };
83
+ export type SignerConfig = {
84
+ email: EmailConfig;
85
+ };
70
86
  export type AuthProviderConfig = {
71
87
  id: string;
72
88
  isCustomProvider?: boolean;
@@ -104,12 +120,10 @@ export type SignerEndpoints = [
104
120
  Route: "/v1/auth";
105
121
  Body: Omit<EmailAuthParams, "redirectParams"> & {
106
122
  redirectParams?: string;
107
- multiFactors?: VerifyMfaParams[];
108
123
  };
109
124
  Response: {
110
125
  orgId: string;
111
126
  otpId?: string;
112
- multiFactors?: MfaFactor[];
113
127
  };
114
128
  },
115
129
  {
@@ -141,48 +155,22 @@ export type SignerEndpoints = [
141
155
  Route: "/v1/otp";
142
156
  Body: OtpParams;
143
157
  Response: {
144
- credentialBundle: string | null;
158
+ credentialBundle: string;
145
159
  };
146
160
  },
147
161
  {
148
- Route: "/v1/auth-list-multi-factors";
149
- Body: {
150
- stampedRequest: TSignedRequest;
151
- };
152
- Response: {
153
- multiFactors: MfaFactor[];
154
- };
162
+ Route: "/v1/auth-jwt";
163
+ Body: JwtParams;
164
+ Response: JwtResponse;
155
165
  },
156
166
  {
157
- Route: "/v1/auth-delete-multi-factors";
158
- Body: {
159
- stampedRequest: TSignedRequest;
160
- multiFactorIds: string[];
161
- };
162
- Response: {
163
- multiFactors: MfaFactor[];
164
- };
165
- },
166
- {
167
- Route: "/v1/auth-request-multi-factor";
168
- Body: {
169
- stampedRequest: TSignedRequest;
170
- multiFactorType: MultiFactorType;
171
- };
172
- Response: EnableMfaResult;
173
- },
174
- {
175
- Route: "/v1/auth-verify-multi-factor";
176
- Body: VerifyMfaParams & {
177
- stampedRequest: TSignedRequest;
178
- };
179
- Response: {
180
- multiFactors: MfaFactor[];
181
- };
167
+ Route: "/v1/signer-config";
168
+ Body: {};
169
+ Response: SignerConfig;
182
170
  }
183
171
  ];
184
172
  export type AuthenticatingEventMetadata = {
185
- type: "email" | "passkey" | "oauth" | "otp" | "otpVerify";
173
+ type: "email" | "passkey" | "oauth" | "otp" | "otpVerify" | "custom-jwt";
186
174
  };
187
175
  export type AlchemySignerClientEvents = {
188
176
  connected(user: User): void;
@@ -192,6 +180,7 @@ export type AlchemySignerClientEvents = {
192
180
  connectedPasskey(user: User): void;
193
181
  connectedOauth(user: User, bundle: string): void;
194
182
  connectedOtp(user: User, bundle: string): void;
183
+ connectedJwt(user: User, bundle: string): void;
195
184
  disconnected(): void;
196
185
  };
197
186
  export type AlchemySignerClientEvent = keyof AlchemySignerClientEvents;
@@ -216,30 +205,3 @@ export type GetOauthProviderUrlArgs = {
216
205
  oauthConfig?: OauthConfig;
217
206
  usesRelativeUrl?: boolean;
218
207
  };
219
- export type MfaFactor = {
220
- multiFactorId: string;
221
- multiFactorType: string;
222
- };
223
- type MultiFactorType = "totp";
224
- export type EnableMfaParams = {
225
- multiFactorType: MultiFactorType;
226
- };
227
- export type EnableMfaResult = {
228
- multiFactorType: MultiFactorType;
229
- multiFactorId: string;
230
- multiFactorTotpUrl: string;
231
- };
232
- export type VerifyMfaParams = {
233
- multiFactorId: string;
234
- multiFactorCode: string;
235
- };
236
- export type RemoveMfaParams = {
237
- multiFactorIds: string[];
238
- };
239
- export type MfaChallenge = {
240
- multiFactorId: string;
241
- multiFactorChallenge: {
242
- code: string;
243
- } | Record<string, any>;
244
- };
245
- export {};
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/client/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Address } from \"@aa-sdk/core\";\nimport type { TSignedRequest, getWebAuthnAttestation } from \"@turnkey/http\";\nimport type { Hex } from \"viem\";\nimport type { AuthParams } from \"../signer\";\n\nexport type CredentialCreationOptionOverrides = {\n publicKey?: Partial<CredentialCreationOptions[\"publicKey\"]>;\n} & Pick<CredentialCreationOptions, \"signal\">;\n\n// [!region User]\nexport type User = {\n email?: string;\n orgId: string;\n userId: string;\n address: Address;\n solanaAddress?: string;\n credentialId?: string;\n idToken?: string;\n claims?: Record<string, unknown>;\n};\n// [!endregion User]\n\nexport type ExportWalletParams = {\n iframeContainerId: string;\n iframeElementId?: string;\n};\n\nexport type CreateAccountParams =\n | {\n type: \"email\";\n email: string;\n emailMode?: EmailType;\n expirationSeconds?: number;\n redirectParams?: URLSearchParams;\n }\n | {\n type: \"passkey\";\n email: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | {\n type: \"passkey\";\n username: string;\n creationOpts?: CredentialCreationOptionOverrides;\n };\n\nexport type EmailType = \"magicLink\" | \"otp\";\n\nexport type EmailAuthParams = {\n email: string;\n emailMode?: EmailType;\n expirationSeconds?: number;\n targetPublicKey: string;\n redirectParams?: URLSearchParams;\n multiFactors?: VerifyMfaParams[];\n};\n\nexport type OauthParams = Extract<AuthParams, { type: \"oauth\" }> & {\n expirationSeconds?: number;\n};\n\nexport type OtpParams = {\n orgId: string;\n otpId: string;\n otpCode: string;\n targetPublicKey: string;\n expirationSeconds?: number;\n multiFactors?: VerifyMfaParams[];\n};\n\nexport type SignupResponse = {\n orgId: string;\n userId?: string;\n address?: Address;\n otpId?: string;\n};\n\nexport type OauthConfig = {\n codeChallenge: string;\n requestKey: string;\n authProviders: AuthProviderConfig[];\n};\n\nexport type AuthProviderConfig = {\n id: string;\n isCustomProvider?: boolean;\n clientId: string;\n authEndpoint: string;\n};\n\nexport type SignerRoutes = SignerEndpoints[number][\"Route\"];\nexport type SignerBody<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Body\"];\nexport type SignerResponse<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Response\"];\n\nexport type SignerEndpoints = [\n {\n Route: \"/v1/signup\";\n Body:\n | (Omit<EmailAuthParams, \"redirectParams\"> & {\n redirectParams?: string;\n })\n | {\n passkey: {\n challenge: string;\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n };\n };\n Response: SignupResponse;\n },\n {\n Route: \"/v1/whoami\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: User;\n },\n {\n Route: \"/v1/auth\";\n Body: Omit<EmailAuthParams, \"redirectParams\"> & {\n redirectParams?: string;\n multiFactors?: VerifyMfaParams[];\n };\n Response: {\n orgId: string;\n otpId?: string;\n multiFactors?: MfaFactor[];\n };\n },\n {\n Route: \"/v1/lookup\";\n Body: {\n email: string;\n };\n Response: {\n orgId: string | null;\n };\n },\n {\n Route: \"/v1/sign-payload\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: {\n signature: Hex;\n };\n },\n {\n Route: \"/v1/prepare-oauth\";\n Body: {\n nonce: string;\n };\n Response: OauthConfig;\n },\n {\n Route: \"/v1/otp\";\n Body: OtpParams;\n Response: {\n credentialBundle: string | null;\n };\n },\n {\n Route: \"/v1/auth-list-multi-factors\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: {\n multiFactors: MfaFactor[];\n };\n },\n {\n Route: \"/v1/auth-delete-multi-factors\";\n Body: {\n stampedRequest: TSignedRequest;\n multiFactorIds: string[];\n };\n Response: {\n multiFactors: MfaFactor[];\n };\n },\n {\n Route: \"/v1/auth-request-multi-factor\";\n Body: {\n stampedRequest: TSignedRequest;\n multiFactorType: MultiFactorType;\n };\n Response: EnableMfaResult;\n },\n {\n Route: \"/v1/auth-verify-multi-factor\";\n Body: VerifyMfaParams & {\n stampedRequest: TSignedRequest;\n };\n Response: {\n multiFactors: MfaFactor[];\n };\n }\n];\n\nexport type AuthenticatingEventMetadata = {\n type: \"email\" | \"passkey\" | \"oauth\" | \"otp\" | \"otpVerify\";\n};\n\nexport type AlchemySignerClientEvents = {\n connected(user: User): void;\n newUserSignup(): void;\n authenticating(data: AuthenticatingEventMetadata): void;\n connectedEmail(user: User, bundle: string): void;\n connectedPasskey(user: User): void;\n connectedOauth(user: User, bundle: string): void;\n connectedOtp(user: User, bundle: string): void;\n disconnected(): void;\n};\n\nexport type AlchemySignerClientEvent = keyof AlchemySignerClientEvents;\n\nexport type GetWebAuthnAttestationResult = {\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n challenge: ArrayBuffer;\n authenticatorUserId: ArrayBuffer;\n};\n\nexport type OauthState = {\n authProviderId: string;\n isCustomProvider?: boolean;\n requestKey: string;\n turnkeyPublicKey: string;\n expirationSeconds?: number;\n redirectUrl?: string;\n openerOrigin?: string;\n};\n\nexport type GetOauthProviderUrlArgs = {\n oauthParams: OauthParams;\n turnkeyPublicKey: string;\n oauthCallbackUrl: string;\n oauthConfig?: OauthConfig;\n usesRelativeUrl?: boolean;\n};\n\nexport type MfaFactor = {\n multiFactorId: string;\n multiFactorType: string;\n};\n\ntype MultiFactorType = \"totp\";\n\nexport type EnableMfaParams = {\n multiFactorType: MultiFactorType;\n};\n\nexport type EnableMfaResult = {\n multiFactorType: MultiFactorType;\n multiFactorId: string;\n multiFactorTotpUrl: string;\n};\n\nexport type VerifyMfaParams = {\n multiFactorId: string;\n multiFactorCode: string;\n};\n\nexport type RemoveMfaParams = {\n multiFactorIds: string[];\n};\n\nexport type MfaChallenge = {\n multiFactorId: string;\n multiFactorChallenge:\n | {\n code: string;\n }\n | Record<string, any>;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/client/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Address } from \"@aa-sdk/core\";\nimport type { TSignedRequest, getWebAuthnAttestation } from \"@turnkey/http\";\nimport type { Hex } from \"viem\";\nimport type { AuthParams } from \"../signer\";\n\nexport type CredentialCreationOptionOverrides = {\n publicKey?: Partial<CredentialCreationOptions[\"publicKey\"]>;\n} & Pick<CredentialCreationOptions, \"signal\">;\n\n// [!region User]\nexport type User = {\n email?: string;\n orgId: string;\n userId: string;\n address: Address;\n solanaAddress?: string;\n credentialId?: string;\n idToken?: string;\n claims?: Record<string, unknown>;\n};\n// [!endregion User]\n\nexport type ExportWalletParams = {\n iframeContainerId: string;\n iframeElementId?: string;\n};\n\nexport type CreateAccountParams =\n | {\n type: \"email\";\n email: string;\n /** @deprecated This option will be overriden by dashboard settings. Please use the dashboard settings instead. This option will be removed in a future release. */\n emailMode?: EmailType;\n expirationSeconds?: number;\n redirectParams?: URLSearchParams;\n }\n | {\n type: \"passkey\";\n email: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | {\n type: \"passkey\";\n username: string;\n creationOpts?: CredentialCreationOptionOverrides;\n };\n\nexport type EmailType = \"magicLink\" | \"otp\";\n\nexport type EmailAuthParams = {\n email: string;\n /** @deprecated This option will be overriden by dashboard settings. Please use the dashboard settings instead. This option will be removed in a future release. */\n emailMode?: EmailType;\n expirationSeconds?: number;\n targetPublicKey: string;\n redirectParams?: URLSearchParams;\n};\n\nexport type OauthParams = Extract<AuthParams, { type: \"oauth\" }> & {\n expirationSeconds?: number;\n};\n\nexport type OtpParams = {\n orgId: string;\n otpId: string;\n otpCode: string;\n targetPublicKey: string;\n expirationSeconds?: number;\n};\n\nexport type JwtParams = {\n jwt: string;\n targetPublicKey: string;\n authProvider: string;\n};\n\nexport type JwtResponse = {\n isSignUp: boolean;\n orgId: string;\n credentialBundle: string;\n};\n\nexport type SignupResponse = {\n orgId: string;\n userId?: string;\n address?: Address;\n otpId?: string;\n};\n\nexport type OauthConfig = {\n codeChallenge: string;\n requestKey: string;\n authProviders: AuthProviderConfig[];\n};\n\nexport type EmailConfig = {\n mode?: \"MAGIC_LINK\" | \"OTP\";\n};\n\nexport type SignerConfig = {\n email: EmailConfig;\n};\n\nexport type AuthProviderConfig = {\n id: string;\n isCustomProvider?: boolean;\n clientId: string;\n authEndpoint: string;\n};\n\nexport type SignerRoutes = SignerEndpoints[number][\"Route\"];\nexport type SignerBody<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Body\"];\nexport type SignerResponse<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Response\"];\n\nexport type SignerEndpoints = [\n {\n Route: \"/v1/signup\";\n Body:\n | (Omit<EmailAuthParams, \"redirectParams\"> & {\n redirectParams?: string;\n })\n | {\n passkey: {\n challenge: string;\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n };\n };\n Response: SignupResponse;\n },\n {\n Route: \"/v1/whoami\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: User;\n },\n {\n Route: \"/v1/auth\";\n Body: Omit<EmailAuthParams, \"redirectParams\"> & {\n redirectParams?: string;\n };\n Response: {\n orgId: string;\n otpId?: string;\n };\n },\n {\n Route: \"/v1/lookup\";\n Body: {\n email: string;\n };\n Response: {\n orgId: string | null;\n };\n },\n {\n Route: \"/v1/sign-payload\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: {\n signature: Hex;\n };\n },\n {\n Route: \"/v1/prepare-oauth\";\n Body: {\n nonce: string;\n };\n Response: OauthConfig;\n },\n {\n Route: \"/v1/otp\";\n Body: OtpParams;\n Response: { credentialBundle: string };\n },\n {\n Route: \"/v1/auth-jwt\";\n Body: JwtParams;\n Response: JwtResponse;\n },\n {\n Route: \"/v1/signer-config\";\n Body: {};\n Response: SignerConfig;\n }\n];\n\nexport type AuthenticatingEventMetadata = {\n type: \"email\" | \"passkey\" | \"oauth\" | \"otp\" | \"otpVerify\" | \"custom-jwt\";\n};\n\nexport type AlchemySignerClientEvents = {\n connected(user: User): void;\n newUserSignup(): void;\n authenticating(data: AuthenticatingEventMetadata): void;\n connectedEmail(user: User, bundle: string): void;\n connectedPasskey(user: User): void;\n connectedOauth(user: User, bundle: string): void;\n connectedOtp(user: User, bundle: string): void;\n connectedJwt(user: User, bundle: string): void;\n disconnected(): void;\n};\n\nexport type AlchemySignerClientEvent = keyof AlchemySignerClientEvents;\n\nexport type GetWebAuthnAttestationResult = {\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n challenge: ArrayBuffer;\n authenticatorUserId: ArrayBuffer;\n};\n\nexport type OauthState = {\n authProviderId: string;\n isCustomProvider?: boolean;\n requestKey: string;\n turnkeyPublicKey: string;\n expirationSeconds?: number;\n redirectUrl?: string;\n openerOrigin?: string;\n};\n\nexport type GetOauthProviderUrlArgs = {\n oauthParams: OauthParams;\n turnkeyPublicKey: string;\n oauthCallbackUrl: string;\n oauthConfig?: OauthConfig;\n usesRelativeUrl?: boolean;\n};\n"]}
@@ -1,5 +1,4 @@
1
1
  import { BaseError } from "@aa-sdk/core";
2
- import type { MfaFactor } from "./client/types";
3
2
  export declare class NotAuthenticatedError extends BaseError {
4
3
  name: string;
5
4
  constructor();
@@ -8,8 +7,3 @@ export declare class OAuthProvidersError extends BaseError {
8
7
  name: string;
9
8
  constructor();
10
9
  }
11
- export declare class MfaRequiredError extends BaseError {
12
- name: string;
13
- multiFactors: MfaFactor[];
14
- constructor(multiFactors: MfaFactor[]);
15
- }
@@ -28,22 +28,4 @@ export class OAuthProvidersError extends BaseError {
28
28
  });
29
29
  }
30
30
  }
31
- export class MfaRequiredError extends BaseError {
32
- constructor(multiFactors) {
33
- super("MFA is required for this user");
34
- Object.defineProperty(this, "name", {
35
- enumerable: true,
36
- configurable: true,
37
- writable: true,
38
- value: "MfaRequiredError"
39
- });
40
- Object.defineProperty(this, "multiFactors", {
41
- enumerable: true,
42
- configurable: true,
43
- writable: true,
44
- value: void 0
45
- });
46
- this.multiFactors = multiFactors;
47
- }
48
- }
49
31
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,MAAM,OAAO,qBAAsB,SAAQ,SAAS;IAElD;QACE,KAAK,CACH;YACE,0BAA0B;YAC1B,wCAAwC;SACzC,CAAC,IAAI,CAAC,IAAI,CAAC,EACZ;YACE,QAAQ,EAAE,2CAA2C;SACtD,CACF,CAAC;QAVK;;;;mBAAO,uBAAuB;WAAC;IAWxC,CAAC;CACF;AAED,MAAM,OAAO,mBAAoB,SAAQ,SAAS;IAEhD;QACE,KAAK,CAAC,2BAA2B,EAAE;YACjC,QAAQ,EAAE,wBAAwB;SACnC,CAAC,CAAC;QAJI;;;;mBAAO,qBAAqB;WAAC;IAKtC,CAAC;CACF;AAED,MAAM,OAAO,gBAAiB,SAAQ,SAAS;IAI7C,YAAY,YAAyB;QACnC,KAAK,CAAC,+BAA+B,CAAC,CAAC;QAJhC;;;;mBAAO,kBAAkB;WAAC;QAC5B;;;;;WAA0B;QAI/B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACnC,CAAC;CACF","sourcesContent":["import { BaseError } from \"@aa-sdk/core\";\nimport type { MfaFactor } from \"./client/types\";\nexport class NotAuthenticatedError extends BaseError {\n override name = \"NotAuthenticatedError\";\n constructor() {\n super(\n [\n \"Signer not authenticated\",\n \"Please authenticate to use this signer\",\n ].join(\"\\n\"),\n {\n docsPath: \"/signers/alchemy-signer/introduction.html\",\n }\n );\n }\n}\n\nexport class OAuthProvidersError extends BaseError {\n override name = \"OAuthProvidersError\";\n constructor() {\n super(\"OAuth providers not found\", {\n docsPath: \"/react/getting-started\",\n });\n }\n}\n\nexport class MfaRequiredError extends BaseError {\n override name = \"MfaRequiredError\";\n public multiFactors: MfaFactor[];\n\n constructor(multiFactors: MfaFactor[]) {\n super(\"MFA is required for this user\");\n this.multiFactors = multiFactors;\n }\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,MAAM,OAAO,qBAAsB,SAAQ,SAAS;IAElD;QACE,KAAK,CACH;YACE,0BAA0B;YAC1B,wCAAwC;SACzC,CAAC,IAAI,CAAC,IAAI,CAAC,EACZ;YACE,QAAQ,EAAE,2CAA2C;SACtD,CACF,CAAC;QAVK;;;;mBAAO,uBAAuB;WAAC;IAWxC,CAAC;CACF;AAED,MAAM,OAAO,mBAAoB,SAAQ,SAAS;IAEhD;QACE,KAAK,CAAC,2BAA2B,EAAE;YACjC,QAAQ,EAAE,wBAAwB;SACnC,CAAC,CAAC;QAJI;;;;mBAAO,qBAAqB;WAAC;IAKtC,CAAC;CACF","sourcesContent":["import { BaseError } from \"@aa-sdk/core\";\n\nexport class NotAuthenticatedError extends BaseError {\n override name = \"NotAuthenticatedError\";\n constructor() {\n super(\n [\n \"Signer not authenticated\",\n \"Please authenticate to use this signer\",\n ].join(\"\\n\"),\n {\n docsPath: \"/signers/alchemy-signer/introduction.html\",\n }\n );\n }\n}\n\nexport class OAuthProvidersError extends BaseError {\n override name = \"OAuthProvidersError\";\n constructor() {\n super(\"OAuth providers not found\", {\n docsPath: \"/react/getting-started\",\n });\n }\n}\n"]}
@@ -2,7 +2,7 @@ export { BaseAlchemySigner } from "./base.js";
2
2
  export { BaseSignerClient } from "./client/base.js";
3
3
  export { AlchemySignerWebClient, OauthCancelledError, OauthFailedError, } from "./client/index.js";
4
4
  export type * from "./client/types.js";
5
- export { NotAuthenticatedError, OAuthProvidersError, MfaRequiredError, } from "./errors.js";
5
+ export { NotAuthenticatedError, OAuthProvidersError } from "./errors.js";
6
6
  export { DEFAULT_SESSION_MS, SessionManagerParamsSchema, } from "./session/manager.js";
7
7
  export type * from "./signer.js";
8
8
  export { AlchemyWebSigner } from "./signer.js";
package/dist/esm/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { BaseAlchemySigner } from "./base.js";
2
2
  export { BaseSignerClient } from "./client/base.js";
3
3
  export { AlchemySignerWebClient, OauthCancelledError, OauthFailedError, } from "./client/index.js";
4
- export { NotAuthenticatedError, OAuthProvidersError, MfaRequiredError, } from "./errors.js";
4
+ export { NotAuthenticatedError, OAuthProvidersError } from "./errors.js";
5
5
  export { DEFAULT_SESSION_MS, SessionManagerParamsSchema, } from "./session/manager.js";
6
6
  export { AlchemyWebSigner } from "./signer.js";
7
7
  export { AlchemySignerStatus } from "./types.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC","sourcesContent":["export { BaseAlchemySigner } from \"./base.js\";\nexport { BaseSignerClient } from \"./client/base.js\";\nexport {\n AlchemySignerWebClient,\n OauthCancelledError,\n OauthFailedError,\n} from \"./client/index.js\";\nexport type * from \"./client/types.js\";\nexport {\n NotAuthenticatedError,\n OAuthProvidersError,\n MfaRequiredError,\n} from \"./errors.js\";\nexport {\n DEFAULT_SESSION_MS,\n SessionManagerParamsSchema,\n} from \"./session/manager.js\";\nexport type * from \"./signer.js\";\nexport { AlchemyWebSigner } from \"./signer.js\";\nexport type * from \"./solanaSigner.js\";\nexport type * from \"./types.js\";\nexport { AlchemySignerStatus } from \"./types.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC","sourcesContent":["export { BaseAlchemySigner } from \"./base.js\";\nexport { BaseSignerClient } from \"./client/base.js\";\nexport {\n AlchemySignerWebClient,\n OauthCancelledError,\n OauthFailedError,\n} from \"./client/index.js\";\nexport type * from \"./client/types.js\";\nexport { NotAuthenticatedError, OAuthProvidersError } from \"./errors.js\";\nexport {\n DEFAULT_SESSION_MS,\n SessionManagerParamsSchema,\n} from \"./session/manager.js\";\nexport type * from \"./signer.js\";\nexport { AlchemyWebSigner } from \"./signer.js\";\nexport type * from \"./solanaSigner.js\";\nexport type * from \"./types.js\";\nexport { AlchemySignerStatus } from \"./types.js\";\n"]}
@@ -7,6 +7,9 @@ export type SignerEventsSchema = [
7
7
  } | {
8
8
  authType: "oauth";
9
9
  provider: string;
10
+ } | {
11
+ authType: "custom-jwt";
12
+ provider: string;
10
13
  };
11
14
  },
12
15
  {
@@ -1 +1 @@
1
- {"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../src/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAuBvC,MAAM,CAAC,MAAM,YAAY,GAAG,YAAY,CAAqB;IAC3D,OAAO,EAAE,qBAAqB;IAC9B,OAAO,EAAE,OAAO;CACjB,CAAC,CAAC","sourcesContent":["import { createLogger } from \"@account-kit/logging\";\nimport { VERSION } from \"./version.js\";\n\nexport type SignerEventsSchema = [\n {\n EventName: \"signer_authnticate\";\n EventData:\n | {\n authType:\n | \"email\"\n | \"passkey_anon\"\n | \"passkey_email\"\n | \"otp\"\n | \"oauthReturn\";\n provider?: never;\n }\n | { authType: \"oauth\"; provider: string };\n },\n {\n EventName: \"signer_sign_message\";\n EventData: undefined;\n }\n];\n\nexport const SignerLogger = createLogger<SignerEventsSchema>({\n package: \"@account-kit/signer\",\n version: VERSION,\n});\n"]}
1
+ {"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../src/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAwBvC,MAAM,CAAC,MAAM,YAAY,GAAG,YAAY,CAAqB;IAC3D,OAAO,EAAE,qBAAqB;IAC9B,OAAO,EAAE,OAAO;CACjB,CAAC,CAAC","sourcesContent":["import { createLogger } from \"@account-kit/logging\";\nimport { VERSION } from \"./version.js\";\n\nexport type SignerEventsSchema = [\n {\n EventName: \"signer_authnticate\";\n EventData:\n | {\n authType:\n | \"email\"\n | \"passkey_anon\"\n | \"passkey_email\"\n | \"otp\"\n | \"oauthReturn\";\n provider?: never;\n }\n | { authType: \"oauth\"; provider: string }\n | { authType: \"custom-jwt\"; provider: string };\n },\n {\n EventName: \"signer_sign_message\";\n EventData: undefined;\n }\n];\n\nexport const SignerLogger = createLogger<SignerEventsSchema>({\n package: \"@account-kit/signer\",\n version: VERSION,\n});\n"]}
@@ -1,15 +1,16 @@
1
1
  import type { KnownAuthProvider } from "./signer";
2
- export type ScopeAndClaims = {
2
+ export type AuthProviderCustomization = {
3
3
  scope: string;
4
4
  claims?: string;
5
+ otherParameters?: Record<string, string>;
5
6
  };
6
7
  /**
7
- * Returns the default scope and claims when using a known auth provider
8
+ * Returns the default customization parameters when using a known auth provider
8
9
  *
9
10
  * @param {string} knownAuthProviderId id of a known auth provider, e.g. "google"
10
- * @returns {ScopeAndClaims | undefined} default scope and claims
11
+ * @returns {AuthProviderCustomization | undefined} default customization parameters
11
12
  */
12
- export declare function getDefaultScopeAndClaims(knownAuthProviderId: KnownAuthProvider): ScopeAndClaims | undefined;
13
+ export declare function getDefaultProviderCustomization(knownAuthProviderId: KnownAuthProvider): AuthProviderCustomization | undefined;
13
14
  /**
14
15
  * "openid" is a required scope in the OIDC protocol. Insert it if the user
15
16
  * forgot.
package/dist/esm/oauth.js CHANGED
@@ -1,17 +1,27 @@
1
- const DEFAULT_SCOPE_AND_CLAIMS = {
1
+ const DEFAULT_PROVIDER_CUSTOMIZATION = {
2
2
  google: { scope: "openid email" },
3
3
  apple: { scope: "openid email" },
4
- facebook: { scope: "openid email" },
4
+ facebook: {
5
+ scope: "openid email",
6
+ // Fixes Facebook mobile login so that `window.opener` doesn't get nullified.
7
+ otherParameters: { sdk: "joey" },
8
+ },
9
+ twitch: {
10
+ scope: "openid user:read:email",
11
+ claims: JSON.stringify({ id_token: { email: null } }),
12
+ // Forces Twitch to show the login page even if the user is already logged in.
13
+ otherParameters: { force_verify: "true" },
14
+ },
5
15
  auth0: { scope: "openid email" },
6
16
  };
7
17
  /**
8
- * Returns the default scope and claims when using a known auth provider
18
+ * Returns the default customization parameters when using a known auth provider
9
19
  *
10
20
  * @param {string} knownAuthProviderId id of a known auth provider, e.g. "google"
11
- * @returns {ScopeAndClaims | undefined} default scope and claims
21
+ * @returns {AuthProviderCustomization | undefined} default customization parameters
12
22
  */
13
- export function getDefaultScopeAndClaims(knownAuthProviderId) {
14
- return DEFAULT_SCOPE_AND_CLAIMS[knownAuthProviderId];
23
+ export function getDefaultProviderCustomization(knownAuthProviderId) {
24
+ return DEFAULT_PROVIDER_CUSTOMIZATION[knownAuthProviderId];
15
25
  }
16
26
  /**
17
27
  * "openid" is a required scope in the OIDC protocol. Insert it if the user
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../src/oauth.ts"],"names":[],"mappings":"AAOA,MAAM,wBAAwB,GAA8C;IAC1E,MAAM,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE;IACjC,KAAK,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE;IAChC,QAAQ,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE;IACnC,KAAK,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE;CACjC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,mBAAsC;IAEtC,OAAO,wBAAwB,CAAC,mBAAmB,CAAC,CAAC;AACvD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAa;IAC7C,OAAO,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,KAAK,EAAE,CAAC;AAC/D,CAAC","sourcesContent":["import type { KnownAuthProvider } from \"./signer\";\n\nexport type ScopeAndClaims = {\n scope: string;\n claims?: string;\n};\n\nconst DEFAULT_SCOPE_AND_CLAIMS: Record<KnownAuthProvider, ScopeAndClaims> = {\n google: { scope: \"openid email\" },\n apple: { scope: \"openid email\" },\n facebook: { scope: \"openid email\" },\n auth0: { scope: \"openid email\" },\n};\n\n/**\n * Returns the default scope and claims when using a known auth provider\n *\n * @param {string} knownAuthProviderId id of a known auth provider, e.g. \"google\"\n * @returns {ScopeAndClaims | undefined} default scope and claims\n */\nexport function getDefaultScopeAndClaims(\n knownAuthProviderId: KnownAuthProvider\n): ScopeAndClaims | undefined {\n return DEFAULT_SCOPE_AND_CLAIMS[knownAuthProviderId];\n}\n\n/**\n * \"openid\" is a required scope in the OIDC protocol. Insert it if the user\n * forgot.\n *\n * @param {string} scope scope param which may be missing \"openid\"\n * @returns {string} scope which most definitely contains \"openid\"\n */\nexport function addOpenIdIfAbsent(scope: string): string {\n return scope.match(/\\bopenid\\b/) ? scope : `openid ${scope}`;\n}\n"]}
1
+ {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../src/oauth.ts"],"names":[],"mappings":"AAQA,MAAM,8BAA8B,GAGhC;IACF,MAAM,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE;IACjC,KAAK,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE;IAChC,QAAQ,EAAE;QACR,KAAK,EAAE,cAAc;QACrB,6EAA6E;QAC7E,eAAe,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE;KACjC;IACD,MAAM,EAAE;QACN,KAAK,EAAE,wBAAwB;QAC/B,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC;QACrD,8EAA8E;QAC9E,eAAe,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE;KAC1C;IACD,KAAK,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE;CACjC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAC7C,mBAAsC;IAEtC,OAAO,8BAA8B,CAAC,mBAAmB,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAa;IAC7C,OAAO,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,KAAK,EAAE,CAAC;AAC/D,CAAC","sourcesContent":["import type { KnownAuthProvider } from \"./signer\";\n\nexport type AuthProviderCustomization = {\n scope: string;\n claims?: string;\n otherParameters?: Record<string, string>;\n};\n\nconst DEFAULT_PROVIDER_CUSTOMIZATION: Record<\n KnownAuthProvider,\n AuthProviderCustomization\n> = {\n google: { scope: \"openid email\" },\n apple: { scope: \"openid email\" },\n facebook: {\n scope: \"openid email\",\n // Fixes Facebook mobile login so that `window.opener` doesn't get nullified.\n otherParameters: { sdk: \"joey\" },\n },\n twitch: {\n scope: \"openid user:read:email\",\n claims: JSON.stringify({ id_token: { email: null } }),\n // Forces Twitch to show the login page even if the user is already logged in.\n otherParameters: { force_verify: \"true\" },\n },\n auth0: { scope: \"openid email\" },\n};\n\n/**\n * Returns the default customization parameters when using a known auth provider\n *\n * @param {string} knownAuthProviderId id of a known auth provider, e.g. \"google\"\n * @returns {AuthProviderCustomization | undefined} default customization parameters\n */\nexport function getDefaultProviderCustomization(\n knownAuthProviderId: KnownAuthProvider\n): AuthProviderCustomization | undefined {\n return DEFAULT_PROVIDER_CUSTOMIZATION[knownAuthProviderId];\n}\n\n/**\n * \"openid\" is a required scope in the OIDC protocol. Insert it if the user\n * forgot.\n *\n * @param {string} scope scope param which may be missing \"openid\"\n * @returns {string} scope which most definitely contains \"openid\"\n */\nexport function addOpenIdIfAbsent(scope: string): string {\n return scope.match(/\\bopenid\\b/) ? scope : `openid ${scope}`;\n}\n"]}
@@ -24,7 +24,6 @@ export type SessionManagerParams = z.input<typeof SessionManagerParamsSchema>;
24
24
  type TemporarySession = {
25
25
  orgId: string;
26
26
  isNewUser?: boolean;
27
- isMfaRequired?: boolean;
28
27
  };
29
28
  export declare class SessionManager {
30
29
  private sessionKey;
@@ -66,6 +66,7 @@ export class SessionManager {
66
66
  switch (existingSession.type) {
67
67
  case "email":
68
68
  case "oauth":
69
+ case "custom-jwt":
69
70
  case "otp": {
70
71
  const connectedEventName = (() => {
71
72
  switch (existingSession.type) {
@@ -75,6 +76,8 @@ export class SessionManager {
75
76
  return "connectedOauth";
76
77
  case "otp":
77
78
  return "connectedOtp";
79
+ case "custom-jwt":
80
+ return "connectedJwt";
78
81
  }
79
82
  })();
80
83
  const result = await this.client
@@ -216,6 +219,7 @@ export class SessionManager {
216
219
  this.setSession({ type: "passkey", user });
217
220
  },
218
221
  connectedOauth: (user, bundle) => this.setSessionWithUserAndBundle({ type: "oauth", user, bundle }),
222
+ connectedJwt: (user, bundle) => this.setSessionWithUserAndBundle({ type: "custom-jwt", user, bundle }),
219
223
  connectedOtp: (user, bundle) => {
220
224
  this.setSessionWithUserAndBundle({ type: "otp", user, bundle });
221
225
  },
@@ -1 +1 @@
1
- {"version":3,"file":"manager.js","sourceRoot":"","sources":["../../../src/session/manager.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,iBAAiB,EACjB,OAAO,EACP,qBAAqB,GACtB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,WAAW,EAA8B,MAAM,iBAAiB,CAAC;AAO1E,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAGzD,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,aAAa;AAE/D,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC,MAAM,CAAC;IACjD,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,wBAAwB,CAAC;IACxD,OAAO,EAAE,CAAC;SACP,IAAI,CAAC,CAAC,cAAc,EAAE,gBAAgB,CAAC,CAAC;SACxC,OAAO,CAAC,c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";\nimport { z } from \"zod\";\nimport {\n createJSONStorage,\n persist,\n subscribeWithSelector,\n} from \"zustand/middleware\";\nimport { createStore, type Mutate, type StoreApi } from \"zustand/vanilla\";\nimport type { BaseSignerClient } from \"../client/base\";\nimport type {\n AlchemySignerClientEvent,\n AlchemySignerClientEvents,\n User,\n} from \"../client/types\";\nimport { assertNever } from \"../utils/typeAssertions.js\";\nimport type { Session, SessionManagerEvents } from \"./types\";\n\nexport const DEFAULT_SESSION_MS = 15 * 60 * 1000; // 15 minutes\n\nexport const SessionManagerParamsSchema = z.object({\n sessionKey: z.string().default(\"alchemy-signer-session\"),\n storage: z\n .enum([\"localStorage\", \"sessionStorage\"])\n .default(\"localStorage\")\n .or(z.custom<Storage>()),\n expirationTimeMs: z\n .number()\n .default(DEFAULT_SESSION_MS)\n .describe(\n \"The time in milliseconds that a session should last before expiring [default: 15 minutes]\"\n ),\n client: z.custom<BaseSignerClient>(),\n});\n\nexport type SessionManagerParams = z.input<typeof SessionManagerParamsSchema>;\n\ntype SessionState = {\n session: Session | null;\n};\n\ntype Store = Mutate<\n StoreApi<SessionState>,\n [[\"zustand/subscribeWithSelector\", never], [\"zustand/persist\", SessionState]]\n>;\n\ntype TemporarySession = {\n orgId: string;\n isNewUser?: boolean;\n isMfaRequired?: boolean;\n};\n\nexport class SessionManager {\n private sessionKey: string;\n private client: BaseSignerClient;\n private eventEmitter: EventEmitter<SessionManagerEvents>;\n readonly expirationTimeMs: number;\n private store: Store;\n private clearSessionHandle: NodeJS.Timeout | null = null;\n\n constructor(params: SessionManagerParams) {\n const {\n sessionKey,\n storage: storageType,\n expirationTimeMs,\n client,\n } = SessionManagerParamsSchema.parse(params);\n this.sessionKey = sessionKey;\n const storage =\n typeof storageType === \"string\"\n ? storageType === \"localStorage\"\n ? localStorage\n : sessionStorage\n : storageType;\n this.expirationTimeMs = expirationTimeMs;\n this.client = client;\n this.eventEmitter = new EventEmitter<SessionManagerEvents>();\n\n this.store = createStore(\n subscribeWithSelector(\n persist(this.getInitialState, {\n name: this.sessionKey,\n storage: createJSONStorage<SessionState>(() => storage),\n })\n )\n );\n\n this.registerEventListeners();\n }\n\n public getSessionUser = async (): Promise<User | null> => {\n const existingSession = this.getSession();\n if (existingSession == null) {\n return null;\n }\n\n switch (existingSession.type) {\n case \"email\":\n case \"oauth\":\n case \"otp\": {\n const connectedEventName = (() => {\n switch (existingSession.type) {\n case \"email\":\n return \"connectedEmail\";\n case \"oauth\":\n return \"connectedOauth\";\n case \"otp\":\n return \"connectedOtp\";\n }\n })();\n const result = await this.client\n .completeAuthWithBundle({\n bundle: existingSession.bundle,\n orgId: existingSession.user.orgId,\n authenticatingType: existingSession.type,\n connectedEventName,\n idToken: existingSession.user.idToken,\n })\n .catch((e) => {\n console.warn(\"Failed to load user from session\", e);\n return null;\n });\n\n if (!result) {\n this.clearSession();\n return null;\n }\n\n return result;\n }\n case \"passkey\": {\n // we don't need to do much here if we already have a user\n // this will setup the client with the user context, but\n // requests still have to be signed by the user on first request\n // so this is fine\n return this.client.lookupUserWithPasskey(existingSession.user);\n }\n default:\n assertNever(\n existingSession,\n `Unknown session type: ${(existingSession as any).type}`\n );\n }\n };\n\n public clearSession = () => {\n this.store.setState({ session: null });\n localStorage.removeItem(`${this.sessionKey}:temporary`);\n\n if (this.clearSessionHandle) {\n clearTimeout(this.clearSessionHandle);\n }\n };\n\n public setTemporarySession = (session: TemporarySession) => {\n // temporary session must be placed in localStorage so that it can be accessed across tabs\n localStorage.setItem(\n `${this.sessionKey}:temporary`,\n JSON.stringify(session)\n );\n };\n\n public getTemporarySession = (): TemporarySession | null => {\n // temporary session must be placed in localStorage so that it can be accessed across tabs\n const sessionStr = localStorage.getItem(`${this.sessionKey}:temporary`);\n\n if (!sessionStr) {\n return null;\n }\n\n return JSON.parse(sessionStr);\n };\n\n on = <E extends keyof SessionManagerEvents>(\n event: E,\n listener: SessionManagerEvents[E]\n ) => {\n this.eventEmitter.on(event, listener as any);\n\n return () => this.eventEmitter.removeListener(event, listener as any);\n };\n\n private getSession = (): Session | null => {\n const session = this.store.getState().session;\n\n if (!session) {\n return null;\n }\n\n /**\n * TODO: this isn't really good enough\n * A user's session could be about to expire and we would still return it\n *\n * Instead we should check if a session is about to expire and refresh it\n * We should revisit this later\n */\n if (session.expirationDateMs < Date.now()) {\n this.client.disconnect();\n this.clearSession();\n return null;\n }\n\n this.registerSessionExpirationHandler(session);\n\n return session;\n };\n\n private setSession = (\n session_:\n | Omit<\n Extract<Session, { type: \"email\" | \"oauth\" | \"otp\" }>,\n \"expirationDateMs\"\n >\n | Omit<Extract<Session, { type: \"passkey\" }>, \"expirationDateMs\">\n ) => {\n const session = {\n ...session_,\n expirationDateMs: Date.now() + this.expirationTimeMs,\n };\n\n this.registerSessionExpirationHandler(session);\n\n this.store.setState({ session });\n };\n\n public initialize() {\n this.getSessionUser()\n .then((user) => {\n // once we complete auth we can update the state of the session to connected or disconnected\n if (user) this.eventEmitter.emit(\"connected\", this.getSession()!);\n else this.eventEmitter.emit(\"disconnected\");\n })\n .finally(() => {\n this.eventEmitter.emit(\"initialized\");\n });\n }\n\n private getInitialState(): SessionState {\n return {\n session: null,\n };\n }\n\n private registerEventListeners = () => {\n this.store.subscribe(\n ({ session }) => session,\n (session, prevSession) => {\n if (session != null && prevSession == null) {\n this.eventEmitter.emit(\"connected\", session);\n } else if (session == null && prevSession != null) {\n this.eventEmitter.emit(\"disconnected\");\n }\n }\n );\n\n // Helper type to ensure that a listener is either defined or explicitly\n // omitted for every event type.\n type Listeners = {\n [K in keyof AlchemySignerClientEvents]:\n | AlchemySignerClientEvents[K]\n | undefined;\n };\n\n const listeners: Listeners = {\n connected: undefined,\n newUserSignup: undefined,\n authenticating: undefined,\n connectedEmail: (user, bundle) =>\n this.setSessionWithUserAndBundle({ type: \"email\", user, bundle }),\n connectedPasskey: (user) => {\n const existingSession = this.getSession();\n if (\n existingSession != null &&\n existingSession.type === \"passkey\" &&\n existingSession.user.userId === user.userId\n ) {\n return;\n }\n\n this.setSession({ type: \"passkey\", user });\n },\n connectedOauth: (user, bundle) =>\n this.setSessionWithUserAndBundle({ type: \"oauth\", user, bundle }),\n connectedOtp: (user, bundle) => {\n this.setSessionWithUserAndBundle({ type: \"otp\", user, bundle });\n },\n disconnected: () => this.clearSession(),\n };\n\n for (const [event, listener] of Object.entries(listeners)) {\n if (listener) {\n this.client.on(event as AlchemySignerClientEvent, listener);\n }\n }\n\n // sync local state if persisted state has changed from another tab\n // only do this in the browser\n // Add a try catch to prevent potential crashes in non-browser environments\n try {\n if (\n typeof window !== \"undefined\" &&\n typeof window.addEventListener !== \"undefined\"\n ) {\n window.addEventListener(\"focus\", () => {\n const oldSession = this.store.getState().session;\n this.store.persist.rehydrate();\n const newSession = this.store.getState().session;\n if (\n (oldSession?.expirationDateMs ?? 0) < Date.now() ||\n oldSession?.user.orgId !== newSession?.user.orgId ||\n oldSession?.user.userId !== newSession?.user.userId\n ) {\n // Initialize if the user has changed.\n this.initialize();\n }\n });\n }\n } catch (e) {\n console.error(\"Error registering event listeners\", e);\n }\n };\n\n private registerSessionExpirationHandler = (session: Session) => {\n if (this.clearSessionHandle) {\n clearTimeout(this.clearSessionHandle);\n }\n\n this.clearSessionHandle = setTimeout(() => {\n this.client.disconnect();\n this.clearSession();\n }, Math.min(session.expirationDateMs - Date.now(), Math.pow(2, 31) - 1));\n };\n\n private setSessionWithUserAndBundle = ({\n type,\n user,\n bundle,\n }: {\n type: \"email\" | \"oauth\" | \"otp\";\n user: User;\n bundle: string;\n }) => {\n const existingSession = this.getSession();\n if (\n existingSession != null &&\n existingSession.type === type &&\n existingSession.user.userId === user.userId &&\n // if the bundle is different, then we've refreshed the session\n // so we need to reset the session\n existingSession.bundle === bundle\n ) {\n return;\n }\n\n this.setSession({ type, user, bundle });\n };\n}\n"]}
1
+ {"version":3,"file":"manager.js","sourceRoot":"","sources":["../../../src/session/manager.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,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B,qBAAqB,CACnB,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE;YAC5B,IAAI,EAAE,IAAI,CAAC,UAAU;YACrB,OAAO,EAAE,iBAAiB,CAAe,GAAG,EAAE,CAAC,OAAO,CAAC;SACxD,CAAC,CACH,CACF,CAAC;QAEF,IAAI,CAAC,sBAAsB,EAAE,CAAC;IAChC,CAAC;IA4IM,UAAU;QACf,IAAI,CAAC,cAAc,EAAE;aAClB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;YACb,4FAA4F;YAC5F,IAAI,IAAI;gBAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,UAAU,EAAG,CAAC,CAAC;;gBAC7D,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9C,CAAC,CAAC;aACD,OAAO,CAAC,GAAG,EAAE;YACZ,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;IACP,CAAC;IAEO,eAAe;QACrB,OAAO;YACL,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC;CAqHF","sourcesContent":["import EventEmitter from \"eventemitter3\";\nimport { z } from \"zod\";\nimport {\n createJSONStorage,\n persist,\n subscribeWithSelector,\n} from \"zustand/middleware\";\nimport { createStore, type Mutate, type StoreApi } from \"zustand/vanilla\";\nimport type { BaseSignerClient } from \"../client/base\";\nimport type {\n AlchemySignerClientEvent,\n AlchemySignerClientEvents,\n User,\n} from \"../client/types\";\nimport { assertNever } from \"../utils/typeAssertions.js\";\nimport type { Session, SessionManagerEvents } from \"./types\";\n\nexport const DEFAULT_SESSION_MS = 15 * 60 * 1000; // 15 minutes\n\nexport const SessionManagerParamsSchema = z.object({\n sessionKey: z.string().default(\"alchemy-signer-session\"),\n storage: z\n .enum([\"localStorage\", \"sessionStorage\"])\n .default(\"localStorage\")\n .or(z.custom<Storage>()),\n expirationTimeMs: z\n .number()\n .default(DEFAULT_SESSION_MS)\n .describe(\n \"The time in milliseconds that a session should last before expiring [default: 15 minutes]\"\n ),\n client: z.custom<BaseSignerClient>(),\n});\n\nexport type SessionManagerParams = z.input<typeof SessionManagerParamsSchema>;\n\ntype SessionState = {\n session: Session | null;\n};\n\ntype Store = Mutate<\n StoreApi<SessionState>,\n [[\"zustand/subscribeWithSelector\", never], [\"zustand/persist\", SessionState]]\n>;\n\ntype TemporarySession = { orgId: string; isNewUser?: boolean };\n\nexport class SessionManager {\n private sessionKey: string;\n private client: BaseSignerClient;\n private eventEmitter: EventEmitter<SessionManagerEvents>;\n readonly expirationTimeMs: number;\n private store: Store;\n private clearSessionHandle: NodeJS.Timeout | null = null;\n\n constructor(params: SessionManagerParams) {\n const {\n sessionKey,\n storage: storageType,\n expirationTimeMs,\n client,\n } = SessionManagerParamsSchema.parse(params);\n this.sessionKey = sessionKey;\n const storage =\n typeof storageType === \"string\"\n ? storageType === \"localStorage\"\n ? localStorage\n : sessionStorage\n : storageType;\n this.expirationTimeMs = expirationTimeMs;\n this.client = client;\n this.eventEmitter = new EventEmitter<SessionManagerEvents>();\n\n this.store = createStore(\n subscribeWithSelector(\n persist(this.getInitialState, {\n name: this.sessionKey,\n storage: createJSONStorage<SessionState>(() => storage),\n })\n )\n );\n\n this.registerEventListeners();\n }\n\n public getSessionUser = async (): Promise<User | null> => {\n const existingSession = this.getSession();\n if (existingSession == null) {\n return null;\n }\n\n switch (existingSession.type) {\n case \"email\":\n case \"oauth\":\n case \"custom-jwt\":\n case \"otp\": {\n const connectedEventName = (() => {\n switch (existingSession.type) {\n case \"email\":\n return \"connectedEmail\";\n case \"oauth\":\n return \"connectedOauth\";\n case \"otp\":\n return \"connectedOtp\";\n case \"custom-jwt\":\n return \"connectedJwt\";\n }\n })();\n const result = await this.client\n .completeAuthWithBundle({\n bundle: existingSession.bundle,\n orgId: existingSession.user.orgId,\n authenticatingType: existingSession.type,\n connectedEventName,\n idToken: existingSession.user.idToken,\n })\n .catch((e) => {\n console.warn(\"Failed to load user from session\", e);\n return null;\n });\n\n if (!result) {\n this.clearSession();\n return null;\n }\n\n return result;\n }\n case \"passkey\": {\n // we don't need to do much here if we already have a user\n // this will setup the client with the user context, but\n // requests still have to be signed by the user on first request\n // so this is fine\n return this.client.lookupUserWithPasskey(existingSession.user);\n }\n default:\n assertNever(\n existingSession,\n `Unknown session type: ${(existingSession as any).type}`\n );\n }\n };\n\n public clearSession = () => {\n this.store.setState({ session: null });\n localStorage.removeItem(`${this.sessionKey}:temporary`);\n\n if (this.clearSessionHandle) {\n clearTimeout(this.clearSessionHandle);\n }\n };\n\n public setTemporarySession = (session: TemporarySession) => {\n // temporary session must be placed in localStorage so that it can be accessed across tabs\n localStorage.setItem(\n `${this.sessionKey}:temporary`,\n JSON.stringify(session)\n );\n };\n\n public getTemporarySession = (): TemporarySession | null => {\n // temporary session must be placed in localStorage so that it can be accessed across tabs\n const sessionStr = localStorage.getItem(`${this.sessionKey}:temporary`);\n\n if (!sessionStr) {\n return null;\n }\n\n return JSON.parse(sessionStr);\n };\n\n on = <E extends keyof SessionManagerEvents>(\n event: E,\n listener: SessionManagerEvents[E]\n ) => {\n this.eventEmitter.on(event, listener as any);\n\n return () => this.eventEmitter.removeListener(event, listener as any);\n };\n\n private getSession = (): Session | null => {\n const session = this.store.getState().session;\n\n if (!session) {\n return null;\n }\n\n /**\n * TODO: this isn't really good enough\n * A user's session could be about to expire and we would still return it\n *\n * Instead we should check if a session is about to expire and refresh it\n * We should revisit this later\n */\n if (session.expirationDateMs < Date.now()) {\n this.client.disconnect();\n this.clearSession();\n return null;\n }\n\n this.registerSessionExpirationHandler(session);\n\n return session;\n };\n\n private setSession = (\n session_:\n | Omit<\n Extract<Session, { type: \"email\" | \"oauth\" | \"otp\" | \"custom-jwt\" }>,\n \"expirationDateMs\"\n >\n | Omit<Extract<Session, { type: \"passkey\" }>, \"expirationDateMs\">\n ) => {\n const session = {\n ...session_,\n expirationDateMs: Date.now() + this.expirationTimeMs,\n };\n\n this.registerSessionExpirationHandler(session);\n\n this.store.setState({ session });\n };\n\n public initialize() {\n this.getSessionUser()\n .then((user) => {\n // once we complete auth we can update the state of the session to connected or disconnected\n if (user) this.eventEmitter.emit(\"connected\", this.getSession()!);\n else this.eventEmitter.emit(\"disconnected\");\n })\n .finally(() => {\n this.eventEmitter.emit(\"initialized\");\n });\n }\n\n private getInitialState(): SessionState {\n return {\n session: null,\n };\n }\n\n private registerEventListeners = () => {\n this.store.subscribe(\n ({ session }) => session,\n (session, prevSession) => {\n if (session != null && prevSession == null) {\n this.eventEmitter.emit(\"connected\", session);\n } else if (session == null && prevSession != null) {\n this.eventEmitter.emit(\"disconnected\");\n }\n }\n );\n\n // Helper type to ensure that a listener is either defined or explicitly\n // omitted for every event type.\n type Listeners = {\n [K in keyof AlchemySignerClientEvents]:\n | AlchemySignerClientEvents[K]\n | undefined;\n };\n\n const listeners: Listeners = {\n connected: undefined,\n newUserSignup: undefined,\n authenticating: undefined,\n connectedEmail: (user, bundle) =>\n this.setSessionWithUserAndBundle({ type: \"email\", user, bundle }),\n connectedPasskey: (user) => {\n const existingSession = this.getSession();\n if (\n existingSession != null &&\n existingSession.type === \"passkey\" &&\n existingSession.user.userId === user.userId\n ) {\n return;\n }\n\n this.setSession({ type: \"passkey\", user });\n },\n connectedOauth: (user, bundle) =>\n this.setSessionWithUserAndBundle({ type: \"oauth\", user, bundle }),\n connectedJwt: (user, bundle) =>\n this.setSessionWithUserAndBundle({ type: \"custom-jwt\", user, bundle }),\n connectedOtp: (user, bundle) => {\n this.setSessionWithUserAndBundle({ type: \"otp\", user, bundle });\n },\n disconnected: () => this.clearSession(),\n };\n\n for (const [event, listener] of Object.entries(listeners)) {\n if (listener) {\n this.client.on(event as AlchemySignerClientEvent, listener);\n }\n }\n\n // sync local state if persisted state has changed from another tab\n // only do this in the browser\n // Add a try catch to prevent potential crashes in non-browser environments\n try {\n if (\n typeof window !== \"undefined\" &&\n typeof window.addEventListener !== \"undefined\"\n ) {\n window.addEventListener(\"focus\", () => {\n const oldSession = this.store.getState().session;\n this.store.persist.rehydrate();\n const newSession = this.store.getState().session;\n if (\n (oldSession?.expirationDateMs ?? 0) < Date.now() ||\n oldSession?.user.orgId !== newSession?.user.orgId ||\n oldSession?.user.userId !== newSession?.user.userId\n ) {\n // Initialize if the user has changed.\n this.initialize();\n }\n });\n }\n } catch (e) {\n console.error(\"Error registering event listeners\", e);\n }\n };\n\n private registerSessionExpirationHandler = (session: Session) => {\n if (this.clearSessionHandle) {\n clearTimeout(this.clearSessionHandle);\n }\n\n this.clearSessionHandle = setTimeout(() => {\n this.client.disconnect();\n this.clearSession();\n }, Math.min(session.expirationDateMs - Date.now(), Math.pow(2, 31) - 1));\n };\n\n private setSessionWithUserAndBundle = ({\n type,\n user,\n bundle,\n }: {\n type: \"email\" | \"oauth\" | \"otp\" | \"custom-jwt\";\n user: User;\n bundle: string;\n }) => {\n const existingSession = this.getSession();\n if (\n existingSession != null &&\n existingSession.type === type &&\n existingSession.user.userId === user.userId &&\n // if the bundle is different, then we've refreshed the session\n // so we need to reset the session\n existingSession.bundle === bundle\n ) {\n return;\n }\n\n this.setSession({ type, user, bundle });\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { User } from "../client/types";
2
2
  export type Session = {
3
- type: "email" | "oauth" | "otp";
3
+ type: "email" | "oauth" | "otp" | "custom-jwt";
4
4
  bundle: string;
5
5
  expirationDateMs: number;
6
6
  user: User;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/session/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { User } from \"../client/types\";\n\nexport type Session =\n | {\n type: \"email\" | \"oauth\" | \"otp\";\n bundle: string;\n expirationDateMs: number;\n user: User;\n }\n | { type: \"passkey\"; user: User; expirationDateMs: number };\n\nexport type SessionManagerEvents = {\n connected(session: Session): void;\n disconnected(): void;\n initialized(): void;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/session/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { User } from \"../client/types\";\n\nexport type Session =\n | {\n type: \"email\" | \"oauth\" | \"otp\" | \"custom-jwt\";\n bundle: string;\n expirationDateMs: number;\n user: User;\n }\n | { type: \"passkey\"; user: User; expirationDateMs: number };\n\nexport type SessionManagerEvents = {\n connected(session: Session): void;\n disconnected(): void;\n initialized(): void;\n};\n"]}
@@ -1,13 +1,13 @@
1
1
  import { z } from "zod";
2
2
  import { BaseAlchemySigner } from "./base.js";
3
3
  import { AlchemySignerWebClient } from "./client/index.js";
4
- import type { CredentialCreationOptionOverrides, VerifyMfaParams } from "./client/types.js";
4
+ import type { CredentialCreationOptionOverrides } from "./client/types.js";
5
5
  export type AuthParams = {
6
6
  type: "email";
7
7
  email: string;
8
+ /** @deprecated This option will be overriden by dashboard settings. Please use the dashboard settings instead. This option will be removed in a future release. */
8
9
  emailMode?: "magicLink" | "otp";
9
10
  redirectParams?: URLSearchParams;
10
- multiFactors?: VerifyMfaParams[];
11
11
  } | {
12
12
  type: "email";
13
13
  bundle: string;
@@ -29,7 +29,11 @@ export type AuthParams = {
29
29
  type: "oauth";
30
30
  scope?: string;
31
31
  claims?: string;
32
- } & OauthProviderConfig & OauthRedirectConfig) | {
32
+ otherParameters?: Record<string, string>;
33
+ } & OauthProviderConfig & OauthRedirectConfig) | ({
34
+ type: "custom-jwt";
35
+ jwt: string;
36
+ } & OauthProviderConfig) | {
33
37
  type: "oauthReturn";
34
38
  bundle: string;
35
39
  orgId: string;
@@ -38,7 +42,6 @@ export type AuthParams = {
38
42
  } | {
39
43
  type: "otp";
40
44
  otpCode: string;
41
- multiFactors?: VerifyMfaParams[];
42
45
  };
43
46
  export type OauthProviderConfig = {
44
47
  authProviderId: "auth0";
@@ -60,7 +63,7 @@ export type OauthRedirectConfig = {
60
63
  mode: "popup";
61
64
  redirectUrl?: never;
62
65
  };
63
- export type KnownAuthProvider = "google" | "apple" | "facebook" | "auth0";
66
+ export type KnownAuthProvider = "google" | "apple" | "facebook" | "twitch" | "auth0";
64
67
  export type OauthMode = "redirect" | "popup";
65
68
  export declare const AlchemySignerParamsSchema: z.ZodObject<{
66
69
  client: z.ZodUnion<[z.ZodType<AlchemySignerWebClient, z.ZodTypeDef, AlchemySignerWebClient>, z.ZodObject<{
@@ -1 +1 @@
1
- {"version":3,"file":"signer.js","sourceRoot":"","sources":["../../src/signer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EACL,+BAA+B,EAC/B,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAsElE,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC;KACvC,MAAM,CAAC;IACN,MAAM,EAAE,CAAC;SACN,MAAM,EAA0B;SAChC,EAAE,CAAC,+BAA+B,CAAC;CACvC,CAAC;KACD,MAAM,CAAC;IACN,aAAa,EAAE,0BAA0B,CAAC,IAAI,CAAC;QAC7C,MAAM,EAAE,IAAI;KACb,CAAC,CAAC,QAAQ,EAAE;CACd,CAAC,CAAC;AAIL;;GAEG;AACH,MAAM,OAAO,gBAAiB,SAAQ,iBAAyC;IAC7E;;;;;;;;;;;;;;;;;;;;OAoBG;IAEH,YAAY,MAA2B;QACrC,MAAM,EAAE,aAAa,EAAE,GAAG,OAAO,EAAE,GACjC,yBAAyB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAE1C,IAAI,MAA8B,CAAC;QACnC,IAAI,YAAY,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;YACnC,MAAM,GAAG,IAAI,sBAAsB,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACtD,CAAC;aAAM,CAAC;YACN,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC1B,CAAC;QACD,MAAM,EACJ,WAAW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AG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QAChD,MAAM,KAAK,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,SAAS,CAAC;QACvD,eAAe,KAAf,eAAe,GAAK,KAAK,IAAI,IAAI,EAAC;QAClC,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACpB,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IACD,IAAI,eAAe,EAAE,CAAC;QACpB,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACxE,CAAC;IACD,OAAO,MAAgD,CAAC;AAC1D,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { BaseAlchemySigner } from \"./base.js\";\nimport {\n AlchemySignerClientParamsSchema,\n AlchemySignerWebClient,\n} from \"./client/index.js\";\nimport type {\n CredentialCreationOptionOverrides,\n VerifyMfaParams,\n} from \"./client/types.js\";\nimport { SessionManagerParamsSchema } from \"./session/manager.js\";\n\nexport type AuthParams =\n | {\n type: \"email\";\n email: string;\n emailMode?: \"magicLink\" | \"otp\";\n redirectParams?: URLSearchParams;\n multiFactors?: VerifyMfaParams[];\n }\n | { type: \"email\"; bundle: string; orgId?: string; isNewUser?: boolean }\n | {\n type: \"passkey\";\n email: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | {\n type: \"passkey\";\n createNew: false;\n }\n | {\n type: \"passkey\";\n createNew: true;\n username: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | ({\n type: \"oauth\";\n scope?: string;\n claims?: string;\n } & OauthProviderConfig &\n OauthRedirectConfig)\n | {\n type: \"oauthReturn\";\n bundle: string;\n orgId: string;\n idToken: string;\n isNewUser?: boolean;\n }\n | {\n type: \"otp\";\n otpCode: string;\n multiFactors?: VerifyMfaParams[];\n };\n\nexport type OauthProviderConfig =\n | {\n authProviderId: \"auth0\";\n isCustomProvider?: false;\n auth0Connection?: string;\n }\n | {\n authProviderId: KnownAuthProvider;\n isCustomProvider?: false;\n auth0Connection?: never;\n }\n | {\n authProviderId: string;\n isCustomProvider: true;\n auth0Connection?: never;\n };\n\nexport type OauthRedirectConfig =\n | { mode: \"redirect\"; redirectUrl: string }\n | { mode: \"popup\"; redirectUrl?: never };\n\nexport type KnownAuthProvider = \"google\" | \"apple\" | \"facebook\" | \"auth0\";\n\nexport type OauthMode = \"redirect\" | \"popup\";\n\nexport const AlchemySignerParamsSchema = z\n .object({\n client: z\n .custom<AlchemySignerWebClient>()\n .or(AlchemySignerClientParamsSchema),\n })\n .extend({\n sessionConfig: SessionManagerParamsSchema.omit({\n client: true,\n }).optional(),\n });\n\nexport type AlchemySignerParams = z.input<typeof AlchemySignerParamsSchema>;\n\n/**\n * A SmartAccountSigner that can be used with any SmartContractAccount\n */\nexport class AlchemyWebSigner extends BaseAlchemySigner<AlchemySignerWebClient> {\n /**\n * Initializes an instance with the provided Alchemy signer parameters after parsing them with a schema.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n * ```\n *\n * @param {AlchemySignerParams} params The parameters for the Alchemy signer, including the client and session configuration\n */\n\n constructor(params: AlchemySignerParams) {\n const { sessionConfig, ...params_ } =\n AlchemySignerParamsSchema.parse(params);\n\n let client: AlchemySignerWebClient;\n if (\"connection\" in params_.client) {\n client = new AlchemySignerWebClient(params_.client);\n } else {\n client = params_.client;\n }\n const {\n emailBundle,\n oauthBundle,\n oauthOrgId,\n oauthError,\n idToken,\n isSignup,\n } = getAndRemoveQueryParams({\n emailBundle: \"bundle\",\n // We don't need this, but we still want to remove it from the URL.\n emailOrgId: \"orgId\",\n oauthBundle: \"alchemy-bundle\",\n oauthOrgId: \"alchemy-org-id\",\n oauthError: \"alchemy-error\",\n idToken: \"alchemy-id-token\",\n isSignup: \"aa-is-signup\",\n });\n\n const initialError =\n oauthError != null\n ? { name: \"OauthError\", message: oauthError }\n : undefined;\n\n super({ client, sessionConfig, initialError });\n\n const isNewUser = isSignup === \"true\";\n\n this.signerType = \"alchemy-signer\";\n\n if (emailBundle) {\n this.authenticate({\n type: \"email\",\n bundle: emailBundle,\n isNewUser,\n });\n } else if (oauthBundle && oauthOrgId && idToken) {\n this.authenticate({\n type: \"oauthReturn\",\n bundle: oauthBundle,\n orgId: oauthOrgId,\n idToken,\n isNewUser,\n });\n }\n }\n}\n\n/**\n * Reads and removes the specified query params from the URL.\n *\n * @param {T} keys object whose values are the query parameter keys to read and\n * remove\n * @returns {{ [K in keyof T]: string | undefined }} object with the same keys\n * as the input whose values are the values of the query params.\n */\nfunction getAndRemoveQueryParams<T extends Record<string, string>>(\n keys: T\n): { [K in keyof T]: string | undefined } {\n const url = new URL(window.location.href);\n const result: Record<string, string | undefined> = {};\n let foundQueryParam = false;\n for (const [key, param] of Object.entries(keys)) {\n const value = url.searchParams.get(param) ?? undefined;\n foundQueryParam ||= value != null;\n result[key] = value;\n url.searchParams.delete(param);\n }\n if (foundQueryParam) {\n window.history.replaceState(window.history.state, \"\", url.toString());\n }\n return result as { [K in keyof T]: string | undefined };\n}\n"]}
1
+ {"version":3,"file":"signer.js","sourceRoot":"","sources":["../../src/signer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EACL,+BAA+B,EAC/B,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AA+ElE,MAAM,CAAC,M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,OAAO,MAAgD,CAAC;AAC1D,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { BaseAlchemySigner } from \"./base.js\";\nimport {\n AlchemySignerClientParamsSchema,\n AlchemySignerWebClient,\n} from \"./client/index.js\";\nimport type { CredentialCreationOptionOverrides } from \"./client/types.js\";\nimport { SessionManagerParamsSchema } from \"./session/manager.js\";\n\nexport type AuthParams =\n | {\n type: \"email\";\n email: string;\n /** @deprecated This option will be overriden by dashboard settings. Please use the dashboard settings instead. This option will be removed in a future release. */\n emailMode?: \"magicLink\" | \"otp\";\n redirectParams?: URLSearchParams;\n }\n | { type: \"email\"; bundle: string; orgId?: string; isNewUser?: boolean }\n | {\n type: \"passkey\";\n email: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | {\n type: \"passkey\";\n createNew: false;\n }\n | {\n type: \"passkey\";\n createNew: true;\n username: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | ({\n type: \"oauth\";\n scope?: string;\n claims?: string;\n otherParameters?: Record<string, string>;\n } & OauthProviderConfig &\n OauthRedirectConfig)\n | ({\n type: \"custom-jwt\";\n jwt: string;\n } & OauthProviderConfig)\n | {\n type: \"oauthReturn\";\n bundle: string;\n orgId: string;\n idToken: string;\n isNewUser?: boolean;\n }\n | {\n type: \"otp\";\n otpCode: string;\n };\n\nexport type OauthProviderConfig =\n | {\n authProviderId: \"auth0\";\n isCustomProvider?: false;\n auth0Connection?: string;\n }\n | {\n authProviderId: KnownAuthProvider;\n isCustomProvider?: false;\n auth0Connection?: never;\n }\n | {\n authProviderId: string;\n isCustomProvider: true;\n auth0Connection?: never;\n };\n\nexport type OauthRedirectConfig =\n | { mode: \"redirect\"; redirectUrl: string }\n | { mode: \"popup\"; redirectUrl?: never };\n\nexport type KnownAuthProvider =\n | \"google\"\n | \"apple\"\n | \"facebook\"\n | \"twitch\"\n | \"auth0\";\n\nexport type OauthMode = \"redirect\" | \"popup\";\n\nexport const AlchemySignerParamsSchema = z\n .object({\n client: z\n .custom<AlchemySignerWebClient>()\n .or(AlchemySignerClientParamsSchema),\n })\n .extend({\n sessionConfig: SessionManagerParamsSchema.omit({\n client: true,\n }).optional(),\n });\n\nexport type AlchemySignerParams = z.input<typeof AlchemySignerParamsSchema>;\n\n/**\n * A SmartAccountSigner that can be used with any SmartContractAccount\n */\nexport class AlchemyWebSigner extends BaseAlchemySigner<AlchemySignerWebClient> {\n /**\n * Initializes an instance with the provided Alchemy signer parameters after parsing them with a schema.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n * ```\n *\n * @param {AlchemySignerParams} params The parameters for the Alchemy signer, including the client and session configuration\n */\n\n constructor(params: AlchemySignerParams) {\n const { sessionConfig, ...params_ } =\n AlchemySignerParamsSchema.parse(params);\n\n let client: AlchemySignerWebClient;\n if (\"connection\" in params_.client) {\n client = new AlchemySignerWebClient(params_.client);\n } else {\n client = params_.client;\n }\n const {\n emailBundle,\n oauthBundle,\n oauthOrgId,\n oauthError,\n idToken,\n isSignup,\n } = getAndRemoveQueryParams({\n emailBundle: \"bundle\",\n // We don't need this, but we still want to remove it from the URL.\n emailOrgId: \"orgId\",\n oauthBundle: \"alchemy-bundle\",\n oauthOrgId: \"alchemy-org-id\",\n oauthError: \"alchemy-error\",\n idToken: \"alchemy-id-token\",\n isSignup: \"aa-is-signup\",\n });\n\n const initialError =\n oauthError != null\n ? { name: \"OauthError\", message: oauthError }\n : undefined;\n\n super({ client, sessionConfig, initialError });\n\n const isNewUser = isSignup === \"true\";\n\n this.signerType = \"alchemy-signer\";\n\n if (emailBundle) {\n this.authenticate({\n type: \"email\",\n bundle: emailBundle,\n isNewUser,\n });\n } else if (oauthBundle && oauthOrgId && idToken) {\n this.authenticate({\n type: \"oauthReturn\",\n bundle: oauthBundle,\n orgId: oauthOrgId,\n idToken,\n isNewUser,\n });\n }\n }\n}\n\n/**\n * Reads and removes the specified query params from the URL.\n *\n * @param {T} keys object whose values are the query parameter keys to read and\n * remove\n * @returns {{ [K in keyof T]: string | undefined }} object with the same keys\n * as the input whose values are the values of the query params.\n */\nfunction getAndRemoveQueryParams<T extends Record<string, string>>(\n keys: T\n): { [K in keyof T]: string | undefined } {\n const url = new URL(window.location.href);\n const result: Record<string, string | undefined> = {};\n let foundQueryParam = false;\n for (const [key, param] of Object.entries(keys)) {\n const value = url.searchParams.get(param) ?? undefined;\n foundQueryParam ||= value != null;\n result[key] = value;\n url.searchParams.delete(param);\n }\n if (foundQueryParam) {\n window.history.replaceState(window.history.state, \"\", url.toString());\n }\n return result as { [K in keyof T]: string | undefined };\n}\n"]}
@@ -5,10 +5,6 @@ export type AlchemySignerEvents = {
5
5
  disconnected(): void;
6
6
  statusChanged(status: AlchemySignerStatus): void;
7
7
  errorChanged(error: ErrorInfo | undefined): void;
8
- mfaStatusChanged(mfaStatus: {
9
- mfaRequired: boolean;
10
- mfaFactorId?: string;
11
- }): void;
12
8
  };
13
9
  export type AlchemySignerEvent = keyof AlchemySignerEvents;
14
10
  export declare enum AlchemySignerStatus {
@@ -19,11 +15,8 @@ export declare enum AlchemySignerStatus {
19
15
  AUTHENTICATING_EMAIL = "AUTHENTICATING_EMAIL",
20
16
  AUTHENTICATING_OAUTH = "AUTHENTICATING_OAUTH",
21
17
  AWAITING_EMAIL_AUTH = "AWAITING_EMAIL_AUTH",
22
- AWAITING_OTP_AUTH = "AWAITING_OTP_AUTH"
23
- }
24
- export declare enum AlchemyMfaStatus {
25
- NOT_REQUIRED = "not_required",
26
- REQUIRED = "required"
18
+ AWAITING_OTP_AUTH = "AWAITING_OTP_AUTH",
19
+ AUTHENTICATING_JWT = "AUTHENTICATING_JWT"
27
20
  }
28
21
  export interface ErrorInfo {
29
22
  name: string;