@privy-io/js-sdk-core 0.68.0 → 0.68.2

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.
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("eventemitter3"),t=require("jose"),s=require("js-cookie"),r=require("./Error.js"),o=require("./Token.js"),i=require("./session/keys.js"),a=require("./utils/allSettled.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=/*#__PURE__*/n(e),h=/*#__PURE__*/n(s);let d="did:privy:";class c extends l.default{set isUsingServerCookies(e){this._isUsingServerCookies=e}setStoredUsersCallback(e){this._setStoredUsers=e,this.getSavedUserIds().then((e=>{this._hasEmittedStoredUsers||this._setStoredUsers?.({users:e.map((e=>({id:e})))})}))}async getCustomerAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(i.toCustomerAccessTokenStorageKey(e));try{return"string"==typeof t?new o.Token(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getPrivyAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(i.toPrivyAccessTokenStorageKey(e));try{return"string"==typeof t?new o.Token(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getRefreshToken(){let e=await this.getActiveUserId(),t=await this._storage.get(i.toRefreshTokenStorageKey(e));return"string"==typeof t?t:null}async getIdentityToken(){let e=await this.getActiveUserId(),t=await this._storage.get(i.toIdentityTokenStorageKey(e));return"string"==typeof t?t:null}async mightHaveServerCookies(){try{let e=await this.getActiveUserId(),t=h.default.get(i.toSessionCookieKey(e));if(void 0!==t&&t.length>0)return!0;let s=h.default.get(i.toSessionCookieKey(null));return void 0!==s&&s.length>0}catch(e){console.error(e)}return!1}async hasRefreshCredentials(e,t){return await this.mightHaveServerCookies()||"string"==typeof e&&"string"==typeof t}tokenIsActive(e){if(!e)return!1;let t=o.Token.parse(e);return null!==t&&!t.isExpired(30)}async destroyLocalState(e){let t=await this.getActiveUserId(),s=[this._storage.del(i.toCustomerAccessTokenStorageKey(null)),this._storage.del(i.toPrivyAccessTokenStorageKey(null)),this._storage.del(i.toRefreshTokenStorageKey(null)),this._storage.del(i.toIdentityTokenStorageKey(null)),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),this._storage.del(i.ACTIVE_USER_STORAGE_KEY)];t&&s.push(this._storage.del(i.toCustomerAccessTokenStorageKey(t)),this._storage.del(i.toPrivyAccessTokenStorageKey(t)),this._storage.del(i.toRefreshTokenStorageKey(t)),this._storage.del(i.toIdentityTokenStorageKey(t)),this.removeSavedUserId(t)),await a.allSettled(s),h.default.remove(i.toCustomerAccessTokenCookieKey(null)),h.default.remove(i.toRefreshTokenCookieKey(null)),h.default.remove(i.toIdentityTokenCookieKey(null)),h.default.remove(i.toSessionCookieKey(null)),t&&(h.default.remove(i.toCustomerAccessTokenCookieKey(t)),h.default.remove(i.toRefreshTokenCookieKey(t)),h.default.remove(i.toIdentityTokenCookieKey(t)),h.default.remove(i.toSessionCookieKey(t))),e?.reason&&this.emit("storage_cleared",{reason:e.reason})}async storeCustomerAccessToken(e){let t=await this.getActiveUserId();await this.storeCustomerAccessTokenForUser(t,e)}async storeCustomerAccessTokenForUser(e,t){let s=i.toCustomerAccessTokenStorageKey(e),r=i.toCustomerAccessTokenCookieKey(e);if("string"==typeof t){let e=await this._storage.get(s);if(await this._storage.put(s,t),!this._isUsingServerCookies){let e=o.Token.parse(t)?.expiration;h.default.set(r,t,{sameSite:"Strict",secure:!0,expires:e?new Date(1e3*e):void 0})}e!==t&&this.emit("token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(s);await this._storage.del(s),h.default.remove(r),null!==e&&this.emit("token_cleared",{reason:"set_with_non_string_value"})}}async storePrivyAccessToken(e){let t=await this.getActiveUserId();await this.storePrivyAccessTokenForUser(t,e)}async storePrivyAccessTokenForUser(e,t){let s=i.toPrivyAccessTokenStorageKey(e);"string"==typeof t?await this._storage.put(s,t):await this._storage.del(s)}async storeRefreshTokenForUser(e,t){let s=i.toRefreshTokenStorageKey(e),r=i.toRefreshTokenCookieKey(e),o=i.toSessionCookieKey(e);"string"==typeof t?(await this._storage.put(s,t),this._isUsingServerCookies||(h.default.set(o,"t",{sameSite:"Strict",secure:!0,expires:30}),h.default.set(r,t,{sameSite:"Strict",secure:!0,expires:30})),this.emit("refresh_token_stored",{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(s),h.default.remove(r),h.default.remove(o),this.emit("refresh_token_cleared",{reason:"set_with_non_string_value"}))}async updateWithTokensResponse(e){let t=e.user.id,s=(await a.allSettled([this.storeCustomerAccessTokenForUser(t,e.token),this.storePrivyAccessTokenForUser(t,e.privy_access_token),this.storeRefreshTokenForUser(t,e.refresh_token),this.storeIdentityTokenForUser(t,e.identity_token)])).filter((e=>"rejected"===e.status));if(s.length>0)return void this.emit("error_storing_tokens",s.map((e=>String(e.reason))).join(", "));let r=(await a.allSettled([this.storeCustomerAccessTokenForUser(null,e.token),this.storePrivyAccessTokenForUser(null,e.privy_access_token),this.storeRefreshTokenForUser(null,e.refresh_token),this.storeIdentityTokenForUser(null,e.identity_token)])).filter((e=>"rejected"===e.status));if(r.length>0)return void this.emit("error_storing_tokens",r.map((e=>String(e.reason))).join(", "));await this.storeActiveUserId(t);let o=(await a.allSettled([this.processOAuthTokens(e.oauth_tokens)])).filter((e=>"rejected"===e.status));o.length>0&&this.emit("error_storing_tokens",o.map((e=>String(e.reason))).join(", "))}async backfillLegacySession(){if(await this.getActiveUserId())return;let[e,t,s,r]=await Promise.all([this._storage.get(i.toCustomerAccessTokenStorageKey(null)),this._storage.get(i.toPrivyAccessTokenStorageKey(null)),this._storage.get(i.toRefreshTokenStorageKey(null)),this._storage.get(i.toIdentityTokenStorageKey(null))]);if("string"!=typeof e||"string"!=typeof s)return;let n=(e=>e?.startsWith(d)?e.slice(10):e)(o.Token.parse(e)?.subject);if("string"!=typeof n||0===n.length)return;let l=[this.storeCustomerAccessTokenForUser(n,e),this.storeRefreshTokenForUser(n,s)];"string"==typeof t&&l.push(this.storePrivyAccessTokenForUser(n,t)),"string"==typeof r&&l.push(this.storeIdentityTokenForUser(n,r));let h=(await a.allSettled(l)).filter((e=>"rejected"===e.status));h.length>0?this.emit("error_storing_tokens",h.map((e=>String(e.reason))).join(", ")):await this.storeActiveUserId(n)}async processOAuthTokens(e){e&&this.emit("oauth_tokens_granted",e)}async storeIdentityToken(e){let t=await this.getActiveUserId();await this.storeIdentityTokenForUser(t,e)}async storeIdentityTokenForUser(e,t){let s=i.toIdentityTokenStorageKey(e),r=i.toIdentityTokenCookieKey(e);if("string"==typeof t){let e=await this._storage.get(s);if(await this._storage.put(s,t),!this._isUsingServerCookies){let e=o.Token.parse(t)?.expiration;h.default.set(r,t,{sameSite:"Strict",secure:!0,expires:e?new Date(1e3*e):void 0})}e!==t&&this.emit("identity_token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(s);await this._storage.del(s),h.default.remove(r),null!==e&&this.emit("identity_token_cleared",{reason:"set_with_non_string_value"})}}async getOrCreateGuestCredential(){let e=await this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(e&&"string"==typeof e)return e;let s=t.base64url.encode(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,s),s}async getActiveUserId(){let e=await this._storage.get(i.ACTIVE_USER_STORAGE_KEY);return"string"==typeof e?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(i.ACTIVE_USER_STORAGE_KEY,e)}async getSavedUserIds(){let e=await this._storage.get(i.SAVED_USERS_STORAGE_KEY);if("string"!=typeof e)return[];try{let t=JSON.parse(e),s=Array.isArray(t)?t.filter((e=>"string"==typeof e)):[];return[...new Set(s)]}catch{return[]}}async storeSavedUserIds(e){let t=[...new Set(e)];t.length>0?await this._storage.put(i.SAVED_USERS_STORAGE_KEY,JSON.stringify(t)):await this._storage.del(i.SAVED_USERS_STORAGE_KEY),this._setStoredUsers&&(this._hasEmittedStoredUsers=!0,this._setStoredUsers({users:t.map((e=>({id:e})))}))}async removeSavedUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds(t.filter((t=>t!==e)))}async switchActiveUserId(e){if(!(await this.getSavedUserIds()).includes(e))throw new r.PrivyClientError({code:"invalid_input",error:"Cannot switch active user because the user ID is not saved on this device"});await this._storage.put(i.ACTIVE_USER_STORAGE_KEY,e)}constructor(e){super(),this._isUsingServerCookies=!1,this._hasEmittedStoredUsers=!1,this._storage=e.storage,this.GUEST_CREDENTIAL_STORAGE_KEY=`privy:guest:${e.appId}`,this._setStoredUsers=e.setStoredUsers}}c.events=["storage_cleared","token_cleared","refresh_token_cleared","identity_token_cleared","token_stored","refresh_token_stored","identity_token_stored","oauth_tokens_granted","error_storing_tokens"],exports.Session=c;
1
+ "use strict";var e=require("eventemitter3"),t=require("jose"),s=require("js-cookie"),r=require("./Error.js"),o=require("./Token.js"),i=require("./session/keys.js"),a=require("./utils/allSettled.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=/*#__PURE__*/n(e),h=/*#__PURE__*/n(s);class d extends l.default{set isUsingServerCookies(e){this._isUsingServerCookies=e}setStoredUsersCallback(e){this._setStoredUsers=e,this.getSavedUserIds().then((e=>{this._hasEmittedStoredUsers||this._setStoredUsers?.({users:e.map((e=>({id:e})))})}))}async getCustomerAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(i.toCustomerAccessTokenStorageKey(e));try{return"string"==typeof t?new o.Token(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getPrivyAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(i.toPrivyAccessTokenStorageKey(e));try{return"string"==typeof t?new o.Token(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getRefreshToken(){let e=await this.getActiveUserId(),t=await this._storage.get(i.toRefreshTokenStorageKey(e));return"string"==typeof t?t:null}async getIdentityToken(){let e=await this.getActiveUserId(),t=await this._storage.get(i.toIdentityTokenStorageKey(e));return"string"==typeof t?t:null}async mightHaveServerCookies(){try{let e=await this.getActiveUserId(),t=h.default.get(i.toSessionCookieKey(e));if(void 0!==t&&t.length>0)return!0;let s=h.default.get(i.toSessionCookieKey(null));return void 0!==s&&s.length>0}catch(e){console.error(e)}return!1}async hasRefreshCredentials(e,t){return await this.mightHaveServerCookies()||"string"==typeof e&&"string"==typeof t}tokenIsActive(e){if(!e)return!1;let t=o.Token.parse(e);return null!==t&&!t.isExpired(30)}async destroyLocalState(e){let t=await this.getActiveUserId(),s=[this._storage.del(i.toCustomerAccessTokenStorageKey(null)),this._storage.del(i.toPrivyAccessTokenStorageKey(null)),this._storage.del(i.toRefreshTokenStorageKey(null)),this._storage.del(i.toIdentityTokenStorageKey(null)),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),this._storage.del(i.ACTIVE_USER_STORAGE_KEY)];t&&s.push(this._storage.del(i.toCustomerAccessTokenStorageKey(t)),this._storage.del(i.toPrivyAccessTokenStorageKey(t)),this._storage.del(i.toRefreshTokenStorageKey(t)),this._storage.del(i.toIdentityTokenStorageKey(t)),this.removeSavedUserId(t)),await a.allSettled(s),h.default.remove(i.toCustomerAccessTokenCookieKey(null)),h.default.remove(i.toRefreshTokenCookieKey(null)),h.default.remove(i.toIdentityTokenCookieKey(null)),h.default.remove(i.toSessionCookieKey(null)),t&&(h.default.remove(i.toCustomerAccessTokenCookieKey(t)),h.default.remove(i.toRefreshTokenCookieKey(t)),h.default.remove(i.toIdentityTokenCookieKey(t)),h.default.remove(i.toSessionCookieKey(t))),e?.reason&&this.emit("storage_cleared",{reason:e.reason})}async storeCustomerAccessToken(e){let t=await this.getActiveUserId();await this.storeCustomerAccessTokenForUser(t,e)}async storeCustomerAccessTokenForUser(e,t){let s=i.toCustomerAccessTokenStorageKey(e),r=i.toCustomerAccessTokenCookieKey(e);if("string"==typeof t){let e=await this._storage.get(s);if(await this._storage.put(s,t),!this._isUsingServerCookies){let e=o.Token.parse(t)?.expiration;h.default.set(r,t,{sameSite:"Strict",secure:!0,expires:e?new Date(1e3*e):void 0})}e!==t&&this.emit("token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(s);await this._storage.del(s),h.default.remove(r),null!==e&&this.emit("token_cleared",{reason:"set_with_non_string_value"})}}async storePrivyAccessToken(e){let t=await this.getActiveUserId();await this.storePrivyAccessTokenForUser(t,e)}async storePrivyAccessTokenForUser(e,t){let s=i.toPrivyAccessTokenStorageKey(e);"string"==typeof t?await this._storage.put(s,t):await this._storage.del(s)}async storeRefreshTokenForUser(e,t){let s=i.toRefreshTokenStorageKey(e),r=i.toRefreshTokenCookieKey(e),o=i.toSessionCookieKey(e);"string"==typeof t?(await this._storage.put(s,t),this._isUsingServerCookies||(h.default.set(o,"t",{sameSite:"Strict",secure:!0,expires:30}),h.default.set(r,t,{sameSite:"Strict",secure:!0,expires:30})),this.emit("refresh_token_stored",{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(s),h.default.remove(r),h.default.remove(o),this.emit("refresh_token_cleared",{reason:"set_with_non_string_value"}))}async updateWithTokensResponse(e){let t=e.user.id,s=(await a.allSettled([this.storeCustomerAccessTokenForUser(t,e.token),this.storePrivyAccessTokenForUser(t,e.privy_access_token),this.storeRefreshTokenForUser(t,e.refresh_token),this.storeIdentityTokenForUser(t,e.identity_token)])).filter((e=>"rejected"===e.status));if(s.length>0)return void this.emit("error_storing_tokens",s.map((e=>String(e.reason))).join(", "));let r=(await a.allSettled([this.storeCustomerAccessTokenForUser(null,e.token),this.storePrivyAccessTokenForUser(null,e.privy_access_token),this.storeRefreshTokenForUser(null,e.refresh_token),this.storeIdentityTokenForUser(null,e.identity_token)])).filter((e=>"rejected"===e.status));if(r.length>0)return void this.emit("error_storing_tokens",r.map((e=>String(e.reason))).join(", "));await this.storeActiveUserId(t);let o=(await a.allSettled([this.processOAuthTokens(e.oauth_tokens)])).filter((e=>"rejected"===e.status));o.length>0&&this.emit("error_storing_tokens",o.map((e=>String(e.reason))).join(", "))}async backfillLegacySession(){if(await this.getActiveUserId())return;let[e,t,s,r]=await Promise.all([this._storage.get(i.toCustomerAccessTokenStorageKey(null)),this._storage.get(i.toPrivyAccessTokenStorageKey(null)),this._storage.get(i.toRefreshTokenStorageKey(null)),this._storage.get(i.toIdentityTokenStorageKey(null))]);if("string"!=typeof e||"string"!=typeof s)return;let n=o.Token.parse(e)?.subject;if("string"!=typeof n||0===n.length)return;let l=[this.storeCustomerAccessTokenForUser(n,e),this.storeRefreshTokenForUser(n,s)];"string"==typeof t&&l.push(this.storePrivyAccessTokenForUser(n,t)),"string"==typeof r&&l.push(this.storeIdentityTokenForUser(n,r));let h=(await a.allSettled(l)).filter((e=>"rejected"===e.status));h.length>0?this.emit("error_storing_tokens",h.map((e=>String(e.reason))).join(", ")):await this.storeActiveUserId(n)}async processOAuthTokens(e){e&&this.emit("oauth_tokens_granted",e)}async storeIdentityToken(e){let t=await this.getActiveUserId();await this.storeIdentityTokenForUser(t,e)}async storeIdentityTokenForUser(e,t){let s=i.toIdentityTokenStorageKey(e),r=i.toIdentityTokenCookieKey(e);if("string"==typeof t){let e=await this._storage.get(s);if(await this._storage.put(s,t),!this._isUsingServerCookies){let e=o.Token.parse(t)?.expiration;h.default.set(r,t,{sameSite:"Strict",secure:!0,expires:e?new Date(1e3*e):void 0})}e!==t&&this.emit("identity_token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(s);await this._storage.del(s),h.default.remove(r),null!==e&&this.emit("identity_token_cleared",{reason:"set_with_non_string_value"})}}async getOrCreateGuestCredential(){let e=await this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(e&&"string"==typeof e)return e;let s=t.base64url.encode(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,s),s}async getActiveUserId(){let e=await this._storage.get(i.ACTIVE_USER_STORAGE_KEY);return"string"==typeof e?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(i.ACTIVE_USER_STORAGE_KEY,e)}async getSavedUserIds(){let e=await this._storage.get(i.SAVED_USERS_STORAGE_KEY);if("string"!=typeof e)return[];try{let t=JSON.parse(e),s=Array.isArray(t)?t.filter((e=>"string"==typeof e)):[];return[...new Set(s)]}catch{return[]}}async storeSavedUserIds(e){let t=[...new Set(e)];t.length>0?await this._storage.put(i.SAVED_USERS_STORAGE_KEY,JSON.stringify(t)):await this._storage.del(i.SAVED_USERS_STORAGE_KEY),this._setStoredUsers&&(this._hasEmittedStoredUsers=!0,this._setStoredUsers({users:t.map((e=>({id:e})))}))}async removeSavedUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds(t.filter((t=>t!==e)))}async switchActiveUserId(e){if(!(await this.getSavedUserIds()).includes(e))throw new r.PrivyClientError({code:"invalid_input",error:"Cannot switch active user because the user ID is not saved on this device"});await this._storage.put(i.ACTIVE_USER_STORAGE_KEY,e)}constructor(e){super(),this._isUsingServerCookies=!1,this._hasEmittedStoredUsers=!1,this._storage=e.storage,this.GUEST_CREDENTIAL_STORAGE_KEY=`privy:guest:${e.appId}`,this._setStoredUsers=e.setStoredUsers}}d.events=["storage_cleared","token_cleared","refresh_token_cleared","identity_token_cleared","token_stored","refresh_token_stored","identity_token_stored","oauth_tokens_granted","error_storing_tokens"],exports.Session=d;
2
2
  //# sourceMappingURL=Session.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Session.js","sources":["../../src/Session.ts"],"names":["PRIVY_DID_PREFIX","Session","EventEmitter","isUsingServerCookies","this","_isUsingServerCookies","setStoredUsersCallback","cb","_setStoredUsers","getSavedUserIds","then","e","_hasEmittedStoredUsers","users","ids","map","id","getCustomerAccessToken","userId","getActiveUserId","token","_storage","get","toCustomerAccessTokenStorageKey","Token","value","error","console","destroyLocalState","reason","getPrivyAccessToken","toPrivyAccessTokenStorageKey","getRefreshToken","refreshToken","toRefreshTokenStorageKey","getIdentityToken","identityToken","toIdentityTokenStorageKey","mightHaveServerCookies","sessionToken","Cookies","toSessionCookieKey","length","legacySessionToken","hasRefreshCredentials","tokenIsActive","tokenRaw","parse","isExpired","opts","deletes","del","GUEST_CREDENTIAL_STORAGE_KEY","ACTIVE_USER_STORAGE_KEY","push","removeSavedUserId","allSettled","remove","toCustomerAccessTokenCookieKey","toRefreshTokenCookieKey","toIdentityTokenCookieKey","emit","storeCustomerAccessToken","storeCustomerAccessTokenForUser","storageKey","cookieKey","previousToken","put","exp","expiration","set","sameSite","secure","expires","Date","undefined","cookiesEnabled","storePrivyAccessToken","storePrivyAccessTokenForUser","key","storeRefreshTokenForUser","refreshCookieKey","sessionCookieKey","updateWithTokensResponse","user","primaryErrors","privy_access_token","refresh_token","storeIdentityTokenForUser","identity_token","filter","x","status","String","join","legacyErrors","storeActiveUserId","oauthErrors","processOAuthTokens","oauth_tokens","backfillLegacySession","privyAccessToken","Promise","all","startsWith","slice","toStoredUserId","subject","writes","errors","oAuthTokens","storeIdentityToken","previousIdentityToken","getOrCreateGuestCredential","guestCredential","entropy","base64url","encode","crypto","getRandomValues","Uint8Array","storeSavedUserIds","savedUsers","SAVED_USERS_STORAGE_KEY","parsed","JSON","Array","isArray","Set","uniqueIds","stringify","t","savedId","switchActiveUserId","includes","PrivyClientError","code","constructor","o","super","storage","appId","setStoredUsers","events"],"mappings":"2TAkDA,IAAMA,EAAmB,aAqClB,MAAMC,UAAgBC,EAAAA,QA+B3B,wBAAIC,CAAqBA,GACvBC,KAAKC,sBAAwBF,CAC/B,CAEA,sBAAAG,CAA8BC,GAC5BH,KAAKI,gBAAkBD,EAClBH,KAAKK,kBAAkBC,MAAKC,IAC1BP,KAAKQ,wBACRR,KAAKI,kBAAkB,CAACK,MAAOC,EAAIC,KAAKC,KAASA,GAAAA,UAGvD,CAEA,4BAAMC,GACJ,IAAMC,QAAed,KAAKe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ources":["../../src/Session.ts"],"names":["Session","EventEmitter","isUsingServerCookies","this","_isUsingServerCookies","setStoredUsersCallback","cb","_setStoredUsers","getSavedUserIds","then","e","_hasEmittedStoredUsers","users","ids","map","id","getCustomerAccessToken","userId","getActiveUserId","token","_storage","get","toCustomerAccessTokenStorageKey","Token","value","error","console","destroyLocalState","reason","getPrivyAccessToken","toPrivyAccessTokenStorageKey","getRefreshToken","refreshToken","toRefreshTokenStorageKey","getIdentityToken","identityToken","toIdentityTokenStorageKey","mightHaveServerCookies","sessionToken","Cookies","toSessionCookieKey","length","legacySessionToken","hasRefreshCredentials","tokenIsActive","tokenRaw","parse","isExpired","opts","deletes","del","GUEST_CREDENTIAL_STORAGE_KEY","ACTIVE_USER_STORAGE_KEY","push","removeSavedUserId","allSettled","remove","toCustomerAccessTokenCookieKey","toRefreshTokenCookieKey","toIdentityTokenCookieKey","emit","storeCustomerAccessToken","storeCustomerAccessTokenForUser","storageKey","cookieKey","previousToken","put","exp","expiration","set","sameSite","secure","expires","Date","undefined","cookiesEnabled","storePrivyAccessToken","storePrivyAccessTokenForUser","key","storeRefreshTokenForUser","refreshCookieKey","sessionCookieKey","updateWithTokensResponse","user","primaryErrors","privy_access_token","refresh_token","storeIdentityTokenForUser","identity_token","filter","x","status","String","join","legacyErrors","storeActiveUserId","oauthErrors","processOAuthTokens","oauth_tokens","backfillLegacySession","privyAccessToken","Promise","all","subject","writes","errors","oAuthTokens","storeIdentityToken","previousIdentityToken","getOrCreateGuestCredential","guestCredential","entropy","base64url","encode","crypto","getRandomValues","Uint8Array","storeSavedUserIds","savedUsers","SAVED_USERS_STORAGE_KEY","parsed","JSON","Array","isArray","Set","uniqueIds","stringify","t","savedId","switchActiveUserId","includes","PrivyClientError","code","constructor","o","super","storage","appId","setStoredUsers","events"],"mappings":"2TAkFO,MAAMA,UAAgBC,EAAAA,QA+B3B,wBAAIC,CAAqBA,GACvBC,KAAKC,sBAAwBF,CAC/B,CAEA,sBAAAG,CAA8BC,GAC5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I,EACJ2I,OAjCM,CACb,kBACA,gBACA,wBACA,yBACA,eACA,uBACA,wBACA,uBACA"}
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("fetch-retry"),t=require("@privy-io/api-base"),s=require("@privy-io/routes"),i=require("../Error.js"),r=require("../Session.js"),a=require("../toAbortSignalTimeout.js"),n=require("../utils/toSearchParams.js"),o=require("./logger.js");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("eventemitter3"),require("jose"),require("js-cookie"),require("../Token.js"),require("../session/keys.js"),require("../utils/allSettled.js"),require("../utils/noop.js");var c=/*#__PURE__*/h(e);let l="privy:caid";exports.PrivyInternal=class{setCallbacks(e){this.callbacks={...this.callbacks,...e},this.session.setStoredUsersCallback(this.callbacks?.setStoredUsers)}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady)this.callbacks?.setIsReady?.(!0);else{if(!await this.isStorageAccessible())throw new i.PrivyClientError({code:"storage_error",error:"Unable to access storage"});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.isMultiUserModeEnabled&&await this.session.backfillLegacySession(),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:i}){return`${this.baseUrl}${s.getPathWithParams(e.path,t)}${n.toSearchParams(i)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new i.PrivyClientError({code:"invalid_input",error:'Unauthenticated requests require sessions.mode to be set to "multi-user"'});return this.fetch(e,{...t,onRequest:this._beforeRequestWithoutAuth.bind(this)})}async fetchForLogin(e,t){return this.isMultiUserModeEnabled?this.fetchWithoutAuthentication(e,t):this.fetch(e,t)}async fetch(e,{body:t,params:s,query:r,headers:a,onRequest:n=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:s,query:r}),{method:e.method,body:JSON.stringify(t),headers:a}),h=await n(o),c=await this._fetch(o,h),l=await c.json();if(c.status>299)throw new i.PrivyApiError({...l,status:c.status});return l}async _beforeRequestWithoutInitialize(e){let t=await this.session.getPrivyAccessToken()??await this.session.getCustomerAccessToken(),s=new Headers(e.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),t&&s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");let i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:a.default(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequestWithoutAuth(e){await this._initialize();let t=new Headers(e.headers);t.set("privy-app-id",this.appId),this.appClientId&&t.set("privy-client-id",this.appClientId),t.set("privy-client",this._sdkVersion),t.set("Content-Type","application/json"),t.set("Accept","application/json");let s=await this._getOrGenerateClientAnalyticsId();return s&&t.set("privy-ca-id",s),this.nativeAppIdentifier&&t.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:a.default(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(s.AppConfig,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(l);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error("Unable to load clientId",e)}try{this._analyticsId=this._crypto.randomUUID()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(this._analyticsId){try{await this._storage.put(l,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}}async destroyClientAnalyticsId(){try{return await this._storage.del(l)}catch(e){this.logger.error("Unable to delete clientId",e)}}async createAnalyticsEvent(e,t){try{await this.fetch(s.AnalyticsEvent,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(e){}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new i.PrivyClientError({code:"storage_error",error:"Unable to access storage"});let t=await this.session.getRefreshToken()??void 0,s=t??"key",r=this._cache.get(s);if(r)return this.logger.debug("[privy:refresh] found in-flight session refresh request, deduping"),await r;let a=this._refreshSession(t,e);this._cache.set(s,a);try{return await a}finally{this._cache.delete(s)}}async _refreshSession(e,r){let a=await this.session.getCustomerAccessToken();if(!await this.session.hasRefreshCredentials(a,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new i.PrivyApiError({code:t.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage",status:401});try{this.logger.debug(`[privy:refresh] fetching: ${s.RefreshSession.path}`);let t=await this.fetch(s.RefreshSession,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),i=t.session_update_action;return this.logger.debug(`[privy:refresh] response: ${i}`),"set"===i&&(await this.session.updateWithTokensResponse(t),this.logger.debug("[privy:refresh] tokens stored")),"clear"===i&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),r||this.callbacks?.setUser?.(null)),"ignore"===i&&(t.token&&(await this.session.storeCustomerAccessToken(t.token),this.logger.debug("[privy:refresh] token stored (CAT)")),t.privy_access_token&&(await this.session.storePrivyAccessToken(t.privy_access_token),this.logger.debug("[privy:refresh] token stored (PAT)")),t.identity_token&&(this.logger.debug("[privy:refresh] token stored (IDT)"),await this.session.storeIdentityToken(t.identity_token))),this.logger.debug("[privy:refresh] returning response"),r||this.callbacks?.setUser?.(t.user),t}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof i.PrivyApiError&&e.code===t.PrivyErrorCode.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),r||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getCustomerAccessToken(),this.session.getRefreshToken()]);if(e&&!this.session.tokenIsActive(e)&&await this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getCustomerAccessToken();return t.token||this.logger.debug("[privy:getAccessToken] expected token received null"),t.token===e&&this.logger.debug("[privy:getAccessToken] expected new token in response received existing"),s===e&&this.logger.debug("[privy:getAccessToken] expected new token in storage received existing"),t.token??s}return e&&!this.session.tokenIsActive(e)?(this.logger.debug("[privy:getAccessToken] unable to refresh inactive token"),this.callbacks?.setUser?.(null),await this.session.destroyLocalState(),null):e}async getAccessTokenInternal(){let e=await this.getAccessToken();return await this.session.getPrivyAccessToken()??e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${this._crypto.randomUUID()}`,t="blobby";await this._storage.put(e,t);let s=await this._storage.get(e);return await this._storage.del(e),s===t}catch(e){return this.logger.error(e),!1}}constructor(e){this._sdkVersion="js-sdk-core:0.68.0",this._cache=new Map,this.logger=o.toLoggerWithLevel({level:e.logger?.level??e.logLevel??"ERROR",logger:e.logger??console}),this._storage=e.storage,this._crypto=e.crypto,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=e.baseUrl??"https://auth.privy.io",this.appId=e.appId,this.appClientId=e.appClientId,this._sdkVersion=e.sdkVersion??this._sdkVersion,this.callbacks=e.callbacks,this.nativeAppIdentifier=e.nativeAppIdentifier,this.isMultiUserModeEnabled=e.isMultiUserModeEnabled,this.session=new r.Session({storage:this._storage,isUsingServerCookies:!1,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=c.default(globalThis.fetch,{retries:3,retryDelay:e=>3**e*500,retryOn:[408,409,425,500,502,503,504]}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}};
1
+ "use strict";var e=require("fetch-retry"),t=require("@privy-io/api-base"),s=require("@privy-io/routes"),i=require("../Error.js"),r=require("../Session.js"),a=require("../toAbortSignalTimeout.js"),n=require("../utils/toSearchParams.js"),o=require("./logger.js");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("eventemitter3"),require("jose"),require("js-cookie"),require("../Token.js"),require("../session/keys.js"),require("../utils/allSettled.js"),require("../utils/noop.js");var c=/*#__PURE__*/h(e);let l="privy:caid";exports.PrivyInternal=class{setCallbacks(e){this.callbacks={...this.callbacks,...e},this.session.setStoredUsersCallback(this.callbacks?.setStoredUsers)}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady)this.callbacks?.setIsReady?.(!0);else{if(!await this.isStorageAccessible())throw new i.PrivyClientError({code:"storage_error",error:"Unable to access storage"});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.isMultiUserModeEnabled&&await this.session.backfillLegacySession(),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:i}){return`${this.baseUrl}${s.getPathWithParams(e.path,t)}${n.toSearchParams(i)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new i.PrivyClientError({code:"invalid_input",error:'Unauthenticated requests require sessions.mode to be set to "multi-user"'});return this.fetch(e,{...t,onRequest:this._beforeRequestWithoutAuth.bind(this)})}async fetchForLogin(e,t){return this.isMultiUserModeEnabled?this.fetchWithoutAuthentication(e,t):this.fetch(e,t)}async fetch(e,{body:t,params:s,query:r,headers:a,onRequest:n=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:s,query:r}),{method:e.method,body:JSON.stringify(t),headers:a}),h=await n(o),c=await this._fetch(o,h),l=await c.json();if(c.status>299)throw new i.PrivyApiError({...l,status:c.status});return l}async _beforeRequestWithoutInitialize(e){let t=await this.session.getPrivyAccessToken()??await this.session.getCustomerAccessToken(),s=new Headers(e.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),t&&s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");let i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:a.default(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequestWithoutAuth(e){await this._initialize();let t=new Headers(e.headers);t.set("privy-app-id",this.appId),this.appClientId&&t.set("privy-client-id",this.appClientId),t.set("privy-client",this._sdkVersion),t.set("Content-Type","application/json"),t.set("Accept","application/json");let s=await this._getOrGenerateClientAnalyticsId();return s&&t.set("privy-ca-id",s),this.nativeAppIdentifier&&t.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:a.default(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(s.AppConfig,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(l);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error("Unable to load clientId",e)}try{this._analyticsId=this._crypto.randomUUID()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(this._analyticsId){try{await this._storage.put(l,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}}async destroyClientAnalyticsId(){try{return await this._storage.del(l)}catch(e){this.logger.error("Unable to delete clientId",e)}}async createAnalyticsEvent(e,t){try{await this.fetch(s.AnalyticsEvent,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(e){}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new i.PrivyClientError({code:"storage_error",error:"Unable to access storage"});let t=await this.session.getRefreshToken()??void 0,s=t??"key",r=this._cache.get(s);if(r)return this.logger.debug("[privy:refresh] found in-flight session refresh request, deduping"),await r;let a=this._refreshSession(t,e);this._cache.set(s,a);try{return await a}finally{this._cache.delete(s)}}async _refreshSession(e,r){let a=await this.session.getCustomerAccessToken();if(!await this.session.hasRefreshCredentials(a,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new i.PrivyApiError({code:t.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage",status:401});try{this.logger.debug(`[privy:refresh] fetching: ${s.RefreshSession.path}`);let t=await this.fetch(s.RefreshSession,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),i=t.session_update_action;return this.logger.debug(`[privy:refresh] response: ${i}`),"set"===i&&(await this.session.updateWithTokensResponse(t),this.logger.debug("[privy:refresh] tokens stored")),"clear"===i&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),r||this.callbacks?.setUser?.(null)),"ignore"===i&&(t.token&&(await this.session.storeCustomerAccessToken(t.token),this.logger.debug("[privy:refresh] token stored (CAT)")),t.privy_access_token&&(await this.session.storePrivyAccessToken(t.privy_access_token),this.logger.debug("[privy:refresh] token stored (PAT)")),t.identity_token&&(this.logger.debug("[privy:refresh] token stored (IDT)"),await this.session.storeIdentityToken(t.identity_token))),this.logger.debug("[privy:refresh] returning response"),r||this.callbacks?.setUser?.(t.user),t}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof i.PrivyApiError&&e.code===t.PrivyErrorCode.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),r||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getCustomerAccessToken(),this.session.getRefreshToken()]);if(e&&!this.session.tokenIsActive(e)&&await this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getCustomerAccessToken();return t.token||this.logger.debug("[privy:getAccessToken] expected token received null"),t.token===e&&this.logger.debug("[privy:getAccessToken] expected new token in response received existing"),s===e&&this.logger.debug("[privy:getAccessToken] expected new token in storage received existing"),t.token??s}return e&&!this.session.tokenIsActive(e)?(this.logger.debug("[privy:getAccessToken] unable to refresh inactive token"),this.callbacks?.setUser?.(null),await this.session.destroyLocalState(),null):e}async getAccessTokenInternal(){let e=await this.getAccessToken();return await this.session.getPrivyAccessToken()??e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${this._crypto.randomUUID()}`,t="blobby";await this._storage.put(e,t);let s=await this._storage.get(e);return await this._storage.del(e),s===t}catch(e){return this.logger.error(e),!1}}constructor(e){this._sdkVersion="js-sdk-core:0.68.2",this._cache=new Map,this.logger=o.toLoggerWithLevel({level:e.logger?.level??e.logLevel??"ERROR",logger:e.logger??console}),this._storage=e.storage,this._crypto=e.crypto,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=e.baseUrl??"https://auth.privy.io",this.appId=e.appId,this.appClientId=e.appClientId,this._sdkVersion=e.sdkVersion??this._sdkVersion,this.callbacks=e.callbacks,this.nativeAppIdentifier=e.nativeAppIdentifier,this.isMultiUserModeEnabled=e.isMultiUserModeEnabled,this.session=new r.Session({storage:this._storage,isUsingServerCookies:!1,appId:e.appId,setStoredUsers:e.callbacks?.setStoredUsers}),this._fetch=c.default(globalThis.fetch,{retries:3,retryDelay:e=>3**e*500,retryOn:[408,409,425,500,502,503,504]}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}};
2
2
  //# sourceMappingURL=PrivyInternal.js.map
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("@privy-io/routes"),r=require("../Error.js"),t=require("./generate-authorization-signature.js"),i=require("./types.js");require("canonicalize"),require("@privy-io/encoding"),exports.rpc=async function(a,o,{wallet_id:n,...l}){let u=a.getCompiledPath(e.WalletRpc,{params:{wallet_id:n}}),p=String(Date.now()+i.DEFAULT_EXPIRY_TIME_MS),s={version:1,url:u,method:e.WalletRpc.method,headers:{"privy-app-id":a.app.appId,[i.PRIVY_REQUEST_EXPIRY_HEADER_NAME]:p},body:{...l}},{signature:d}=await t.generateAuthorizationSignature(o,s);if(Date.now()>Number(p))throw new r.PrivyClientError({error:"Wallet request expired before it could be sent. Please try again.",code:"embedded_wallet_request_expired"});return await a.fetchPrivyRoute(e.WalletRpc,{body:l,params:{wallet_id:n},headers:{"privy-authorization-signature":d,[i.PRIVY_REQUEST_EXPIRY_HEADER_NAME]:p}})};
1
+ "use strict";var e=require("@privy-io/routes"),r=require("../Error.js"),t=require("./generate-authorization-signature.js"),i=require("./types.js");require("canonicalize"),require("@privy-io/encoding"),exports.rpc=async function(a,o,{wallet_id:n,headers:l,...u}){let s=a.getCompiledPath(e.WalletRpc,{params:{wallet_id:n}}),d=String(Date.now()+i.DEFAULT_EXPIRY_TIME_MS),p={version:1,url:s,method:e.WalletRpc.method,headers:{"privy-app-id":a.app.appId,[i.PRIVY_REQUEST_EXPIRY_HEADER_NAME]:d},body:{...u}},{signature:E}=await t.generateAuthorizationSignature(o,p);if(Date.now()>Number(d))throw new r.PrivyClientError({error:"Wallet request expired before it could be sent. Please try again.",code:"embedded_wallet_request_expired"});return await a.fetchPrivyRoute(e.WalletRpc,{body:u,params:{wallet_id:n},headers:{"privy-authorization-signature":E,[i.PRIVY_REQUEST_EXPIRY_HEADER_NAME]:d,...l??{}}})};
2
2
  //# sourceMappingURL=rpc.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rpc.js","sources":["../../../src/wallet-api/rpc.ts"],"names":["async","context","sign","wallet_id","request","url","getCompiledPath","WalletRpc","params","requestExpiry","String","Date","now","DEFAULT_EXPIRY_TIME_MS","payload","version","method","headers","app","appId","PRIVY_REQUEST_EXPIRY_HEADER_NAME","body","signature","generateAuthorizationSignature","Number","PrivyClientError","error","code","fetchPrivyRoute"],"mappings":"qNAqBOA,eACLC,EACAC,GACCC,UAAAA,KAAcC,IAGf,IAAMC,EAAMJ,EAAQK,gBAAgBC,YAAW,CAACC,OAAQ,CAACL,UAAAA,KAEnDM,EAAgBC,OAAOC,KAAKC,MAAQC,0BAEpCC,EAAU,CACdC,QAAS,EACTV,IAAAA,EACAW,OAAQT,EAAAA,UAAUS,OAClBC,QAAS,CACP,eAAgBhB,EAAQiB,IAAIC,MAC5B,CAACC,EAAAA,kCAAmCX,GAEtCY,KAAM,IACDjB,KAIAkB,UAAAA,SAAmBC,EAAAA,+BAA+BrB,EAAMY,GAK/D,GAAIH,KAAKC,MAAQY,OAAOf,GACtB,MAAM,IAAIgB,EAAAA,iBAAiB,CACzBC,MAAO,oEACPC,KAAM,oCAIV,aAAa1B,EAAQ2B,gBAAgBrB,EAAAA,UAAW,CAC9Cc,KAAMjB,EACNI,OAAQ,CACNL,UAAWA,GAEbc,QAAS,CACP,gCAAiCK,EACjC,CAACF,EAAAA,kCAAmCX,IAG1C"}
1
+ {"version":3,"file":"rpc.js","sources":["../../../src/wallet-api/rpc.ts"],"names":["async","context","sign","wallet_id","headers","extraHeaders","request","url","getCompiledPath","WalletRpc","params","requestExpiry","String","Date","now","DEFAULT_EXPIRY_TIME_MS","payload","version","method","app","appId","PRIVY_REQUEST_EXPIRY_HEADER_NAME","body","signature","generateAuthorizationSignature","Number","PrivyClientError","error","code","fetchPrivyRoute"],"mappings":"qNAqBOA,eACLC,EACAC,GACCC,UAAAA,EAAWC,QAASC,KAAiBC,IAGtC,IAAMC,EAAMN,EAAQO,gBAAgBC,YAAW,CAACC,OAAQ,CAACP,UAAAA,KAEnDQ,EAAgBC,OAAOC,KAAKC,MAAQC,0BAEpCC,EAAU,CACdC,QAAS,EACTV,IAAAA,EACAW,OAAQT,EAAAA,UAAUS,OAClBd,QAAS,CACP,eAAgBH,EAAQkB,IAAIC,MAC5B,CAACC,EAAAA,kCAAmCV,GAEtCW,KAAM,IACDhB,KAIAiB,UAAAA,SAAmBC,EAAAA,+BAA+BtB,EAAMc,GAK/D,GAAIH,KAAKC,MAAQW,OAAOd,GACtB,MAAM,IAAIe,mBAAiB,CACzBC,MAAO,oEACPC,KAAM,oCAIV,aAAa3B,EAAQ4B,gBAAgBpB,EAAAA,UAAW,CAC9Ca,KAAMhB,EACNI,OAAQ,CACNP,UAAWA,GAEbC,QAAS,CACP,gCAAiCmB,EACjC,CAACF,EAAAA,kCAAmCV,KAChCN,GAAgB,CAAA,IAG1B"}
@@ -2914,6 +2914,7 @@ declare function create(context: WalletApiActionContext, { request, headers }: I
2914
2914
 
2915
2915
  type Input$2 = WalletRpcParams & {
2916
2916
  wallet_id: string;
2917
+ headers?: Record<string, string>;
2917
2918
  };
2918
2919
  /**
2919
2920
  * Executes a Wallet API RPC request.
@@ -2923,7 +2924,7 @@ type Input$2 = WalletRpcParams & {
2923
2924
  * @param input The input to the Wallet API RPC request
2924
2925
  * @returns The response from the Wallet API RPC request
2925
2926
  */
2926
- declare function rpc(context: WalletApiActionContext, sign: SignWalletRequest, { wallet_id, ...request }: Input$2): Promise<WalletRpcResponse>;
2927
+ declare function rpc(context: WalletApiActionContext, sign: SignWalletRequest, { wallet_id, headers: extraHeaders, ...request }: Input$2): Promise<WalletRpcResponse>;
2927
2928
 
2928
2929
  type Input$1 = WalletRawSignParams & {
2929
2930
  wallet_id: string;
@@ -2914,6 +2914,7 @@ declare function create(context: WalletApiActionContext, { request, headers }: I
2914
2914
 
2915
2915
  type Input$2 = WalletRpcParams & {
2916
2916
  wallet_id: string;
2917
+ headers?: Record<string, string>;
2917
2918
  };
2918
2919
  /**
2919
2920
  * Executes a Wallet API RPC request.
@@ -2923,7 +2924,7 @@ type Input$2 = WalletRpcParams & {
2923
2924
  * @param input The input to the Wallet API RPC request
2924
2925
  * @returns The response from the Wallet API RPC request
2925
2926
  */
2926
- declare function rpc(context: WalletApiActionContext, sign: SignWalletRequest, { wallet_id, ...request }: Input$2): Promise<WalletRpcResponse>;
2927
+ declare function rpc(context: WalletApiActionContext, sign: SignWalletRequest, { wallet_id, headers: extraHeaders, ...request }: Input$2): Promise<WalletRpcResponse>;
2927
2928
 
2928
2929
  type Input$1 = WalletRawSignParams & {
2929
2930
  wallet_id: string;
@@ -1,2 +1,2 @@
1
- import e from"eventemitter3";import{base64url as t}from"jose";import s from"js-cookie";import{PrivyClientError as r}from"./Error.mjs";import{Token as i}from"./Token.mjs";import{toCustomerAccessTokenStorageKey as o,toPrivyAccessTokenStorageKey as a,toRefreshTokenStorageKey as n,toIdentityTokenStorageKey as l,toSessionCookieKey as h,ACTIVE_USER_STORAGE_KEY as g,toCustomerAccessTokenCookieKey as c,toRefreshTokenCookieKey as d,toIdentityTokenCookieKey as _,SAVED_USERS_STORAGE_KEY as u}from"./session/keys.mjs";import{allSettled as v}from"./utils/allSettled.mjs";let y="did:privy:";class k extends e{set isUsingServerCookies(e){this._isUsingServerCookies=e}setStoredUsersCallback(e){this._setStoredUsers=e,this.getSavedUserIds().then((e=>{this._hasEmittedStoredUsers||this._setStoredUsers?.({users:e.map((e=>({id:e})))})}))}async getCustomerAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(o(e));try{return"string"==typeof t?new i(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getPrivyAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(a(e));try{return"string"==typeof t?new i(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getRefreshToken(){let e=await this.getActiveUserId(),t=await this._storage.get(n(e));return"string"==typeof t?t:null}async getIdentityToken(){let e=await this.getActiveUserId(),t=await this._storage.get(l(e));return"string"==typeof t?t:null}async mightHaveServerCookies(){try{let e=await this.getActiveUserId(),t=s.get(h(e));if(void 0!==t&&t.length>0)return!0;let r=s.get(h(null));return void 0!==r&&r.length>0}catch(e){console.error(e)}return!1}async hasRefreshCredentials(e,t){return await this.mightHaveServerCookies()||"string"==typeof e&&"string"==typeof t}tokenIsActive(e){if(!e)return!1;let t=i.parse(e);return null!==t&&!t.isExpired(30)}async destroyLocalState(e){let t=await this.getActiveUserId(),r=[this._storage.del(o(null)),this._storage.del(a(null)),this._storage.del(n(null)),this._storage.del(l(null)),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),this._storage.del(g)];t&&r.push(this._storage.del(o(t)),this._storage.del(a(t)),this._storage.del(n(t)),this._storage.del(l(t)),this.removeSavedUserId(t)),await v(r),s.remove(c(null)),s.remove(d(null)),s.remove(_(null)),s.remove(h(null)),t&&(s.remove(c(t)),s.remove(d(t)),s.remove(_(t)),s.remove(h(t))),e?.reason&&this.emit("storage_cleared",{reason:e.reason})}async storeCustomerAccessToken(e){let t=await this.getActiveUserId();await this.storeCustomerAccessTokenForUser(t,e)}async storeCustomerAccessTokenForUser(e,t){let r=o(e),a=c(e);if("string"==typeof t){let e=await this._storage.get(r);if(await this._storage.put(r,t),!this._isUsingServerCookies){let e=i.parse(t)?.expiration;s.set(a,t,{sameSite:"Strict",secure:!0,expires:e?new Date(1e3*e):void 0})}e!==t&&this.emit("token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(r);await this._storage.del(r),s.remove(a),null!==e&&this.emit("token_cleared",{reason:"set_with_non_string_value"})}}async storePrivyAccessToken(e){let t=await this.getActiveUserId();await this.storePrivyAccessTokenForUser(t,e)}async storePrivyAccessTokenForUser(e,t){let s=a(e);"string"==typeof t?await this._storage.put(s,t):await this._storage.del(s)}async storeRefreshTokenForUser(e,t){let r=n(e),i=d(e),o=h(e);"string"==typeof t?(await this._storage.put(r,t),this._isUsingServerCookies||(s.set(o,"t",{sameSite:"Strict",secure:!0,expires:30}),s.set(i,t,{sameSite:"Strict",secure:!0,expires:30})),this.emit("refresh_token_stored",{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(r),s.remove(i),s.remove(o),this.emit("refresh_token_cleared",{reason:"set_with_non_string_value"}))}async updateWithTokensResponse(e){let t=e.user.id,s=(await v([this.storeCustomerAccessTokenForUser(t,e.token),this.storePrivyAccessTokenForUser(t,e.privy_access_token),this.storeRefreshTokenForUser(t,e.refresh_token),this.storeIdentityTokenForUser(t,e.identity_token)])).filter((e=>"rejected"===e.status));if(s.length>0)return void this.emit("error_storing_tokens",s.map((e=>String(e.reason))).join(", "));let r=(await v([this.storeCustomerAccessTokenForUser(null,e.token),this.storePrivyAccessTokenForUser(null,e.privy_access_token),this.storeRefreshTokenForUser(null,e.refresh_token),this.storeIdentityTokenForUser(null,e.identity_token)])).filter((e=>"rejected"===e.status));if(r.length>0)return void this.emit("error_storing_tokens",r.map((e=>String(e.reason))).join(", "));await this.storeActiveUserId(t);let i=(await v([this.processOAuthTokens(e.oauth_tokens)])).filter((e=>"rejected"===e.status));i.length>0&&this.emit("error_storing_tokens",i.map((e=>String(e.reason))).join(", "))}async backfillLegacySession(){if(await this.getActiveUserId())return;let[e,t,s,r]=await Promise.all([this._storage.get(o(null)),this._storage.get(a(null)),this._storage.get(n(null)),this._storage.get(l(null))]);if("string"!=typeof e||"string"!=typeof s)return;let h=(e=>e?.startsWith(y)?e.slice(10):e)(i.parse(e)?.subject);if("string"!=typeof h||0===h.length)return;let g=[this.storeCustomerAccessTokenForUser(h,e),this.storeRefreshTokenForUser(h,s)];"string"==typeof t&&g.push(this.storePrivyAccessTokenForUser(h,t)),"string"==typeof r&&g.push(this.storeIdentityTokenForUser(h,r));let c=(await v(g)).filter((e=>"rejected"===e.status));c.length>0?this.emit("error_storing_tokens",c.map((e=>String(e.reason))).join(", ")):await this.storeActiveUserId(h)}async processOAuthTokens(e){e&&this.emit("oauth_tokens_granted",e)}async storeIdentityToken(e){let t=await this.getActiveUserId();await this.storeIdentityTokenForUser(t,e)}async storeIdentityTokenForUser(e,t){let r=l(e),o=_(e);if("string"==typeof t){let e=await this._storage.get(r);if(await this._storage.put(r,t),!this._isUsingServerCookies){let e=i.parse(t)?.expiration;s.set(o,t,{sameSite:"Strict",secure:!0,expires:e?new Date(1e3*e):void 0})}e!==t&&this.emit("identity_token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(r);await this._storage.del(r),s.remove(o),null!==e&&this.emit("identity_token_cleared",{reason:"set_with_non_string_value"})}}async getOrCreateGuestCredential(){let e=await this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(e&&"string"==typeof e)return e;let s=t.encode(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,s),s}async getActiveUserId(){let e=await this._storage.get(g);return"string"==typeof e?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(g,e)}async getSavedUserIds(){let e=await this._storage.get(u);if("string"!=typeof e)return[];try{let t=JSON.parse(e),s=Array.isArray(t)?t.filter((e=>"string"==typeof e)):[];return[...new Set(s)]}catch{return[]}}async storeSavedUserIds(e){let t=[...new Set(e)];t.length>0?await this._storage.put(u,JSON.stringify(t)):await this._storage.del(u),this._setStoredUsers&&(this._hasEmittedStoredUsers=!0,this._setStoredUsers({users:t.map((e=>({id:e})))}))}async removeSavedUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds(t.filter((t=>t!==e)))}async switchActiveUserId(e){if(!(await this.getSavedUserIds()).includes(e))throw new r({code:"invalid_input",error:"Cannot switch active user because the user ID is not saved on this device"});await this._storage.put(g,e)}constructor(e){super(),this._isUsingServerCookies=!1,this._hasEmittedStoredUsers=!1,this._storage=e.storage,this.GUEST_CREDENTIAL_STORAGE_KEY=`privy:guest:${e.appId}`,this._setStoredUsers=e.setStoredUsers}}k.events=["storage_cleared","token_cleared","refresh_token_cleared","identity_token_cleared","token_stored","refresh_token_stored","identity_token_stored","oauth_tokens_granted","error_storing_tokens"];export{k as Session};
1
+ import e from"eventemitter3";import{base64url as t}from"jose";import s from"js-cookie";import{PrivyClientError as r}from"./Error.mjs";import{Token as i}from"./Token.mjs";import{toCustomerAccessTokenStorageKey as o,toPrivyAccessTokenStorageKey as a,toRefreshTokenStorageKey as n,toIdentityTokenStorageKey as l,toSessionCookieKey as h,ACTIVE_USER_STORAGE_KEY as g,toCustomerAccessTokenCookieKey as c,toRefreshTokenCookieKey as _,toIdentityTokenCookieKey as d,SAVED_USERS_STORAGE_KEY as u}from"./session/keys.mjs";import{allSettled as v}from"./utils/allSettled.mjs";class y extends e{set isUsingServerCookies(e){this._isUsingServerCookies=e}setStoredUsersCallback(e){this._setStoredUsers=e,this.getSavedUserIds().then((e=>{this._hasEmittedStoredUsers||this._setStoredUsers?.({users:e.map((e=>({id:e})))})}))}async getCustomerAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(o(e));try{return"string"==typeof t?new i(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getPrivyAccessToken(){let e=await this.getActiveUserId(),t=await this._storage.get(a(e));try{return"string"==typeof t?new i(t).value:null}catch(e){return console.error(e),await this.destroyLocalState({reason:"getToken_error"}),null}}async getRefreshToken(){let e=await this.getActiveUserId(),t=await this._storage.get(n(e));return"string"==typeof t?t:null}async getIdentityToken(){let e=await this.getActiveUserId(),t=await this._storage.get(l(e));return"string"==typeof t?t:null}async mightHaveServerCookies(){try{let e=await this.getActiveUserId(),t=s.get(h(e));if(void 0!==t&&t.length>0)return!0;let r=s.get(h(null));return void 0!==r&&r.length>0}catch(e){console.error(e)}return!1}async hasRefreshCredentials(e,t){return await this.mightHaveServerCookies()||"string"==typeof e&&"string"==typeof t}tokenIsActive(e){if(!e)return!1;let t=i.parse(e);return null!==t&&!t.isExpired(30)}async destroyLocalState(e){let t=await this.getActiveUserId(),r=[this._storage.del(o(null)),this._storage.del(a(null)),this._storage.del(n(null)),this._storage.del(l(null)),this._storage.del(this.GUEST_CREDENTIAL_STORAGE_KEY),this._storage.del(g)];t&&r.push(this._storage.del(o(t)),this._storage.del(a(t)),this._storage.del(n(t)),this._storage.del(l(t)),this.removeSavedUserId(t)),await v(r),s.remove(c(null)),s.remove(_(null)),s.remove(d(null)),s.remove(h(null)),t&&(s.remove(c(t)),s.remove(_(t)),s.remove(d(t)),s.remove(h(t))),e?.reason&&this.emit("storage_cleared",{reason:e.reason})}async storeCustomerAccessToken(e){let t=await this.getActiveUserId();await this.storeCustomerAccessTokenForUser(t,e)}async storeCustomerAccessTokenForUser(e,t){let r=o(e),a=c(e);if("string"==typeof t){let e=await this._storage.get(r);if(await this._storage.put(r,t),!this._isUsingServerCookies){let e=i.parse(t)?.expiration;s.set(a,t,{sameSite:"Strict",secure:!0,expires:e?new Date(1e3*e):void 0})}e!==t&&this.emit("token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(r);await this._storage.del(r),s.remove(a),null!==e&&this.emit("token_cleared",{reason:"set_with_non_string_value"})}}async storePrivyAccessToken(e){let t=await this.getActiveUserId();await this.storePrivyAccessTokenForUser(t,e)}async storePrivyAccessTokenForUser(e,t){let s=a(e);"string"==typeof t?await this._storage.put(s,t):await this._storage.del(s)}async storeRefreshTokenForUser(e,t){let r=n(e),i=_(e),o=h(e);"string"==typeof t?(await this._storage.put(r,t),this._isUsingServerCookies||(s.set(o,"t",{sameSite:"Strict",secure:!0,expires:30}),s.set(i,t,{sameSite:"Strict",secure:!0,expires:30})),this.emit("refresh_token_stored",{cookiesEnabled:this._isUsingServerCookies})):(await this._storage.del(r),s.remove(i),s.remove(o),this.emit("refresh_token_cleared",{reason:"set_with_non_string_value"}))}async updateWithTokensResponse(e){let t=e.user.id,s=(await v([this.storeCustomerAccessTokenForUser(t,e.token),this.storePrivyAccessTokenForUser(t,e.privy_access_token),this.storeRefreshTokenForUser(t,e.refresh_token),this.storeIdentityTokenForUser(t,e.identity_token)])).filter((e=>"rejected"===e.status));if(s.length>0)return void this.emit("error_storing_tokens",s.map((e=>String(e.reason))).join(", "));let r=(await v([this.storeCustomerAccessTokenForUser(null,e.token),this.storePrivyAccessTokenForUser(null,e.privy_access_token),this.storeRefreshTokenForUser(null,e.refresh_token),this.storeIdentityTokenForUser(null,e.identity_token)])).filter((e=>"rejected"===e.status));if(r.length>0)return void this.emit("error_storing_tokens",r.map((e=>String(e.reason))).join(", "));await this.storeActiveUserId(t);let i=(await v([this.processOAuthTokens(e.oauth_tokens)])).filter((e=>"rejected"===e.status));i.length>0&&this.emit("error_storing_tokens",i.map((e=>String(e.reason))).join(", "))}async backfillLegacySession(){if(await this.getActiveUserId())return;let[e,t,s,r]=await Promise.all([this._storage.get(o(null)),this._storage.get(a(null)),this._storage.get(n(null)),this._storage.get(l(null))]);if("string"!=typeof e||"string"!=typeof s)return;let h=i.parse(e)?.subject;if("string"!=typeof h||0===h.length)return;let g=[this.storeCustomerAccessTokenForUser(h,e),this.storeRefreshTokenForUser(h,s)];"string"==typeof t&&g.push(this.storePrivyAccessTokenForUser(h,t)),"string"==typeof r&&g.push(this.storeIdentityTokenForUser(h,r));let c=(await v(g)).filter((e=>"rejected"===e.status));c.length>0?this.emit("error_storing_tokens",c.map((e=>String(e.reason))).join(", ")):await this.storeActiveUserId(h)}async processOAuthTokens(e){e&&this.emit("oauth_tokens_granted",e)}async storeIdentityToken(e){let t=await this.getActiveUserId();await this.storeIdentityTokenForUser(t,e)}async storeIdentityTokenForUser(e,t){let r=l(e),o=d(e);if("string"==typeof t){let e=await this._storage.get(r);if(await this._storage.put(r,t),!this._isUsingServerCookies){let e=i.parse(t)?.expiration;s.set(o,t,{sameSite:"Strict",secure:!0,expires:e?new Date(1e3*e):void 0})}e!==t&&this.emit("identity_token_stored",{cookiesEnabled:this._isUsingServerCookies})}else{let e=await this._storage.get(r);await this._storage.del(r),s.remove(o),null!==e&&this.emit("identity_token_cleared",{reason:"set_with_non_string_value"})}}async getOrCreateGuestCredential(){let e=await this._storage.get(this.GUEST_CREDENTIAL_STORAGE_KEY);if(e&&"string"==typeof e)return e;let s=t.encode(crypto.getRandomValues(new Uint8Array(32)));return await this._storage.put(this.GUEST_CREDENTIAL_STORAGE_KEY,s),s}async getActiveUserId(){let e=await this._storage.get(g);return"string"==typeof e?e:null}async storeActiveUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds([...t,e]),await this._storage.put(g,e)}async getSavedUserIds(){let e=await this._storage.get(u);if("string"!=typeof e)return[];try{let t=JSON.parse(e),s=Array.isArray(t)?t.filter((e=>"string"==typeof e)):[];return[...new Set(s)]}catch{return[]}}async storeSavedUserIds(e){let t=[...new Set(e)];t.length>0?await this._storage.put(u,JSON.stringify(t)):await this._storage.del(u),this._setStoredUsers&&(this._hasEmittedStoredUsers=!0,this._setStoredUsers({users:t.map((e=>({id:e})))}))}async removeSavedUserId(e){let t=await this.getSavedUserIds();await this.storeSavedUserIds(t.filter((t=>t!==e)))}async switchActiveUserId(e){if(!(await this.getSavedUserIds()).includes(e))throw new r({code:"invalid_input",error:"Cannot switch active user because the user ID is not saved on this device"});await this._storage.put(g,e)}constructor(e){super(),this._isUsingServerCookies=!1,this._hasEmittedStoredUsers=!1,this._storage=e.storage,this.GUEST_CREDENTIAL_STORAGE_KEY=`privy:guest:${e.appId}`,this._setStoredUsers=e.setStoredUsers}}y.events=["storage_cleared","token_cleared","refresh_token_cleared","identity_token_cleared","token_stored","refresh_token_stored","identity_token_stored","oauth_tokens_granted","error_storing_tokens"];export{y as Session};
2
2
  //# sourceMappingURL=Session.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Session.mjs","sources":["../../src/Session.ts"],"names":["PRIVY_DID_PREFIX","Session","EventEmitter","isUsingServerCookies","this","_isUsingServerCookies","setStoredUsersCallback","cb","_setStoredUsers","getSavedUserIds","then","e","_hasEmittedStoredUsers","users","ids","map","id","getCustomerAccessToken","userId","getActiveUserId","token","_storage","get","toCustomerAccessTokenStorageKey","Token","value","error","console","destroyLocalState","reason","getPrivyAccessToken","toPrivyAccessTokenStorageKey","getRefreshToken","refreshToken","toRefreshTokenStorageKey","getIdentityToken","identityToken","toIdentityTokenStorageKey","mightHaveServerCookies","sessionToken","Cookies","toSessionCookieKey","length","legacySessionToken","hasRefreshCredentials","tokenIsActive","tokenRaw","parse","isExpired","opts","deletes","del","GUEST_CREDENTIAL_STORAGE_KEY","ACTIVE_USER_STORAGE_KEY","push","removeSavedUserId","allSettled","remove","toCustomerAccessTokenCookieKey","toRefreshTokenCookieKey","toIdentityTokenCookieKey","emit","storeCustomerAccessToken","storeCustomerAccessTokenForUser","storageKey","cookieKey","previousToken","put","exp","expiration","set","sameSite","secure","expires","Date","undefined","cookiesEnabled","storePrivyAccessToken","storePrivyAccessTokenForUser","key","storeRefreshTokenForUser","refreshCookieKey","sessionCookieKey","updateWithTokensResponse","user","primaryErrors","privy_access_token","refresh_token","storeIdentityTokenForUser","identity_token","filter","x","status","String","join","legacyErrors","storeActiveUserId","oauthErrors","processOAuthTokens","oauth_tokens","backfillLegacySession","privyAccessToken","Promise","all","startsWith","slice","toStoredUserId","subject","writes","errors","oAuthTokens","storeIdentityToken","previousIdentityToken","getOrCreateGuestCredential","guestCredential","entropy","base64url","encode","crypto","getRandomValues","Uint8Array","storeSavedUserIds","savedUsers","SAVED_USERS_STORAGE_KEY","parsed","JSON","Array","isArray","Set","uniqueIds","stringify","t","savedId","switchActiveUserId","includes","PrivyClientError","code","constructor","o","super","storage","appId","setStoredUsers","events"],"mappings":"mjBAkDA,IAAMA,EAAmB,aAqClB,MAAMC,UAAgBC,EA+B3B,wBAAIC,CAAqBA,GACvBC,KAAKC,sBAAwBF,CAC/B,CAEA,sBAAAG,CAA8BC,GAC5BH,KAAKI,gBAAkBD,EAClBH,KAAKK,kBAAkBC,MAAKC,IAC1BP,KAAKQ,wBACRR,KAAKI,kBAAkB,CAACK,MAAOC,EAAIC,KAAKC,KAASA,GAAAA,UAGvD,CAEA,4BAAMC,GACJ,IAAMC,QAAed,KAAKe,kBACpBC,QAAchB,KAAKiB,SAASC,IAAIC,EAAgCL,IAEtE,IACE,MAAI,iBAAOE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KAAKI,kBACPJ,KAAKQ,wBAAyB,EAC9BR,KAAKI,gBAAgB,CAACK,MAAOoH,EAAUlH,KAAIJ,IAACK,CAASA,GAAAA,QAEzD,CAKA,uBAAcuC,CAAkBvC,GAC9B,IAAMF,QAAYV,KAAKK,wBACjBL,KAAKqH,kBAAkB3G,EAAI4E,QAAOyC,GAAaC,IAAYpH,IACnE,CAOA,wBAAaqH,CAAmBnH,GAG9B,WAF2Bd,KAAKK,mBAEd6H,SAASpH,GACzB,MAAM,IAAIqH,EAAiB,CACzBC,KAAM,gBACN9G,MAAO,oFAILtB,KAAKiB,SAAS8C,IAAId,EAAyBnC,EACnD,CAlgBAuH,WAAAA,CAAYC,GACVC,QApBYvI,KACNC,uBAAwB,EAe/BD,KACOQ,wBAAyB,EAI/BR,KAAKiB,SAAWqH,EAAEE,QAClBxI,KAAKgD,6BAA+B,eAAesF,EAAEG,QACrDzI,KAAKI,gBAAkBkI,EAAEI,cAC3B,EA7BW7I,EACJ8I,OAjCM,CACb,kBACA,gBACA,wBACA,yBACA,eACA,uBACA,wBACA,uBACA"}
1
+ {"version":3,"file":"Session.mjs","sources":["../../src/Session.ts"],"names":["Session","EventEmitter","isUsingServerCookies","this","_isUsingServerCookies","setStoredUsersCallback","cb","_setStoredUsers","getSavedUserIds","then","e","_hasEmittedStoredUsers","users","ids","map","id","getCustomerAccessToken","userId","getActiveUserId","token","_storage","get","toCustomerAccessTokenStorageKey","Token","value","error","console","destroyLocalState","reason","getPrivyAccessToken","toPrivyAccessTokenStorageKey","getRefreshToken","refreshToken","toRefreshTokenStorageKey","getIdentityToken","identityToken","toIdentityTokenStorageKey","mightHaveServerCookies","sessionToken","Cookies","toSessionCookieKey","length","legacySessionToken","hasRefreshCredentials","tokenIsActive","tokenRaw","parse","isExpired","opts","deletes","del","GUEST_CREDENTIAL_STORAGE_KEY","ACTIVE_USER_STORAGE_KEY","push","removeSavedUserId","allSettled","remove","toCustomerAccessTokenCookieKey","toRefreshTokenCookieKey","toIdentityTokenCookieKey","emit","storeCustomerAccessToken","storeCustomerAccessTokenForUser","storageKey","cookieKey","previousToken","put","exp","expiration","set","sameSite","secure","expires","Date","undefined","cookiesEnabled","storePrivyAccessToken","storePrivyAccessTokenForUser","key","storeRefreshTokenForUser","refreshCookieKey","sessionCookieKey","updateWithTokensResponse","user","primaryErrors","privy_access_token","refresh_token","storeIdentityTokenForUser","identity_token","filter","x","status","String","join","legacyErrors","storeActiveUserId","oauthErrors","processOAuthTokens","oauth_tokens","backfillLegacySession","privyAccessToken","Promise","all","subject","writes","errors","oAuthTokens","storeIdentityToken","previousIdentityToken","getOrCreateGuestCredential","guestCredential","entropy","base64url","encode","crypto","getRandomValues","Uint8Array","storeSavedUserIds","savedUsers","SAVED_USERS_STORAGE_KEY","parsed","JSON","Array","isArray","Set","uniqueIds","stringify","t","savedId","switchActiveUserId","includes","PrivyClientError","code","constructor","o","super","storage","appId","setStoredUsers","events"],"mappings":"mjBAkFO,MAAMA,UAAgBC,EA+B3B,wBAAIC,CAAqBA,GACvBC,KAAKC,sBAAwBF,CAC/B,CAEA,sBAAAG,CAA8BC,GAC5BH,KAAKI,gBAAkBD,EAClBH,KAAKK,kBAAkBC,MAAKC,IAC1BP,KAAKQ,wBACRR,KAAKI,kBAAkB,CAACK,MAAOC,EAAIC,KAAKC,KAASA,GAAAA,UAGvD,CAEA,4BAAMC,GACJ,IAAMC,QAAed,KAAKe,kBACpBC,QAAchB,KAAKiB,SAASC,IAAIC,EAAgCL,IAEtE,IACE,MAAI,iBAAOE,EAEF,IAAII,EAAMJ,GAAOK,MAEjB,IAEX,CAAE,MAAOC,GAGP,OAFAC,QAAQD,MAAMA,SACRtB,KAAKwB,kBAAkB,CAACC,OAAQ,mBAC/B,IACT,CACF,CAEA,yBAAMC,GACJ,IAAMZ,QAAed,KAAKe,kBACpBC,QAAchB,KAAKiB,SAASC,IAAIS,EAA6Bb,IAEnE,IACE,MAAI,iBAAOE,EAEF,IAAII,EAAMJ,GAAOK,MAEj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iB,SAAS8C,IAAId,EAAyBnC,EACnD,CAlgBAoH,WAAAA,CAAYC,GACVC,QApBYpI,KACNC,uBAAwB,EAe/BD,KACOQ,wBAAyB,EAI/BR,KAAKiB,SAAWkH,EAAEE,QAClBrI,KAAKgD,6BAA+B,eAAemF,EAAEG,QACrDtI,KAAKI,gBAAkB+H,EAAEI,cAC3B,EA7BW1I,EACJ2I,OAjCM,CACb,kBACA,gBACA,wBACA,yBACA,eACA,uBACA,wBACA,uBACA"}
@@ -1,2 +1,2 @@
1
- import e from"fetch-retry";import{PrivyErrorCode as t}from"@privy-io/api-base";import{getPathWithParams as s,AppConfig as i,AnalyticsEvent as r,RefreshSession as a}from"@privy-io/routes";import{PrivyClientError as n,PrivyApiError as o}from"../Error.mjs";import{Session as h}from"../Session.mjs";import c from"../toAbortSignalTimeout.mjs";import{toSearchParams as l}from"../utils/toSearchParams.mjs";import{toLoggerWithLevel as d}from"./logger.mjs";import"eventemitter3";import"jose";import"js-cookie";import"../Token.mjs";import"../session/keys.mjs";import"../utils/allSettled.mjs";import"../utils/noop.mjs";let g="privy:caid";class p{setCallbacks(e){this.callbacks={...this.callbacks,...e},this.session.setStoredUsersCallback(this.callbacks?.setStoredUsers)}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady)this.callbacks?.setIsReady?.(!0);else{if(!await this.isStorageAccessible())throw new n({code:"storage_error",error:"Unable to access storage"});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.isMultiUserModeEnabled&&await this.session.backfillLegacySession(),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:i}){return`${this.baseUrl}${s(e.path,t)}${l(i)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new n({code:"invalid_input",error:'Unauthenticated requests require sessions.mode to be set to "multi-user"'});return this.fetch(e,{...t,onRequest:this._beforeRequestWithoutAuth.bind(this)})}async fetchForLogin(e,t){return this.isMultiUserModeEnabled?this.fetchWithoutAuthentication(e,t):this.fetch(e,t)}async fetch(e,{body:t,params:s,query:i,headers:r,onRequest:a=this._beforeRequest.bind(this)}){let n=new Request(this.getPath(e,{params:s,query:i}),{method:e.method,body:JSON.stringify(t),headers:r}),h=await a(n),c=await this._fetch(n,h),l=await c.json();if(c.status>299)throw new o({...l,status:c.status});return l}async _beforeRequestWithoutInitialize(e){let t=await this.session.getPrivyAccessToken()??await this.session.getCustomerAccessToken(),s=new Headers(e.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),t&&s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");let i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:c(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequestWithoutAuth(e){await this._initialize();let t=new Headers(e.headers);t.set("privy-app-id",this.appId),this.appClientId&&t.set("privy-client-id",this.appClientId),t.set("privy-client",this._sdkVersion),t.set("Content-Type","application/json"),t.set("Accept","application/json");let s=await this._getOrGenerateClientAnalyticsId();return s&&t.set("privy-ca-id",s),this.nativeAppIdentifier&&t.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:c(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(i,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(g);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error("Unable to load clientId",e)}try{this._analyticsId=this._crypto.randomUUID()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(this._analyticsId){try{await this._storage.put(g,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}}async destroyClientAnalyticsId(){try{return await this._storage.del(g)}catch(e){this.logger.error("Unable to delete clientId",e)}}async createAnalyticsEvent(e,t){try{await this.fetch(r,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(e){}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new n({code:"storage_error",error:"Unable to access storage"});let t=await this.session.getRefreshToken()??void 0,s=t??"key",i=this._cache.get(s);if(i)return this.logger.debug("[privy:refresh] found in-flight session refresh request, deduping"),await i;let r=this._refreshSession(t,e);this._cache.set(s,r);try{return await r}finally{this._cache.delete(s)}}async _refreshSession(e,s){let i=await this.session.getCustomerAccessToken();if(!await this.session.hasRefreshCredentials(i,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new o({code:t.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage",status:401});try{this.logger.debug(`[privy:refresh] fetching: ${a.path}`);let t=await this.fetch(a,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),i=t.session_update_action;return this.logger.debug(`[privy:refresh] response: ${i}`),"set"===i&&(await this.session.updateWithTokensResponse(t),this.logger.debug("[privy:refresh] tokens stored")),"clear"===i&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),s||this.callbacks?.setUser?.(null)),"ignore"===i&&(t.token&&(await this.session.storeCustomerAccessToken(t.token),this.logger.debug("[privy:refresh] token stored (CAT)")),t.privy_access_token&&(await this.session.storePrivyAccessToken(t.privy_access_token),this.logger.debug("[privy:refresh] token stored (PAT)")),t.identity_token&&(this.logger.debug("[privy:refresh] token stored (IDT)"),await this.session.storeIdentityToken(t.identity_token))),this.logger.debug("[privy:refresh] returning response"),s||this.callbacks?.setUser?.(t.user),t}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof o&&e.code===t.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),s||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getCustomerAccessToken(),this.session.getRefreshToken()]);if(e&&!this.session.tokenIsActive(e)&&await this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getCustomerAccessToken();return t.token||this.logger.debug("[privy:getAccessToken] expected token received null"),t.token===e&&this.logger.debug("[privy:getAccessToken] expected new token in response received existing"),s===e&&this.logger.debug("[privy:getAccessToken] expected new token in storage received existing"),t.token??s}return e&&!this.session.tokenIsActive(e)?(this.logger.debug("[privy:getAccessToken] unable to refresh inactive token"),this.callbacks?.setUser?.(null),await this.session.destroyLocalState(),null):e}async getAccessTokenInternal(){let e=await this.getAccessToken();return await this.session.getPrivyAccessToken()??e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${this._crypto.randomUUID()}`,t="blobby";await this._storage.put(e,t);let s=await this._storage.get(e);return await this._storage.del(e),s===t}catch(e){return this.logger.error(e),!1}}constructor(t){this._sdkVersion="js-sdk-core:0.68.0",this._cache=new Map,this.logger=d({level:t.logger?.level??t.logLevel??"ERROR",logger:t.logger??console}),this._storage=t.storage,this._crypto=t.crypto,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=t.baseUrl??"https://auth.privy.io",this.appId=t.appId,this.appClientId=t.appClientId,this._sdkVersion=t.sdkVersion??this._sdkVersion,this.callbacks=t.callbacks,this.nativeAppIdentifier=t.nativeAppIdentifier,this.isMultiUserModeEnabled=t.isMultiUserModeEnabled,this.session=new h({storage:this._storage,isUsingServerCookies:!1,appId:t.appId,setStoredUsers:t.callbacks?.setStoredUsers}),this._fetch=e(globalThis.fetch,{retries:3,retryDelay:e=>3**e*500,retryOn:[408,409,425,500,502,503,504]}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}}export{p as PrivyInternal};
1
+ import e from"fetch-retry";import{PrivyErrorCode as t}from"@privy-io/api-base";import{getPathWithParams as s,AppConfig as i,AnalyticsEvent as r,RefreshSession as a}from"@privy-io/routes";import{PrivyClientError as n,PrivyApiError as o}from"../Error.mjs";import{Session as h}from"../Session.mjs";import c from"../toAbortSignalTimeout.mjs";import{toSearchParams as l}from"../utils/toSearchParams.mjs";import{toLoggerWithLevel as d}from"./logger.mjs";import"eventemitter3";import"jose";import"js-cookie";import"../Token.mjs";import"../session/keys.mjs";import"../utils/allSettled.mjs";import"../utils/noop.mjs";let g="privy:caid";class p{setCallbacks(e){this.callbacks={...this.callbacks,...e},this.session.setStoredUsersCallback(this.callbacks?.setStoredUsers)}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady)this.callbacks?.setIsReady?.(!0);else{if(!await this.isStorageAccessible())throw new n({code:"storage_error",error:"Unable to access storage"});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.isMultiUserModeEnabled&&await this.session.backfillLegacySession(),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:i}){return`${this.baseUrl}${s(e.path,t)}${l(i)}`}async fetchWithoutAuthentication(e,t){if(!this.isMultiUserModeEnabled)throw new n({code:"invalid_input",error:'Unauthenticated requests require sessions.mode to be set to "multi-user"'});return this.fetch(e,{...t,onRequest:this._beforeRequestWithoutAuth.bind(this)})}async fetchForLogin(e,t){return this.isMultiUserModeEnabled?this.fetchWithoutAuthentication(e,t):this.fetch(e,t)}async fetch(e,{body:t,params:s,query:i,headers:r,onRequest:a=this._beforeRequest.bind(this)}){let n=new Request(this.getPath(e,{params:s,query:i}),{method:e.method,body:JSON.stringify(t),headers:r}),h=await a(n),c=await this._fetch(n,h),l=await c.json();if(c.status>299)throw new o({...l,status:c.status});return l}async _beforeRequestWithoutInitialize(e){let t=await this.session.getPrivyAccessToken()??await this.session.getCustomerAccessToken(),s=new Headers(e.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),t&&s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");let i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:c(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequestWithoutAuth(e){await this._initialize();let t=new Headers(e.headers);t.set("privy-app-id",this.appId),this.appClientId&&t.set("privy-client-id",this.appClientId),t.set("privy-client",this._sdkVersion),t.set("Content-Type","application/json"),t.set("Accept","application/json");let s=await this._getOrGenerateClientAnalyticsId();return s&&t.set("privy-ca-id",s),this.nativeAppIdentifier&&t.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:c(2e4),headers:t}}async _beforeRequest(e){return await this._initialize(),await this.getAccessTokenInternal(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(i,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(g);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error("Unable to load clientId",e)}try{this._analyticsId=this._crypto.randomUUID()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(this._analyticsId){try{await this._storage.put(g,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}}async destroyClientAnalyticsId(){try{return await this._storage.del(g)}catch(e){this.logger.error("Unable to delete clientId",e)}}async createAnalyticsEvent(e,t){try{await this.fetch(r,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(e){}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new n({code:"storage_error",error:"Unable to access storage"});let t=await this.session.getRefreshToken()??void 0,s=t??"key",i=this._cache.get(s);if(i)return this.logger.debug("[privy:refresh] found in-flight session refresh request, deduping"),await i;let r=this._refreshSession(t,e);this._cache.set(s,r);try{return await r}finally{this._cache.delete(s)}}async _refreshSession(e,s){let i=await this.session.getCustomerAccessToken();if(!await this.session.hasRefreshCredentials(i,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new o({code:t.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage",status:401});try{this.logger.debug(`[privy:refresh] fetching: ${a.path}`);let t=await this.fetch(a,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),i=t.session_update_action;return this.logger.debug(`[privy:refresh] response: ${i}`),"set"===i&&(await this.session.updateWithTokensResponse(t),this.logger.debug("[privy:refresh] tokens stored")),"clear"===i&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),s||this.callbacks?.setUser?.(null)),"ignore"===i&&(t.token&&(await this.session.storeCustomerAccessToken(t.token),this.logger.debug("[privy:refresh] token stored (CAT)")),t.privy_access_token&&(await this.session.storePrivyAccessToken(t.privy_access_token),this.logger.debug("[privy:refresh] token stored (PAT)")),t.identity_token&&(this.logger.debug("[privy:refresh] token stored (IDT)"),await this.session.storeIdentityToken(t.identity_token))),this.logger.debug("[privy:refresh] returning response"),s||this.callbacks?.setUser?.(t.user),t}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof o&&e.code===t.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),s||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getCustomerAccessToken(),this.session.getRefreshToken()]);if(e&&!this.session.tokenIsActive(e)&&await this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getCustomerAccessToken();return t.token||this.logger.debug("[privy:getAccessToken] expected token received null"),t.token===e&&this.logger.debug("[privy:getAccessToken] expected new token in response received existing"),s===e&&this.logger.debug("[privy:getAccessToken] expected new token in storage received existing"),t.token??s}return e&&!this.session.tokenIsActive(e)?(this.logger.debug("[privy:getAccessToken] unable to refresh inactive token"),this.callbacks?.setUser?.(null),await this.session.destroyLocalState(),null):e}async getAccessTokenInternal(){let e=await this.getAccessToken();return await this.session.getPrivyAccessToken()??e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${this._crypto.randomUUID()}`,t="blobby";await this._storage.put(e,t);let s=await this._storage.get(e);return await this._storage.del(e),s===t}catch(e){return this.logger.error(e),!1}}constructor(t){this._sdkVersion="js-sdk-core:0.68.2",this._cache=new Map,this.logger=d({level:t.logger?.level??t.logLevel??"ERROR",logger:t.logger??console}),this._storage=t.storage,this._crypto=t.crypto,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=t.baseUrl??"https://auth.privy.io",this.appId=t.appId,this.appClientId=t.appClientId,this._sdkVersion=t.sdkVersion??this._sdkVersion,this.callbacks=t.callbacks,this.nativeAppIdentifier=t.nativeAppIdentifier,this.isMultiUserModeEnabled=t.isMultiUserModeEnabled,this.session=new h({storage:this._storage,isUsingServerCookies:!1,appId:t.appId,setStoredUsers:t.callbacks?.setStoredUsers}),this._fetch=e(globalThis.fetch,{retries:3,retryDelay:e=>3**e*500,retryOn:[408,409,425,500,502,503,504]}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}}export{p as PrivyInternal};
2
2
  //# sourceMappingURL=PrivyInternal.mjs.map
@@ -1,2 +1,2 @@
1
- import{WalletRpc as e}from"@privy-io/routes";import{PrivyClientError as r}from"../Error.mjs";import{generateAuthorizationSignature as t}from"./generate-authorization-signature.mjs";import{PRIVY_REQUEST_EXPIRY_HEADER_NAME as i,DEFAULT_EXPIRY_TIME_MS as o}from"./types.mjs";import"canonicalize";import"@privy-io/encoding";async function a(a,p,{wallet_id:n,...d}){let m=a.getCompiledPath(e,{params:{wallet_id:n}}),s=String(Date.now()+o),l={version:1,url:m,method:e.method,headers:{"privy-app-id":a.app.appId,[i]:s},body:{...d}},{signature:u}=await t(p,l);if(Date.now()>Number(s))throw new r({error:"Wallet request expired before it could be sent. Please try again.",code:"embedded_wallet_request_expired"});return await a.fetchPrivyRoute(e,{body:d,params:{wallet_id:n},headers:{"privy-authorization-signature":u,[i]:s}})}export{a as rpc};
1
+ import{WalletRpc as e}from"@privy-io/routes";import{PrivyClientError as r}from"../Error.mjs";import{generateAuthorizationSignature as t}from"./generate-authorization-signature.mjs";import{PRIVY_REQUEST_EXPIRY_HEADER_NAME as i,DEFAULT_EXPIRY_TIME_MS as a}from"./types.mjs";import"canonicalize";import"@privy-io/encoding";async function o(o,p,{wallet_id:d,headers:n,...m}){let s=o.getCompiledPath(e,{params:{wallet_id:d}}),l=String(Date.now()+a),u={version:1,url:s,method:e.method,headers:{"privy-app-id":o.app.appId,[i]:l},body:{...m}},{signature:h}=await t(p,u);if(Date.now()>Number(l))throw new r({error:"Wallet request expired before it could be sent. Please try again.",code:"embedded_wallet_request_expired"});return await o.fetchPrivyRoute(e,{body:m,params:{wallet_id:d},headers:{"privy-authorization-signature":h,[i]:l,...n??{}}})}export{o as rpc};
2
2
  //# sourceMappingURL=rpc.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"rpc.mjs","sources":["../../../src/wallet-api/rpc.ts"],"names":["async","rpc","context","sign","wallet_id","request","url","getCompiledPath","WalletRpc","params","requestExpiry","String","Date","now","DEFAULT_EXPIRY_TIME_MS","payload","version","method","headers","app","appId","PRIVY_REQUEST_EXPIRY_HEADER_NAME","body","signature","generateAuthorizationSignature","Number","PrivyClientError","error","code","fetchPrivyRoute"],"mappings":"gUAqBOA,eAAeC,EACpBC,EACAC,GACCC,UAAAA,KAAcC,IAGf,IAAMC,EAAMJ,EAAQK,gBAAgBC,EAAW,CAACC,OAAQ,CAACL,UAAAA,KAEnDM,EAAgBC,OAAOC,KAAKC,MAAQC,GAEpCC,EAAU,CACdC,QAAS,EACTV,IAAAA,EACAW,OAAQT,EAAUS,OAClBC,QAAS,CACP,eAAgBhB,EAAQiB,IAAIC,MAC5BC,CAACA,GAAmCX,GAEtCY,KAAM,IACDjB,KAIAkB,UAAAA,SAAmBC,EAA+BrB,EAAMY,GAK/D,GAAIH,KAAKC,MAAQY,OAAOf,GACtB,MAAM,IAAIgB,EAAiB,CACzBC,MAAO,oEACPC,KAAM,oCAIV,aAAa1B,EAAQ2B,gBAAgBrB,EAAW,CAC9Cc,KAAMjB,EACNI,OAAQ,CACNL,UAAWA,GAEbc,QAAS,CACP,gCAAiCK,EACjCF,CAACA,GAAmCX,IAG1C"}
1
+ {"version":3,"file":"rpc.mjs","sources":["../../../src/wallet-api/rpc.ts"],"names":["async","rpc","context","sign","wallet_id","headers","extraHeaders","request","url","getCompiledPath","WalletRpc","params","requestExpiry","String","Date","now","DEFAULT_EXPIRY_TIME_MS","payload","version","method","app","appId","PRIVY_REQUEST_EXPIRY_HEADER_NAME","body","signature","generateAuthorizationSignature","Number","PrivyClientError","error","code","fetchPrivyRoute"],"mappings":"gUAqBOA,eAAeC,EACpBC,EACAC,GACCC,UAAAA,EAAWC,QAASC,KAAiBC,IAGtC,IAAMC,EAAMN,EAAQO,gBAAgBC,EAAW,CAACC,OAAQ,CAACP,UAAAA,KAEnDQ,EAAgBC,OAAOC,KAAKC,MAAQC,GAEpCC,EAAU,CACdC,QAAS,EACTV,IAAAA,EACAW,OAAQT,EAAUS,OAClBd,QAAS,CACP,eAAgBH,EAAQkB,IAAIC,MAC5BC,CAACA,GAAmCV,GAEtCW,KAAM,IACDhB,KAIAiB,UAAAA,SAAmBC,EAA+BtB,EAAMc,GAK/D,GAAIH,KAAKC,MAAQW,OAAOd,GACtB,MAAM,IAAIe,EAAiB,CACzBC,MAAO,oEACPC,KAAM,oCAIV,aAAa3B,EAAQ4B,gBAAgBpB,EAAW,CAC9Ca,KAAMhB,EACNI,OAAQ,CACNP,UAAWA,GAEbC,QAAS,CACP,gCAAiCmB,EACjCF,CAACA,GAAmCV,KAChCN,GAAgB,CAAA,IAG1B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@privy-io/js-sdk-core",
3
- "version": "0.68.0",
3
+ "version": "0.68.2",
4
4
  "description": "Vanilla JS client for the Privy Auth API",
5
5
  "keywords": [
6
6
  "authentication",
@@ -58,8 +58,8 @@
58
58
  "js-cookie": "^3.0.5",
59
59
  "libphonenumber-js": "^1.12.10",
60
60
  "set-cookie-parser": "^2.6.0",
61
- "@privy-io/api-base": "1.9.1",
62
- "@privy-io/chains": "0.4.0",
61
+ "@privy-io/api-base": "1.9.3",
62
+ "@privy-io/chains": "0.5.0",
63
63
  "@privy-io/encoding": "0.2.1",
64
64
  "@privy-io/ethereum": "0.2.0",
65
65
  "@privy-io/routes": "0.2.6"
@@ -95,8 +95,8 @@
95
95
  "text-encoding": "^0.7.0",
96
96
  "ts-jest": "^29.2.6",
97
97
  "typescript": "~6.0.2",
98
- "@privy-io/tsconfig": "0.0.0",
99
- "@privy-io/build-config": "1.0.0"
98
+ "@privy-io/build-config": "1.0.0",
99
+ "@privy-io/tsconfig": "0.0.0"
100
100
  },
101
101
  "peerDependencies": {
102
102
  "permissionless": "^0.2.47",