@privy-io/js-sdk-core
Advanced tools
Comparing version
@@ -1,1 +0,1 @@ | ||
"use strict";var e=require("fetch-retry"),t=require("uuid"),s=require("@privy-io/api-base"),i=require("@privy-io/public-api"),r=require("../Error.js"),a=require("../Session.js"),n=require("../toAbortSignalTimeout.js"),o=require("../utils/toSearchParams.js"),h=require("./logger.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("eventemitter3"),require("jose"),require("js-cookie"),require("../Token.js"),require("../utils/allSettled.js"),require("../utils/noop.js");var c=/*#__PURE__*/l(e);let g="privy:caid";exports.PrivyInternal=class{setCallbacks(e){this.callbacks={...this.callbacks,...e}}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 r.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.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:s}){return`${this.baseUrl}${i.getPathWithParams(e.path,t)}${o.toSearchParams(s)}`}async fetch(e,{body:t,params:s,query:i,headers:a,onRequest:n=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:s,query:i}),{method:e.method,body:JSON.stringify(t),headers:a}),h=await n(o),l=await this._fetch(o,h),c=await l.json();if(l.status>299)throw new r.PrivyApiError(c);return c}async _beforeRequestWithoutInitialize(e){let t=await this.session.getToken(),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:n.default(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequest(e){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(i.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(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=t.v4()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;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(i.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 r.PrivyClientError({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 a=this._refreshSession(t,e);this._cache.set(s,a);try{return await a}finally{this._cache.delete(s)}}async _refreshSession(e,t){let a=await this.session.getToken();if(!this.session.hasRefreshCredentials(a,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new r.PrivyApiError({code:s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{this.logger.debug(`[privy:refresh] fetching: ${i.RefreshSession.path}`);let s=await this.fetch(i.RefreshSession,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),r=s.session_update_action;return this.logger.debug(`[privy:refresh] response: ${r}`),t||this.callbacks?.setUser?.(s.user),"set"===r&&(await this.session.updateWithTokensResponse(s),this.logger.debug("[privy:refresh] tokens stored")),"clear"===r&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),t||this.callbacks?.setUser?.(null)),"ignore"===r&&s.token&&(await this.session.storeToken(s.token),this.logger.debug("[privy:refresh] access token stored"),s.identity_token&&(this.logger.debug("[privy:refresh] identity token stored"),await this.session.storeIdentityToken(s.identity_token))),this.logger.debug("[privy:refresh] returning response"),s}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof r.PrivyApiError&&e.code===s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),t||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);if(!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getToken();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}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${t.v4()}`,s="blobby";await this._storage.put(e,s);let i=await this._storage.get(e);return await this._storage.del(e),i===s}catch(e){return this.logger.error(e),!1}}constructor(e){this._sdkVersion="js-sdk-core:0.50.1-beta-20250505220758",this._cache=new Map,this.logger=h.toConsoleLogger({level:e.logLevel??"ERROR"}),this._storage=e.storage,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.session=new a.Session({storage:this._storage,isUsingServerCookies:!1,appId:e.appId}),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})}))}}; | ||
"use strict";var e=require("fetch-retry"),t=require("uuid"),s=require("@privy-io/api-base"),i=require("@privy-io/public-api"),r=require("../Error.js"),a=require("../Session.js"),n=require("../toAbortSignalTimeout.js"),o=require("../utils/toSearchParams.js"),h=require("./logger.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("eventemitter3"),require("jose"),require("js-cookie"),require("../Token.js"),require("../utils/allSettled.js"),require("../utils/noop.js");var c=/*#__PURE__*/l(e);let g="privy:caid";exports.PrivyInternal=class{setCallbacks(e){this.callbacks={...this.callbacks,...e}}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 r.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.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:s}){return`${this.baseUrl}${i.getPathWithParams(e.path,t)}${o.toSearchParams(s)}`}async fetch(e,{body:t,params:s,query:i,headers:a,onRequest:n=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:s,query:i}),{method:e.method,body:JSON.stringify(t),headers:a}),h=await n(o),l=await this._fetch(o,h),c=await l.json();if(l.status>299)throw new r.PrivyApiError(c);return c}async _beforeRequestWithoutInitialize(e){let t=await this.session.getToken(),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:n.default(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequest(e){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(i.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(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=t.v4()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;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(i.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 r.PrivyClientError({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 a=this._refreshSession(t,e);this._cache.set(s,a);try{return await a}finally{this._cache.delete(s)}}async _refreshSession(e,t){let a=await this.session.getToken();if(!this.session.hasRefreshCredentials(a,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new r.PrivyApiError({code:s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{this.logger.debug(`[privy:refresh] fetching: ${i.RefreshSession.path}`);let s=await this.fetch(i.RefreshSession,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),r=s.session_update_action;return this.logger.debug(`[privy:refresh] response: ${r}`),t||this.callbacks?.setUser?.(s.user),"set"===r&&(await this.session.updateWithTokensResponse(s),this.logger.debug("[privy:refresh] tokens stored")),"clear"===r&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),t||this.callbacks?.setUser?.(null)),"ignore"===r&&s.token&&(await this.session.storeToken(s.token),this.logger.debug("[privy:refresh] access token stored"),s.identity_token&&(this.logger.debug("[privy:refresh] identity token stored"),await this.session.storeIdentityToken(s.identity_token))),this.logger.debug("[privy:refresh] returning response"),s}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof r.PrivyApiError&&e.code===s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),t||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);if(!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getToken();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}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${t.v4()}`,s="blobby";await this._storage.put(e,s);let i=await this._storage.get(e);return await this._storage.del(e),i===s}catch(e){return this.logger.error(e),!1}}constructor(e){this._sdkVersion="js-sdk-core:0.50.1-beta-20250508214717",this._cache=new Map,this.logger=h.toConsoleLogger({level:e.logLevel??"ERROR"}),this._storage=e.storage,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.session=new a.Session({storage:this._storage,isUsingServerCookies:!1,appId:e.appId}),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})}))}}; |
{ | ||
"name": "@privy-io/js-sdk-core", | ||
"version": "0.50.1-beta-20250505220758", | ||
"version": "0.50.1-beta-20250508214717", | ||
"description": "Vanilla JS client for the Privy Auth API", | ||
@@ -70,4 +70,4 @@ "keywords": [ | ||
"@ethersproject/units": "^5.7.0", | ||
"@privy-io/api-base": "1.5.1-beta-20250505220758", | ||
"@privy-io/public-api": "2.24.2-beta-20250505220758", | ||
"@privy-io/api-base": "1.5.1-beta-20250508214717", | ||
"@privy-io/public-api": "2.25.0-beta-20250508214717", | ||
"canonicalize": "^2.0.0", | ||
@@ -74,0 +74,0 @@ "@privy-io/chains": "0.0.1", |
Sorry, the diff of this file is not supported yet
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
+ Added
+ Added
- Removed
- Removed