@openfort/openfort-js 1.3.5 → 1.3.7
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/cjs/sdk/src/index.cjs +1 -1
- package/dist/cjs/sdk/src/version.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/iframeManager.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/messaging/ReactNativeMessenger.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/messaging/browserMessenger/connectRemoteProxy.cjs +1 -1
- package/dist/index.d.cts +34 -1
- package/dist/index.d.ts +34 -1
- package/dist/sdk/src/index.js +1 -1
- package/dist/sdk/src/version.js +1 -1
- package/dist/sdk/src/wallets/iframeManager.js +1 -1
- package/dist/sdk/src/wallets/messaging/ReactNativeMessenger.js +1 -1
- package/dist/sdk/src/wallets/messaging/browserMessenger/connectRemoteProxy.js +1 -1
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var r=require("./core/openfort.cjs"),e=require("./api/auth.cjs"),o=require("./api/embeddedWallet.cjs"),t=require("./api/proxy.cjs"),s=require("./api/user.cjs"),n=require("./core/errors/authErrorCodes.cjs"),i=require("./core/errors/openfortError.cjs"),p=require("./core/passkey/errors.cjs"),u=require("./core/passkey/handler.cjs"),a=require("./core/passkey/utils.cjs"),E=require("./core/config/config.cjs"),c=require("./core/openfortInternal.cjs"),d=require("./utils/authorization.cjs"),
|
|
1
|
+
"use strict";var r=require("./core/openfort.cjs"),e=require("./api/auth.cjs"),o=require("./api/embeddedWallet.cjs"),t=require("./api/proxy.cjs"),s=require("./api/user.cjs"),n=require("./core/errors/authErrorCodes.cjs"),i=require("./core/errors/openfortError.cjs"),p=require("./core/passkey/errors.cjs"),u=require("./core/passkey/handler.cjs"),a=require("./core/passkey/utils.cjs"),E=require("./core/config/config.cjs"),c=require("./core/openfortInternal.cjs"),d=require("./utils/authorization.cjs"),f=require("./wallets/iframeManager.cjs"),y=require("./types/types.cjs"),x=require("./utils/crypto.cjs");const P=r.Openfort.getEventEmitter();exports.Openfort=r.Openfort,exports.AuthApi=e.AuthApi,exports.EmbeddedWalletApi=o.EmbeddedWalletApi,exports.ProxyApi=t.ProxyApi,exports.UserApi=s.UserApi,exports.OPENFORT_AUTH_ERROR_CODES=n.OPENFORT_AUTH_ERROR_CODES,exports.OPENFORT_ERROR_CODES=n.OPENFORT_ERROR_CODES,exports.AuthenticationError=i.AuthenticationError,exports.AuthorizationError=i.AuthorizationError,exports.ConfigurationError=i.ConfigurationError,exports.OAuthError=i.OAuthError,exports.OTPError=i.OTPError,exports.OpenfortError=i.OpenfortError,exports.RecoveryError=i.RecoveryError,exports.RequestError=i.RequestError,exports.SessionError=i.SessionError,exports.SignerError=i.SignerError,exports.UserError=i.UserError,exports.PASSKEY_ERROR_CODES=p.PASSKEY_ERROR_CODES,exports.PasskeyAssertionFailedError=p.PasskeyAssertionFailedError,exports.PasskeyCreationFailedError=p.PasskeyCreationFailedError,exports.PasskeyPRFNotSupportedError=p.PasskeyPRFNotSupportedError,exports.PasskeySeedInvalidError=p.PasskeySeedInvalidError,exports.PasskeyUserCancelledError=p.PasskeyUserCancelledError,exports.PasskeyHandler=u.PasskeyHandler,exports.arrayBufferToBase64URL=a.arrayBufferToBase64URL,exports.base64ToArrayBuffer=a.base64ToArrayBuffer,exports.OpenfortConfiguration=E.OpenfortConfiguration,exports.SDKConfiguration=E.SDKConfiguration,exports.ShieldConfiguration=E.ShieldConfiguration,exports.OpenfortInternal=c.OpenfortInternal,exports.prepareAndSignAuthorization=d.prepareAndSignAuthorization,exports.serializeSignedAuthorization=d.serializeSignedAuthorization,exports.signAuthorization=d.signAuthorization,exports.IframeSignEmptyResponseError=f.IframeSignEmptyResponseError,exports.IframeSignTimeoutError=f.IframeSignTimeoutError,exports.MissingProjectEntropyError=f.MissingProjectEntropyError,exports.MissingRecoveryPasswordError=f.MissingRecoveryPasswordError,exports.NotConfiguredError=f.NotConfiguredError,exports.OTPRequiredError=f.OTPRequiredError,exports.SessionEndedBeforeSetupError=f.SessionEndedBeforeSetupError,exports.WrongPasskeyError=f.WrongPasskeyError,exports.WrongRecoveryPasswordError=f.WrongRecoveryPasswordError,Object.defineProperty(exports,"AccountTypeEnum",{enumerable:!0,get:function(){return y.AccountTypeEnum}}),Object.defineProperty(exports,"AuthActionRequiredActions",{enumerable:!0,get:function(){return y.AuthActionRequiredActions}}),Object.defineProperty(exports,"AuthType",{enumerable:!0,get:function(){return y.AuthType}}),Object.defineProperty(exports,"BasicAuthProvider",{enumerable:!0,get:function(){return y.BasicAuthProvider}}),Object.defineProperty(exports,"ChainTypeEnum",{enumerable:!0,get:function(){return y.ChainTypeEnum}}),Object.defineProperty(exports,"EmbeddedState",{enumerable:!0,get:function(){return y.EmbeddedState}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return y.OAuthProvider}}),Object.defineProperty(exports,"OpenfortEvents",{enumerable:!0,get:function(){return y.OpenfortEvents}}),Object.defineProperty(exports,"RecoveryMethod",{enumerable:!0,get:function(){return y.RecoveryMethod}}),Object.defineProperty(exports,"ThirdPartyOAuthProvider",{enumerable:!0,get:function(){return y.ThirdPartyAuthProvider}}),Object.defineProperty(exports,"TokenType",{enumerable:!0,get:function(){return y.TokenType}}),exports.cryptoDigest=x.cryptoDigest,exports.openfortEvents=P;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.3.
|
|
1
|
+
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.3.7";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../core/configuration/account.cjs"),i=require("../core/configuration/authentication.cjs"),r=require("../core/errors/authErrorCodes.cjs"),n=require("../core/errors/openfortError.cjs"),t=require("../core/errors/sentry.cjs"),o=require("../storage/istorage.cjs"),s=require("../utils/crypto.cjs"),a=require("../utils/debug.cjs"),d=require("./messaging/ReactNativeMessenger.cjs"),c=require("./messaging/browserMessenger/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var u=require("./types.cjs");class h extends n.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class l extends n.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class g extends n.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class y extends n.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class p extends n.SignerError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class R extends n.OpenfortError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new n.ConfigurationError("Configuration is required for IframeManager");if(!i)throw new n.ConfigurationError("Storage is required for IframeManager");if(!r)throw new n.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new n.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,a.debugLog("IframeManager connection established")}catch(e){const i=e;throw t.sentry.captureException(i),this.destroy(),a.debugLog("Failed to establish connection:",i),new n.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n \n In apps built with:\n - react native\n - swift\n - unity (non-webgl) \n \n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new n.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(u.isErrorResponse(e)){if(e.error===u.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new p;if(e.error===u.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new g;if(e.error===u.INCORRECT_USER_ENTROPY_ERROR)throw new y;if(e.error===u.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.INCORRECT_PASSKEY_ERROR)throw new l;if(e.error===u.OTP_REQUIRED_ERROR)throw new R;throw this.storage.remove(o.StorageKeys.ACCOUNT),new n.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new n.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const t={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:t,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new n.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const t={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:t,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const n={uuid:s.randomUUID(),action:u.Event.CREATE,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},t=await i.create(n);return u.isErrorResponse(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t}async import(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const n={uuid:s.randomUUID(),action:u.Event.IMPORT,privateKey:e.privateKey,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},t=await i.import(n);return u.isErrorResponse(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await e.Account.fromStorage(this.storage),n=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=r?.chainId??null,t.password=i?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:i?.entropy?.encryptionSession},t.passkey=i?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:u.Event.RECOVER,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await n.recover(o);return u.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,r,n){a.debugLog("[iframe] ensureConnection");const t=await this.ensureConnection(),o=new u.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,n);a.debugLog("[iframe] done ensureConnection");const d=await t.sign(o);return a.debugLog("[iframe] response",d),u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),r=new u.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),n=await i.switchChain(r);return u.isErrorResponse(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new u.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),r=await e.export(i);return u.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}async setRecoveryMethod(e,i,r,n,t){const o=await this.ensureConnection(),a=new u.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,n,t),d=await o.setRecoveryMethod(a);u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new u.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return u.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof p)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await i.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const r=new u.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(r);u.isErrorResponse(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s.randomUUID()};await e.logout(i)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=g,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=p,exports.OTPRequiredError=R,exports.WrongPasskeyError=l,exports.WrongRecoveryPasswordError=y;
|
|
1
|
+
"use strict";var e=require("../core/configuration/account.cjs"),r=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),t=require("../core/errors/openfortError.cjs"),n=require("../core/errors/sentry.cjs"),o=require("../storage/istorage.cjs"),s=require("../utils/crypto.cjs"),a=require("../utils/debug.cjs"),d=require("./messaging/ReactNativeMessenger.cjs"),c=require("./messaging/browserMessenger/CallOptions.cjs"),u=require("./messaging/browserMessenger/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var h=require("./messaging/browserMessenger/PenpalError.cjs"),l=require("./types.cjs");class g extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class y extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class p extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class f extends t.SignerError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class E extends t.OpenfortError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}class w extends t.SignerError{constructor(e){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Iframe signer did not respond within ${e}ms. The signing prompt may have been dismissed or the iframe is unresponsive.`),this.name="IframeSignTimeoutError",Object.setPrototypeOf(this,w.prototype)}}class O extends t.SignerError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Iframe signer returned an empty signature."),this.name="IframeSignEmptyResponseError",Object.setPrototypeOf(this,O.prototype)}}class C extends t.OpenfortError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Wallet session ended before setup completed."),Object.setPrototypeOf(this,C.prototype)}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;isDestroyed=!1;hasFailed=!1;constructor(e,r,i){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!r)throw new t.ConfigurationError("Storage is required for IframeManager");if(!i)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=r,this.messenger=i}assertAlive(){if(this.isDestroyed)throw new C}async initialize(){if(this.assertAlive(),!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)return await this.initializationPromise,void this.assertAlive();this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.assertAlive(),this.isInitialized=!0}catch(e){if(this.initializationPromise=null,e instanceof C)throw e;throw this.hasFailed=!0,e}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.assertAlive(),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=u({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,this.assertAlive(),a.debugLog("IframeManager connection established")}catch(e){this.isDestroyed&&a.debugLog("Connection rejected after destroy() — surfacing teardown error"),this.assertAlive();const r=e;throw n.sentry.captureException(r),this.clearConnection(),a.debugLog("Failed to establish connection:",r),new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${r.cause||r.message}\n\n In apps built with:\n - react native\n - swift\n - unity (non-webgl)\n\n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}clearConnection(){if(this.connection)try{this.connection.destroy()}catch(e){a.debugLog("clearConnection: connection.destroy() threw, swallowing:",e)}this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(l.isErrorResponse(e)){if(e.error===l.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new f;if(e.error===l.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new g;if(e.error===l.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new p;if(e.error===l.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===l.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new g;if(e.error===l.INCORRECT_PASSKEY_ERROR)throw new y;if(e.error===l.OTP_REQUIRED_ERROR)throw new E;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:l.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:l.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await this.ensureConnection(),i=await this.buildIFrameRequestConfiguration();i.chainId=e.chainId??null,i.password=e?.entropy?.recoveryPassword??null,i.recovery={...i.recovery,encryptionSession:e?.entropy?.encryptionSession},i.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:l.Event.CREATE,recovery:i.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:i.accessToken,playerID:i.playerID,thirdPartyProvider:i.thirdPartyProvider,thirdPartyTokenType:i.thirdPartyTokenType,encryptionKey:i.password,encryptionSession:i.recovery?.encryptionSession??null,passkey:i.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await r.create(t);return l.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async import(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await this.ensureConnection(),i=await this.buildIFrameRequestConfiguration();i.chainId=e.chainId??null,i.password=e?.entropy?.recoveryPassword??null,i.recovery={...i.recovery,encryptionSession:e?.entropy?.encryptionSession},i.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:l.Event.IMPORT,privateKey:e.privateKey,recovery:i.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:i.accessToken,playerID:i.playerID,thirdPartyProvider:i.thirdPartyProvider,thirdPartyTokenType:i.thirdPartyTokenType,encryptionKey:i.password,encryptionSession:i.recovery?.encryptionSession??null,passkey:i.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await r.import(t);return l.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(r){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=i?.chainId??null,n.password=r?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:r?.entropy?.encryptionSession},n.passkey=r?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:l.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:r.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return l.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,r,i,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new l.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t);let d;a.debugLog("[iframe] done ensureConnection"),this.assertAlive();try{d=await n.sign(o,new c({timeout:9e4}))}catch(e){if(e instanceof h&&"METHOD_CALL_TIMEOUT"===e.code)throw this.hasFailed=!0,new w(9e4);throw e}if(a.debugLog("[iframe] response",d),l.isErrorResponse(d)&&this.handleError(d),!d.signature)throw new O;return"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const r=await this.ensureConnection(),i=new l.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await r.switchChain(i);return l.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),r=new l.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),i=await e.export(r);return l.isErrorResponse(i)&&this.handleError(i),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",i.version??"undefined"),i.key}async setRecoveryMethod(e,r,i,t,n){const o=await this.ensureConnection(),a=new l.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t,n),d=await o.setRecoveryMethod(a);l.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const r=await this.ensureConnection(),i=new l.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await r.getCurrentDevice(i);return l.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof f)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await r.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const i=new l.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(i);l.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),r={uuid:s.randomUUID()};await e.logout(r)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.clearConnection())}},exports.IframeSignEmptyResponseError=O,exports.IframeSignTimeoutError=w,exports.MissingProjectEntropyError=p,exports.MissingRecoveryPasswordError=g,exports.NotConfiguredError=f,exports.OTPRequiredError=E,exports.SessionEndedBeforeSetupError=C,exports.WrongPasskeyError=y,exports.WrongRecoveryPasswordError=R;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../utils/debug.cjs"),t=require("./browserMessenger/PenpalError.cjs");require("./browserMessenger/backwardCompatibility.cjs");exports.ReactNativeMessenger=class{messagePoster;handlers=new Set;isInitialized=!1;hasBeenUsed=!1;validateMessage;messageBuffer=[];nextNumericId=1;stringToNumericId=new Map;numericToStringId=new Map;constructor(s){if(this.messagePoster=s,!s||"function"!=typeof s.postMessage)throw new t("CONNECTION_DESTROYED","Invalid message poster provided");e.debugLog("ReactNativeMessenger created")}initialize
|
|
1
|
+
"use strict";var e=require("../../utils/debug.cjs"),t=require("./browserMessenger/PenpalError.cjs");require("./browserMessenger/backwardCompatibility.cjs");exports.ReactNativeMessenger=class{messagePoster;handlers=new Set;isInitialized=!1;hasBeenUsed=!1;validateMessage;messageBuffer=[];nextNumericId=1;stringToNumericId=new Map;numericToStringId=new Map;constructor(s){if(this.messagePoster=s,!s||"function"!=typeof s.postMessage)throw new t("CONNECTION_DESTROYED","Invalid message poster provided");e.debugLog("ReactNativeMessenger created")}initialize=s=>{if(this.isInitialized)return void e.debugLog("ReactNativeMessenger already initialized");if(this.hasBeenUsed)throw new t("CONNECTION_DESTROYED","A messenger can only be used for a single connection");this.validateMessage=s?.validateReceivedMessage,this.isInitialized=!0,this.hasBeenUsed=!0,e.debugLog(`ReactNativeMessenger initialized, processing ${this.messageBuffer.length} buffered messages`);const a=[...this.messageBuffer];this.messageBuffer=[],a.forEach(e=>{this.processMessage(e)})};sendMessage=(s,a)=>{if(!this.isInitialized)throw new t("CONNECTION_DESTROYED","ReactNativeMessenger not initialized");a&&a.length>0&&e.debugLog("React Native: Ignoring transferables (not supported)"),e.debugLog("ReactNativeMessenger sending message:",s);try{let t=s;"penpal"===s?.namespace&&(t=this.convertToDeprecatedFormat(s),e.debugLog("React Native: Converted message:",t));const a=JSON.stringify(t);this.messagePoster.postMessage(a)}catch(e){throw new t("TRANSMISSION_FAILED",`Failed to send message through React Native WebView: ${e instanceof Error?e.message:String(e)}`)}};addMessageHandler=t=>{this.handlers.add(t),e.debugLog(`Message handler added, total handlers: ${this.handlers.size}`)};removeMessageHandler=t=>{this.handlers.delete(t),e.debugLog(`Message handler removed, total handlers: ${this.handlers.size}`)};handleMessage=t=>{if(e.debugLog("[HANDSHAKE DEBUG] ReactNativeMessenger.handleMessage called with:",t),!this.isInitialized){const s=this.messageBuffer.length+1;return e.debugLog(`[HANDSHAKE DEBUG] ReactNativeMessenger: Message received but not initialized, buffering message (${s} total)`),void this.messageBuffer.push(t)}e.debugLog("[HANDSHAKE DEBUG] ReactNativeMessenger is initialized, processing message"),this.processMessage(t)};processMessage(t){e.debugLog("[HANDSHAKE DEBUG] ReactNativeMessenger processing message:",t);const s=this.convertFromDeprecatedFormat(t);if(e.debugLog("[HANDSHAKE DEBUG] Message after conversion:",s),this.validateMessage&&!this.validateMessage(s))return void e.debugLog("[HANDSHAKE DEBUG] Message validation failed:",s);e.debugLog(`[HANDSHAKE DEBUG] Routing message to ${this.handlers.size} handlers`);let a=0;this.handlers.forEach(t=>{a++;try{e.debugLog(`[HANDSHAKE DEBUG] Calling handler ${a}/${this.handlers.size}`),t(s),e.debugLog(`[HANDSHAKE DEBUG] Handler ${a} completed successfully`)}catch(t){e.debugLog(`[HANDSHAKE DEBUG] Error in handler ${a}:`,t)}})}convertToDeprecatedFormat(t){if("penpal"!==t?.namespace)return t;switch(t.type){case"SYN":{const s={originalMessage:t};return e.debugLog("React Native: Converting SYN to deprecated format to avoid MessagePorts",s),{penpal:"syn",participantId:t.participantId}}case"ACK1":return e.debugLog("React Native: Converting ACK1 to deprecated format",{originalMessage:t}),{penpal:"synAck",methodNames:t.methodPaths||[]};case"ACK2":return e.debugLog("React Native: Converting ACK2 to deprecated format",{originalMessage:t}),{penpal:"ack"};case"REPLY":{e.debugLog("React Native: Converting REPLY to deprecated format",{originalMessage:t});const s=this.getNumericId(t.callId);return t.isError?{penpal:"reply",id:s,resolution:"rejected",returnValue:t.value,returnValueIsError:t.isSerializedErrorInstance||!1}:{penpal:"reply",id:s,resolution:"fulfilled",returnValue:t.value}}case"CALL":e.debugLog("React Native: Converting CALL to deprecated format",{originalMessage:t});return{penpal:"call",id:this.getNumericId(t.id),methodName:t.methodPath.join("."),args:t.args};case"DESTROY":return{namespace:"penpal",type:"DESTROY"};default:return t}}convertFromDeprecatedFormat(t){if(t?.penpal)switch(t.penpal){case"syn":{e.debugLog("[HANDSHAKE DEBUG] React Native: Converting deprecated SYN to modern format",{originalMessage:t});const s={namespace:"penpal",type:"SYN",participantId:t.participantId};return e.debugLog("[HANDSHAKE DEBUG] Converted SYN:",s),s}case"synAck":{e.debugLog("[HANDSHAKE DEBUG] React Native: Converting deprecated synAck to modern ACK1 format",{originalMessage:t});const s={namespace:"penpal",type:"ACK1",methodPaths:t.methodNames?.map(e=>e.split("."))||[],channel:void 0};return e.debugLog("[HANDSHAKE DEBUG] Converted ACK1:",s),s}case"ack":{e.debugLog("[HANDSHAKE DEBUG] React Native: Converting deprecated ack to modern ACK2 format",{originalMessage:t});const s={namespace:"penpal",type:"ACK2",channel:void 0};return e.debugLog("[HANDSHAKE DEBUG] Converted ACK2:",s),s}case"reply":{e.debugLog("React Native: Converting deprecated reply to modern REPLY format",{originalMessage:t});const s=this.getStringId(t.id);s||e.debugLog(`Warning: No string ID mapping found for numeric ID ${t.id}, using as-is`);const a=s||String(t.id);return"fulfilled"===t.resolution?{namespace:"penpal",type:"REPLY",callId:a,value:t.returnValue}:{namespace:"penpal",type:"REPLY",callId:a,isError:!0,value:t.returnValue,isSerializedErrorInstance:t.returnValueIsError||!1}}case"call":{e.debugLog("React Native: Converting deprecated call to modern CALL format",{originalMessage:t});const s=this.getStringId(t.id);return s||e.debugLog(`Warning: No string ID mapping found for numeric ID ${t.id}, using as-is`),{namespace:"penpal",type:"CALL",id:s||String(t.id),methodPath:t.methodName.split("."),args:t.args}}default:return e.debugLog("React Native: Unknown deprecated penpal message type:",t.penpal),t}return t}setupMessagePort=t=>{e.debugLog("React Native: setupMessagePort called but ignored (MessagePort not supported)")};destroy=()=>{this.isInitialized&&(this.handlers.clear(),this.messageBuffer=[],this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextNumericId=1,this.isInitialized=!1,this.hasBeenUsed=!1,e.debugLog("ReactNativeMessenger destroyed and ready for reuse"))};reset=()=>{e.debugLog("ReactNativeMessenger reset for reuse"),this.handlers.clear(),this.messageBuffer=[],this.isInitialized=!1,this.hasBeenUsed=!1,this.nextNumericId=1,this.stringToNumericId.clear(),this.numericToStringId.clear()};getNumericId(t){let s=this.stringToNumericId.get(t);return s||(s=this.nextNumericId++,this.stringToNumericId.set(t,s),this.numericToStringId.set(s,t),e.debugLog(`ID mapping created: "${t}" -> ${s}`)),s}getStringId(e){return this.numericToStringId.get(e)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../../utils/crypto.cjs"),t=require("./CallOptions.cjs"),r=require("./errorSerialization.cjs"),
|
|
1
|
+
"use strict";var e=require("../../../utils/crypto.cjs"),t=require("./CallOptions.cjs"),r=require("./errorSerialization.cjs"),o=require("./guards.cjs"),a=require("./methodSerialization.cjs"),s=require("./namespace.cjs"),n=require("./PenpalError.cjs");const i=new Set(["apply","call","bind"]),l=(e,t,r=[])=>new Proxy(r.length?()=>{}:Object.create(null),{get(o,a){if("then"!==a)return r.length&&i.has(a)?Reflect.get(o,a):l(e,t,[...r,a])},apply:(t,o,a)=>e(r,a)}),c=e=>new n("CONNECTION_DESTROYED",`Method call ${a.formatMethodPath(e)}() failed due to destroyed connection`);module.exports=(i,d,h)=>{let u=!1;const m=new Map,f=e=>{if(!o.isReplyMessage(e))return;const{callId:t,value:s,isError:n,isSerializedErrorInstance:i}=e,l=m.get(t);l&&(m.delete(t),clearTimeout(l.timeoutId),h?.(`Received ${a.formatMethodPath(l.methodPath)}() call`,e),n?l.reject(i?r.deserializeError(s):s):l.resolve(s))};i.addMessageHandler(f);return{remoteProxy:l((r,o)=>{if(u)throw c(r);const l=e.randomUUID(),f=o[o.length-1],g=f instanceof t,{timeout:M,transferables:p}=g?f:{},P=g?o.slice(0,-1):o;return new Promise((e,t)=>{const o=void 0!==M?window.setTimeout(()=>{m.delete(l),t(new n("METHOD_CALL_TIMEOUT",`Method call ${a.formatMethodPath(r)}() timed out after ${M}ms`))},M):void 0;m.set(l,{methodPath:r,resolve:e,reject:t,timeoutId:o});try{const e={namespace:s,channel:d,type:"CALL",id:l,methodPath:r,args:P};h?.(`Sending ${a.formatMethodPath(r)}() call`,e),i.sendMessage(e,p)}catch(e){t(new n("TRANSMISSION_FAILED",e.message))}})},h),destroy:()=>{u=!0,i.removeMessageHandler(f);for(const{methodPath:e,reject:t,timeoutId:r}of m.values())clearTimeout(r),t(c(e));m.clear()}}};
|
package/dist/index.d.cts
CHANGED
|
@@ -12955,6 +12955,39 @@ declare class NotConfiguredError extends SignerError {
|
|
|
12955
12955
|
declare class OTPRequiredError extends OpenfortError {
|
|
12956
12956
|
constructor();
|
|
12957
12957
|
}
|
|
12958
|
+
/**
|
|
12959
|
+
* Thrown when the iframe signer does not respond to a `sign` request within
|
|
12960
|
+
* the configured timeout window. The handshake itself succeeded — penpal is
|
|
12961
|
+
* connected — but `remote.sign()` never resolved. In practice this means the
|
|
12962
|
+
* passkey/biometry prompt was dismissed, the iframe is frozen, or a
|
|
12963
|
+
* postMessage was dropped. Without this timeout the promise hangs forever
|
|
12964
|
+
* and the caller sees an endless "Processing" spinner with no error.
|
|
12965
|
+
*/
|
|
12966
|
+
declare class IframeSignTimeoutError extends SignerError {
|
|
12967
|
+
constructor(timeoutMs: number);
|
|
12968
|
+
}
|
|
12969
|
+
/**
|
|
12970
|
+
* Thrown when the iframe signer returns a response without a signature
|
|
12971
|
+
* (empty string, undefined, or null). The transport succeeded but the
|
|
12972
|
+
* payload is unusable — posting it downstream would create a malformed
|
|
12973
|
+
* UserOperation, so fail fast instead.
|
|
12974
|
+
*/
|
|
12975
|
+
declare class IframeSignEmptyResponseError extends SignerError {
|
|
12976
|
+
constructor();
|
|
12977
|
+
}
|
|
12978
|
+
/**
|
|
12979
|
+
* Thrown when the consumer calls `destroy()` on an `IframeManager` before its
|
|
12980
|
+
* connection handshake has finished. The two paths that produce this error are
|
|
12981
|
+
* (a) `initialize()` called on a manager that was already destroyed, and
|
|
12982
|
+
* (b) `destroy()` racing an in-flight `initialize()` (component unmount during
|
|
12983
|
+
* the penpal handshake). The original "configure your origin" copy is
|
|
12984
|
+
* intentionally NOT surfaced here, because it misled customers (Sentry
|
|
12985
|
+
* OPENFORT-JS-HD) into believing their dashboard origin config was wrong when
|
|
12986
|
+
* the real cause was a teardown race.
|
|
12987
|
+
*/
|
|
12988
|
+
declare class SessionEndedBeforeSetupError extends OpenfortError {
|
|
12989
|
+
constructor();
|
|
12990
|
+
}
|
|
12958
12991
|
|
|
12959
12992
|
interface Signer$1 {
|
|
12960
12993
|
sign(message: Uint8Array | string, requireArrayify?: boolean, requireHash?: boolean): Promise<string>;
|
|
@@ -13252,4 +13285,4 @@ declare function cryptoDigest(algorithm: string, data: BufferSource): Promise<Ar
|
|
|
13252
13285
|
*/
|
|
13253
13286
|
declare const openfortEvents: TypedEventEmitter<OpenfortEventMap>;
|
|
13254
13287
|
|
|
13255
|
-
export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
|
|
13288
|
+
export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
|
package/dist/index.d.ts
CHANGED
|
@@ -12955,6 +12955,39 @@ declare class NotConfiguredError extends SignerError {
|
|
|
12955
12955
|
declare class OTPRequiredError extends OpenfortError {
|
|
12956
12956
|
constructor();
|
|
12957
12957
|
}
|
|
12958
|
+
/**
|
|
12959
|
+
* Thrown when the iframe signer does not respond to a `sign` request within
|
|
12960
|
+
* the configured timeout window. The handshake itself succeeded — penpal is
|
|
12961
|
+
* connected — but `remote.sign()` never resolved. In practice this means the
|
|
12962
|
+
* passkey/biometry prompt was dismissed, the iframe is frozen, or a
|
|
12963
|
+
* postMessage was dropped. Without this timeout the promise hangs forever
|
|
12964
|
+
* and the caller sees an endless "Processing" spinner with no error.
|
|
12965
|
+
*/
|
|
12966
|
+
declare class IframeSignTimeoutError extends SignerError {
|
|
12967
|
+
constructor(timeoutMs: number);
|
|
12968
|
+
}
|
|
12969
|
+
/**
|
|
12970
|
+
* Thrown when the iframe signer returns a response without a signature
|
|
12971
|
+
* (empty string, undefined, or null). The transport succeeded but the
|
|
12972
|
+
* payload is unusable — posting it downstream would create a malformed
|
|
12973
|
+
* UserOperation, so fail fast instead.
|
|
12974
|
+
*/
|
|
12975
|
+
declare class IframeSignEmptyResponseError extends SignerError {
|
|
12976
|
+
constructor();
|
|
12977
|
+
}
|
|
12978
|
+
/**
|
|
12979
|
+
* Thrown when the consumer calls `destroy()` on an `IframeManager` before its
|
|
12980
|
+
* connection handshake has finished. The two paths that produce this error are
|
|
12981
|
+
* (a) `initialize()` called on a manager that was already destroyed, and
|
|
12982
|
+
* (b) `destroy()` racing an in-flight `initialize()` (component unmount during
|
|
12983
|
+
* the penpal handshake). The original "configure your origin" copy is
|
|
12984
|
+
* intentionally NOT surfaced here, because it misled customers (Sentry
|
|
12985
|
+
* OPENFORT-JS-HD) into believing their dashboard origin config was wrong when
|
|
12986
|
+
* the real cause was a teardown race.
|
|
12987
|
+
*/
|
|
12988
|
+
declare class SessionEndedBeforeSetupError extends OpenfortError {
|
|
12989
|
+
constructor();
|
|
12990
|
+
}
|
|
12958
12991
|
|
|
12959
12992
|
interface Signer$1 {
|
|
12960
12993
|
sign(message: Uint8Array | string, requireArrayify?: boolean, requireHash?: boolean): Promise<string>;
|
|
@@ -13252,4 +13285,4 @@ declare function cryptoDigest(algorithm: string, data: BufferSource): Promise<Ar
|
|
|
13252
13285
|
*/
|
|
13253
13286
|
declare const openfortEvents: TypedEventEmitter<OpenfortEventMap>;
|
|
13254
13287
|
|
|
13255
|
-
export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
|
|
13288
|
+
export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
|
package/dist/sdk/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Openfort as r}from"./core/openfort.js";export{AuthApi}from"./api/auth.js";export{EmbeddedWalletApi}from"./api/embeddedWallet.js";export{ProxyApi}from"./api/proxy.js";export{UserApi}from"./api/user.js";export{OPENFORT_AUTH_ERROR_CODES,OPENFORT_ERROR_CODES}from"./core/errors/authErrorCodes.js";export{AuthenticationError,AuthorizationError,ConfigurationError,OAuthError,OTPError,OpenfortError,RecoveryError,RequestError,SessionError,SignerError,UserError}from"./core/errors/openfortError.js";export{PASSKEY_ERROR_CODES,PasskeyAssertionFailedError,PasskeyCreationFailedError,PasskeyPRFNotSupportedError,PasskeySeedInvalidError,PasskeyUserCancelledError}from"./core/passkey/errors.js";export{PasskeyHandler}from"./core/passkey/handler.js";export{arrayBufferToBase64URL,base64ToArrayBuffer}from"./core/passkey/utils.js";export{OpenfortConfiguration,SDKConfiguration,ShieldConfiguration}from"./core/config/config.js";export{OpenfortInternal}from"./core/openfortInternal.js";export{prepareAndSignAuthorization,serializeSignedAuthorization,signAuthorization}from"./utils/authorization.js";export{MissingProjectEntropyError,MissingRecoveryPasswordError,NotConfiguredError,OTPRequiredError,WrongPasskeyError,WrongRecoveryPasswordError}from"./wallets/iframeManager.js";export{AccountTypeEnum,AuthActionRequiredActions,AuthType,BasicAuthProvider,ChainTypeEnum,EmbeddedState,OAuthProvider,OpenfortEvents,RecoveryMethod,ThirdPartyAuthProvider as ThirdPartyOAuthProvider,TokenType}from"./types/types.js";export{cryptoDigest}from"./utils/crypto.js";const o=r.getEventEmitter();export{r as Openfort,o as openfortEvents};
|
|
1
|
+
import{Openfort as r}from"./core/openfort.js";export{AuthApi}from"./api/auth.js";export{EmbeddedWalletApi}from"./api/embeddedWallet.js";export{ProxyApi}from"./api/proxy.js";export{UserApi}from"./api/user.js";export{OPENFORT_AUTH_ERROR_CODES,OPENFORT_ERROR_CODES}from"./core/errors/authErrorCodes.js";export{AuthenticationError,AuthorizationError,ConfigurationError,OAuthError,OTPError,OpenfortError,RecoveryError,RequestError,SessionError,SignerError,UserError}from"./core/errors/openfortError.js";export{PASSKEY_ERROR_CODES,PasskeyAssertionFailedError,PasskeyCreationFailedError,PasskeyPRFNotSupportedError,PasskeySeedInvalidError,PasskeyUserCancelledError}from"./core/passkey/errors.js";export{PasskeyHandler}from"./core/passkey/handler.js";export{arrayBufferToBase64URL,base64ToArrayBuffer}from"./core/passkey/utils.js";export{OpenfortConfiguration,SDKConfiguration,ShieldConfiguration}from"./core/config/config.js";export{OpenfortInternal}from"./core/openfortInternal.js";export{prepareAndSignAuthorization,serializeSignedAuthorization,signAuthorization}from"./utils/authorization.js";export{IframeSignEmptyResponseError,IframeSignTimeoutError,MissingProjectEntropyError,MissingRecoveryPasswordError,NotConfiguredError,OTPRequiredError,SessionEndedBeforeSetupError,WrongPasskeyError,WrongRecoveryPasswordError}from"./wallets/iframeManager.js";export{AccountTypeEnum,AuthActionRequiredActions,AuthType,BasicAuthProvider,ChainTypeEnum,EmbeddedState,OAuthProvider,OpenfortEvents,RecoveryMethod,ThirdPartyAuthProvider as ThirdPartyOAuthProvider,TokenType}from"./types/types.js";export{cryptoDigest}from"./utils/crypto.js";const o=r.getEventEmitter();export{r as Openfort,o as openfortEvents};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="1.3.
|
|
1
|
+
const o="1.3.7",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as n}from"../core/errors/authErrorCodes.js";import{RecoveryError as t,SignerError as r,OpenfortError as o,ConfigurationError as s,SessionError as a}from"../core/errors/openfortError.js";import{sentry as d}from"../core/errors/sentry.js";import{StorageKeys as c}from"../storage/istorage.js";import{randomUUID as h}from"../utils/crypto.js";import{debugLog as u}from"../utils/debug.js";import{ReactNativeMessenger as l}from"./messaging/ReactNativeMessenger.js";import y from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as p,NOT_CONFIGURED_ERROR as f,MISSING_USER_ENTROPY_ERROR as g,MISSING_PROJECT_ENTROPY_ERROR as w,INCORRECT_USER_ENTROPY_ERROR as m,MISSING_PASSKEY_ERROR as v,INCORRECT_PASSKEY_ERROR as C,OTP_REQUIRED_ERROR as k,ShieldAuthType as I,Event as P,SignRequest as b,SwitchChainRequest as T,ExportPrivateKeyRequest as R,SetRecoveryMethodRequest as E,GetCurrentDeviceRequest as S,UpdateAuthenticationRequest as A}from"./types.js";class N extends t{constructor(){super(n.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class O extends t{constructor(){super(n.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class U extends t{constructor(){super(n.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class K extends t{constructor(){super(n.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class D extends r{constructor(){super(n.NOT_CONFIGURED,"Signer is not configured")}}class z extends o{constructor(){super(n.OTP_REQUIRED,"OTP verification required")}}class M{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,n){if(!e)throw new s("Configuration is required for IframeManager");if(!i)throw new s("Storage is required for IframeManager");if(!n)throw new s("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=n}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new o(n.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){u("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=y({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,u("IframeManager connection established")}catch(e){const i=e;throw d.captureException(i),this.destroy(),u("Failed to establish connection:",i),new o(n.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n \n In apps built with:\n - react native\n - swift\n - unity (non-webgl) \n \n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new o(n.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(p(e)){if(e.error===f)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===g)throw this.storage.remove(c.ACCOUNT),new N;if(e.error===w)throw this.storage.remove(c.ACCOUNT),new U;if(e.error===m)throw new K;if(e.error===v)throw this.storage.remove(c.ACCOUNT),new N;if(e.error===C)throw new O;if(e.error===k)throw new z;throw this.storage.remove(c.ACCOUNT),new o(n.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(n.NOT_LOGGED_IN,"Must be authenticated to create a signer");const t={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:t,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(n.NOT_LOGGED_IN,"Must be authenticated to create a signer");const t={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:t,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=e.chainId??null,n.password=e?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:e?.entropy?.encryptionSession},n.passkey=e?.entropy?.passkey??null;const t={uuid:h(),action:P.CREATE,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(t);return p(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async import(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=e.chainId??null,n.password=e?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:e?.entropy?.encryptionSession},n.passkey=e?.entropy?.passkey??null;const t={uuid:h(),action:P.IMPORT,privateKey:e.privateKey,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.import(t);return p(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const n=await e.fromStorage(this.storage),t=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=n?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession},r.passkey=i?.entropy?.passkey??null;const o={uuid:h(),action:P.RECOVER,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},s=await t.recover(o);return p(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s}async sign(e,i,n,t){u("[iframe] ensureConnection");const r=await this.ensureConnection(),o=new b(h(),e,await this.buildRequestConfiguration(),i,n,t);u("[iframe] done ensureConnection");const s=await r.sign(o);return u("[iframe] response",s),p(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s.signature}async switchChain(e){const i=await this.ensureConnection(),n=new T(h(),e,await this.buildRequestConfiguration()),t=await i.switchChain(n);return p(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),i=new R(h(),await this.buildRequestConfiguration()),n=await e.export(i);return p(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n.key}async setRecoveryMethod(e,i,n,t,r){const o=await this.ensureConnection(),s=new E(h(),e,await this.buildRequestConfiguration(),i,n,t,r),a=await o.setRecoveryMethod(s);p(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),n=new S(h(),e);try{const e=await i.getCurrentDevice(n);return p(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof D)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void u("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void u("No authentication found, skipping update");const n=new A(h(),e.token);u("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(n);p(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:h()};await e.logout(i)}async onMessage(e){u("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof l?(this.isInitialized||this.connection?u(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(u("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{u("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),u("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):u("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{M as IframeManager,U as MissingProjectEntropyError,N as MissingRecoveryPasswordError,D as NotConfiguredError,z as OTPRequiredError,O as WrongPasskeyError,K as WrongRecoveryPasswordError};
|
|
1
|
+
import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{SignerError as n,RecoveryError as r,OpenfortError as s,ConfigurationError as o,SessionError as a}from"../core/errors/openfortError.js";import{sentry as d}from"../core/errors/sentry.js";import{StorageKeys as c}from"../storage/istorage.js";import{randomUUID as h}from"../utils/crypto.js";import{debugLog as u}from"../utils/debug.js";import{ReactNativeMessenger as l}from"./messaging/ReactNativeMessenger.js";import y from"./messaging/browserMessenger/CallOptions.js";import p from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import f from"./messaging/browserMessenger/PenpalError.js";import{isErrorResponse as g,NOT_CONFIGURED_ERROR as m,MISSING_USER_ENTROPY_ERROR as w,MISSING_PROJECT_ENTROPY_ERROR as v,INCORRECT_USER_ENTROPY_ERROR as C,MISSING_PASSKEY_ERROR as I,INCORRECT_PASSKEY_ERROR as k,OTP_REQUIRED_ERROR as P,ShieldAuthType as R,Event as T,SignRequest as b,SwitchChainRequest as E,ExportPrivateKeyRequest as A,SetRecoveryMethodRequest as S,GetCurrentDeviceRequest as N,UpdateAuthenticationRequest as O}from"./types.js";class D extends r{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class U extends r{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class K extends r{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class M extends r{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class z extends n{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class _ extends s{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class L extends n{constructor(e){super(t.INTERNAL_ERROR,`Iframe signer did not respond within ${e}ms. The signing prompt may have been dismissed or the iframe is unresponsive.`),this.name="IframeSignTimeoutError",Object.setPrototypeOf(this,L.prototype)}}class j extends n{constructor(){super(t.INTERNAL_ERROR,"Iframe signer returned an empty signature."),this.name="IframeSignEmptyResponseError",Object.setPrototypeOf(this,j.prototype)}}class F extends s{constructor(){super(t.INTERNAL_ERROR,"Wallet session ended before setup completed."),Object.setPrototypeOf(this,F.prototype)}}class q{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;isDestroyed=!1;hasFailed=!1;constructor(e,i,t){if(!e)throw new o("Configuration is required for IframeManager");if(!i)throw new o("Storage is required for IframeManager");if(!t)throw new o("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=t}assertAlive(){if(this.isDestroyed)throw new F}async initialize(){if(this.assertAlive(),!this.isInitialized){if(this.hasFailed)throw new s(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)return await this.initializationPromise,void this.assertAlive();this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.assertAlive(),this.isInitialized=!0}catch(e){if(this.initializationPromise=null,e instanceof F)throw e;throw this.hasFailed=!0,e}}}async doInitialize(){u("Initializing IframeManager connection..."),this.assertAlive(),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=p({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,this.assertAlive(),u("IframeManager connection established")}catch(e){this.isDestroyed&&u("Connection rejected after destroy() — surfacing teardown error"),this.assertAlive();const i=e;throw d.captureException(i),this.clearConnection(),u("Failed to establish connection:",i),new s(t.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n\n In apps built with:\n - react native\n - swift\n - unity (non-webgl)\n\n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}clearConnection(){if(this.connection)try{this.connection.destroy()}catch(e){u("clearConnection: connection.destroy() threw, swallowing:",e)}this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new s(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(g(e)){if(e.error===m)throw this.storage.remove(c.ACCOUNT),new z;if(e.error===w)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===v)throw this.storage.remove(c.ACCOUNT),new K;if(e.error===C)throw new M;if(e.error===I)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===k)throw new U;if(e.error===P)throw new _;throw this.storage.remove(c.ACCOUNT),new s(t.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:R.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:R.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:T.CREATE,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(n);return g(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async import(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:T.IMPORT,privateKey:e.privateKey,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.import(n);return g(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await e.fromStorage(this.storage),n=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=t?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession},r.passkey=i?.entropy?.passkey??null;const s={uuid:h(),action:T.RECOVER,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},o=await n.recover(s);return g(o)&&this.handleError(o),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",o.version??"undefined"),o}async sign(e,i,t,n){u("[iframe] ensureConnection");const r=await this.ensureConnection(),s=new b(h(),e,await this.buildRequestConfiguration(),i,t,n);let o;u("[iframe] done ensureConnection"),this.assertAlive();try{o=await r.sign(s,new y({timeout:9e4}))}catch(e){if(e instanceof f&&"METHOD_CALL_TIMEOUT"===e.code)throw this.hasFailed=!0,new L(9e4);throw e}if(u("[iframe] response",o),g(o)&&this.handleError(o),!o.signature)throw new j;return"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",o.version??"undefined"),o.signature}async switchChain(e){const i=await this.ensureConnection(),t=new E(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return g(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new A(h(),await this.buildRequestConfiguration()),t=await e.export(i);return g(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t,n,r){const s=await this.ensureConnection(),o=new S(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await s.setRecoveryMethod(o);g(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new N(h(),e);try{const e=await i.getCurrentDevice(t);return g(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof z)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void u("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void u("No authentication found, skipping update");const t=new O(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);g(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:h()};await e.logout(i)}async onMessage(e){u("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof l?(this.isInitialized||this.connection?u(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(u("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{u("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),u("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):u("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.clearConnection())}}export{q as IframeManager,j as IframeSignEmptyResponseError,L as IframeSignTimeoutError,K as MissingProjectEntropyError,D as MissingRecoveryPasswordError,z as NotConfiguredError,_ as OTPRequiredError,F as SessionEndedBeforeSetupError,U as WrongPasskeyError,M as WrongRecoveryPasswordError};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{debugLog as e}from"../../utils/debug.js";import t from"./browserMessenger/PenpalError.js";import"./browserMessenger/backwardCompatibility.js";class s{messagePoster;handlers=new Set;isInitialized=!1;hasBeenUsed=!1;validateMessage;messageBuffer=[];nextNumericId=1;stringToNumericId=new Map;numericToStringId=new Map;constructor(s){if(this.messagePoster=s,!s||"function"!=typeof s.postMessage)throw new t("CONNECTION_DESTROYED","Invalid message poster provided");e("ReactNativeMessenger created")}initialize
|
|
1
|
+
import{debugLog as e}from"../../utils/debug.js";import t from"./browserMessenger/PenpalError.js";import"./browserMessenger/backwardCompatibility.js";class s{messagePoster;handlers=new Set;isInitialized=!1;hasBeenUsed=!1;validateMessage;messageBuffer=[];nextNumericId=1;stringToNumericId=new Map;numericToStringId=new Map;constructor(s){if(this.messagePoster=s,!s||"function"!=typeof s.postMessage)throw new t("CONNECTION_DESTROYED","Invalid message poster provided");e("ReactNativeMessenger created")}initialize=s=>{if(this.isInitialized)return void e("ReactNativeMessenger already initialized");if(this.hasBeenUsed)throw new t("CONNECTION_DESTROYED","A messenger can only be used for a single connection");this.validateMessage=s?.validateReceivedMessage,this.isInitialized=!0,this.hasBeenUsed=!0,e(`ReactNativeMessenger initialized, processing ${this.messageBuffer.length} buffered messages`);const a=[...this.messageBuffer];this.messageBuffer=[],a.forEach(e=>{this.processMessage(e)})};sendMessage=(s,a)=>{if(!this.isInitialized)throw new t("CONNECTION_DESTROYED","ReactNativeMessenger not initialized");a&&a.length>0&&e("React Native: Ignoring transferables (not supported)"),e("ReactNativeMessenger sending message:",s);try{let t=s;"penpal"===s?.namespace&&(t=this.convertToDeprecatedFormat(s),e("React Native: Converted message:",t));const a=JSON.stringify(t);this.messagePoster.postMessage(a)}catch(e){throw new t("TRANSMISSION_FAILED",`Failed to send message through React Native WebView: ${e instanceof Error?e.message:String(e)}`)}};addMessageHandler=t=>{this.handlers.add(t),e(`Message handler added, total handlers: ${this.handlers.size}`)};removeMessageHandler=t=>{this.handlers.delete(t),e(`Message handler removed, total handlers: ${this.handlers.size}`)};handleMessage=t=>{if(e("[HANDSHAKE DEBUG] ReactNativeMessenger.handleMessage called with:",t),!this.isInitialized){const s=this.messageBuffer.length+1;return e(`[HANDSHAKE DEBUG] ReactNativeMessenger: Message received but not initialized, buffering message (${s} total)`),void this.messageBuffer.push(t)}e("[HANDSHAKE DEBUG] ReactNativeMessenger is initialized, processing message"),this.processMessage(t)};processMessage(t){e("[HANDSHAKE DEBUG] ReactNativeMessenger processing message:",t);const s=this.convertFromDeprecatedFormat(t);if(e("[HANDSHAKE DEBUG] Message after conversion:",s),this.validateMessage&&!this.validateMessage(s))return void e("[HANDSHAKE DEBUG] Message validation failed:",s);e(`[HANDSHAKE DEBUG] Routing message to ${this.handlers.size} handlers`);let a=0;this.handlers.forEach(t=>{a++;try{e(`[HANDSHAKE DEBUG] Calling handler ${a}/${this.handlers.size}`),t(s),e(`[HANDSHAKE DEBUG] Handler ${a} completed successfully`)}catch(t){e(`[HANDSHAKE DEBUG] Error in handler ${a}:`,t)}})}convertToDeprecatedFormat(t){if("penpal"!==t?.namespace)return t;switch(t.type){case"SYN":return e("React Native: Converting SYN to deprecated format to avoid MessagePorts",{originalMessage:t}),{penpal:"syn",participantId:t.participantId};case"ACK1":return e("React Native: Converting ACK1 to deprecated format",{originalMessage:t}),{penpal:"synAck",methodNames:t.methodPaths||[]};case"ACK2":return e("React Native: Converting ACK2 to deprecated format",{originalMessage:t}),{penpal:"ack"};case"REPLY":{e("React Native: Converting REPLY to deprecated format",{originalMessage:t});const s=this.getNumericId(t.callId);return t.isError?{penpal:"reply",id:s,resolution:"rejected",returnValue:t.value,returnValueIsError:t.isSerializedErrorInstance||!1}:{penpal:"reply",id:s,resolution:"fulfilled",returnValue:t.value}}case"CALL":e("React Native: Converting CALL to deprecated format",{originalMessage:t});return{penpal:"call",id:this.getNumericId(t.id),methodName:t.methodPath.join("."),args:t.args};case"DESTROY":return{namespace:"penpal",type:"DESTROY"};default:return t}}convertFromDeprecatedFormat(t){if(t?.penpal)switch(t.penpal){case"syn":{e("[HANDSHAKE DEBUG] React Native: Converting deprecated SYN to modern format",{originalMessage:t});const s={namespace:"penpal",type:"SYN",participantId:t.participantId};return e("[HANDSHAKE DEBUG] Converted SYN:",s),s}case"synAck":{e("[HANDSHAKE DEBUG] React Native: Converting deprecated synAck to modern ACK1 format",{originalMessage:t});const s={namespace:"penpal",type:"ACK1",methodPaths:t.methodNames?.map(e=>e.split("."))||[],channel:void 0};return e("[HANDSHAKE DEBUG] Converted ACK1:",s),s}case"ack":{e("[HANDSHAKE DEBUG] React Native: Converting deprecated ack to modern ACK2 format",{originalMessage:t});const s={namespace:"penpal",type:"ACK2",channel:void 0};return e("[HANDSHAKE DEBUG] Converted ACK2:",s),s}case"reply":{e("React Native: Converting deprecated reply to modern REPLY format",{originalMessage:t});const s=this.getStringId(t.id);s||e(`Warning: No string ID mapping found for numeric ID ${t.id}, using as-is`);const a=s||String(t.id);return"fulfilled"===t.resolution?{namespace:"penpal",type:"REPLY",callId:a,value:t.returnValue}:{namespace:"penpal",type:"REPLY",callId:a,isError:!0,value:t.returnValue,isSerializedErrorInstance:t.returnValueIsError||!1}}case"call":{e("React Native: Converting deprecated call to modern CALL format",{originalMessage:t});const s=this.getStringId(t.id);return s||e(`Warning: No string ID mapping found for numeric ID ${t.id}, using as-is`),{namespace:"penpal",type:"CALL",id:s||String(t.id),methodPath:t.methodName.split("."),args:t.args}}default:return e("React Native: Unknown deprecated penpal message type:",t.penpal),t}return t}setupMessagePort=t=>{e("React Native: setupMessagePort called but ignored (MessagePort not supported)")};destroy=()=>{this.isInitialized&&(this.handlers.clear(),this.messageBuffer=[],this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextNumericId=1,this.isInitialized=!1,this.hasBeenUsed=!1,e("ReactNativeMessenger destroyed and ready for reuse"))};reset=()=>{e("ReactNativeMessenger reset for reuse"),this.handlers.clear(),this.messageBuffer=[],this.isInitialized=!1,this.hasBeenUsed=!1,this.nextNumericId=1,this.stringToNumericId.clear(),this.numericToStringId.clear()};getNumericId(t){let s=this.stringToNumericId.get(t);return s||(s=this.nextNumericId++,this.stringToNumericId.set(t,s),this.numericToStringId.set(s,t),e(`ID mapping created: "${t}" -> ${s}`)),s}getStringId(e){return this.numericToStringId.get(e)}}export{s as ReactNativeMessenger};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as e}from"../../../utils/crypto.js";import t from"./CallOptions.js";import{deserializeError as r}from"./errorSerialization.js";import{isReplyMessage as o}from"./guards.js";import{formatMethodPath as a}from"./methodSerialization.js";import s from"./namespace.js";import n from"./PenpalError.js";const l=new Set(["apply","call","bind"]),i=(e,t,r=[])=>new Proxy(r.length?()=>{}:Object.create(null),{get(o,a){if("then"!==a)return r.length&&l.has(a)?Reflect.get(o,a):i(e,t,[...r,a])},apply:(t,o,a)=>e(r,a)}),c=e=>new n("CONNECTION_DESTROYED",`Method call ${a(e)}() failed due to destroyed connection`),d=(l,d,m)=>{let h=!1;const p=new Map,
|
|
1
|
+
import{randomUUID as e}from"../../../utils/crypto.js";import t from"./CallOptions.js";import{deserializeError as r}from"./errorSerialization.js";import{isReplyMessage as o}from"./guards.js";import{formatMethodPath as a}from"./methodSerialization.js";import s from"./namespace.js";import n from"./PenpalError.js";const l=new Set(["apply","call","bind"]),i=(e,t,r=[])=>new Proxy(r.length?()=>{}:Object.create(null),{get(o,a){if("then"!==a)return r.length&&l.has(a)?Reflect.get(o,a):i(e,t,[...r,a])},apply:(t,o,a)=>e(r,a)}),c=e=>new n("CONNECTION_DESTROYED",`Method call ${a(e)}() failed due to destroyed connection`),d=(l,d,m)=>{let h=!1;const p=new Map,u=e=>{if(!o(e))return;const{callId:t,value:s,isError:n,isSerializedErrorInstance:l}=e,i=p.get(t);i&&(p.delete(t),clearTimeout(i.timeoutId),m?.(`Received ${a(i.methodPath)}() call`,e),n?i.reject(l?r(s):s):i.resolve(s))};l.addMessageHandler(u);return{remoteProxy:i((r,o)=>{if(h)throw c(r);const i=e(),u=o[o.length-1],f=u instanceof t,{timeout:g,transferables:j}=f?u:{},w=f?o.slice(0,-1):o;return new Promise((e,t)=>{const o=void 0!==g?window.setTimeout(()=>{p.delete(i),t(new n("METHOD_CALL_TIMEOUT",`Method call ${a(r)}() timed out after ${g}ms`))},g):void 0;p.set(i,{methodPath:r,resolve:e,reject:t,timeoutId:o});try{const e={namespace:s,channel:d,type:"CALL",id:i,methodPath:r,args:w};m?.(`Sending ${a(r)}() call`,e),l.sendMessage(e,j)}catch(e){t(new n("TRANSMISSION_FAILED",e.message))}})},m),destroy:()=>{h=!0,l.removeMessageHandler(u);for(const{methodPath:e,reject:t,timeoutId:r}of p.values())clearTimeout(r),t(c(e));p.clear()}}};export{d as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openfort/openfort-js",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.7",
|
|
4
4
|
"author": "Openfort (https://www.openfort.io)",
|
|
5
5
|
"bugs": "https://github.com/openfort-xyz/openfort-js/issues",
|
|
6
6
|
"repository": "openfort-xyz/openfort-js.git",
|
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
"rollup-plugin-dts": "^5.3.1",
|
|
60
60
|
"rollup-plugin-visualizer": "^5.14.0",
|
|
61
61
|
"typescript": "^5.9.3",
|
|
62
|
+
"vite-tsconfig-paths": "6.1.1",
|
|
62
63
|
"vitest": "^4.1.8",
|
|
63
64
|
"@openfort/openapi-clients": "0.0.1"
|
|
64
65
|
},
|