@account-kit/signer 4.14.0 → 4.15.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/dist/esm/base.d.ts +1 -1
- package/dist/esm/base.js +6 -2
- package/dist/esm/base.js.map +1 -1
- package/dist/esm/session/manager.js +3 -0
- package/dist/esm/session/manager.js.map +1 -1
- package/dist/esm/signer.js +4 -1
- package/dist/esm/signer.js.map +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/dist/types/base.d.ts +1 -1
- package/dist/types/base.d.ts.map +1 -1
- package/dist/types/session/manager.d.ts.map +1 -1
- package/dist/types/signer.d.ts.map +1 -1
- package/dist/types/version.d.ts +1 -1
- package/package.json +4 -4
- package/src/base.ts +7 -3
- package/src/session/manager.ts +3 -0
- package/src/signer.ts +6 -1
- package/src/version.ts +1 -1
package/dist/esm/base.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export interface BaseAlchemySignerParams<TClient extends BaseSignerClient> {
|
|
|
16
16
|
* Implements the `SmartAccountAuthenticator` interface and handles various signer events.
|
|
17
17
|
*/
|
|
18
18
|
export declare abstract class BaseAlchemySigner<TClient extends BaseSignerClient> implements SmartAccountAuthenticator<AuthParams, User, TClient> {
|
|
19
|
-
signerType:
|
|
19
|
+
signerType: "alchemy-signer" | "rn-alchemy-signer";
|
|
20
20
|
inner: TClient;
|
|
21
21
|
private sessionManager;
|
|
22
22
|
private store;
|
package/dist/esm/base.js
CHANGED
|
@@ -681,7 +681,9 @@ export class BaseAlchemySigner {
|
|
|
681
681
|
? { orgId: params.orgId }
|
|
682
682
|
: this.sessionManager.getTemporarySession();
|
|
683
683
|
if (!temporarySession) {
|
|
684
|
-
this.store.setState({
|
|
684
|
+
this.store.setState({
|
|
685
|
+
status: AlchemySignerStatus.DISCONNECTED,
|
|
686
|
+
});
|
|
685
687
|
throw new Error("Could not find email auth init session!");
|
|
686
688
|
}
|
|
687
689
|
const user = await this.inner.completeAuthWithBundle({
|
|
@@ -722,7 +724,9 @@ export class BaseAlchemySigner {
|
|
|
722
724
|
else {
|
|
723
725
|
user = await this.inner.lookupUserWithPasskey();
|
|
724
726
|
if (!user) {
|
|
725
|
-
this.store.setState({
|
|
727
|
+
this.store.setState({
|
|
728
|
+
status: AlchemySignerStatus.DISCONNECTED,
|
|
729
|
+
});
|
|
726
730
|
throw new Error("No user found");
|
|
727
731
|
}
|
|
728
732
|
}
|
package/dist/esm/base.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../src/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAkC,MAAM,cAAc,CAAC;AACzE,OAAO,EACL,WAAW,EACX,aAAa,EACb,SAAS,EACT,oBAAoB,GAWrB,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EACL,cAAc,GAEf,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,mBAAmB,GAIpB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAExD,OAAO,EAAE,iBAAiB,EAAsB,MAAM,mBAAmB,CAAC;AA2B1E;;;GAGG;AACH,MAAM,OAAgB,iBAAiB;IAQrC;;;;;;;;;OASG;IACH,YAAY,EACV,MAAM,EACN,aAAa,EACb,YAAY,GACqB;QAnBnC;;;;mBAAqB,gBAAgB;WAAC;QACtC;;;;;WAAe;QACP;;;;;WAA+B;QAC/B;;;;;WAAqB;QAyC7B;;;;;;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AAE,CAAC;AAClD,CAAC","sourcesContent":["import { takeBytes, type SmartAccountAuthenticator } from \"@aa-sdk/core\";\nimport {\n hashMessage,\n hashTypedData,\n keccak256,\n serializeTransaction,\n type GetTransactionType,\n type Hex,\n type IsNarrowable,\n type LocalAccount,\n type SerializeTransactionFn,\n type SignableMessage,\n type TransactionSerializable,\n type TransactionSerialized,\n type TypedData,\n type TypedDataDefinition,\n} from \"viem\";\nimport { toAccount } from \"viem/accounts\";\nimport type { Mutate, StoreApi } from \"zustand\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport { createStore } from \"zustand/vanilla\";\nimport type { BaseSignerClient } from \"./client/base\";\nimport type { OauthConfig, OauthParams, User } from \"./client/types\";\nimport { NotAuthenticatedError } from \"./errors.js\";\nimport { SignerLogger } from \"./metrics.js\";\nimport {\n SessionManager,\n type SessionManagerParams,\n} from \"./session/manager.js\";\nimport type { AuthParams } from \"./signer\";\nimport {\n AlchemySignerStatus,\n type AlchemySignerEvent,\n type AlchemySignerEvents,\n type ErrorInfo,\n} from \"./types.js\";\nimport { assertNever } from \"./utils/typeAssertions.js\";\nimport type { SessionManagerEvents } from \"./session/types\";\nimport { hashAuthorization, type Authorization } from \"viem/experimental\";\n\nexport interface BaseAlchemySignerParams<TClient extends BaseSignerClient> {\n client: TClient;\n sessionConfig?: Omit<SessionManagerParams, \"client\">;\n initialError?: ErrorInfo;\n}\n\ntype AlchemySignerStore = {\n user: User | null;\n status: AlchemySignerStatus;\n error: ErrorInfo | null;\n otpId?: string;\n isNewUser?: boolean;\n};\n\ntype UnpackedSignature = {\n r: `0x${string}`;\n s: `0x${string}`;\n v: bigint;\n};\n\ntype InternalStore = Mutate<\n StoreApi<AlchemySignerStore>,\n [[\"zustand/subscribeWithSelector\", never]]\n>;\n\n/**\n * Base abstract class for Alchemy Signer, providing authentication and session management for smart accounts.\n * Implements the `SmartAccountAuthenticator` interface and handles various signer events.\n */\nexport abstract class BaseAlchemySigner<TClient extends BaseSignerClient>\n implements SmartAccountAuthenticator<AuthParams, User, TClient>\n{\n signerType: string = \"alchemy-signer\";\n inner: TClient;\n private sessionManager: SessionManager;\n private store: InternalStore;\n\n /**\n * Initializes an instance with the provided client and session configuration.\n * This function sets up the internal store, initializes the session manager,\n * registers listeners and initializes the session manager to manage session state.\n *\n * @param {BaseAlchemySignerParams<TClient>} param0 Object containing the client and session configuration\n * @param {TClient} param0.client The client instance to be used internally\n * @param {SessionConfig} param0.sessionConfig Configuration for managing sessions\n * @param {ErrorInfo | undefined} param0.initialError Error already present on the signer when initialized, if any\n */\n constructor({\n client,\n sessionConfig,\n initialError,\n }: BaseAlchemySignerParams<TClient>) {\n this.inner = client;\n this.store = createStore(\n subscribeWithSelector(\n () =>\n ({\n user: null,\n status: AlchemySignerStatus.INITIALIZING,\n error: initialError ?? null,\n } satisfies AlchemySignerStore)\n )\n );\n // NOTE: it's important that the session manager share a client\n // with the signer. The SessionManager leverages the Signer's client\n // to manage session state.\n this.sessionManager = new SessionManager({\n ...sessionConfig,\n client: this.inner,\n });\n // register listeners first\n this.registerListeners();\n // then initialize so that we can catch those events\n this.sessionManager.initialize();\n }\n\n /**\n * Allows you to subscribe to events emitted by the signer\n *\n * @param {AlchemySignerEvent} event the event to subscribe to\n * @param {AlchemySignerEvents[AlchemySignerEvent]} listener the function to run when the event is emitted\n * @returns {() => void} a function to remove the listener\n */\n on = <E extends AlchemySignerEvent>(\n event: E,\n listener: AlchemySignerEvents[E]\n ) => {\n // NOTE: we're using zustand here to handle this because we are able to use the fireImmediately\n // option which deals with a possible race condition where the listener is added after the event\n // is fired. In the Client and SessionManager we use EventEmitter because it's easier to handle internally\n switch (event) {\n case \"connected\":\n return this.store.subscribe(\n ({ status }) => status,\n (status) =>\n status === AlchemySignerStatus.CONNECTED &&\n (listener as AlchemySignerEvents[\"connected\"])(\n this.store.getState().user!\n ),\n { fireImmediately: true }\n );\n case \"disconnected\":\n return this.store.subscribe(\n ({ status }) => status,\n (status) =>\n status === AlchemySignerStatus.DISCONNECTED &&\n (listener as AlchemySignerEvents[\"disconnected\"])(),\n { fireImmediately: true }\n );\n case \"statusChanged\":\n return this.store.subscribe(\n ({ status }) => status,\n listener as AlchemySignerEvents[\"statusChanged\"],\n { fireImmediately: true }\n );\n case \"errorChanged\":\n return this.store.subscribe(\n ({ error }) => error,\n (error) =>\n (listener as AlchemySignerEvents[\"errorChanged\"])(\n error ?? undefined\n ),\n { fireImmediately: true }\n );\n case \"newUserSignup\":\n return this.store.subscribe(\n ({ isNewUser }) => isNewUser,\n (isNewUser) => {\n if (isNewUser) (listener as AlchemySignerEvents[\"newUserSignup\"])();\n },\n { fireImmediately: true }\n );\n default:\n assertNever(event, `Unknown event type ${event}`);\n }\n };\n\n /**\n * Prepares the config needed to use popup-based OAuth login. This must be\n * called before calling `.authenticate` with params `{ type: \"oauth\", mode:\n * \"popup\" }`, and is recommended to be called on page load.\n *\n * This method exists because browsers may prevent popups from opening unless\n * triggered by user interaction, and so the OAuth config must already have\n * been fetched at the time a user clicks a social login button.\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 * await signer.preparePopupOauth();\n * ```\n * @returns {Promise<OauthConfig>} the config which must be loaded before\n * using popup-based OAuth\n */\n preparePopupOauth = (): Promise<OauthConfig> => this.inner.initOauth();\n\n /**\n * Authenticate a user with either an email or a passkey and create a session for that user\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 * const result = await signer.authenticate({\n * type: \"email\",\n * email: \"foo@mail.com\",\n * });\n * ```\n *\n * @param {AuthParams} params - undefined if passkey login, otherwise an object with email and bundle to resolve\n * @returns {Promise<User>} the user that was authenticated\n */\n authenticate: (params: AuthParams) => Promise<User> = SignerLogger.profiled(\n \"BaseAlchemySigner.authenticate\",\n async (params) => {\n const { type } = params;\n const result = (() => {\n switch (type) {\n case \"email\":\n return this.authenticateWithEmail(params);\n case \"passkey\":\n return this.authenticateWithPasskey(params);\n case \"oauth\":\n return this.authenticateWithOauth(params);\n case \"oauthReturn\":\n return this.handleOauthReturn(params);\n case \"otp\":\n return this.authenticateWithOtp(params);\n default:\n assertNever(type, `Unknown auth type: ${type}`);\n }\n })();\n\n this.trackAuthenticateType(params);\n\n return result.catch((error) => {\n /**\n * 2 things going on here:\n * 1. for oauth flows we expect the status to remain in authenticating\n * 2. we do the ternary, because if we explicitly pass in `undefined` for the status, zustand will set the value of status to `undefined`.\n * However, if we omit it, then it will not override the current value of status.\n */\n this.store.setState({\n error: toErrorInfo(error),\n ...(type === \"oauthReturn\" || type === \"oauth\"\n ? {}\n : { status: AlchemySignerStatus.DISCONNECTED }),\n });\n throw error;\n });\n }\n );\n\n private trackAuthenticateType = (params: AuthParams) => {\n const { type } = params;\n switch (type) {\n case \"email\": {\n // we just want to track the start of email auth\n if (\"bundle\" in params) return;\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: { authType: \"email\" },\n });\n return;\n }\n case \"passkey\": {\n const isAnon = !(\"email\" in params) && params.createNew == null;\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: {\n authType: isAnon ? \"passkey_anon\" : \"passkey_email\",\n },\n });\n return;\n }\n case \"oauth\":\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: {\n authType: \"oauth\",\n provider: params.authProviderId,\n },\n });\n break;\n case \"oauthReturn\":\n break;\n case \"otp\":\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: { authType: \"otp\" },\n });\n break;\n default:\n assertNever(type, `Unknown auth type: ${type}`);\n }\n };\n\n /**\n * Clear a user session and log them out\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 * await signer.disconnect();\n * ```\n *\n * @returns {Promise<void>} a promise that resolves when the user is logged out\n */\n disconnect: () => Promise<void> = async () => {\n await this.inner.disconnect();\n };\n\n /**\n * Gets the current logged in user\n * If a user has an ongoing session, it will use that session and\n * try to authenticate\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 * // throws if not logged in\n * const user = await signer.getAuthDetails();\n * ```\n *\n * @throws if there is no user logged in\n * @returns {Promise<User>} the current user\n */\n getAuthDetails = async (): Promise<User> => {\n const sessionUser = await this.sessionManager.getSessionUser();\n if (sessionUser != null) {\n return sessionUser;\n }\n\n return this.inner.whoami();\n };\n\n /**\n * Retrieves the address of the current user by calling the `whoami` method on `this.inner`.\n *\n * @returns {Promise<string>} A promise that resolves to the address of the current user.\n */\n getAddress: () => Promise<`0x${string}`> = SignerLogger.profiled(\n \"BaseAlchemySigner.getAddress\",\n async () => {\n const { address } = await this.inner.whoami();\n\n return address;\n }\n );\n\n /**\n * Signs a raw message after hashing it.\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 * const signature = await signer.signMessage(\"Hello, world!\");\n * ```\n *\n * @param {string} msg the message to be hashed and then signed\n * @returns {Promise<string>} a promise that resolves to the signed message\n */\n signMessage: (msg: SignableMessage) => Promise<`0x${string}`> =\n SignerLogger.profiled(\"BaseAlchemySigner.signMessage\", async (msg) => {\n const messageHash = hashMessage(msg);\n\n const result = await this.inner.signRawMessage(messageHash);\n\n SignerLogger.trackEvent({\n name: \"signer_sign_message\",\n });\n\n return result;\n });\n\n /**\n * Signs a typed message by first hashing it and then signing the hashed message using the `signRawMessage` method.\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 * const signature = await signer.signTypedData({\n * domain: {},\n * types: {},\n * primaryType: \"\",\n * message: {},\n * });\n * ```\n *\n * @param {TypedDataDefinition<TTypedData, TPrimaryType>} params The parameters for the typed message to be hashed and signed\n * @returns {Promise<any>} A promise that resolves to the signed message\n */\n signTypedData: <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | \"EIP712Domain\" = keyof TTypedData\n >(\n params: TypedDataDefinition<TTypedData, TPrimaryType>\n ) => Promise<Hex> = SignerLogger.profiled(\n \"BaseAlchemySigner.signTypedData\",\n async (params) => {\n const messageHash = hashTypedData(params);\n\n return this.inner.signRawMessage(messageHash);\n }\n );\n\n /**\n * Serializes a transaction, signs it with a raw message, and then returns the serialized transaction with the signature.\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 * const tx = await signer.signTransaction({\n * to: \"0x1234\",\n * value: \"0x1234\",\n * data: \"0x1234\",\n * });\n * ```\n *\n * @param {Transaction} tx the transaction to be serialized and signed\n * @param {{serializer?: SerializeTransactionFn}} args options for serialization\n * @param {() => Hex} [args.serializer] an optional serializer function. If not provided, the default `serializeTransaction` function will be used\n * @returns {Promise<string>} a promise that resolves to the serialized transaction with the signature\n */\n signTransaction: <\n serializer extends SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0]\n >(\n transaction: transaction,\n options?:\n | {\n serializer?: serializer | undefined;\n }\n | undefined\n ) => Promise<\n IsNarrowable<\n TransactionSerialized<GetTransactionType<transaction>>,\n Hex\n > extends true\n ? TransactionSerialized<GetTransactionType<transaction>>\n : Hex\n > = SignerLogger.profiled(\n \"BaseAlchemySigner.signTransaction\",\n async (tx, args) => {\n const serializeFn = args?.serializer ?? serializeTransaction;\n const serializedTx = serializeFn(tx);\n const signatureHex = await this.inner.signRawMessage(\n keccak256(serializedTx)\n );\n\n const signature = this.unpackSignRawMessageBytes(signatureHex);\n\n return serializeFn(tx, signature);\n }\n );\n\n /**\n * Signs an EIP-7702 Authorization and then returns the authorization with the signature.\n *\n * @example\n * ```ts twoslash\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 * const tx = await signer.signAuthorization({\n * contractAddress: \"0x1234123412341234123412341234123412341234\",\n * chainId: 1,\n * nonce: 0,\n * });\n * ```\n *\n * @param {Authorization<number, false>} unsignedAuthorization the authorization to be signed\n * @returns {Promise<Authorization<number, true>> | undefined} a promise that resolves to the authorization with the signature\n */\n signAuthorization: (\n unsignedAuthorization: Authorization<number, false>\n ) => Promise<Authorization<number, true>> = SignerLogger.profiled(\n \"BaseAlchemySigner.signAuthorization\",\n async (unsignedAuthorization) => {\n const hashedAuthorization = hashAuthorization(unsignedAuthorization);\n const signedAuthorizationHex = await this.inner.signRawMessage(\n hashedAuthorization\n );\n const signature = this.unpackSignRawMessageBytes(signedAuthorizationHex);\n return { ...unsignedAuthorization, ...signature };\n }\n );\n\n private unpackSignRawMessageBytes = (\n hex: `0x${string}`\n ): UnpackedSignature => {\n return {\n r: takeBytes(hex, { count: 32 }),\n s: takeBytes(hex, { count: 32, offset: 32 }),\n v: BigInt(takeBytes(hex, { count: 1, offset: 64 })),\n };\n };\n\n /**\n * Unauthenticated call to look up a user's organizationId by email\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 * const result = await signer.getUser(\"foo@mail.com\");\n * ```\n *\n * @param {string} email the email to lookup\n * @returns {Promise<{orgId: string}>} the organization id for the user if they exist\n */\n getUser: (email: string) => Promise<{ orgId: string } | null> =\n SignerLogger.profiled(\"BaseAlchemySigner.getUser\", async (email) => {\n const result = await this.inner.lookupUserByEmail(email);\n\n if (result.orgId == null) {\n return null;\n }\n\n return {\n orgId: result.orgId,\n };\n });\n\n /**\n * Adds a passkey to the user's account\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 * const result = await signer.addPasskey()\n * ```\n *\n * @param {CredentialCreationOptions | undefined} params optional parameters for the passkey creation\n * @returns {Promise<string[]>} an array of the authenticator ids added to the user\n */\n addPasskey: (params?: CredentialCreationOptions) => Promise<string[]> =\n SignerLogger.profiled(\"BaseAlchemySigner.addPasskey\", async (params) => {\n return this.inner.addPasskey(params ?? {});\n });\n\n /**\n * Used to export the wallet for a given user\n * If the user is authenticated with an Email, this will return a seed phrase\n * If the user is authenticated with a Passkey, this will return a private key\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 * // the params passed to this are different based on the specific signer\n * const result = signer.exportWallet()\n * ```\n *\n * @param {unknown} params export wallet parameters\n * @returns {boolean} true if the wallet was exported successfully\n */\n exportWallet: (\n params: Parameters<(typeof this.inner)[\"exportWallet\"]>[0]\n ) => Promise<boolean> = async (params) => {\n return this.inner.exportWallet(params);\n };\n\n /**\n * This method lets you adapt your AlchemySigner to a viem LocalAccount, which\n * will let you use the signer as an EOA directly.\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 * const account = signer.toViemAccount();\n * ```\n *\n * @throws if your signer is not authenticated\n * @returns {LocalAccount} a LocalAccount object that can be used with viem's wallet client\n */\n toViemAccount = (): LocalAccount => {\n // if we want this method to be synchronous, then we need to do this check here\n // otherwise we can use the sessionManager to get the user\n if (!this.inner.getUser()) {\n throw new NotAuthenticatedError();\n }\n\n return toAccount({\n address: this.inner.getUser()!.address,\n signMessage: (msg) => this.signMessage(msg.message),\n signTypedData: <\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | \"EIP712Domain\" = keyof typedData\n >(\n typedDataDefinition: TypedDataDefinition<typedData, primaryType>\n ) => this.signTypedData<typedData, primaryType>(typedDataDefinition),\n signTransaction: this.signTransaction,\n });\n };\n\n private authenticateWithEmail = async (\n params: Extract<AuthParams, { type: \"email\" }>\n ): Promise<User> => {\n if (\"email\" in params) {\n const existingUser = await this.getUser(params.email);\n const expirationSeconds = this.getExpirationSeconds();\n\n const { orgId, otpId } = existingUser\n ? await this.inner.initEmailAuth({\n email: params.email,\n emailMode: params.emailMode,\n expirationSeconds,\n redirectParams: params.redirectParams,\n })\n : await this.inner.createAccount({\n type: \"email\",\n email: params.email,\n emailMode: params.emailMode,\n expirationSeconds,\n redirectParams: params.redirectParams,\n });\n\n this.sessionManager.setTemporarySession({\n orgId,\n isNewUser: !existingUser,\n });\n this.store.setState({\n status: AlchemySignerStatus.AWAITING_EMAIL_AUTH,\n otpId,\n error: null,\n });\n\n // We wait for the session manager to emit a connected event if\n // cross tab sessions are permitted\n return new Promise<User>((resolve) => {\n const removeListener = this.sessionManager.on(\n \"connected\",\n (session) => {\n resolve(session.user);\n removeListener();\n }\n );\n });\n } else {\n const temporarySession = params.orgId\n ? { orgId: params.orgId }\n : this.sessionManager.getTemporarySession();\n\n if (!temporarySession) {\n this.store.setState({ status: AlchemySignerStatus.DISCONNECTED });\n throw new Error(\"Could not find email auth init session!\");\n }\n\n const user = await this.inner.completeAuthWithBundle({\n bundle: params.bundle,\n orgId: temporarySession.orgId,\n connectedEventName: \"connectedEmail\",\n authenticatingType: \"email\",\n });\n\n // fire new user event\n this.emitNewUserEvent(params.isNewUser);\n\n return user;\n }\n };\n\n private authenticateWithPasskey = async (\n args: Extract<AuthParams, { type: \"passkey\" }>\n ): Promise<User> => {\n let user: User;\n const shouldCreateNew = async () => {\n if (\"email\" in args) {\n const existingUser = await this.getUser(args.email);\n return existingUser == null;\n }\n\n return args.createNew;\n };\n\n if (await shouldCreateNew()) {\n const result = await this.inner.createAccount(\n args as Extract<\n AuthParams,\n { type: \"passkey\" } & ({ email: string } | { createNew: true })\n >\n );\n // account creation for passkeys returns the whoami response so we don't have to\n // call it again after signup\n user = {\n address: result.address!,\n userId: result.userId!,\n orgId: result.orgId,\n };\n } else {\n user = await this.inner.lookupUserWithPasskey();\n if (!user) {\n this.store.setState({ status: AlchemySignerStatus.DISCONNECTED });\n throw new Error(\"No user found\");\n }\n }\n\n return user;\n };\n\n private authenticateWithOauth = async (\n args: Extract<AuthParams, { type: \"oauth\" }>\n ): Promise<User> => {\n const params: OauthParams = {\n ...args,\n expirationSeconds: this.getExpirationSeconds(),\n };\n if (params.mode === \"redirect\") {\n return this.inner.oauthWithRedirect(params);\n } else {\n return this.inner.oauthWithPopup(params);\n }\n };\n\n private authenticateWithOtp = async (\n args: Extract<AuthParams, { type: \"otp\" }>\n ): Promise<User> => {\n const tempSession = this.sessionManager.getTemporarySession();\n const { orgId, isNewUser } = tempSession ?? {};\n const { otpId } = this.store.getState();\n if (!orgId) {\n throw new Error(\"orgId not found in session\");\n }\n if (!otpId) {\n throw new Error(\"otpId not found in session\");\n }\n const { bundle } = await this.inner.submitOtpCode({\n orgId,\n otpId,\n otpCode: args.otpCode,\n expirationSeconds: this.getExpirationSeconds(),\n });\n const user = await this.inner.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOtp\",\n authenticatingType: \"otp\",\n });\n\n this.emitNewUserEvent(isNewUser);\n if (tempSession) {\n this.sessionManager.setTemporarySession({\n ...tempSession,\n isNewUser: false,\n });\n }\n\n return user;\n };\n\n private handleOauthReturn = ({\n bundle,\n orgId,\n idToken,\n isNewUser,\n }: Extract<AuthParams, { type: \"oauthReturn\" }>): Promise<User> => {\n const user = this.inner.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOauth\",\n authenticatingType: \"oauth\",\n idToken,\n });\n\n this.emitNewUserEvent(isNewUser);\n\n return user;\n };\n\n private getExpirationSeconds = () =>\n Math.floor(this.sessionManager.expirationTimeMs / 1000);\n\n private registerListeners = () => {\n // Declare listeners in an object to typecheck that every event type is\n // handled.\n const listeners: SessionManagerEvents = {\n connected: (session) => {\n this.store.setState({\n user: session.user,\n status: AlchemySignerStatus.CONNECTED,\n error: null,\n });\n },\n disconnected: () => {\n this.store.setState({\n user: null,\n status: AlchemySignerStatus.DISCONNECTED,\n });\n },\n initialized: () => {\n this.store.setState((state) => ({\n status: state.user\n ? AlchemySignerStatus.CONNECTED\n : AlchemySignerStatus.DISCONNECTED,\n ...(state.user ? { error: null } : undefined),\n }));\n },\n };\n\n for (const [event, listener] of Object.entries(listeners)) {\n this.sessionManager.on(event as keyof SessionManagerEvents, listener);\n }\n\n this.inner.on(\"authenticating\", ({ type }) => {\n const status = (() => {\n switch (type) {\n case \"email\":\n return AlchemySignerStatus.AUTHENTICATING_EMAIL;\n case \"passkey\":\n return AlchemySignerStatus.AUTHENTICATING_PASSKEY;\n case \"oauth\":\n return AlchemySignerStatus.AUTHENTICATING_OAUTH;\n case \"otp\":\n case \"otpVerify\":\n return AlchemySignerStatus.AWAITING_OTP_AUTH;\n default:\n assertNever(type, \"unhandled authenticating type\");\n }\n })();\n\n // trigger new user event on signer from client\n this.inner.on(\"newUserSignup\", () => {\n this.emitNewUserEvent(true);\n });\n\n this.store.setState({\n status,\n error: null,\n });\n });\n };\n\n private emitNewUserEvent = (isNewUser?: boolean) => {\n // assumes that if isNewUser is undefined it is a returning user\n if (isNewUser) this.store.setState({ isNewUser });\n };\n}\n\nfunction toErrorInfo(error: unknown): ErrorInfo {\n return error instanceof Error\n ? { name: error.name, message: error.message }\n : { name: \"Error\", message: \"Unknown error\" };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../src/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAkC,MAAM,cAAc,CAAC;AACzE,OAAO,EACL,WAAW,EACX,aAAa,EACb,SAAS,EACT,oBAAoB,GAWrB,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,cA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AC;YACvC,GAAG,aAAa;YAChB,MAAM,EAAE,IAAI,CAAC,KAAK;SACnB,CAAC,CAAC;QACH,2BAA2B;QAC3B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACzB,oDAAoD;QACpD,IAAI,CAAC,cAAc,CAAC,UAAU,EAAE,CAAC;IACnC,CAAC;CAk2BF;AAED,SAAS,WAAW,CAAC,KAAc;IACjC,OAAO,KAAK,YAAY,KAAK;QAC3B,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE;QAC9C,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC;AAClD,CAAC","sourcesContent":["import { takeBytes, type SmartAccountAuthenticator } from \"@aa-sdk/core\";\nimport {\n hashMessage,\n hashTypedData,\n keccak256,\n serializeTransaction,\n type GetTransactionType,\n type Hex,\n type IsNarrowable,\n type LocalAccount,\n type SerializeTransactionFn,\n type SignableMessage,\n type TransactionSerializable,\n type TransactionSerialized,\n type TypedData,\n type TypedDataDefinition,\n} from \"viem\";\nimport { toAccount } from \"viem/accounts\";\nimport type { Mutate, StoreApi } from \"zustand\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport { createStore } from \"zustand/vanilla\";\nimport type { BaseSignerClient } from \"./client/base\";\nimport type { OauthConfig, OauthParams, User } from \"./client/types\";\nimport { NotAuthenticatedError } from \"./errors.js\";\nimport { SignerLogger } from \"./metrics.js\";\nimport {\n SessionManager,\n type SessionManagerParams,\n} from \"./session/manager.js\";\nimport type { AuthParams } from \"./signer\";\nimport {\n AlchemySignerStatus,\n type AlchemySignerEvent,\n type AlchemySignerEvents,\n type ErrorInfo,\n} from \"./types.js\";\nimport { assertNever } from \"./utils/typeAssertions.js\";\nimport type { SessionManagerEvents } from \"./session/types\";\nimport { hashAuthorization, type Authorization } from \"viem/experimental\";\n\nexport interface BaseAlchemySignerParams<TClient extends BaseSignerClient> {\n client: TClient;\n sessionConfig?: Omit<SessionManagerParams, \"client\">;\n initialError?: ErrorInfo;\n}\n\ntype AlchemySignerStore = {\n user: User | null;\n status: AlchemySignerStatus;\n error: ErrorInfo | null;\n otpId?: string;\n isNewUser?: boolean;\n};\n\ntype UnpackedSignature = {\n r: `0x${string}`;\n s: `0x${string}`;\n v: bigint;\n};\n\ntype InternalStore = Mutate<\n StoreApi<AlchemySignerStore>,\n [[\"zustand/subscribeWithSelector\", never]]\n>;\n\n/**\n * Base abstract class for Alchemy Signer, providing authentication and session management for smart accounts.\n * Implements the `SmartAccountAuthenticator` interface and handles various signer events.\n */\nexport abstract class BaseAlchemySigner<TClient extends BaseSignerClient>\n implements SmartAccountAuthenticator<AuthParams, User, TClient>\n{\n signerType: \"alchemy-signer\" | \"rn-alchemy-signer\" = \"alchemy-signer\";\n inner: TClient;\n private sessionManager: SessionManager;\n private store: InternalStore;\n\n /**\n * Initializes an instance with the provided client and session configuration.\n * This function sets up the internal store, initializes the session manager,\n * registers listeners and initializes the session manager to manage session state.\n *\n * @param {BaseAlchemySignerParams<TClient>} param0 Object containing the client and session configuration\n * @param {TClient} param0.client The client instance to be used internally\n * @param {SessionConfig} param0.sessionConfig Configuration for managing sessions\n * @param {ErrorInfo | undefined} param0.initialError Error already present on the signer when initialized, if any\n */\n constructor({\n client,\n sessionConfig,\n initialError,\n }: BaseAlchemySignerParams<TClient>) {\n this.inner = client;\n this.store = createStore(\n subscribeWithSelector(\n () =>\n ({\n user: null,\n status: AlchemySignerStatus.INITIALIZING,\n error: initialError ?? null,\n } satisfies AlchemySignerStore)\n )\n );\n // NOTE: it's important that the session manager share a client\n // with the signer. The SessionManager leverages the Signer's client\n // to manage session state.\n this.sessionManager = new SessionManager({\n ...sessionConfig,\n client: this.inner,\n });\n // register listeners first\n this.registerListeners();\n // then initialize so that we can catch those events\n this.sessionManager.initialize();\n }\n\n /**\n * Allows you to subscribe to events emitted by the signer\n *\n * @param {AlchemySignerEvent} event the event to subscribe to\n * @param {AlchemySignerEvents[AlchemySignerEvent]} listener the function to run when the event is emitted\n * @returns {() => void} a function to remove the listener\n */\n on = <E extends AlchemySignerEvent>(\n event: E,\n listener: AlchemySignerEvents[E]\n ) => {\n // NOTE: we're using zustand here to handle this because we are able to use the fireImmediately\n // option which deals with a possible race condition where the listener is added after the event\n // is fired. In the Client and SessionManager we use EventEmitter because it's easier to handle internally\n switch (event) {\n case \"connected\":\n return this.store.subscribe(\n ({ status }) => status,\n (status) =>\n status === AlchemySignerStatus.CONNECTED &&\n (listener as AlchemySignerEvents[\"connected\"])(\n this.store.getState().user!\n ),\n { fireImmediately: true }\n );\n case \"disconnected\":\n return this.store.subscribe(\n ({ status }) => status,\n (status) =>\n status === AlchemySignerStatus.DISCONNECTED &&\n (listener as AlchemySignerEvents[\"disconnected\"])(),\n { fireImmediately: true }\n );\n case \"statusChanged\":\n return this.store.subscribe(\n ({ status }) => status,\n listener as AlchemySignerEvents[\"statusChanged\"],\n { fireImmediately: true }\n );\n case \"errorChanged\":\n return this.store.subscribe(\n ({ error }) => error,\n (error) =>\n (listener as AlchemySignerEvents[\"errorChanged\"])(\n error ?? undefined\n ),\n { fireImmediately: true }\n );\n case \"newUserSignup\":\n return this.store.subscribe(\n ({ isNewUser }) => isNewUser,\n (isNewUser) => {\n if (isNewUser) (listener as AlchemySignerEvents[\"newUserSignup\"])();\n },\n { fireImmediately: true }\n );\n default:\n assertNever(event, `Unknown event type ${event}`);\n }\n };\n\n /**\n * Prepares the config needed to use popup-based OAuth login. This must be\n * called before calling `.authenticate` with params `{ type: \"oauth\", mode:\n * \"popup\" }`, and is recommended to be called on page load.\n *\n * This method exists because browsers may prevent popups from opening unless\n * triggered by user interaction, and so the OAuth config must already have\n * been fetched at the time a user clicks a social login button.\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 * await signer.preparePopupOauth();\n * ```\n * @returns {Promise<OauthConfig>} the config which must be loaded before\n * using popup-based OAuth\n */\n preparePopupOauth = (): Promise<OauthConfig> => this.inner.initOauth();\n\n /**\n * Authenticate a user with either an email or a passkey and create a session for that user\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 * const result = await signer.authenticate({\n * type: \"email\",\n * email: \"foo@mail.com\",\n * });\n * ```\n *\n * @param {AuthParams} params - undefined if passkey login, otherwise an object with email and bundle to resolve\n * @returns {Promise<User>} the user that was authenticated\n */\n authenticate: (params: AuthParams) => Promise<User> = SignerLogger.profiled(\n \"BaseAlchemySigner.authenticate\",\n async (params) => {\n const { type } = params;\n const result = (() => {\n switch (type) {\n case \"email\":\n return this.authenticateWithEmail(params);\n case \"passkey\":\n return this.authenticateWithPasskey(params);\n case \"oauth\":\n return this.authenticateWithOauth(params);\n case \"oauthReturn\":\n return this.handleOauthReturn(params);\n case \"otp\":\n return this.authenticateWithOtp(params);\n default:\n assertNever(type, `Unknown auth type: ${type}`);\n }\n })();\n\n this.trackAuthenticateType(params);\n\n return result.catch((error) => {\n /**\n * 2 things going on here:\n * 1. for oauth flows we expect the status to remain in authenticating\n * 2. we do the ternary, because if we explicitly pass in `undefined` for the status, zustand will set the value of status to `undefined`.\n * However, if we omit it, then it will not override the current value of status.\n */\n this.store.setState({\n error: toErrorInfo(error),\n ...(type === \"oauthReturn\" || type === \"oauth\"\n ? {}\n : { status: AlchemySignerStatus.DISCONNECTED }),\n });\n throw error;\n });\n }\n );\n\n private trackAuthenticateType = (params: AuthParams) => {\n const { type } = params;\n switch (type) {\n case \"email\": {\n // we just want to track the start of email auth\n if (\"bundle\" in params) return;\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: { authType: \"email\" },\n });\n return;\n }\n case \"passkey\": {\n const isAnon = !(\"email\" in params) && params.createNew == null;\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: {\n authType: isAnon ? \"passkey_anon\" : \"passkey_email\",\n },\n });\n return;\n }\n case \"oauth\":\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: {\n authType: \"oauth\",\n provider: params.authProviderId,\n },\n });\n break;\n case \"oauthReturn\":\n break;\n case \"otp\":\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: { authType: \"otp\" },\n });\n break;\n default:\n assertNever(type, `Unknown auth type: ${type}`);\n }\n };\n\n /**\n * Clear a user session and log them out\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 * await signer.disconnect();\n * ```\n *\n * @returns {Promise<void>} a promise that resolves when the user is logged out\n */\n disconnect: () => Promise<void> = async () => {\n await this.inner.disconnect();\n };\n\n /**\n * Gets the current logged in user\n * If a user has an ongoing session, it will use that session and\n * try to authenticate\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 * // throws if not logged in\n * const user = await signer.getAuthDetails();\n * ```\n *\n * @throws if there is no user logged in\n * @returns {Promise<User>} the current user\n */\n getAuthDetails = async (): Promise<User> => {\n const sessionUser = await this.sessionManager.getSessionUser();\n if (sessionUser != null) {\n return sessionUser;\n }\n\n return this.inner.whoami();\n };\n\n /**\n * Retrieves the address of the current user by calling the `whoami` method on `this.inner`.\n *\n * @returns {Promise<string>} A promise that resolves to the address of the current user.\n */\n getAddress: () => Promise<`0x${string}`> = SignerLogger.profiled(\n \"BaseAlchemySigner.getAddress\",\n async () => {\n const { address } = await this.inner.whoami();\n\n return address;\n }\n );\n\n /**\n * Signs a raw message after hashing it.\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 * const signature = await signer.signMessage(\"Hello, world!\");\n * ```\n *\n * @param {string} msg the message to be hashed and then signed\n * @returns {Promise<string>} a promise that resolves to the signed message\n */\n signMessage: (msg: SignableMessage) => Promise<`0x${string}`> =\n SignerLogger.profiled(\"BaseAlchemySigner.signMessage\", async (msg) => {\n const messageHash = hashMessage(msg);\n\n const result = await this.inner.signRawMessage(messageHash);\n\n SignerLogger.trackEvent({\n name: \"signer_sign_message\",\n });\n\n return result;\n });\n\n /**\n * Signs a typed message by first hashing it and then signing the hashed message using the `signRawMessage` method.\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 * const signature = await signer.signTypedData({\n * domain: {},\n * types: {},\n * primaryType: \"\",\n * message: {},\n * });\n * ```\n *\n * @param {TypedDataDefinition<TTypedData, TPrimaryType>} params The parameters for the typed message to be hashed and signed\n * @returns {Promise<any>} A promise that resolves to the signed message\n */\n signTypedData: <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | \"EIP712Domain\" = keyof TTypedData\n >(\n params: TypedDataDefinition<TTypedData, TPrimaryType>\n ) => Promise<Hex> = SignerLogger.profiled(\n \"BaseAlchemySigner.signTypedData\",\n async (params) => {\n const messageHash = hashTypedData(params);\n\n return this.inner.signRawMessage(messageHash);\n }\n );\n\n /**\n * Serializes a transaction, signs it with a raw message, and then returns the serialized transaction with the signature.\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 * const tx = await signer.signTransaction({\n * to: \"0x1234\",\n * value: \"0x1234\",\n * data: \"0x1234\",\n * });\n * ```\n *\n * @param {Transaction} tx the transaction to be serialized and signed\n * @param {{serializer?: SerializeTransactionFn}} args options for serialization\n * @param {() => Hex} [args.serializer] an optional serializer function. If not provided, the default `serializeTransaction` function will be used\n * @returns {Promise<string>} a promise that resolves to the serialized transaction with the signature\n */\n signTransaction: <\n serializer extends SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0]\n >(\n transaction: transaction,\n options?:\n | {\n serializer?: serializer | undefined;\n }\n | undefined\n ) => Promise<\n IsNarrowable<\n TransactionSerialized<GetTransactionType<transaction>>,\n Hex\n > extends true\n ? TransactionSerialized<GetTransactionType<transaction>>\n : Hex\n > = SignerLogger.profiled(\n \"BaseAlchemySigner.signTransaction\",\n async (tx, args) => {\n const serializeFn = args?.serializer ?? serializeTransaction;\n const serializedTx = serializeFn(tx);\n const signatureHex = await this.inner.signRawMessage(\n keccak256(serializedTx)\n );\n\n const signature = this.unpackSignRawMessageBytes(signatureHex);\n\n return serializeFn(tx, signature);\n }\n );\n\n /**\n * Signs an EIP-7702 Authorization and then returns the authorization with the signature.\n *\n * @example\n * ```ts twoslash\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 * const tx = await signer.signAuthorization({\n * contractAddress: \"0x1234123412341234123412341234123412341234\",\n * chainId: 1,\n * nonce: 0,\n * });\n * ```\n *\n * @param {Authorization<number, false>} unsignedAuthorization the authorization to be signed\n * @returns {Promise<Authorization<number, true>> | undefined} a promise that resolves to the authorization with the signature\n */\n signAuthorization: (\n unsignedAuthorization: Authorization<number, false>\n ) => Promise<Authorization<number, true>> = SignerLogger.profiled(\n \"BaseAlchemySigner.signAuthorization\",\n async (unsignedAuthorization) => {\n const hashedAuthorization = hashAuthorization(unsignedAuthorization);\n const signedAuthorizationHex = await this.inner.signRawMessage(\n hashedAuthorization\n );\n const signature = this.unpackSignRawMessageBytes(signedAuthorizationHex);\n return { ...unsignedAuthorization, ...signature };\n }\n );\n\n private unpackSignRawMessageBytes = (\n hex: `0x${string}`\n ): UnpackedSignature => {\n return {\n r: takeBytes(hex, { count: 32 }),\n s: takeBytes(hex, { count: 32, offset: 32 }),\n v: BigInt(takeBytes(hex, { count: 1, offset: 64 })),\n };\n };\n\n /**\n * Unauthenticated call to look up a user's organizationId by email\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 * const result = await signer.getUser(\"foo@mail.com\");\n * ```\n *\n * @param {string} email the email to lookup\n * @returns {Promise<{orgId: string}>} the organization id for the user if they exist\n */\n getUser: (email: string) => Promise<{ orgId: string } | null> =\n SignerLogger.profiled(\"BaseAlchemySigner.getUser\", async (email) => {\n const result = await this.inner.lookupUserByEmail(email);\n\n if (result.orgId == null) {\n return null;\n }\n\n return {\n orgId: result.orgId,\n };\n });\n\n /**\n * Adds a passkey to the user's account\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 * const result = await signer.addPasskey()\n * ```\n *\n * @param {CredentialCreationOptions | undefined} params optional parameters for the passkey creation\n * @returns {Promise<string[]>} an array of the authenticator ids added to the user\n */\n addPasskey: (params?: CredentialCreationOptions) => Promise<string[]> =\n SignerLogger.profiled(\"BaseAlchemySigner.addPasskey\", async (params) => {\n return this.inner.addPasskey(params ?? {});\n });\n\n /**\n * Used to export the wallet for a given user\n * If the user is authenticated with an Email, this will return a seed phrase\n * If the user is authenticated with a Passkey, this will return a private key\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 * // the params passed to this are different based on the specific signer\n * const result = signer.exportWallet()\n * ```\n *\n * @param {unknown} params export wallet parameters\n * @returns {boolean} true if the wallet was exported successfully\n */\n exportWallet: (\n params: Parameters<(typeof this.inner)[\"exportWallet\"]>[0]\n ) => Promise<boolean> = async (params) => {\n return this.inner.exportWallet(params);\n };\n\n /**\n * This method lets you adapt your AlchemySigner to a viem LocalAccount, which\n * will let you use the signer as an EOA directly.\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 * const account = signer.toViemAccount();\n * ```\n *\n * @throws if your signer is not authenticated\n * @returns {LocalAccount} a LocalAccount object that can be used with viem's wallet client\n */\n toViemAccount = (): LocalAccount => {\n // if we want this method to be synchronous, then we need to do this check here\n // otherwise we can use the sessionManager to get the user\n if (!this.inner.getUser()) {\n throw new NotAuthenticatedError();\n }\n\n return toAccount({\n address: this.inner.getUser()!.address,\n signMessage: (msg) => this.signMessage(msg.message),\n signTypedData: <\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | \"EIP712Domain\" = keyof typedData\n >(\n typedDataDefinition: TypedDataDefinition<typedData, primaryType>\n ) => this.signTypedData<typedData, primaryType>(typedDataDefinition),\n signTransaction: this.signTransaction,\n });\n };\n\n private authenticateWithEmail = async (\n params: Extract<AuthParams, { type: \"email\" }>\n ): Promise<User> => {\n if (\"email\" in params) {\n const existingUser = await this.getUser(params.email);\n const expirationSeconds = this.getExpirationSeconds();\n\n const { orgId, otpId } = existingUser\n ? await this.inner.initEmailAuth({\n email: params.email,\n emailMode: params.emailMode,\n expirationSeconds,\n redirectParams: params.redirectParams,\n })\n : await this.inner.createAccount({\n type: \"email\",\n email: params.email,\n emailMode: params.emailMode,\n expirationSeconds,\n redirectParams: params.redirectParams,\n });\n\n this.sessionManager.setTemporarySession({\n orgId,\n isNewUser: !existingUser,\n });\n this.store.setState({\n status: AlchemySignerStatus.AWAITING_EMAIL_AUTH,\n otpId,\n error: null,\n });\n\n // We wait for the session manager to emit a connected event if\n // cross tab sessions are permitted\n return new Promise<User>((resolve) => {\n const removeListener = this.sessionManager.on(\n \"connected\",\n (session) => {\n resolve(session.user);\n removeListener();\n }\n );\n });\n } else {\n const temporarySession = params.orgId\n ? { orgId: params.orgId }\n : this.sessionManager.getTemporarySession();\n\n if (!temporarySession) {\n this.store.setState({\n status: AlchemySignerStatus.DISCONNECTED,\n });\n throw new Error(\"Could not find email auth init session!\");\n }\n\n const user = await this.inner.completeAuthWithBundle({\n bundle: params.bundle,\n orgId: temporarySession.orgId,\n connectedEventName: \"connectedEmail\",\n authenticatingType: \"email\",\n });\n\n // fire new user event\n this.emitNewUserEvent(params.isNewUser);\n\n return user;\n }\n };\n\n private authenticateWithPasskey = async (\n args: Extract<AuthParams, { type: \"passkey\" }>\n ): Promise<User> => {\n let user: User;\n const shouldCreateNew = async () => {\n if (\"email\" in args) {\n const existingUser = await this.getUser(args.email);\n return existingUser == null;\n }\n\n return args.createNew;\n };\n\n if (await shouldCreateNew()) {\n const result = await this.inner.createAccount(\n args as Extract<\n AuthParams,\n { type: \"passkey\" } & ({ email: string } | { createNew: true })\n >\n );\n // account creation for passkeys returns the whoami response so we don't have to\n // call it again after signup\n user = {\n address: result.address!,\n userId: result.userId!,\n orgId: result.orgId,\n };\n } else {\n user = await this.inner.lookupUserWithPasskey();\n if (!user) {\n this.store.setState({\n status: AlchemySignerStatus.DISCONNECTED,\n });\n throw new Error(\"No user found\");\n }\n }\n\n return user;\n };\n\n private authenticateWithOauth = async (\n args: Extract<AuthParams, { type: \"oauth\" }>\n ): Promise<User> => {\n const params: OauthParams = {\n ...args,\n expirationSeconds: this.getExpirationSeconds(),\n };\n if (params.mode === \"redirect\") {\n return this.inner.oauthWithRedirect(params);\n } else {\n return this.inner.oauthWithPopup(params);\n }\n };\n\n private authenticateWithOtp = async (\n args: Extract<AuthParams, { type: \"otp\" }>\n ): Promise<User> => {\n const tempSession = this.sessionManager.getTemporarySession();\n const { orgId, isNewUser } = tempSession ?? {};\n const { otpId } = this.store.getState();\n if (!orgId) {\n throw new Error(\"orgId not found in session\");\n }\n if (!otpId) {\n throw new Error(\"otpId not found in session\");\n }\n const { bundle } = await this.inner.submitOtpCode({\n orgId,\n otpId,\n otpCode: args.otpCode,\n expirationSeconds: this.getExpirationSeconds(),\n });\n const user = await this.inner.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOtp\",\n authenticatingType: \"otp\",\n });\n\n this.emitNewUserEvent(isNewUser);\n if (tempSession) {\n this.sessionManager.setTemporarySession({\n ...tempSession,\n isNewUser: false,\n });\n }\n\n return user;\n };\n\n private handleOauthReturn = ({\n bundle,\n orgId,\n idToken,\n isNewUser,\n }: Extract<AuthParams, { type: \"oauthReturn\" }>): Promise<User> => {\n const user = this.inner.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOauth\",\n authenticatingType: \"oauth\",\n idToken,\n });\n\n this.emitNewUserEvent(isNewUser);\n\n return user;\n };\n\n private getExpirationSeconds = () =>\n Math.floor(this.sessionManager.expirationTimeMs / 1000);\n\n private registerListeners = () => {\n // Declare listeners in an object to typecheck that every event type is\n // handled.\n const listeners: SessionManagerEvents = {\n connected: (session) => {\n this.store.setState({\n user: session.user,\n status: AlchemySignerStatus.CONNECTED,\n error: null,\n });\n },\n disconnected: () => {\n this.store.setState({\n user: null,\n status: AlchemySignerStatus.DISCONNECTED,\n });\n },\n initialized: () => {\n this.store.setState((state) => ({\n status: state.user\n ? AlchemySignerStatus.CONNECTED\n : AlchemySignerStatus.DISCONNECTED,\n ...(state.user ? { error: null } : undefined),\n }));\n },\n };\n\n for (const [event, listener] of Object.entries(listeners)) {\n this.sessionManager.on(event as keyof SessionManagerEvents, listener);\n }\n\n this.inner.on(\"authenticating\", ({ type }) => {\n const status = (() => {\n switch (type) {\n case \"email\":\n return AlchemySignerStatus.AUTHENTICATING_EMAIL;\n case \"passkey\":\n return AlchemySignerStatus.AUTHENTICATING_PASSKEY;\n case \"oauth\":\n return AlchemySignerStatus.AUTHENTICATING_OAUTH;\n case \"otp\":\n case \"otpVerify\":\n return AlchemySignerStatus.AWAITING_OTP_AUTH;\n default:\n assertNever(type, \"unhandled authenticating type\");\n }\n })();\n\n // trigger new user event on signer from client\n this.inner.on(\"newUserSignup\", () => {\n this.emitNewUserEvent(true);\n });\n\n this.store.setState({\n status,\n error: null,\n });\n });\n };\n\n private emitNewUserEvent = (isNewUser?: boolean) => {\n // assumes that if isNewUser is undefined it is a returning user\n if (isNewUser) this.store.setState({ isNewUser });\n };\n}\n\nfunction toErrorInfo(error: unknown): ErrorInfo {\n return error instanceof Error\n ? { name: error.name, message: error.message }\n : { name: \"Error\", message: \"Unknown error\" };\n}\n"]}
|
|
@@ -113,6 +113,7 @@ export class SessionManager {
|
|
|
113
113
|
writable: true,
|
|
114
114
|
value: () => {
|
|
115
115
|
this.store.setState({ session: null });
|
|
116
|
+
localStorage.removeItem(`${this.sessionKey}:temporary`);
|
|
116
117
|
if (this.clearSessionHandle) {
|
|
117
118
|
clearTimeout(this.clearSessionHandle);
|
|
118
119
|
}
|
|
@@ -166,6 +167,7 @@ export class SessionManager {
|
|
|
166
167
|
* We should revisit this later
|
|
167
168
|
*/
|
|
168
169
|
if (session.expirationDateMs < Date.now()) {
|
|
170
|
+
this.client.disconnect();
|
|
169
171
|
this.clearSession();
|
|
170
172
|
return null;
|
|
171
173
|
}
|
|
@@ -257,6 +259,7 @@ export class SessionManager {
|
|
|
257
259
|
clearTimeout(this.clearSessionHandle);
|
|
258
260
|
}
|
|
259
261
|
this.clearSessionHandle = setTimeout(() => {
|
|
262
|
+
this.client.disconnect();
|
|
260
263
|
this.clearSession();
|
|
261
264
|
}, Math.min(session.expirationDateMs - Date.now(), Math.pow(2, 31) - 1));
|
|
262
265
|
}
|
|
@@ -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,CA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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 \"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\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.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.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,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,iBAAiB,EACjB,OAAO,EACP,qBAAqB,GACtB,MAAM,oBAAoB,CAA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AA4F;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;CAmHF","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 \"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"]}
|
package/dist/esm/signer.js
CHANGED
|
@@ -9,7 +9,9 @@ export const AlchemySignerParamsSchema = z
|
|
|
9
9
|
.or(AlchemySignerClientParamsSchema),
|
|
10
10
|
})
|
|
11
11
|
.extend({
|
|
12
|
-
sessionConfig: SessionManagerParamsSchema.omit({
|
|
12
|
+
sessionConfig: SessionManagerParamsSchema.omit({
|
|
13
|
+
client: true,
|
|
14
|
+
}).optional(),
|
|
13
15
|
});
|
|
14
16
|
/**
|
|
15
17
|
* A SmartAccountSigner that can be used with any SmartContractAccount
|
|
@@ -60,6 +62,7 @@ export class AlchemyWebSigner extends BaseAlchemySigner {
|
|
|
60
62
|
: undefined;
|
|
61
63
|
super({ client, sessionConfig, initialError });
|
|
62
64
|
const isNewUser = isSignup === "true";
|
|
65
|
+
this.signerType = "alchemy-signer";
|
|
63
66
|
if (emailBundle) {
|
|
64
67
|
this.authenticate({
|
|
65
68
|
type: "email",
|
package/dist/esm/signer.js.map
CHANGED
|
@@ -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;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAoElE,MAAM,CAAC,MAAM,yBAAyB,GAAG,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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 { CredentialCreationOptionOverrides } 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 }\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 };\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"]}
|
package/dist/esm/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "4.
|
|
1
|
+
export declare const VERSION = "4.15.0";
|
package/dist/esm/version.js
CHANGED
package/dist/esm/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,yBAAyB;AACzB,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// This file is autogenerated by inject-version.ts. Any changes will be\n// overwritten on commit!\nexport const VERSION = \"4.
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,yBAAyB;AACzB,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// This file is autogenerated by inject-version.ts. Any changes will be\n// overwritten on commit!\nexport const VERSION = \"4.15.0\";\n"]}
|
package/dist/types/base.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export interface BaseAlchemySignerParams<TClient extends BaseSignerClient> {
|
|
|
16
16
|
* Implements the `SmartAccountAuthenticator` interface and handles various signer events.
|
|
17
17
|
*/
|
|
18
18
|
export declare abstract class BaseAlchemySigner<TClient extends BaseSignerClient> implements SmartAccountAuthenticator<AuthParams, User, TClient> {
|
|
19
|
-
signerType:
|
|
19
|
+
signerType: "alchemy-signer" | "rn-alchemy-signer";
|
|
20
20
|
inner: TClient;
|
|
21
21
|
private sessionManager;
|
|
22
22
|
private store;
|
package/dist/types/base.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../src/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,yBAAyB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EAKL,KAAK,kBAAkB,EACvB,KAAK,GAAG,EACR,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,sBAAsB,EAC3B,KAAK,eAAe,EACpB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,KAAK,SAAS,EACd,KAAK,mBAAmB,EACzB,MAAM,MAAM,CAAC;AAKd,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,WAAW,EAAe,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAGrE,OAAO,EAEL,KAAK,oBAAoB,EAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAC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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAUlC,CAAC;AAEL,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,yBAAyB,CAAC,CAAC;AAE5E;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,iBAAiB,CAAC,sBAAsB,CAAC;IAC7E;;;;;;;;;;;;;;;;;;;;OAoBG;gBAES,MAAM,EAAE,mBAAmB;CAuDxC"}
|
package/dist/types/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const VERSION = "4.
|
|
1
|
+
export declare const VERSION = "4.15.0";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@account-kit/signer",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.15.0",
|
|
4
4
|
"description": "Core interfaces and clients for interfacing with the Alchemy Signer API",
|
|
5
5
|
"author": "Alchemy",
|
|
6
6
|
"license": "MIT",
|
|
@@ -49,8 +49,8 @@
|
|
|
49
49
|
"vitest": "^2.0.4"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@aa-sdk/core": "^4.
|
|
53
|
-
"@account-kit/logging": "^4.
|
|
52
|
+
"@aa-sdk/core": "^4.15.0",
|
|
53
|
+
"@account-kit/logging": "^4.15.0",
|
|
54
54
|
"@turnkey/http": "^2.6.2",
|
|
55
55
|
"@turnkey/iframe-stamper": "^1.0.0",
|
|
56
56
|
"@turnkey/viem": "^0.4.8",
|
|
@@ -73,5 +73,5 @@
|
|
|
73
73
|
"url": "https://github.com/alchemyplatform/aa-sdk/issues"
|
|
74
74
|
},
|
|
75
75
|
"homepage": "https://github.com/alchemyplatform/aa-sdk#readme",
|
|
76
|
-
"gitHead": "
|
|
76
|
+
"gitHead": "9561e51d921c231e51e2f859b3f5c93f47b6ffd0"
|
|
77
77
|
}
|
package/src/base.ts
CHANGED
|
@@ -70,7 +70,7 @@ type InternalStore = Mutate<
|
|
|
70
70
|
export abstract class BaseAlchemySigner<TClient extends BaseSignerClient>
|
|
71
71
|
implements SmartAccountAuthenticator<AuthParams, User, TClient>
|
|
72
72
|
{
|
|
73
|
-
signerType:
|
|
73
|
+
signerType: "alchemy-signer" | "rn-alchemy-signer" = "alchemy-signer";
|
|
74
74
|
inner: TClient;
|
|
75
75
|
private sessionManager: SessionManager;
|
|
76
76
|
private store: InternalStore;
|
|
@@ -782,7 +782,9 @@ export abstract class BaseAlchemySigner<TClient extends BaseSignerClient>
|
|
|
782
782
|
: this.sessionManager.getTemporarySession();
|
|
783
783
|
|
|
784
784
|
if (!temporarySession) {
|
|
785
|
-
this.store.setState({
|
|
785
|
+
this.store.setState({
|
|
786
|
+
status: AlchemySignerStatus.DISCONNECTED,
|
|
787
|
+
});
|
|
786
788
|
throw new Error("Could not find email auth init session!");
|
|
787
789
|
}
|
|
788
790
|
|
|
@@ -830,7 +832,9 @@ export abstract class BaseAlchemySigner<TClient extends BaseSignerClient>
|
|
|
830
832
|
} else {
|
|
831
833
|
user = await this.inner.lookupUserWithPasskey();
|
|
832
834
|
if (!user) {
|
|
833
|
-
this.store.setState({
|
|
835
|
+
this.store.setState({
|
|
836
|
+
status: AlchemySignerStatus.DISCONNECTED,
|
|
837
|
+
});
|
|
834
838
|
throw new Error("No user found");
|
|
835
839
|
}
|
|
836
840
|
}
|
package/src/session/manager.ts
CHANGED
|
@@ -140,6 +140,7 @@ export class SessionManager {
|
|
|
140
140
|
|
|
141
141
|
public clearSession = () => {
|
|
142
142
|
this.store.setState({ session: null });
|
|
143
|
+
localStorage.removeItem(`${this.sessionKey}:temporary`);
|
|
143
144
|
|
|
144
145
|
if (this.clearSessionHandle) {
|
|
145
146
|
clearTimeout(this.clearSessionHandle);
|
|
@@ -189,6 +190,7 @@ export class SessionManager {
|
|
|
189
190
|
* We should revisit this later
|
|
190
191
|
*/
|
|
191
192
|
if (session.expirationDateMs < Date.now()) {
|
|
193
|
+
this.client.disconnect();
|
|
192
194
|
this.clearSession();
|
|
193
195
|
return null;
|
|
194
196
|
}
|
|
@@ -319,6 +321,7 @@ export class SessionManager {
|
|
|
319
321
|
}
|
|
320
322
|
|
|
321
323
|
this.clearSessionHandle = setTimeout(() => {
|
|
324
|
+
this.client.disconnect();
|
|
322
325
|
this.clearSession();
|
|
323
326
|
}, Math.min(session.expirationDateMs - Date.now(), Math.pow(2, 31) - 1));
|
|
324
327
|
};
|
package/src/signer.ts
CHANGED
|
@@ -80,7 +80,9 @@ export const AlchemySignerParamsSchema = z
|
|
|
80
80
|
.or(AlchemySignerClientParamsSchema),
|
|
81
81
|
})
|
|
82
82
|
.extend({
|
|
83
|
-
sessionConfig: SessionManagerParamsSchema.omit({
|
|
83
|
+
sessionConfig: SessionManagerParamsSchema.omit({
|
|
84
|
+
client: true,
|
|
85
|
+
}).optional(),
|
|
84
86
|
});
|
|
85
87
|
|
|
86
88
|
export type AlchemySignerParams = z.input<typeof AlchemySignerParamsSchema>;
|
|
@@ -110,6 +112,7 @@ export class AlchemyWebSigner extends BaseAlchemySigner<AlchemySignerWebClient>
|
|
|
110
112
|
*
|
|
111
113
|
* @param {AlchemySignerParams} params The parameters for the Alchemy signer, including the client and session configuration
|
|
112
114
|
*/
|
|
115
|
+
|
|
113
116
|
constructor(params: AlchemySignerParams) {
|
|
114
117
|
const { sessionConfig, ...params_ } =
|
|
115
118
|
AlchemySignerParamsSchema.parse(params);
|
|
@@ -147,6 +150,8 @@ export class AlchemyWebSigner extends BaseAlchemySigner<AlchemySignerWebClient>
|
|
|
147
150
|
|
|
148
151
|
const isNewUser = isSignup === "true";
|
|
149
152
|
|
|
153
|
+
this.signerType = "alchemy-signer";
|
|
154
|
+
|
|
150
155
|
if (emailBundle) {
|
|
151
156
|
this.authenticate({
|
|
152
157
|
type: "email",
|
package/src/version.ts
CHANGED