@blimu/react 0.7.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/auth.service.cjs +1 -1
- package/dist/client/auth.service.cjs.map +1 -1
- package/dist/client/auth.service.d.ts.map +1 -1
- package/dist/client/auth.service.js +15 -13
- package/dist/client/auth.service.js.map +1 -1
- package/dist/client/runtime-client.cjs +1 -1
- package/dist/client/runtime-client.cjs.map +1 -1
- package/dist/client/runtime-client.js +5 -5
- package/dist/client/runtime-client.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("@blimu/client"),o=require("../node_modules/js-cookie/dist/js.cookie.cjs"),A=require("../node_modules/jwt-decode/build/esm/index.cjs"),a="__bli_session",d="__lh_jwt",
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("@blimu/client"),o=require("../node_modules/js-cookie/dist/js.cookie.cjs"),A=require("../node_modules/jwt-decode/build/esm/index.cjs"),a="__bli_session",d="__lh_jwt",c="__lh_jwt",S=10,_=1e3,m=n=>Math.floor(n*_),O=n=>Math.floor(n/_),C=()=>O(Date.now()),T=n=>m(n),P=(n,e)=>{const s=T(n),r=m(e),t=Date.now();return Math.max(s-r-t,0)},u=(n,e)=>{const s=C();return n-e<s};class b{constructor(e,s,r,t,l){this.isLive=e,this.client=s,this.store=r,this.pendingRefresher=null,this.refreshPromise=null,this.refreshingSignals=new Set,this.refreshingSignalAbortController=null,this.localClient=new E.Blimu({baseURL:t,credentials:"include",headers:{"x-blimu-publishable-key":l}}),this.handleRequestError=this.handleRequestError.bind(this)}setCookie(e,s,r={}){const t={secure:this.isLive,sameSite:"lax",path:"/"};r.maxAge!==void 0&&(t.expires=r.maxAge/(1440*60)),o.set(e,s,t)}getSessionPayload(){const e=o.get(a);return e?A.jwtDecode(e):null}async getSessionToken(){const e=this.getSessionPayload();if(e)return this.refreshPromise?(await this.refreshPromise,o.get(a)):(u(e.exp,0)&&await this.refreshSession(),o.get(a))}async handleRequestError(e){return e instanceof E.BlimuError&&[401,500].includes(e.status)?(o.remove(a),o.remove(c),{error:e.message,user:null}):e instanceof DOMException?{error:e.message,user:null}:e instanceof Error?{error:e.message,user:null}:{error:"unknown error",user:null}}async initialize({signal:e}={}){const s=new URL(window.location.href),r=s.searchParams.get(d)??void 0;r&&(s.searchParams.delete(d),window.history.replaceState({},"",s.toString())),r&&this.setCookie(c,r,{maxAge:720*60*60});const t=o.get(c);if(console.log("localhostJWTCookie",t),t&&!o.get(a)){const i=await this.refreshSession({signal:e}).catch(this.handleRequestError);if("error"in i)return i}const l=this.getSessionPayload();if(!l)return{error:null,user:null};if(u(l.exp,S)){const i=await this.refreshSession().catch(this.handleRequestError);if("error"in i)return i}const h=await this.client.auth.getSession().catch(this.handleRequestError);return"error"in h?h:{error:null,user:h.user}}scheduleRefresh(){const e=new AbortController;let s=!0,r=null;const t=()=>{s=!0,this.pendingRefresher&&(this.pendingRefresher(),this.pendingRefresher=null)},l=()=>{s=!1};window.addEventListener("online",t),window.addEventListener("offline",l);const h=()=>{r!==null&&(window.clearTimeout(r),r=null);const i=this.getSessionPayload();if(!i||u(i.exp,0))return;const g=P(i.exp,S);if(g<0)return;const w=async()=>{if(r=null,!s){this.pendingRefresher=w;return}const f=await this.refreshSession({signal:e.signal});if("error"in f){if(f.error==="aborted")return;this.store.setState({status:"error",user:null,error:f.error});return}else h()};r=window.setTimeout(w,g)};return h(),()=>{r&&window.clearTimeout(r),e.abort(),window.removeEventListener("online",t),window.removeEventListener("offline",l)}}async refreshSession({signal:e}={}){if(e&&(this.refreshingSignals.add(e),e.addEventListener("abort",()=>{this.refreshingSignals.delete(e),this.refreshingSignals.size===0&&this.refreshingSignalAbortController?.abort()})),this.refreshPromise)return this.refreshPromise;this.refreshingSignalAbortController=new AbortController,this.refreshingSignalAbortController.signal.addEventListener("abort",()=>{this.refreshPromise=null,this.refreshingSignalAbortController=null,this.refreshingSignals.clear()});const s=this.isLive?void 0:o.get(c),r={};s&&(r.__lh_jwt=s),this.refreshPromise=this.localClient.auth.refresh(r,{signal:this.refreshingSignalAbortController.signal}).then(t=>(this.isLive||this.setCookie(a,t.sessionToken,{maxAge:720*60*60}),t)).catch(this.handleRequestError);try{return await this.refreshPromise}finally{this.refreshPromise=null,this.refreshingSignalAbortController=null,this.refreshingSignals.clear()}}}exports.AuthSessionService=b;exports.LOCALHOST_JWT_COOKIE_NAME=c;exports.LOCALHOST_JWT_URL_PARAM_NAME=d;exports.SESSION_COOKIE_NAME=a;exports.SESSION_EXPIRATION_BUFFER=S;exports.isExpiredIn=u;
|
|
2
2
|
//# sourceMappingURL=auth.service.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.service.cjs","sources":["../../src/client/auth.service.ts"],"sourcesContent":["import { Blimu, BlimuError } from '@blimu/client';\nimport type { RefreshResponse } from '@blimu/client/schema';\nimport Cookies from 'js-cookie';\nimport { jwtDecode } from 'jwt-decode';\n\nimport type { AuthState, User } from '../types';\nimport { ExternalStore } from './external-store';\n\nexport const SESSION_COOKIE_NAME = '__bli_session';\nexport const LOCALHOST_JWT_URL_PARAM_NAME = '__lh_jwt';\nexport const LOCALHOST_JWT_COOKIE_NAME = '__lh_jwt';\nexport const SESSION_EXPIRATION_BUFFER = 10;\n\n/**\n * Time conversion utilities\n * JWT tokens use seconds (Unix timestamp), JavaScript Date uses milliseconds\n */\nconst SECONDS_TO_MS = 1000;\n\n/**\n * Convert seconds to milliseconds\n */\nconst secondsToMilliseconds = (seconds: number): number => Math.floor(seconds * SECONDS_TO_MS);\n\n/**\n * Convert milliseconds to seconds\n */\nconst millisecondsToSeconds = (ms: number): number => Math.floor(ms / SECONDS_TO_MS);\n\n/**\n * Get current time in seconds (Unix timestamp)\n */\nconst nowInSeconds = (): number => millisecondsToSeconds(Date.now());\n\n/**\n * Convert JWT expiration time (seconds) to milliseconds\n */\nconst jwtExpToMilliseconds = (exp: number): number => secondsToMilliseconds(exp);\n\n/**\n * Calculate timeout delay in milliseconds for refreshing before expiration\n * @param expirationSeconds - JWT exp claim in seconds\n * @param bufferSeconds - Buffer time in seconds before expiration\n * @returns Timeout delay in milliseconds\n */\nconst calculateTimeoutDelay = (expirationSeconds: number, bufferSeconds: number): number => {\n const expirationMS = jwtExpToMilliseconds(expirationSeconds);\n const bufferMS = secondsToMilliseconds(bufferSeconds);\n const nowMS = Date.now();\n return Math.max(expirationMS - bufferMS - nowMS, 0);\n};\n\n/**\n * Check if a JWT expiration time (in seconds) is expired or will expire within the buffer\n * @param expiration - JWT exp claim in seconds (Unix timestamp)\n * @param buffer - Buffer time in seconds before expiration to consider it expired\n * @returns true if expired or will expire within buffer\n */\nexport const isExpiredIn = (expiration: number, buffer: number): boolean => {\n const now = nowInSeconds();\n return expiration - buffer < now;\n};\n\nexport class AuthSessionService {\n private pendingRefresher: (() => void) | null = null;\n private refreshPromise: Promise<RefreshResponse | { error: string; user: null }> | null = null;\n private refreshingSignals: Set<AbortSignal> = new Set();\n private refreshingSignalAbortController: AbortController | null = null;\n // A local client that doesn't call getSessionToken() which calls refreshSession().\n private localClient: Blimu;\n\n constructor(\n private readonly isLive: boolean,\n private readonly client: Blimu,\n private readonly store: ExternalStore<AuthState>,\n baseURL: string,\n publishableKey: string,\n ) {\n this.localClient = new Blimu({\n baseURL,\n credentials: 'include',\n headers: { 'x-blimu-publishable-key': publishableKey },\n });\n this.handleRequestError = this.handleRequestError.bind(this);\n }\n\n /**\n * Set cookie with appropriate security settings based on environment\n */\n private setCookie(name: string, value: string, options: { maxAge?: number } = {}): void {\n const cookieOptions: Cookies.CookieAttributes = {\n secure: this.isLive, // true for live environments, false for localhost\n sameSite: 'lax',\n path: '/',\n };\n\n if (options.maxAge !== undefined) {\n cookieOptions.expires = options.maxAge / (24 * 60 * 60); // Convert seconds to days\n }\n\n Cookies.set(name, value, cookieOptions);\n }\n\n getSessionPayload(): {\n sub: string;\n environmentId: string;\n type: string;\n iat: number;\n exp: number;\n } | null {\n const token = Cookies.get(SESSION_COOKIE_NAME);\n\n if (!token) {\n return null;\n }\n\n const decoded = jwtDecode<{\n sub: string;\n environmentId: string;\n type: string;\n iat: number;\n exp: number;\n }>(token);\n\n return decoded;\n }\n\n async getSessionToken(): Promise<string | undefined> {\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload) {\n return undefined;\n }\n\n // If a refresh is already in progress, wait for it to complete\n // This prevents infinite recursion when refreshSession() calls client.auth.refresh()\n // which triggers accessToken() which calls getSessionToken()\n if (this.refreshPromise) {\n await this.refreshPromise;\n // After refresh completes, return the updated token from cookie\n return Cookies.get(SESSION_COOKIE_NAME);\n }\n\n if (isExpiredIn(sessionPayload.exp, 0)) {\n await this.refreshSession();\n }\n\n return Cookies.get(SESSION_COOKIE_NAME);\n }\n\n async handleRequestError(error: unknown): Promise<{ error: string; user: null }> {\n if (error instanceof BlimuError && [401, 500].includes(error.status)) {\n Cookies.remove(SESSION_COOKIE_NAME);\n Cookies.remove(LOCALHOST_JWT_COOKIE_NAME);\n\n return {\n error: error.message,\n user: null,\n };\n }\n\n if (error instanceof DOMException)\n return {\n error: error.message,\n user: null,\n };\n\n if (error instanceof Error) {\n return {\n error: error.message,\n user: null,\n };\n }\n\n return {\n error: 'unknown error',\n user: null,\n };\n }\n\n async initialize({ signal }: { signal?: AbortSignal } = {}): Promise<{\n error: string | null;\n user: User | null;\n }> {\n const url = new URL(window.location.href);\n const localhostJWT = url.searchParams.get(LOCALHOST_JWT_URL_PARAM_NAME) ?? undefined;\n\n // Clean up URL parameters immediately to prevent re-processing on re-renders\n if (localhostJWT) {\n url.searchParams.delete(LOCALHOST_JWT_URL_PARAM_NAME);\n window.history.replaceState({}, '', url.toString());\n }\n\n // Handle localhost JWT from URL parameter\n if (localhostJWT) {\n // Set localhost JWT cookie on customer app domain\n this.setCookie(LOCALHOST_JWT_COOKIE_NAME, localhostJWT, {\n maxAge: 30 * 24 * 60 * 60, // 30 days\n });\n }\n\n const localhostJWTCookie = Cookies.get(LOCALHOST_JWT_COOKIE_NAME);\n\n if (localhostJWTCookie && !Cookies.get(SESSION_COOKIE_NAME)) {\n const result = await this.refreshSession({ signal }).catch(this.handleRequestError);\n if ('error' in result) return result;\n }\n\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload) {\n return {\n error: null,\n user: null,\n };\n }\n\n if (isExpiredIn(sessionPayload.exp, SESSION_EXPIRATION_BUFFER)) {\n const result = await this.refreshSession().catch(this.handleRequestError);\n if ('error' in result) return result;\n }\n\n const result = await this.client.auth.getSession().catch(this.handleRequestError);\n if ('error' in result) return result;\n\n return {\n error: null,\n user: result.user,\n };\n }\n\n scheduleRefresh() {\n const abortController = new AbortController();\n let isOnline = true;\n let timeoutId: number | null = null;\n\n const onlineHandler = () => {\n isOnline = true;\n if (this.pendingRefresher) {\n this.pendingRefresher();\n this.pendingRefresher = null;\n }\n };\n const offlineHandler = () => {\n isOnline = false;\n };\n\n window.addEventListener('online', onlineHandler);\n window.addEventListener('offline', offlineHandler);\n\n const refresh = () => {\n // Clear any existing timeout before scheduling a new one\n // This prevents infinite loops when refresh() is called recursively\n if (timeoutId !== null) {\n window.clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload || isExpiredIn(sessionPayload.exp, 0)) return;\n\n // Calculate timeout delay: refresh SESSION_EXPIRATION_BUFFER seconds before expiration\n const timeoutDelayMS = calculateTimeoutDelay(sessionPayload.exp, SESSION_EXPIRATION_BUFFER);\n\n // Prevent scheduling if timeout is negative (token already expired)\n // Allow 0ms delays to handle edge cases where we're exactly at the refresh point\n // This prevents immediate re-scheduling that could cause infinite loops\n if (timeoutDelayMS < 0) {\n return;\n }\n\n // Having this function outside timeout, allows us to call refresh immediately when back online\n const refresher = async () => {\n // Clear timeoutId since we're executing now\n timeoutId = null;\n\n if (!isOnline) {\n // Keep closure of refresh function alive\n this.pendingRefresher = refresher;\n return;\n }\n\n const result = await this.refreshSession({ signal: abortController.signal });\n\n if ('error' in result) {\n // If the refresh was aborted (e.g., due to React strict mode unmounting),\n // don't treat it as an error - just return and let the component remount handle it\n if (result.error === 'aborted') {\n return;\n }\n // For real errors, update the store\n this.store.setState({\n status: 'error',\n user: null,\n error: result.error,\n });\n return;\n } else {\n // After successful refresh, schedule the next refresh with the new token\n refresh();\n }\n };\n\n timeoutId = window.setTimeout(refresher, timeoutDelayMS);\n };\n\n refresh();\n\n return () => {\n if (timeoutId) {\n window.clearTimeout(timeoutId);\n }\n abortController.abort();\n window.removeEventListener('online', onlineHandler);\n window.removeEventListener('offline', offlineHandler);\n };\n }\n\n private async refreshSession({ signal }: { signal?: AbortSignal } = {}) {\n if (signal) {\n // Add signal to tracking set (was using .has() instead of .add() - bug fix)\n this.refreshingSignals.add(signal);\n\n signal.addEventListener('abort', () => {\n this.refreshingSignals.delete(signal);\n\n if (this.refreshingSignals.size === 0) {\n this.refreshingSignalAbortController?.abort();\n }\n });\n }\n\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n this.refreshingSignalAbortController = new AbortController();\n\n this.refreshingSignalAbortController.signal.addEventListener('abort', () => {\n this.refreshPromise = null;\n this.refreshingSignalAbortController = null;\n this.refreshingSignals.clear();\n });\n\n // Get localhost_jwt from cookie to send as query parameter (only for non-live environments)\n const localhostJWT = !this.isLive ? Cookies.get(LOCALHOST_JWT_COOKIE_NAME) : undefined;\n\n // Build query parameters - only include __lh_jwt for non-live environments when cookie exists\n const queryParams: { __lh_jwt?: string } = {};\n if (localhostJWT) {\n queryParams.__lh_jwt = localhostJWT;\n }\n\n // Use local client to avoid infinite recursion. Regular client calls getSessionToken() which calls refreshSession().\n // There are hacks to avoid infinite recursion, but they are not reliable.\n // The localhost_jwt is sent as a query parameter only in non-live environments\n // Note: Type assertion needed because the generated SDK type doesn't include 'query' in RequestInit,\n // but the underlying CoreClient.request() method does support it\n this.refreshPromise = this.localClient.auth\n .refresh(queryParams, {\n signal: this.refreshingSignalAbortController.signal,\n })\n .then((response) => {\n // Update cookie with new session token from response body\n // Server also sets it via Set-Cookie header on auth domain, but we set it manually on customer domain\n if (!this.isLive) {\n this.setCookie(SESSION_COOKIE_NAME, response.sessionToken, {\n maxAge: 30 * 24 * 60 * 60, // 30 days\n });\n }\n return response;\n })\n .catch(this.handleRequestError);\n\n try {\n return await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n this.refreshingSignalAbortController = null;\n this.refreshingSignals.clear();\n }\n }\n}\n"],"names":["SESSION_COOKIE_NAME","LOCALHOST_JWT_URL_PARAM_NAME","LOCALHOST_JWT_COOKIE_NAME","SESSION_EXPIRATION_BUFFER","SECONDS_TO_MS","secondsToMilliseconds","seconds","millisecondsToSeconds","ms","nowInSeconds","jwtExpToMilliseconds","exp","calculateTimeoutDelay","expirationSeconds","bufferSeconds","expirationMS","bufferMS","nowMS","isExpiredIn","expiration","buffer","now","AuthSessionService","isLive","client","store","baseURL","publishableKey","Blimu","name","value","options","cookieOptions","Cookies","token","jwtDecode","sessionPayload","error","BlimuError","signal","url","localhostJWT","result","abortController","isOnline","timeoutId","onlineHandler","offlineHandler","refresh","timeoutDelayMS","refresher","queryParams","response"],"mappings":"uOAQaA,EAAsB,gBACtBC,EAA+B,WAC/BC,EAA4B,WAC5BC,EAA4B,GAMnCC,EAAgB,IAKhBC,EAAyBC,GAA4B,KAAK,MAAMA,EAAUF,CAAa,EAKvFG,EAAyBC,GAAuB,KAAK,MAAMA,EAAKJ,CAAa,EAK7EK,EAAe,IAAcF,EAAsB,KAAK,KAAK,EAK7DG,EAAwBC,GAAwBN,EAAsBM,CAAG,EAQzEC,EAAwB,CAACC,EAA2BC,IAAkC,CAC1F,MAAMC,EAAeL,EAAqBG,CAAiB,EACrDG,EAAWX,EAAsBS,CAAa,EAC9CG,EAAQ,KAAK,IAAA,EACnB,OAAO,KAAK,IAAIF,EAAeC,EAAWC,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C,IAAI,gBAE3C,KAAK,gCAAgC,OAAO,iBAAiB,QAAS,IAAM,CAC1E,KAAK,eAAiB,KACtB,KAAK,gCAAkC,KACvC,KAAK,kBAAkB,MAAA,CACzB,CAAC,EAGD,MAAME,EAAgB,KAAK,OAAkD,OAAzCR,EAAQ,IAAI/B,CAAyB,EAGnEiD,EAAqC,CAAA,EACvCV,IACFU,EAAY,SAAWV,GAQzB,KAAK,eAAiB,KAAK,YAAY,KACpC,QAAQU,EAAa,CACpB,OAAQ,KAAK,gCAAgC,MAAA,CAC9C,EACA,KAAMC,IAGA,KAAK,QACR,KAAK,UAAUpD,EAAqBoD,EAAS,aAAc,CACzD,OAAQ,IAAU,GAAK,EAAA,CACxB,EAEIA,EACR,EACA,MAAM,KAAK,kBAAkB,EAEhC,GAAI,CACF,OAAO,MAAM,KAAK,cACpB,QAAA,CACE,KAAK,eAAiB,KACtB,KAAK,gCAAkC,KACvC,KAAK,kBAAkB,MAAA,CACzB,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"auth.service.cjs","sources":["../../src/client/auth.service.ts"],"sourcesContent":["import { Blimu, BlimuError } from '@blimu/client';\nimport type { RefreshResponse } from '@blimu/client/schema';\nimport Cookies from 'js-cookie';\nimport { jwtDecode } from 'jwt-decode';\n\nimport type { AuthState, User } from '../types';\nimport { ExternalStore } from './external-store';\n\nexport const SESSION_COOKIE_NAME = '__bli_session';\nexport const LOCALHOST_JWT_URL_PARAM_NAME = '__lh_jwt';\nexport const LOCALHOST_JWT_COOKIE_NAME = '__lh_jwt';\nexport const SESSION_EXPIRATION_BUFFER = 10;\n\n/**\n * Time conversion utilities\n * JWT tokens use seconds (Unix timestamp), JavaScript Date uses milliseconds\n */\nconst SECONDS_TO_MS = 1000;\n\n/**\n * Convert seconds to milliseconds\n */\nconst secondsToMilliseconds = (seconds: number): number => Math.floor(seconds * SECONDS_TO_MS);\n\n/**\n * Convert milliseconds to seconds\n */\nconst millisecondsToSeconds = (ms: number): number => Math.floor(ms / SECONDS_TO_MS);\n\n/**\n * Get current time in seconds (Unix timestamp)\n */\nconst nowInSeconds = (): number => millisecondsToSeconds(Date.now());\n\n/**\n * Convert JWT expiration time (seconds) to milliseconds\n */\nconst jwtExpToMilliseconds = (exp: number): number => secondsToMilliseconds(exp);\n\n/**\n * Calculate timeout delay in milliseconds for refreshing before expiration\n * @param expirationSeconds - JWT exp claim in seconds\n * @param bufferSeconds - Buffer time in seconds before expiration\n * @returns Timeout delay in milliseconds\n */\nconst calculateTimeoutDelay = (expirationSeconds: number, bufferSeconds: number): number => {\n const expirationMS = jwtExpToMilliseconds(expirationSeconds);\n const bufferMS = secondsToMilliseconds(bufferSeconds);\n const nowMS = Date.now();\n return Math.max(expirationMS - bufferMS - nowMS, 0);\n};\n\n/**\n * Check if a JWT expiration time (in seconds) is expired or will expire within the buffer\n * @param expiration - JWT exp claim in seconds (Unix timestamp)\n * @param buffer - Buffer time in seconds before expiration to consider it expired\n * @returns true if expired or will expire within buffer\n */\nexport const isExpiredIn = (expiration: number, buffer: number): boolean => {\n const now = nowInSeconds();\n return expiration - buffer < now;\n};\n\nexport class AuthSessionService {\n private pendingRefresher: (() => void) | null = null;\n private refreshPromise: Promise<RefreshResponse | { error: string; user: null }> | null = null;\n private refreshingSignals: Set<AbortSignal> = new Set();\n private refreshingSignalAbortController: AbortController | null = null;\n // A local client that doesn't call getSessionToken() which calls refreshSession().\n private localClient: Blimu;\n\n constructor(\n private readonly isLive: boolean,\n private readonly client: Blimu,\n private readonly store: ExternalStore<AuthState>,\n baseURL: string,\n publishableKey: string,\n ) {\n this.localClient = new Blimu({\n baseURL,\n credentials: 'include',\n headers: { 'x-blimu-publishable-key': publishableKey },\n });\n this.handleRequestError = this.handleRequestError.bind(this);\n }\n\n /**\n * Set cookie with appropriate security settings based on environment\n */\n private setCookie(name: string, value: string, options: { maxAge?: number } = {}): void {\n const cookieOptions: Cookies.CookieAttributes = {\n secure: this.isLive, // true for live environments, false for localhost\n sameSite: 'lax',\n path: '/',\n };\n\n if (options.maxAge !== undefined) {\n cookieOptions.expires = options.maxAge / (24 * 60 * 60); // Convert seconds to days\n }\n\n Cookies.set(name, value, cookieOptions);\n }\n\n getSessionPayload(): {\n sub: string;\n environmentId: string;\n type: string;\n iat: number;\n exp: number;\n } | null {\n const token = Cookies.get(SESSION_COOKIE_NAME);\n\n if (!token) {\n return null;\n }\n\n const decoded = jwtDecode<{\n sub: string;\n environmentId: string;\n type: string;\n iat: number;\n exp: number;\n }>(token);\n\n return decoded;\n }\n\n async getSessionToken(): Promise<string | undefined> {\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload) {\n return undefined;\n }\n\n // If a refresh is already in progress, wait for it to complete\n // This prevents infinite recursion when refreshSession() calls client.auth.refresh()\n // which triggers accessToken() which calls getSessionToken()\n if (this.refreshPromise) {\n await this.refreshPromise;\n // After refresh completes, return the updated token from cookie\n return Cookies.get(SESSION_COOKIE_NAME);\n }\n\n if (isExpiredIn(sessionPayload.exp, 0)) {\n await this.refreshSession();\n }\n\n return Cookies.get(SESSION_COOKIE_NAME);\n }\n\n async handleRequestError(error: unknown): Promise<{ error: string; user: null }> {\n if (error instanceof BlimuError && [401, 500].includes(error.status)) {\n Cookies.remove(SESSION_COOKIE_NAME);\n Cookies.remove(LOCALHOST_JWT_COOKIE_NAME);\n\n return {\n error: error.message,\n user: null,\n };\n }\n\n if (error instanceof DOMException)\n return {\n error: error.message,\n user: null,\n };\n\n if (error instanceof Error) {\n return {\n error: error.message,\n user: null,\n };\n }\n\n return {\n error: 'unknown error',\n user: null,\n };\n }\n\n async initialize({ signal }: { signal?: AbortSignal } = {}): Promise<{\n error: string | null;\n user: User | null;\n }> {\n const url = new URL(window.location.href);\n const localhostJWT = url.searchParams.get(LOCALHOST_JWT_URL_PARAM_NAME) ?? undefined;\n\n // Clean up URL parameters immediately to prevent re-processing on re-renders\n if (localhostJWT) {\n url.searchParams.delete(LOCALHOST_JWT_URL_PARAM_NAME);\n window.history.replaceState({}, '', url.toString());\n }\n\n // Handle localhost JWT from URL parameter\n if (localhostJWT) {\n // Set localhost JWT cookie on customer app domain\n this.setCookie(LOCALHOST_JWT_COOKIE_NAME, localhostJWT, {\n maxAge: 30 * 24 * 60 * 60, // 30 days\n });\n }\n\n const localhostJWTCookie = Cookies.get(LOCALHOST_JWT_COOKIE_NAME);\n\n console.log('localhostJWTCookie', localhostJWTCookie);\n\n if (localhostJWTCookie && !Cookies.get(SESSION_COOKIE_NAME)) {\n const result = await this.refreshSession({ signal }).catch(this.handleRequestError);\n if ('error' in result) return result;\n }\n\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload) {\n return {\n error: null,\n user: null,\n };\n }\n\n if (isExpiredIn(sessionPayload.exp, SESSION_EXPIRATION_BUFFER)) {\n const result = await this.refreshSession().catch(this.handleRequestError);\n if ('error' in result) return result;\n }\n\n const result = await this.client.auth.getSession().catch(this.handleRequestError);\n if ('error' in result) return result;\n\n return {\n error: null,\n user: result.user,\n };\n }\n\n scheduleRefresh() {\n const abortController = new AbortController();\n let isOnline = true;\n let timeoutId: number | null = null;\n\n const onlineHandler = () => {\n isOnline = true;\n if (this.pendingRefresher) {\n this.pendingRefresher();\n this.pendingRefresher = null;\n }\n };\n const offlineHandler = () => {\n isOnline = false;\n };\n\n window.addEventListener('online', onlineHandler);\n window.addEventListener('offline', offlineHandler);\n\n const refresh = () => {\n // Clear any existing timeout before scheduling a new one\n // This prevents infinite loops when refresh() is called recursively\n if (timeoutId !== null) {\n window.clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload || isExpiredIn(sessionPayload.exp, 0)) return;\n\n // Calculate timeout delay: refresh SESSION_EXPIRATION_BUFFER seconds before expiration\n const timeoutDelayMS = calculateTimeoutDelay(sessionPayload.exp, SESSION_EXPIRATION_BUFFER);\n\n // Prevent scheduling if timeout is negative (token already expired)\n // Allow 0ms delays to handle edge cases where we're exactly at the refresh point\n // This prevents immediate re-scheduling that could cause infinite loops\n if (timeoutDelayMS < 0) {\n return;\n }\n\n // Having this function outside timeout, allows us to call refresh immediately when back online\n const refresher = async () => {\n // Clear timeoutId since we're executing now\n timeoutId = null;\n\n if (!isOnline) {\n // Keep closure of refresh function alive\n this.pendingRefresher = refresher;\n return;\n }\n\n const result = await this.refreshSession({ signal: abortController.signal });\n\n if ('error' in result) {\n // If the refresh was aborted (e.g., due to React strict mode unmounting),\n // don't treat it as an error - just return and let the component remount handle it\n if (result.error === 'aborted') {\n return;\n }\n // For real errors, update the store\n this.store.setState({\n status: 'error',\n user: null,\n error: result.error,\n });\n return;\n } else {\n // After successful refresh, schedule the next refresh with the new token\n refresh();\n }\n };\n\n timeoutId = window.setTimeout(refresher, timeoutDelayMS);\n };\n\n refresh();\n\n return () => {\n if (timeoutId) {\n window.clearTimeout(timeoutId);\n }\n abortController.abort();\n window.removeEventListener('online', onlineHandler);\n window.removeEventListener('offline', offlineHandler);\n };\n }\n\n private async refreshSession({ signal }: { signal?: AbortSignal } = {}) {\n if (signal) {\n // Add signal to tracking set (was using .has() instead of .add() - bug fix)\n this.refreshingSignals.add(signal);\n\n signal.addEventListener('abort', () => {\n this.refreshingSignals.delete(signal);\n\n if (this.refreshingSignals.size === 0) {\n this.refreshingSignalAbortController?.abort();\n }\n });\n }\n\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n this.refreshingSignalAbortController = new AbortController();\n\n this.refreshingSignalAbortController.signal.addEventListener('abort', () => {\n this.refreshPromise = null;\n this.refreshingSignalAbortController = null;\n this.refreshingSignals.clear();\n });\n\n // Get localhost_jwt from cookie to send as query parameter (only for non-live environments)\n const localhostJWT = !this.isLive ? Cookies.get(LOCALHOST_JWT_COOKIE_NAME) : undefined;\n\n // Build query parameters - only include __lh_jwt for non-live environments when cookie exists\n const queryParams: { __lh_jwt?: string } = {};\n if (localhostJWT) {\n queryParams.__lh_jwt = localhostJWT;\n }\n\n // Use local client to avoid infinite recursion. Regular client calls getSessionToken() which calls refreshSession().\n // There are hacks to avoid infinite recursion, but they are not reliable.\n // The localhost_jwt is sent as a query parameter only in non-live environments\n // Note: Type assertion needed because the generated SDK type doesn't include 'query' in RequestInit,\n // but the underlying CoreClient.request() method does support it\n this.refreshPromise = this.localClient.auth\n .refresh(queryParams, {\n signal: this.refreshingSignalAbortController.signal,\n })\n .then((response) => {\n // Update cookie with new session token from response body\n // Server also sets it via Set-Cookie header on auth domain, but we set it manually on customer domain\n if (!this.isLive) {\n this.setCookie(SESSION_COOKIE_NAME, response.sessionToken, {\n maxAge: 30 * 24 * 60 * 60, // 30 days\n });\n }\n return response;\n })\n .catch(this.handleRequestError);\n\n try {\n return await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n this.refreshingSignalAbortController = null;\n this.refreshingSignals.clear();\n }\n }\n}\n"],"names":["SESSION_COOKIE_NAME","LOCALHOST_JWT_URL_PARAM_NAME","LOCALHOST_JWT_COOKIE_NAME","SESSION_EXPIRATION_BUFFER","SECONDS_TO_MS","secondsToMilliseconds","seconds","millisecondsToSeconds","ms","nowInSeconds","jwtExpToMilliseconds","exp","calculateTimeoutDelay","expirationSeconds","bufferSeconds","expirationMS","bufferMS","nowMS","isExpiredIn","expiration","buffer","now","AuthSessionService","isLive","client","store","baseURL","publishableKey","Blimu","name","value","options","cookieOptions","Cookies","token","jwtDecode","sessionPayload","error","BlimuError","signal","url","localhostJWT","localhostJWTCookie","result","abortController","isOnline","timeoutId","onlineHandler","offlineHandler","refresh","timeoutDelayMS","refresher","queryParams","response"],"mappings":"uOAQaA,EAAsB,gBACtBC,EAA+B,WAC/BC,EAA4B,WAC5BC,EAA4B,GAMnCC,EAAgB,IAKhBC,EAAyBC,GAA4B,KAAK,MAAMA,EAAUF,CAAa,EAKvFG,EAAyBC,GAAuB,KAAK,MAAMA,EAAKJ,CAAa,EAK7EK,EAAe,IAAcF,EAAsB,KAAK,KAAK,EAK7DG,EAAwBC,GAAwBN,EAAsBM,CAAG,EAQzEC,EAAwB,CAACC,EAA2B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AM,CAAC;QAAC,IAAI,EAAE,IAAI,CAAA;KAAE,CAAC;IA8B1E,UAAU,CAAC,EAAE,MAAM,EAAE,GAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAO,GAAG,OAAO,CAAC;QACnE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;QACrB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;KACnB,CAAC;IAkDF,eAAe;YAwFD,cAAc;CAgE7B"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { Blimu as _, BlimuError as A } from "@blimu/client";
|
|
2
2
|
import o from "../node_modules/js-cookie/dist/js.cookie.js";
|
|
3
3
|
import { jwtDecode as C } from "../node_modules/jwt-decode/build/esm/index.js";
|
|
4
|
-
const h = "__bli_session", S = "__lh_jwt", u = "__lh_jwt", m = 10, w = 1e3, E = (
|
|
5
|
-
const s = P(
|
|
4
|
+
const h = "__bli_session", S = "__lh_jwt", u = "__lh_jwt", m = 10, w = 1e3, E = (n) => Math.floor(n * w), b = (n) => Math.floor(n / w), p = () => b(Date.now()), P = (n) => E(n), v = (n, e) => {
|
|
5
|
+
const s = P(n), r = E(e), t = Date.now();
|
|
6
6
|
return Math.max(s - r - t, 0);
|
|
7
|
-
}, f = (
|
|
7
|
+
}, f = (n, e) => {
|
|
8
8
|
const s = p();
|
|
9
|
-
return
|
|
9
|
+
return n - e < s;
|
|
10
10
|
};
|
|
11
11
|
class x {
|
|
12
12
|
constructor(e, s, r, t, l) {
|
|
@@ -54,12 +54,14 @@ class x {
|
|
|
54
54
|
}
|
|
55
55
|
async initialize({ signal: e } = {}) {
|
|
56
56
|
const s = new URL(window.location.href), r = s.searchParams.get(S) ?? void 0;
|
|
57
|
-
|
|
57
|
+
r && (s.searchParams.delete(S), window.history.replaceState({}, "", s.toString())), r && this.setCookie(u, r, {
|
|
58
58
|
maxAge: 720 * 60 * 60
|
|
59
59
|
// 30 days
|
|
60
|
-
})
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
});
|
|
61
|
+
const t = o.get(u);
|
|
62
|
+
if (console.log("localhostJWTCookie", t), t && !o.get(h)) {
|
|
63
|
+
const i = await this.refreshSession({ signal: e }).catch(this.handleRequestError);
|
|
64
|
+
if ("error" in i) return i;
|
|
63
65
|
}
|
|
64
66
|
const l = this.getSessionPayload();
|
|
65
67
|
if (!l)
|
|
@@ -68,8 +70,8 @@ class x {
|
|
|
68
70
|
user: null
|
|
69
71
|
};
|
|
70
72
|
if (f(l.exp, m)) {
|
|
71
|
-
const
|
|
72
|
-
if ("error" in
|
|
73
|
+
const i = await this.refreshSession().catch(this.handleRequestError);
|
|
74
|
+
if ("error" in i) return i;
|
|
73
75
|
}
|
|
74
76
|
const a = await this.client.auth.getSession().catch(this.handleRequestError);
|
|
75
77
|
return "error" in a ? a : {
|
|
@@ -88,9 +90,9 @@ class x {
|
|
|
88
90
|
window.addEventListener("online", t), window.addEventListener("offline", l);
|
|
89
91
|
const a = () => {
|
|
90
92
|
r !== null && (window.clearTimeout(r), r = null);
|
|
91
|
-
const
|
|
92
|
-
if (!
|
|
93
|
-
const d = v(
|
|
93
|
+
const i = this.getSessionPayload();
|
|
94
|
+
if (!i || f(i.exp, 0)) return;
|
|
95
|
+
const d = v(i.exp, m);
|
|
94
96
|
if (d < 0)
|
|
95
97
|
return;
|
|
96
98
|
const g = async () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.service.js","sources":["../../src/client/auth.service.ts"],"sourcesContent":["import { Blimu, BlimuError } from '@blimu/client';\nimport type { RefreshResponse } from '@blimu/client/schema';\nimport Cookies from 'js-cookie';\nimport { jwtDecode } from 'jwt-decode';\n\nimport type { AuthState, User } from '../types';\nimport { ExternalStore } from './external-store';\n\nexport const SESSION_COOKIE_NAME = '__bli_session';\nexport const LOCALHOST_JWT_URL_PARAM_NAME = '__lh_jwt';\nexport const LOCALHOST_JWT_COOKIE_NAME = '__lh_jwt';\nexport const SESSION_EXPIRATION_BUFFER = 10;\n\n/**\n * Time conversion utilities\n * JWT tokens use seconds (Unix timestamp), JavaScript Date uses milliseconds\n */\nconst SECONDS_TO_MS = 1000;\n\n/**\n * Convert seconds to milliseconds\n */\nconst secondsToMilliseconds = (seconds: number): number => Math.floor(seconds * SECONDS_TO_MS);\n\n/**\n * Convert milliseconds to seconds\n */\nconst millisecondsToSeconds = (ms: number): number => Math.floor(ms / SECONDS_TO_MS);\n\n/**\n * Get current time in seconds (Unix timestamp)\n */\nconst nowInSeconds = (): number => millisecondsToSeconds(Date.now());\n\n/**\n * Convert JWT expiration time (seconds) to milliseconds\n */\nconst jwtExpToMilliseconds = (exp: number): number => secondsToMilliseconds(exp);\n\n/**\n * Calculate timeout delay in milliseconds for refreshing before expiration\n * @param expirationSeconds - JWT exp claim in seconds\n * @param bufferSeconds - Buffer time in seconds before expiration\n * @returns Timeout delay in milliseconds\n */\nconst calculateTimeoutDelay = (expirationSeconds: number, bufferSeconds: number): number => {\n const expirationMS = jwtExpToMilliseconds(expirationSeconds);\n const bufferMS = secondsToMilliseconds(bufferSeconds);\n const nowMS = Date.now();\n return Math.max(expirationMS - bufferMS - nowMS, 0);\n};\n\n/**\n * Check if a JWT expiration time (in seconds) is expired or will expire within the buffer\n * @param expiration - JWT exp claim in seconds (Unix timestamp)\n * @param buffer - Buffer time in seconds before expiration to consider it expired\n * @returns true if expired or will expire within buffer\n */\nexport const isExpiredIn = (expiration: number, buffer: number): boolean => {\n const now = nowInSeconds();\n return expiration - buffer < now;\n};\n\nexport class AuthSessionService {\n private pendingRefresher: (() => void) | null = null;\n private refreshPromise: Promise<RefreshResponse | { error: string; user: null }> | null = null;\n private refreshingSignals: Set<AbortSignal> = new Set();\n private refreshingSignalAbortController: AbortController | null = null;\n // A local client that doesn't call getSessionToken() which calls refreshSession().\n private localClient: Blimu;\n\n constructor(\n private readonly isLive: boolean,\n private readonly client: Blimu,\n private readonly store: ExternalStore<AuthState>,\n baseURL: string,\n publishableKey: string,\n ) {\n this.localClient = new Blimu({\n baseURL,\n credentials: 'include',\n headers: { 'x-blimu-publishable-key': publishableKey },\n });\n this.handleRequestError = this.handleRequestError.bind(this);\n }\n\n /**\n * Set cookie with appropriate security settings based on environment\n */\n private setCookie(name: string, value: string, options: { maxAge?: number } = {}): void {\n const cookieOptions: Cookies.CookieAttributes = {\n secure: this.isLive, // true for live environments, false for localhost\n sameSite: 'lax',\n path: '/',\n };\n\n if (options.maxAge !== undefined) {\n cookieOptions.expires = options.maxAge / (24 * 60 * 60); // Convert seconds to days\n }\n\n Cookies.set(name, value, cookieOptions);\n }\n\n getSessionPayload(): {\n sub: string;\n environmentId: string;\n type: string;\n iat: number;\n exp: number;\n } | null {\n const token = Cookies.get(SESSION_COOKIE_NAME);\n\n if (!token) {\n return null;\n }\n\n const decoded = jwtDecode<{\n sub: string;\n environmentId: string;\n type: string;\n iat: number;\n exp: number;\n }>(token);\n\n return decoded;\n }\n\n async getSessionToken(): Promise<string | undefined> {\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload) {\n return undefined;\n }\n\n // If a refresh is already in progress, wait for it to complete\n // This prevents infinite recursion when refreshSession() calls client.auth.refresh()\n // which triggers accessToken() which calls getSessionToken()\n if (this.refreshPromise) {\n await this.refreshPromise;\n // After refresh completes, return the updated token from cookie\n return Cookies.get(SESSION_COOKIE_NAME);\n }\n\n if (isExpiredIn(sessionPayload.exp, 0)) {\n await this.refreshSession();\n }\n\n return Cookies.get(SESSION_COOKIE_NAME);\n }\n\n async handleRequestError(error: unknown): Promise<{ error: string; user: null }> {\n if (error instanceof BlimuError && [401, 500].includes(error.status)) {\n Cookies.remove(SESSION_COOKIE_NAME);\n Cookies.remove(LOCALHOST_JWT_COOKIE_NAME);\n\n return {\n error: error.message,\n user: null,\n };\n }\n\n if (error instanceof DOMException)\n return {\n error: error.message,\n user: null,\n };\n\n if (error instanceof Error) {\n return {\n error: error.message,\n user: null,\n };\n }\n\n return {\n error: 'unknown error',\n user: null,\n };\n }\n\n async initialize({ signal }: { signal?: AbortSignal } = {}): Promise<{\n error: string | null;\n user: User | null;\n }> {\n const url = new URL(window.location.href);\n const localhostJWT = url.searchParams.get(LOCALHOST_JWT_URL_PARAM_NAME) ?? undefined;\n\n // Clean up URL parameters immediately to prevent re-processing on re-renders\n if (localhostJWT) {\n url.searchParams.delete(LOCALHOST_JWT_URL_PARAM_NAME);\n window.history.replaceState({}, '', url.toString());\n }\n\n // Handle localhost JWT from URL parameter\n if (localhostJWT) {\n // Set localhost JWT cookie on customer app domain\n this.setCookie(LOCALHOST_JWT_COOKIE_NAME, localhostJWT, {\n maxAge: 30 * 24 * 60 * 60, // 30 days\n });\n }\n\n const localhostJWTCookie = Cookies.get(LOCALHOST_JWT_COOKIE_NAME);\n\n if (localhostJWTCookie && !Cookies.get(SESSION_COOKIE_NAME)) {\n const result = await this.refreshSession({ signal }).catch(this.handleRequestError);\n if ('error' in result) return result;\n }\n\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload) {\n return {\n error: null,\n user: null,\n };\n }\n\n if (isExpiredIn(sessionPayload.exp, SESSION_EXPIRATION_BUFFER)) {\n const result = await this.refreshSession().catch(this.handleRequestError);\n if ('error' in result) return result;\n }\n\n const result = await this.client.auth.getSession().catch(this.handleRequestError);\n if ('error' in result) return result;\n\n return {\n error: null,\n user: result.user,\n };\n }\n\n scheduleRefresh() {\n const abortController = new AbortController();\n let isOnline = true;\n let timeoutId: number | null = null;\n\n const onlineHandler = () => {\n isOnline = true;\n if (this.pendingRefresher) {\n this.pendingRefresher();\n this.pendingRefresher = null;\n }\n };\n const offlineHandler = () => {\n isOnline = false;\n };\n\n window.addEventListener('online', onlineHandler);\n window.addEventListener('offline', offlineHandler);\n\n const refresh = () => {\n // Clear any existing timeout before scheduling a new one\n // This prevents infinite loops when refresh() is called recursively\n if (timeoutId !== null) {\n window.clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload || isExpiredIn(sessionPayload.exp, 0)) return;\n\n // Calculate timeout delay: refresh SESSION_EXPIRATION_BUFFER seconds before expiration\n const timeoutDelayMS = calculateTimeoutDelay(sessionPayload.exp, SESSION_EXPIRATION_BUFFER);\n\n // Prevent scheduling if timeout is negative (token already expired)\n // Allow 0ms delays to handle edge cases where we're exactly at the refresh point\n // This prevents immediate re-scheduling that could cause infinite loops\n if (timeoutDelayMS < 0) {\n return;\n }\n\n // Having this function outside timeout, allows us to call refresh immediately when back online\n const refresher = async () => {\n // Clear timeoutId since we're executing now\n timeoutId = null;\n\n if (!isOnline) {\n // Keep closure of refresh function alive\n this.pendingRefresher = refresher;\n return;\n }\n\n const result = await this.refreshSession({ signal: abortController.signal });\n\n if ('error' in result) {\n // If the refresh was aborted (e.g., due to React strict mode unmounting),\n // don't treat it as an error - just return and let the component remount handle it\n if (result.error === 'aborted') {\n return;\n }\n // For real errors, update the store\n this.store.setState({\n status: 'error',\n user: null,\n error: result.error,\n });\n return;\n } else {\n // After successful refresh, schedule the next refresh with the new token\n refresh();\n }\n };\n\n timeoutId = window.setTimeout(refresher, timeoutDelayMS);\n };\n\n refresh();\n\n return () => {\n if (timeoutId) {\n window.clearTimeout(timeoutId);\n }\n abortController.abort();\n window.removeEventListener('online', onlineHandler);\n window.removeEventListener('offline', offlineHandler);\n };\n }\n\n private async refreshSession({ signal }: { signal?: AbortSignal } = {}) {\n if (signal) {\n // Add signal to tracking set (was using .has() instead of .add() - bug fix)\n this.refreshingSignals.add(signal);\n\n signal.addEventListener('abort', () => {\n this.refreshingSignals.delete(signal);\n\n if (this.refreshingSignals.size === 0) {\n this.refreshingSignalAbortController?.abort();\n }\n });\n }\n\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n this.refreshingSignalAbortController = new AbortController();\n\n this.refreshingSignalAbortController.signal.addEventListener('abort', () => {\n this.refreshPromise = null;\n this.refreshingSignalAbortController = null;\n this.refreshingSignals.clear();\n });\n\n // Get localhost_jwt from cookie to send as query parameter (only for non-live environments)\n const localhostJWT = !this.isLive ? Cookies.get(LOCALHOST_JWT_COOKIE_NAME) : undefined;\n\n // Build query parameters - only include __lh_jwt for non-live environments when cookie exists\n const queryParams: { __lh_jwt?: string } = {};\n if (localhostJWT) {\n queryParams.__lh_jwt = localhostJWT;\n }\n\n // Use local client to avoid infinite recursion. Regular client calls getSessionToken() which calls refreshSession().\n // There are hacks to avoid infinite recursion, but they are not reliable.\n // The localhost_jwt is sent as a query parameter only in non-live environments\n // Note: Type assertion needed because the generated SDK type doesn't include 'query' in RequestInit,\n // but the underlying CoreClient.request() method does support it\n this.refreshPromise = this.localClient.auth\n .refresh(queryParams, {\n signal: this.refreshingSignalAbortController.signal,\n })\n .then((response) => {\n // Update cookie with new session token from response body\n // Server also sets it via Set-Cookie header on auth domain, but we set it manually on customer domain\n if (!this.isLive) {\n this.setCookie(SESSION_COOKIE_NAME, response.sessionToken, {\n maxAge: 30 * 24 * 60 * 60, // 30 days\n });\n }\n return response;\n })\n .catch(this.handleRequestError);\n\n try {\n return await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n this.refreshingSignalAbortController = null;\n this.refreshingSignals.clear();\n }\n }\n}\n"],"names":["SESSION_COOKIE_NAME","LOCALHOST_JWT_URL_PARAM_NAME","LOCALHOST_JWT_COOKIE_NAME","SESSION_EXPIRATION_BUFFER","SECONDS_TO_MS","secondsToMilliseconds","seconds","millisecondsToSeconds","ms","nowInSeconds","jwtExpToMilliseconds","exp","calculateTimeoutDelay","expirationSeconds","bufferSeconds","expirationMS","bufferMS","nowMS","isExpiredIn","expiration","buffer","now","AuthSessionService","isLive","client","store","baseURL","publishableKey","Blimu","name","value","options","cookieOptions","Cookies","token","jwtDecode","sessionPayload","error","BlimuError","signal","url","localhostJWT","result","abortController","isOnline","timeoutId","onlineHandler","offlineHandler","refresh","timeoutDelayMS","refresher","queryParams","response"],"mappings":";;;AAQO,MAAMA,IAAsB,iBACtBC,IAA+B,YAC/BC,IAA4B,YAC5BC,IAA4B,IAMnCC,IAAgB,KAKh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ACzD,QAAQ,MAAU,KAAK;AAAA;AAAA,IAAA,CACxB,GAEIA,EACR,EACA,MAAM,KAAK,kBAAkB;AAEhC,QAAI;AACF,aAAO,MAAM,KAAK;AAAA,IACpB,UAAA;AACE,WAAK,iBAAiB,MACtB,KAAK,kCAAkC,MACvC,KAAK,kBAAkB,MAAA;AAAA,IACzB;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"auth.service.js","sources":["../../src/client/auth.service.ts"],"sourcesContent":["import { Blimu, BlimuError } from '@blimu/client';\nimport type { RefreshResponse } from '@blimu/client/schema';\nimport Cookies from 'js-cookie';\nimport { jwtDecode } from 'jwt-decode';\n\nimport type { AuthState, User } from '../types';\nimport { ExternalStore } from './external-store';\n\nexport const SESSION_COOKIE_NAME = '__bli_session';\nexport const LOCALHOST_JWT_URL_PARAM_NAME = '__lh_jwt';\nexport const LOCALHOST_JWT_COOKIE_NAME = '__lh_jwt';\nexport const SESSION_EXPIRATION_BUFFER = 10;\n\n/**\n * Time conversion utilities\n * JWT tokens use seconds (Unix timestamp), JavaScript Date uses milliseconds\n */\nconst SECONDS_TO_MS = 1000;\n\n/**\n * Convert seconds to milliseconds\n */\nconst secondsToMilliseconds = (seconds: number): number => Math.floor(seconds * SECONDS_TO_MS);\n\n/**\n * Convert milliseconds to seconds\n */\nconst millisecondsToSeconds = (ms: number): number => Math.floor(ms / SECONDS_TO_MS);\n\n/**\n * Get current time in seconds (Unix timestamp)\n */\nconst nowInSeconds = (): number => millisecondsToSeconds(Date.now());\n\n/**\n * Convert JWT expiration time (seconds) to milliseconds\n */\nconst jwtExpToMilliseconds = (exp: number): number => secondsToMilliseconds(exp);\n\n/**\n * Calculate timeout delay in milliseconds for refreshing before expiration\n * @param expirationSeconds - JWT exp claim in seconds\n * @param bufferSeconds - Buffer time in seconds before expiration\n * @returns Timeout delay in milliseconds\n */\nconst calculateTimeoutDelay = (expirationSeconds: number, bufferSeconds: number): number => {\n const expirationMS = jwtExpToMilliseconds(expirationSeconds);\n const bufferMS = secondsToMilliseconds(bufferSeconds);\n const nowMS = Date.now();\n return Math.max(expirationMS - bufferMS - nowMS, 0);\n};\n\n/**\n * Check if a JWT expiration time (in seconds) is expired or will expire within the buffer\n * @param expiration - JWT exp claim in seconds (Unix timestamp)\n * @param buffer - Buffer time in seconds before expiration to consider it expired\n * @returns true if expired or will expire within buffer\n */\nexport const isExpiredIn = (expiration: number, buffer: number): boolean => {\n const now = nowInSeconds();\n return expiration - buffer < now;\n};\n\nexport class AuthSessionService {\n private pendingRefresher: (() => void) | null = null;\n private refreshPromise: Promise<RefreshResponse | { error: string; user: null }> | null = null;\n private refreshingSignals: Set<AbortSignal> = new Set();\n private refreshingSignalAbortController: AbortController | null = null;\n // A local client that doesn't call getSessionToken() which calls refreshSession().\n private localClient: Blimu;\n\n constructor(\n private readonly isLive: boolean,\n private readonly client: Blimu,\n private readonly store: ExternalStore<AuthState>,\n baseURL: string,\n publishableKey: string,\n ) {\n this.localClient = new Blimu({\n baseURL,\n credentials: 'include',\n headers: { 'x-blimu-publishable-key': publishableKey },\n });\n this.handleRequestError = this.handleRequestError.bind(this);\n }\n\n /**\n * Set cookie with appropriate security settings based on environment\n */\n private setCookie(name: string, value: string, options: { maxAge?: number } = {}): void {\n const cookieOptions: Cookies.CookieAttributes = {\n secure: this.isLive, // true for live environments, false for localhost\n sameSite: 'lax',\n path: '/',\n };\n\n if (options.maxAge !== undefined) {\n cookieOptions.expires = options.maxAge / (24 * 60 * 60); // Convert seconds to days\n }\n\n Cookies.set(name, value, cookieOptions);\n }\n\n getSessionPayload(): {\n sub: string;\n environmentId: string;\n type: string;\n iat: number;\n exp: number;\n } | null {\n const token = Cookies.get(SESSION_COOKIE_NAME);\n\n if (!token) {\n return null;\n }\n\n const decoded = jwtDecode<{\n sub: string;\n environmentId: string;\n type: string;\n iat: number;\n exp: number;\n }>(token);\n\n return decoded;\n }\n\n async getSessionToken(): Promise<string | undefined> {\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload) {\n return undefined;\n }\n\n // If a refresh is already in progress, wait for it to complete\n // This prevents infinite recursion when refreshSession() calls client.auth.refresh()\n // which triggers accessToken() which calls getSessionToken()\n if (this.refreshPromise) {\n await this.refreshPromise;\n // After refresh completes, return the updated token from cookie\n return Cookies.get(SESSION_COOKIE_NAME);\n }\n\n if (isExpiredIn(sessionPayload.exp, 0)) {\n await this.refreshSession();\n }\n\n return Cookies.get(SESSION_COOKIE_NAME);\n }\n\n async handleRequestError(error: unknown): Promise<{ error: string; user: null }> {\n if (error instanceof BlimuError && [401, 500].includes(error.status)) {\n Cookies.remove(SESSION_COOKIE_NAME);\n Cookies.remove(LOCALHOST_JWT_COOKIE_NAME);\n\n return {\n error: error.message,\n user: null,\n };\n }\n\n if (error instanceof DOMException)\n return {\n error: error.message,\n user: null,\n };\n\n if (error instanceof Error) {\n return {\n error: error.message,\n user: null,\n };\n }\n\n return {\n error: 'unknown error',\n user: null,\n };\n }\n\n async initialize({ signal }: { signal?: AbortSignal } = {}): Promise<{\n error: string | null;\n user: User | null;\n }> {\n const url = new URL(window.location.href);\n const localhostJWT = url.searchParams.get(LOCALHOST_JWT_URL_PARAM_NAME) ?? undefined;\n\n // Clean up URL parameters immediately to prevent re-processing on re-renders\n if (localhostJWT) {\n url.searchParams.delete(LOCALHOST_JWT_URL_PARAM_NAME);\n window.history.replaceState({}, '', url.toString());\n }\n\n // Handle localhost JWT from URL parameter\n if (localhostJWT) {\n // Set localhost JWT cookie on customer app domain\n this.setCookie(LOCALHOST_JWT_COOKIE_NAME, localhostJWT, {\n maxAge: 30 * 24 * 60 * 60, // 30 days\n });\n }\n\n const localhostJWTCookie = Cookies.get(LOCALHOST_JWT_COOKIE_NAME);\n\n console.log('localhostJWTCookie', localhostJWTCookie);\n\n if (localhostJWTCookie && !Cookies.get(SESSION_COOKIE_NAME)) {\n const result = await this.refreshSession({ signal }).catch(this.handleRequestError);\n if ('error' in result) return result;\n }\n\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload) {\n return {\n error: null,\n user: null,\n };\n }\n\n if (isExpiredIn(sessionPayload.exp, SESSION_EXPIRATION_BUFFER)) {\n const result = await this.refreshSession().catch(this.handleRequestError);\n if ('error' in result) return result;\n }\n\n const result = await this.client.auth.getSession().catch(this.handleRequestError);\n if ('error' in result) return result;\n\n return {\n error: null,\n user: result.user,\n };\n }\n\n scheduleRefresh() {\n const abortController = new AbortController();\n let isOnline = true;\n let timeoutId: number | null = null;\n\n const onlineHandler = () => {\n isOnline = true;\n if (this.pendingRefresher) {\n this.pendingRefresher();\n this.pendingRefresher = null;\n }\n };\n const offlineHandler = () => {\n isOnline = false;\n };\n\n window.addEventListener('online', onlineHandler);\n window.addEventListener('offline', offlineHandler);\n\n const refresh = () => {\n // Clear any existing timeout before scheduling a new one\n // This prevents infinite loops when refresh() is called recursively\n if (timeoutId !== null) {\n window.clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n const sessionPayload = this.getSessionPayload();\n\n if (!sessionPayload || isExpiredIn(sessionPayload.exp, 0)) return;\n\n // Calculate timeout delay: refresh SESSION_EXPIRATION_BUFFER seconds before expiration\n const timeoutDelayMS = calculateTimeoutDelay(sessionPayload.exp, SESSION_EXPIRATION_BUFFER);\n\n // Prevent scheduling if timeout is negative (token already expired)\n // Allow 0ms delays to handle edge cases where we're exactly at the refresh point\n // This prevents immediate re-scheduling that could cause infinite loops\n if (timeoutDelayMS < 0) {\n return;\n }\n\n // Having this function outside timeout, allows us to call refresh immediately when back online\n const refresher = async () => {\n // Clear timeoutId since we're executing now\n timeoutId = null;\n\n if (!isOnline) {\n // Keep closure of refresh function alive\n this.pendingRefresher = refresher;\n return;\n }\n\n const result = await this.refreshSession({ signal: abortController.signal });\n\n if ('error' in result) {\n // If the refresh was aborted (e.g., due to React strict mode unmounting),\n // don't treat it as an error - just return and let the component remount handle it\n if (result.error === 'aborted') {\n return;\n }\n // For real errors, update the store\n this.store.setState({\n status: 'error',\n user: null,\n error: result.error,\n });\n return;\n } else {\n // After successful refresh, schedule the next refresh with the new token\n refresh();\n }\n };\n\n timeoutId = window.setTimeout(refresher, timeoutDelayMS);\n };\n\n refresh();\n\n return () => {\n if (timeoutId) {\n window.clearTimeout(timeoutId);\n }\n abortController.abort();\n window.removeEventListener('online', onlineHandler);\n window.removeEventListener('offline', offlineHandler);\n };\n }\n\n private async refreshSession({ signal }: { signal?: AbortSignal } = {}) {\n if (signal) {\n // Add signal to tracking set (was using .has() instead of .add() - bug fix)\n this.refreshingSignals.add(signal);\n\n signal.addEventListener('abort', () => {\n this.refreshingSignals.delete(signal);\n\n if (this.refreshingSignals.size === 0) {\n this.refreshingSignalAbortController?.abort();\n }\n });\n }\n\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n this.refreshingSignalAbortController = new AbortController();\n\n this.refreshingSignalAbortController.signal.addEventListener('abort', () => {\n this.refreshPromise = null;\n this.refreshingSignalAbortController = null;\n this.refreshingSignals.clear();\n });\n\n // Get localhost_jwt from cookie to send as query parameter (only for non-live environments)\n const localhostJWT = !this.isLive ? Cookies.get(LOCALHOST_JWT_COOKIE_NAME) : undefined;\n\n // Build query parameters - only include __lh_jwt for non-live environments when cookie exists\n const queryParams: { __lh_jwt?: string } = {};\n if (localhostJWT) {\n queryParams.__lh_jwt = localhostJWT;\n }\n\n // Use local client to avoid infinite recursion. Regular client calls getSessionToken() which calls refreshSession().\n // There are hacks to avoid infinite recursion, but they are not reliable.\n // The localhost_jwt is sent as a query parameter only in non-live environments\n // Note: Type assertion needed because the generated SDK type doesn't include 'query' in RequestInit,\n // but the underlying CoreClient.request() method does support it\n this.refreshPromise = this.localClient.auth\n .refresh(queryParams, {\n signal: this.refreshingSignalAbortController.signal,\n })\n .then((response) => {\n // Update cookie with new session token from response body\n // Server also sets it via Set-Cookie header on auth domain, but we set it manually on customer domain\n if (!this.isLive) {\n this.setCookie(SESSION_COOKIE_NAME, response.sessionToken, {\n maxAge: 30 * 24 * 60 * 60, // 30 days\n });\n }\n return response;\n })\n .catch(this.handleRequestError);\n\n try {\n return await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n this.refreshingSignalAbortController = null;\n this.refreshingSignals.clear();\n }\n }\n}\n"],"names":["SESSION_COOKIE_NAME","LOCALHOST_JWT_URL_PARAM_NAME","LOCALHOST_JWT_COOKIE_NAME","SESSION_EXPIRATION_BUFFER","SECONDS_TO_MS","secondsToMilliseconds","seconds","millisecondsToSeconds","ms","nowInSeconds","jwtExpToMilliseconds","exp","calculateTimeoutDelay","expirationSeconds","bufferSeconds","expirationMS","bufferMS","nowMS","isExpiredIn","expiration","buffer","now","AuthSessionService","isLive","client","store","baseURL","publishableKey","Blimu","name","value","options","cookieOptions","Cookies","token","jwtDecode","sessionPayload","error","BlimuError","signal","url","localhostJWT","localhostJWTCookie","result","abortController","isOnline","timeoutId","onlineHandler","offlineHandler","refresh","timeoutDelayMS","refresher","queryParams","response"],"mappings":";;;AAQO,MAAMA,IAAsB,iBACtBC,IAA+B,YAC/BC,IAA4B,YAC5BC,IAA4B,IAMnCC,IAAgB,KAKhBC,IAAwB,CAACC,MAA4B,KAAK,MAAMA,IAAUF,CAAa,GAKvFG,IAAwB,CAACC,MAAuB,KAAK,MAAMA,IAAKJ,CAAa,GAK7EK,IAAe,MAAcF,EAAsB,KAAK,KAAK,GAK7DG,IAAuB,CAACC,MAAwBN,EAAsBM,CAAG,GAQzEC,IAAwB,CAACC,GAA2BC,MAAkC;AAC1F,QAAMC,IAAeL,EAAqBG,CAAiB,GACrDG,IAAWX,EAAsBS,CAAa,GAC9CG,IAAQ,KAAK,IAAA;AACnB,SAAO,KAAK,IAAIF,IAAeC,IAAWC,GAAO,CAAC;AACpD,GAQaC,IAAc,CAACC,GAAoBC,MAA4B;AAC1E,QAAMC,IAAMZ,EAAA;AACZ,SAAOU,IAAaC,IAASC;AAC/B;AAEO,MAAMC,EAAmB;AAAA,EAQ9B,YACmBC,GACAC,GACAC,GACjBC,GACAC,GACA;AALiB,SAAA,SAAAJ,GACA,K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AE,QAAAT,EAAA,IAAqC,IAAI;AActE,QAbIA,MAEF,KAAK,kBAAkB,IAAIA,CAAM,GAEjCA,EAAO,iBAAiB,SAAS,MAAM;AACrC,WAAK,kBAAkB,OAAOA,CAAM,GAEhC,KAAK,kBAAkB,SAAS,KAClC,KAAK,iCAAiC,MAAA;AAAA,IAE1C,CAAC,IAGC,KAAK;AACP,aAAO,KAAK;AAGd,SAAK,kCAAkC,IAAI,gBAAA,GAE3C,KAAK,gCAAgC,OAAO,iBAAiB,SAAS,MAAM;AAC1E,WAAK,iBAAiB,MACtB,KAAK,kCAAkC,MACvC,KAAK,kBAAkB,MAAA;AAAA,IACzB,CAAC;AAGD,UAAME,IAAgB,KAAK,SAAkD,SAAzCR,EAAQ,IAAI/B,CAAyB,GAGnEkD,IAAqC,CAAA;AAC3C,IAAIX,MACFW,EAAY,WAAWX,IAQzB,KAAK,iBAAiB,KAAK,YAAY,KACpC,QAAQW,GAAa;AAAA,MACpB,QAAQ,KAAK,gCAAgC;AAAA,IAAA,CAC9C,EACA,KAAK,CAACC,OAGA,KAAK,UACR,KAAK,UAAUrD,GAAqBqD,EAAS,cAAc;AAAA,MACzD,QAAQ,MAAU,KAAK;AAAA;AAAA,IAAA,CACxB,GAEIA,EACR,EACA,MAAM,KAAK,kBAAkB;AAEhC,QAAI;AACF,aAAO,MAAM,KAAK;AAAA,IACpB,UAAA;AACE,WAAK,iBAAiB,MACtB,KAAK,kCAAkC,MACvC,KAAK,kBAAkB,MAAA;AAAA,IACzB;AAAA,EACF;AACF;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("@blimu/client"),r=require("../utils/publishable-key.cjs"),o=require("./auth.service.cjs"),a=require("./external-store.cjs");class u{constructor(e){if(this.authDomain=null,this.initialized=!1,this.initializePromise=null,this.initializeAbortController=null,this.redirectToAuth=i=>{const n=i||window.location.href,s=new URL(`${this.authDomain}/login`);s.searchParams.set("redirect_url",encodeURIComponent(n)),window.location.href=s.toString()},this.logout=async()=>{try{const i=this.session.getSessionToken();i&&await this.client.auth.logout({headers:{"x-blimu-publishable-key":this.config.publishableKey,Authorization:`Bearer ${i}`}})}catch(i){console.error("Logout error:",i)}finally{this.store.setState({user:null,error:null,status:"unauthenticated"})}},this.getAccessToken=async i=>await this.session.getSessionToken()??null,this.config=e,this.store=new a.ExternalStore({user:null,error:null,status:"idle"}),this.isLive=e.publishableKey.includes("live"),this.authDomain=r.getAuthDomainFromPublishableKey(e.publishableKey),!this.authDomain)throw new Error("Failed to determine auth domain from publishable key");const t=r.getAuthApiUrl(e.publishableKey);if(!t)throw new Error("Failed to determine auth API URL from publishable key");this.client=new l.Blimu({baseURL:t,
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("@blimu/client"),r=require("../utils/publishable-key.cjs"),o=require("./auth.service.cjs"),a=require("./external-store.cjs");class u{constructor(e){if(this.authDomain=null,this.initialized=!1,this.initializePromise=null,this.initializeAbortController=null,this.redirectToAuth=i=>{const n=i||window.location.href,s=new URL(`${this.authDomain}/login`);s.searchParams.set("redirect_url",encodeURIComponent(n)),window.location.href=s.toString()},this.logout=async()=>{try{const i=this.session.getSessionToken();i&&await this.client.auth.logout({headers:{"x-blimu-publishable-key":this.config.publishableKey,Authorization:`Bearer ${i}`}})}catch(i){console.error("Logout error:",i)}finally{this.store.setState({user:null,error:null,status:"unauthenticated"})}},this.getAccessToken=async i=>await this.session.getSessionToken()??null,this.config=e,this.store=new a.ExternalStore({user:null,error:null,status:"idle"}),this.isLive=e.publishableKey.includes("live"),this.authDomain=r.getAuthDomainFromPublishableKey(e.publishableKey),!this.authDomain)throw new Error("Failed to determine auth domain from publishable key");const t=r.getAuthApiUrl(e.publishableKey);if(!t)throw new Error("Failed to determine auth API URL from publishable key");this.client=new l.Blimu({baseURL:t,bearer:()=>this.session.getSessionToken(),headers:{"x-blimu-publishable-key":e.publishableKey}}),this.session=new o.AuthSessionService(this.isLive,this.client,this.store,t,e.publishableKey),this.initialize=this.initialize.bind(this)}initialize(){if(!this.initialized&&!this.initializePromise)return this.initializeAbortController=new AbortController,this.initializePromise=this.session.initialize({signal:this.initializeAbortController.signal}).then(e=>{e.error?this.store.setState({user:null,error:e.error,status:"error"}):e.user?this.store.setState({user:e.user,error:null,status:"authenticated"}):this.store.setState({user:null,error:null,status:"unauthenticated"})}).catch(e=>{console.error("Initialize error:",e),this.store.setState({user:null,error:e instanceof Error?e.message:"Initialization failed",status:"error"})}).finally(()=>{this.initialized=!0,this.initializePromise=null}),()=>{console.log("aborting initialize"),this.initializeAbortController?.abort("unmounting"),this.initializePromise=null}}scheduleRefresh(){return this.session.scheduleRefresh()}getClient(){return this.client}}exports.BlimuRuntimeClientWrapper=u;
|
|
2
2
|
//# sourceMappingURL=runtime-client.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-client.cjs","sources":["../../src/client/runtime-client.ts"],"sourcesContent":["import { Blimu } from '@blimu/client';\n\nimport type { AuthState, BlimuConfig, User } from '../types';\nimport { getAuthApiUrl, getAuthDomainFromPublishableKey } from '../utils/publishable-key';\nimport { AuthSessionService, LOCALHOST_JWT_URL_PARAM_NAME } from './auth.service';\nimport { ExternalStore } from './external-store';\n\nexport class BlimuRuntimeClientWrapper {\n private client: Blimu;\n private authDomain: string | null = null;\n private initialized: boolean = false;\n private readonly session: AuthSessionService;\n\n public config: BlimuConfig;\n public isLive: boolean;\n private initializePromise: Promise<void> | null = null;\n private initializeAbortController: AbortController | null = null;\n\n public readonly store: ExternalStore<AuthState>;\n\n constructor(config: BlimuConfig) {\n this.config = config;\n this.store = new ExternalStore<AuthState>({\n user: null,\n error: null,\n status: 'idle',\n });\n this.isLive = config.publishableKey.includes('live');\n\n // Get auth UI domain from publishable key\n this.authDomain = getAuthDomainFromPublishableKey(config.publishableKey);\n if (!this.authDomain) {\n throw new Error('Failed to determine auth domain from publishable key');\n }\n\n // Get auth API URL from publishable key\n const authApiUrl = getAuthApiUrl(config.publishableKey);\n\n if (!authApiUrl) {\n throw new Error('Failed to determine auth API URL from publishable key');\n }\n\n this.client = new Blimu({\n baseURL: authApiUrl,\n
|
|
1
|
+
{"version":3,"file":"runtime-client.cjs","sources":["../../src/client/runtime-client.ts"],"sourcesContent":["import { Blimu } from '@blimu/client';\n\nimport type { AuthState, BlimuConfig, User } from '../types';\nimport { getAuthApiUrl, getAuthDomainFromPublishableKey } from '../utils/publishable-key';\nimport { AuthSessionService, LOCALHOST_JWT_URL_PARAM_NAME } from './auth.service';\nimport { ExternalStore } from './external-store';\n\nexport class BlimuRuntimeClientWrapper {\n private client: Blimu;\n private authDomain: string | null = null;\n private initialized: boolean = false;\n private readonly session: AuthSessionService;\n\n public config: BlimuConfig;\n public isLive: boolean;\n private initializePromise: Promise<void> | null = null;\n private initializeAbortController: AbortController | null = null;\n\n public readonly store: ExternalStore<AuthState>;\n\n constructor(config: BlimuConfig) {\n this.config = config;\n this.store = new ExternalStore<AuthState>({\n user: null,\n error: null,\n status: 'idle',\n });\n this.isLive = config.publishableKey.includes('live');\n\n // Get auth UI domain from publishable key\n this.authDomain = getAuthDomainFromPublishableKey(config.publishableKey);\n if (!this.authDomain) {\n throw new Error('Failed to determine auth domain from publishable key');\n }\n\n // Get auth API URL from publishable key\n const authApiUrl = getAuthApiUrl(config.publishableKey);\n\n if (!authApiUrl) {\n throw new Error('Failed to determine auth API URL from publishable key');\n }\n\n this.client = new Blimu({\n baseURL: authApiUrl,\n bearer: () => this.session.getSessionToken(),\n headers: { 'x-blimu-publishable-key': config.publishableKey },\n });\n\n this.session = new AuthSessionService(\n this.isLive,\n this.client,\n this.store,\n authApiUrl,\n config.publishableKey,\n );\n\n this.initialize = this.initialize.bind(this);\n }\n\n /**\n * Initialize authentication by checking for existing session\n * Reads session token from cookie and validates it\n * This method is idempotent - if initialization is already in progress, it will wait for that to complete\n */\n initialize(): (() => void) | void {\n // If already initialized, return early\n if (this.initialized) return;\n\n // If initialization is in progress, return early (prevents concurrent calls)\n if (this.initializePromise) return;\n\n this.initializeAbortController = new AbortController();\n\n this.initializePromise = this.session\n .initialize({\n signal: this.initializeAbortController.signal,\n })\n .then((result) => {\n if (result.error) {\n this.store.setState({\n user: null,\n error: result.error,\n status: 'error',\n });\n } else if (result.user) {\n this.store.setState({\n user: result.user,\n error: null,\n status: 'authenticated',\n });\n } else {\n this.store.setState({\n user: null,\n error: null,\n status: 'unauthenticated',\n });\n }\n })\n .catch((error) => {\n console.error('Initialize error:', error);\n this.store.setState({\n user: null,\n error: error instanceof Error ? error.message : 'Initialization failed',\n status: 'error',\n });\n })\n .finally(() => {\n // Mark as initialized after completion (success or failure)\n // This prevents infinite loops from re-renders\n this.initialized = true;\n this.initializePromise = null;\n });\n\n return () => {\n console.log('aborting initialize');\n this.initializeAbortController?.abort('unmounting');\n this.initializePromise = null;\n // Don't reset initialized flag here - let the promise handle it\n };\n }\n\n /**\n * Refresh session token using the client token from httpOnly cookie\n * The client token is stored in an httpOnly cookie and sent automatically\n * Note: The auth worker should extract the __bli_client cookie and include it in the request body\n * This method is idempotent - if a refresh is already in progress, it will wait for that refresh to complete\n */\n public scheduleRefresh() {\n return this.session.scheduleRefresh();\n }\n\n /**\n * Redirect user to auth domain for authentication\n * Uses the auth domain derived from the publishable key\n */\n public redirectToAuth = (returnUrl?: string): void => {\n const redirectUrl = returnUrl || window.location.href;\n\n // Build auth URL on the auth domain\n const authUrl = new URL(`${this.authDomain}/login`);\n authUrl.searchParams.set('redirect_url', encodeURIComponent(redirectUrl));\n\n // Redirect to auth domain\n window.location.href = authUrl.toString();\n };\n\n /**\n * Logout user\n * Calls the logout endpoint on the API domain using this.client\n */\n public logout = async (): Promise<void> => {\n try {\n const sessionToken = this.session.getSessionToken();\n\n if (sessionToken) {\n await this.client.auth.logout({\n headers: {\n 'x-blimu-publishable-key': this.config.publishableKey,\n Authorization: `Bearer ${sessionToken}`,\n },\n });\n }\n } catch (error) {\n console.error('Logout error:', error);\n } finally {\n this.store.setState({\n user: null,\n error: null,\n status: 'unauthenticated',\n });\n }\n };\n\n /**\n * Get the current session token\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getAccessToken = async (_options: { template: 'web' }): Promise<string | null> => {\n return (await this.session.getSessionToken()) ?? null;\n };\n\n /**\n * Get the runtime client for direct API calls\n */\n getClient(): Blimu {\n return this.client;\n }\n}\n"],"names":["BlimuRuntimeClientWrapper","config","returnUrl","redirectUrl","authUrl","sessionToken","error","_options","ExternalStore","getAuthDomainFromPublishableKey","authApiUrl","getAuthApiUrl","Blimu","AuthSessionService","result"],"mappings":"6NAOO,MAAMA,CAA0B,CAarC,YAAYC,EAAqB,CAW/B,GAtBF,KAAQ,WAA4B,KACpC,KAAQ,YAAuB,GAK/B,KAAQ,kBAA0C,KAClD,KAAQ,0BAAoD,KAuH5D,KAAO,eAAkBC,GAA6B,CACpD,MAAMC,EAAcD,GAAa,OAAO,SAAS,KAG3CE,EAAU,IAAI,IAAI,GAAG,KAAK,UAAU,QAAQ,EAClDA,EAAQ,aAAa,IAAI,eAAgB,mBAAmBD,CAAW,CAAC,EAGxE,OAAO,SAAS,KAAOC,EAAQ,SAAA,CACjC,EAMA,KAAO,OAAS,SAA2B,CACzC,GAAI,CACF,MAAMC,EAAe,KAAK,QAAQ,gBAAA,EAE9BA,GACF,MAAM,KAAK,OAAO,KAAK,OAAO,CAC5B,QAAS,CACP,0BAA2B,KAAK,OAAO,eACvC,cAAe,UAAUA,CAAY,EAAA,CACvC,CACD,CAEL,OAASC,EAAO,CACd,QAAQ,MAAM,gBAAiBA,CAAK,CACtC,QAAA,CACE,KAAK,MAAM,SAAS,CAClB,KAAM,KACN,MAAO,KACP,OAAQ,iBAAA,CACT,CACH,CACF,EAMA,KAAA,eAAiB,MAAOC,GACd,MAAM,KAAK,QAAQ,gBAAA,GAAsB,KA7JjD,KAAK,OAASN,EACd,KAAK,MAAQ,IAAIO,gBAAyB,CACxC,KAAM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I,qBAAqB,EACjC,KAAK,2BAA2B,MAAM,YAAY,EAClD,KAAK,kBAAoB,IAE3B,CACF,CAQO,iBAAkB,CACvB,OAAO,KAAK,QAAQ,gBAAA,CACtB,CAuDA,WAAmB,CACjB,OAAO,KAAK,MACd,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Blimu as
|
|
2
|
-
import { getAuthDomainFromPublishableKey as
|
|
1
|
+
import { Blimu as l } from "@blimu/client";
|
|
2
|
+
import { getAuthDomainFromPublishableKey as n, getAuthApiUrl as o } from "../utils/publishable-key.js";
|
|
3
3
|
import { AuthSessionService as a } from "./auth.service.js";
|
|
4
4
|
import { ExternalStore as h } from "./external-store.js";
|
|
5
5
|
class p {
|
|
@@ -29,14 +29,14 @@ class p {
|
|
|
29
29
|
user: null,
|
|
30
30
|
error: null,
|
|
31
31
|
status: "idle"
|
|
32
|
-
}), this.isLive = i.publishableKey.includes("live"), this.authDomain =
|
|
32
|
+
}), this.isLive = i.publishableKey.includes("live"), this.authDomain = n(i.publishableKey), !this.authDomain)
|
|
33
33
|
throw new Error("Failed to determine auth domain from publishable key");
|
|
34
34
|
const t = o(i.publishableKey);
|
|
35
35
|
if (!t)
|
|
36
36
|
throw new Error("Failed to determine auth API URL from publishable key");
|
|
37
|
-
this.client = new
|
|
37
|
+
this.client = new l({
|
|
38
38
|
baseURL: t,
|
|
39
|
-
|
|
39
|
+
bearer: () => this.session.getSessionToken(),
|
|
40
40
|
headers: { "x-blimu-publishable-key": i.publishableKey }
|
|
41
41
|
}), this.session = new a(
|
|
42
42
|
this.isLive,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-client.js","sources":["../../src/client/runtime-client.ts"],"sourcesContent":["import { Blimu } from '@blimu/client';\n\nimport type { AuthState, BlimuConfig, User } from '../types';\nimport { getAuthApiUrl, getAuthDomainFromPublishableKey } from '../utils/publishable-key';\nimport { AuthSessionService, LOCALHOST_JWT_URL_PARAM_NAME } from './auth.service';\nimport { ExternalStore } from './external-store';\n\nexport class BlimuRuntimeClientWrapper {\n private client: Blimu;\n private authDomain: string | null = null;\n private initialized: boolean = false;\n private readonly session: AuthSessionService;\n\n public config: BlimuConfig;\n public isLive: boolean;\n private initializePromise: Promise<void> | null = null;\n private initializeAbortController: AbortController | null = null;\n\n public readonly store: ExternalStore<AuthState>;\n\n constructor(config: BlimuConfig) {\n this.config = config;\n this.store = new ExternalStore<AuthState>({\n user: null,\n error: null,\n status: 'idle',\n });\n this.isLive = config.publishableKey.includes('live');\n\n // Get auth UI domain from publishable key\n this.authDomain = getAuthDomainFromPublishableKey(config.publishableKey);\n if (!this.authDomain) {\n throw new Error('Failed to determine auth domain from publishable key');\n }\n\n // Get auth API URL from publishable key\n const authApiUrl = getAuthApiUrl(config.publishableKey);\n\n if (!authApiUrl) {\n throw new Error('Failed to determine auth API URL from publishable key');\n }\n\n this.client = new Blimu({\n baseURL: authApiUrl,\n
|
|
1
|
+
{"version":3,"file":"runtime-client.js","sources":["../../src/client/runtime-client.ts"],"sourcesContent":["import { Blimu } from '@blimu/client';\n\nimport type { AuthState, BlimuConfig, User } from '../types';\nimport { getAuthApiUrl, getAuthDomainFromPublishableKey } from '../utils/publishable-key';\nimport { AuthSessionService, LOCALHOST_JWT_URL_PARAM_NAME } from './auth.service';\nimport { ExternalStore } from './external-store';\n\nexport class BlimuRuntimeClientWrapper {\n private client: Blimu;\n private authDomain: string | null = null;\n private initialized: boolean = false;\n private readonly session: AuthSessionService;\n\n public config: BlimuConfig;\n public isLive: boolean;\n private initializePromise: Promise<void> | null = null;\n private initializeAbortController: AbortController | null = null;\n\n public readonly store: ExternalStore<AuthState>;\n\n constructor(config: BlimuConfig) {\n this.config = config;\n this.store = new ExternalStore<AuthState>({\n user: null,\n error: null,\n status: 'idle',\n });\n this.isLive = config.publishableKey.includes('live');\n\n // Get auth UI domain from publishable key\n this.authDomain = getAuthDomainFromPublishableKey(config.publishableKey);\n if (!this.authDomain) {\n throw new Error('Failed to determine auth domain from publishable key');\n }\n\n // Get auth API URL from publishable key\n const authApiUrl = getAuthApiUrl(config.publishableKey);\n\n if (!authApiUrl) {\n throw new Error('Failed to determine auth API URL from publishable key');\n }\n\n this.client = new Blimu({\n baseURL: authApiUrl,\n bearer: () => this.session.getSessionToken(),\n headers: { 'x-blimu-publishable-key': config.publishableKey },\n });\n\n this.session = new AuthSessionService(\n this.isLive,\n this.client,\n this.store,\n authApiUrl,\n config.publishableKey,\n );\n\n this.initialize = this.initialize.bind(this);\n }\n\n /**\n * Initialize authentication by checking for existing session\n * Reads session token from cookie and validates it\n * This method is idempotent - if initialization is already in progress, it will wait for that to complete\n */\n initialize(): (() => void) | void {\n // If already initialized, return early\n if (this.initialized) return;\n\n // If initialization is in progress, return early (prevents concurrent calls)\n if (this.initializePromise) return;\n\n this.initializeAbortController = new AbortController();\n\n this.initializePromise = this.session\n .initialize({\n signal: this.initializeAbortController.signal,\n })\n .then((result) => {\n if (result.error) {\n this.store.setState({\n user: null,\n error: result.error,\n status: 'error',\n });\n } else if (result.user) {\n this.store.setState({\n user: result.user,\n error: null,\n status: 'authenticated',\n });\n } else {\n this.store.setState({\n user: null,\n error: null,\n status: 'unauthenticated',\n });\n }\n })\n .catch((error) => {\n console.error('Initialize error:', error);\n this.store.setState({\n user: null,\n error: error instanceof Error ? error.message : 'Initialization failed',\n status: 'error',\n });\n })\n .finally(() => {\n // Mark as initialized after completion (success or failure)\n // This prevents infinite loops from re-renders\n this.initialized = true;\n this.initializePromise = null;\n });\n\n return () => {\n console.log('aborting initialize');\n this.initializeAbortController?.abort('unmounting');\n this.initializePromise = null;\n // Don't reset initialized flag here - let the promise handle it\n };\n }\n\n /**\n * Refresh session token using the client token from httpOnly cookie\n * The client token is stored in an httpOnly cookie and sent automatically\n * Note: The auth worker should extract the __bli_client cookie and include it in the request body\n * This method is idempotent - if a refresh is already in progress, it will wait for that refresh to complete\n */\n public scheduleRefresh() {\n return this.session.scheduleRefresh();\n }\n\n /**\n * Redirect user to auth domain for authentication\n * Uses the auth domain derived from the publishable key\n */\n public redirectToAuth = (returnUrl?: string): void => {\n const redirectUrl = returnUrl || window.location.href;\n\n // Build auth URL on the auth domain\n const authUrl = new URL(`${this.authDomain}/login`);\n authUrl.searchParams.set('redirect_url', encodeURIComponent(redirectUrl));\n\n // Redirect to auth domain\n window.location.href = authUrl.toString();\n };\n\n /**\n * Logout user\n * Calls the logout endpoint on the API domain using this.client\n */\n public logout = async (): Promise<void> => {\n try {\n const sessionToken = this.session.getSessionToken();\n\n if (sessionToken) {\n await this.client.auth.logout({\n headers: {\n 'x-blimu-publishable-key': this.config.publishableKey,\n Authorization: `Bearer ${sessionToken}`,\n },\n });\n }\n } catch (error) {\n console.error('Logout error:', error);\n } finally {\n this.store.setState({\n user: null,\n error: null,\n status: 'unauthenticated',\n });\n }\n };\n\n /**\n * Get the current session token\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getAccessToken = async (_options: { template: 'web' }): Promise<string | null> => {\n return (await this.session.getSessionToken()) ?? null;\n };\n\n /**\n * Get the runtime client for direct API calls\n */\n getClient(): Blimu {\n return this.client;\n }\n}\n"],"names":["BlimuRuntimeClientWrapper","config","returnUrl","redirectUrl","authUrl","sessionToken","error","_options","ExternalStore","getAuthDomainFromPublishableKey","authApiUrl","getAuthApiUrl","Blimu","AuthSessionService","result"],"mappings":";;;;AAOO,MAAMA,EAA0B;AAAA,EAarC,YAAYC,GAAqB;AAW/B,QAtBF,KAAQ,aAA4B,MACpC,KAAQ,cAAuB,IAK/B,KAAQ,oBAA0C,MAClD,KAAQ,4BAAoD,MAuH5D,KAAO,iBAAiB,CAACC,MAA6B;AACpD,YAAMC,IAAcD,KAAa,OAAO,SAAS,MAG3CE,IAAU,IAAI,IAAI,GAAG,KAAK,UAAU,QAAQ;AAClD,MAAAA,EAAQ,aAAa,IAAI,gBAAgB,mBAAmBD,CAAW,CAAC,GAGxE,OAAO,SAAS,OAAOC,EAAQ,SAAA;AAAA,IACjC,GA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,MAAK,eAGL,MAAK;AAET,kBAAK,4BAA4B,IAAI,gBAAA,GAErC,KAAK,oBAAoB,KAAK,QAC3B,WAAW;AAAA,QACV,QAAQ,KAAK,0BAA0B;AAAA,MAAA,CACxC,EACA,KAAK,CAACa,MAAW;AAChB,QAAIA,EAAO,QACT,KAAK,MAAM,SAAS;AAAA,UAClB,MAAM;AAAA,UACN,OAAOA,EAAO;AAAA,UACd,QAAQ;AAAA,QAAA,CACT,IACQA,EAAO,OAChB,KAAK,MAAM,SAAS;AAAA,UAClB,MAAMA,EAAO;AAAA,UACb,OAAO;AAAA,UACP,QAAQ;AAAA,QAAA,CACT,IAED,KAAK,MAAM,SAAS;AAAA,UAClB,MAAM;AAAA,UACN,OAAO;AAAA,UACP,QAAQ;AAAA,QAAA,CACT;AAAA,MAEL,CAAC,EACA,MAAM,CAACR,MAAU;AAChB,gBAAQ,MAAM,qBAAqBA,CAAK,GACxC,KAAK,MAAM,SAAS;AAAA,UAClB,MAAM;AAAA,UACN,OAAOA,aAAiB,QAAQA,EAAM,UAAU;AAAA,UAChD,QAAQ;AAAA,QAAA,CACT;AAAA,MACH,CAAC,EACA,QAAQ,MAAM;AAGb,aAAK,cAAc,IACnB,KAAK,oBAAoB;AAAA,MAC3B,CAAC,GAEI,MAAM;AACX,gBAAQ,IAAI,qBAAqB,GACjC,KAAK,2BAA2B,MAAM,YAAY,GAClD,KAAK,oBAAoB;AAAA,MAE3B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,kBAAkB;AACvB,WAAO,KAAK,QAAQ,gBAAA;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA,EAuDA,YAAmB;AACjB,WAAO,KAAK;AAAA,EACd;AACF;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blimu/react",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "React components and hooks for Blimu authentication and authorization",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
}
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@blimu/client": "
|
|
47
|
+
"@blimu/client": "1.1.0",
|
|
48
48
|
"@radix-ui/react-avatar": "^1.1.11",
|
|
49
49
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
|
50
50
|
"@radix-ui/react-popover": "^1.1.15",
|