@pofsis-nbt/pofsis-auth 1.1.0 → 1.2.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/Documentation.md +1 -1
- package/dist/PofsisAuth.d.ts.map +1 -1
- package/dist/PofsisAuthClient-CRYYsJYc.cjs +2 -0
- package/dist/PofsisAuthClient-CRYYsJYc.cjs.map +1 -0
- package/dist/{PofsisAuthClient-DJSQb0qq.js → PofsisAuthClient-c9BY8iNp.js} +68 -20
- package/dist/PofsisAuthClient-c9BY8iNp.js.map +1 -0
- package/dist/{RequireAuth-BFjNqM_v.js → PofsisAuthModal-DGbtRZ4f.js} +95 -3
- package/dist/PofsisAuthModal-DGbtRZ4f.js.map +1 -0
- package/dist/{RequireAuth-n5Hb1WL9.cjs → PofsisAuthModal-DIzzLJSP.cjs} +2 -2
- package/dist/PofsisAuthModal-DIzzLJSP.cjs.map +1 -0
- package/dist/components/PofsisAuthModal.d.ts +3 -0
- package/dist/components/PofsisAuthModal.d.ts.map +1 -0
- package/dist/components/index.d.ts +1 -0
- package/dist/components/index.d.ts.map +1 -1
- package/dist/core/PofsisAuthClient.d.ts +4 -0
- package/dist/core/PofsisAuthClient.d.ts.map +1 -1
- package/dist/core/popupProtocol.d.ts.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/elements.cjs +1 -1
- package/dist/elements.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/pofsis-auth-elements.js +1 -1
- package/dist/pofsis-auth-elements.js.map +1 -1
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.js +2 -2
- package/dist/types.d.ts +15 -1
- package/dist/types.d.ts.map +1 -1
- package/docs/popup-integration.md +16 -0
- package/package.json +1 -1
- package/dist/PofsisAuthClient-B-07-cNX.cjs +0 -2
- package/dist/PofsisAuthClient-B-07-cNX.cjs.map +0 -1
- package/dist/PofsisAuthClient-DJSQb0qq.js.map +0 -1
- package/dist/RequireAuth-BFjNqM_v.js.map +0 -1
- package/dist/RequireAuth-n5Hb1WL9.cjs.map +0 -1
package/Documentation.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# POFSIS Auth Documentation
|
|
2
2
|
|
|
3
|
-
This is the complete public API and integration reference for `@pofsis-nbt/pofsis-auth@1.
|
|
3
|
+
This is the complete public API and integration reference for `@pofsis-nbt/pofsis-auth@1.2.0`.
|
|
4
4
|
|
|
5
5
|
The repository also includes an interactive [POFSIS Auth documentation portal](./index.html) with required environment configuration, generated setup examples, and authentication scenario links. The portal does not persist or transmit entered values and is intentionally excluded from the npm package.
|
|
6
6
|
|
package/dist/PofsisAuth.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PofsisAuth.d.ts","sourceRoot":"","sources":["../src/PofsisAuth.tsx"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAGR,eAAe,EAGlB,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"PofsisAuth.d.ts","sourceRoot":"","sources":["../src/PofsisAuth.tsx"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAGR,eAAe,EAGlB,MAAM,SAAS,CAAA;AAiMhB,wBAAgB,UAAU,CAAC,EACvB,QAAQ,EACR,OAAO,EACP,UAAU,EACV,OAAO,EACP,KAAK,EACL,YAAY,EACZ,KAAK,EACL,aAAmB,EACnB,UAAU,GACb,EAAE,eAAe,+BAiCjB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
async function e(e){if(e.status===204)return null;let t=await e.text();return t?JSON.parse(t):null}async function t(t,n,r){let i=await fetch(`${t.apiBaseUrl}${n}`,{credentials:`include`,...r,headers:{Accept:`application/json`,...r?.body&&!(r.body instanceof FormData)?{"Content-Type":`application/json`}:{},...r?.headers}});if(!i.ok){let e=Error(`Auth API ${n} failed (${i.status})`);throw e.status=i.status,e}return{status:i.status,data:await e(i)}}async function n(e){let{data:n}=await t(e,`/oauth/clients/${encodeURIComponent(e.appName.toUpperCase())}?origin=${encodeURIComponent(window.location.origin)}`);return n}async function r(e,n,r,i){let{data:a}=await t(e,`/oauth/token`,{method:`POST`,body:JSON.stringify({grant_type:`authorization_code`,client_id:i.client_id,redirect_uri:i.redirect_uri,code:n,code_verifier:r})});return a}async function i(e,n){let{data:r}=await t(e,`/oauth/token`,{method:`POST`,body:JSON.stringify({grant_type:`refresh_token`,client_id:n})});return r||null}async function a(e){try{return await t(e,`/auth/session`),!0}catch{return!1}}async function o(e){await t(e,`/auth/logout`,{method:`POST`})}async function s(e,n){let{data:r}=await t(e,`/auth/profile/me`,{headers:{Authorization:`Bearer ${n}`}});return r}async function c(e,n,r){let{data:i}=await t(e,`/auth/profile/me`,{method:`PATCH`,headers:{Authorization:`Bearer ${n}`},body:JSON.stringify(r)});return i}async function l(e,n,r,i){let a=new FormData;a.append(`file`,i);let{data:o}=await t(e,`/auth/profile/me/images/${r}`,{method:`POST`,headers:{Authorization:`Bearer ${n}`},body:a});return o}async function u(e,n,r){let{data:i}=await t(e,`/auth/profile/me/images/${r}`,{method:`DELETE`,headers:{Authorization:`Bearer ${n}`}});return i}function d(e){return e.replace(/\/$/,``)}function f(e={}){let t=e.appName?.trim(),n=e.apiBaseUrl?.trim(),r=e.authUrl?.trim(),i=e.scope?.trim()||`openid profile email`,a=e.callbackPath?.trim()||`/auth/callback`,o={width:e.popup?.width??480,height:e.popup?.height??720,name:e.popup?.name?.trim()||`pofsis-auth`,timeoutMs:e.popup?.timeoutMs??3e5},s=[];if(t||s.push(`appName`),n||s.push(`apiBaseUrl`),r||s.push(`authUrl`),s.length)throw Error(`@pofsis-nbt/pofsis-auth missing config: ${s.join(`, `)}`);if(!t||!n||!r)throw Error(`@pofsis-nbt/pofsis-auth missing config`);if(!a.startsWith(`/`)||a.startsWith(`//`))throw Error(`@pofsis-nbt/pofsis-auth callbackPath must be application-relative`);if(o.width<=0||o.height<=0||o.timeoutMs<=0)throw Error(`@pofsis-nbt/pofsis-auth popup dimensions and timeout must be positive`);return{appName:t,apiBaseUrl:d(n),authUrl:d(r),scope:i,callbackPath:a,popup:o}}var p=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,m=/^(?:\+63|63|0)?9\d{9}$/,h=new Set([`password`,`passkey`,`otp`]),g=new Set([`login`,`signup`,`reset`]),_=320;function v(e,t=!1){let n=typeof e==`string`?e.trim():``;if(!n||n.length>_)return;if(p.test(n))return n.toLowerCase();let r=n.replace(/[\s()-]/g,``);if(!t&&m.test(r))return`+63${r.replace(/^(?:\+63|63|0)/,``)}`}function y(e,t=`login`){let n=typeof e==`string`?{returnUrl:e}:e||{},r=n.screen===`register`?`signup`:n.screen,i=g.has(r)?r:t,a=h.has(n.method)?n.method:void 0,o=i===`login`||i===`signup`&&(a===`password`||a===`otp`)?a:void 0;return{returnUrl:n.returnUrl,screen:i,loginHint:v(n.loginHint),method:o}}function b(e){let t=new URLSearchParams(e),n=t.get(`login_hint`),r=n===null?v(t.get(`email`),!0):v(n);return y({screen:t.get(`screen`)||void 0,loginHint:r,method:t.get(`method`)||void 0})}function x({authUrl:e,appName:t,query:n,options:r}){let i=y(r),a=new URL(e);if(a.search=n.toString(),i.loginHint&&a.searchParams.set(`login_hint`,i.loginHint),i.screen===`login`&&i.method&&a.searchParams.set(`method`,i.method),i.screen===`login`)return a.toString();let o=i.screen===`signup`?`/signup`:`/forgot-password`,s=new URL(o,a);return s.searchParams.set(`app`,t),s.searchParams.set(`return_to`,`${a.pathname}${a.search}`),i.loginHint&&s.searchParams.set(`login_hint`,i.loginHint),i.screen===`signup`&&s.searchParams.set(`method`,i.method||`password`),s.toString()}var S=`pofsis-auth:callback`;function C(e){if(!e)return;let t=e.indexOf(`.`);return t>0?e.slice(0,t):void 0}function w(e=window.location.origin){let t=window.opener&&!window.opener.closed?window.opener:window.parent===window?null:window.parent;if(!t)return!1;let n=new URLSearchParams(window.location.search),r=n.get(`state`)||void 0,i={type:S,code:n.get(`code`)||void 0,state:r,error:n.get(`error`)||void 0,correlationId:C(r||null)};return t.postMessage(i,e),t===window.opener&&window.close(),!0}var T=e=>btoa(String.fromCharCode(...e)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``),E=()=>T(crypto.getRandomValues(new Uint8Array(32)));async function D(e){return T(new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))))}var O=e=>e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0,k=e=>({token_type:e.token_type,expires_in:e.expires_in,user:e.user}),A=class{config;token=null;session=null;client=null;clientPromise=null;refreshPromise=null;subscribers=new Set;attempt=null;iframeAttempt=null;listening=!1;constructor(e){this.config=f(e),this.attach()}attach(){this.listening||=(window.addEventListener(`message`,this.onPopupMessage),!0)}destroy(){window.removeEventListener(`message`,this.onPopupMessage),this.listening=!1;let e=this.finishAttempt();e&&(e.popup.close(),e.resolve({status:`cancelled`})),this.cancelIframeLogin(),this.subscribers.clear()}getUser(){return this.session?.user??null}getSession(){return this.session}getAccessToken(){return this.token}subscribe(e){return this.attach(),this.subscribers.add(e),e(this.session),()=>{this.subscribers.delete(e)}}emit(){for(let e of this.subscribers)e(this.session)}accept(e){this.token=e.access_token,this.session=k(e),this.emit()}loadClient(){return this.clientPromise||=n(this.config).then(e=>this.client=e).catch(e=>{throw this.clientPromise=null,e}),this.clientPromise}getOAuthClient(){return this.loadClient()}async refreshSession(){let e=await this.loadClient();return this.refreshPromise||=i(this.config,e.client_id).then(e=>{e?this.accept(e):this.clearSession()}).finally(()=>this.refreshPromise=null),this.refreshPromise}async isRemoteSessionActive(){return a(this.config)}clearSession(){this.token=null,this.session=null,this.emit()}replaceUser(e){this.session&&(this.session={...this.session,user:e},this.emit())}async logout(){try{await o(this.config)}finally{this.clearSession()}}signup(e={}){return this.login({...e,screen:`signup`})}resetPassword(e={}){return this.login({...e,screen:`reset`})}async login(e={}){let t=y(e),n=e.presentation??`popup`;return n===`popup`?this.openPopup({...e,...t}):n===`iframe`?this.openIframe({...e,...t}):this.startRedirect({...e,...t})}cancelIframeLogin(){this.finishIframeAttempt()?.resolve({status:`cancelled`})}openIframe(e){let t=e.target;if(!t)return Promise.reject(Error(`POFSIS Auth iframe target is required.`));this.cancelIframeLogin();let n=E(),r=`${n}.${E()}`,i=E(),a=O(e.returnUrl);return new Promise((o,s)=>{let c=setTimeout(()=>{this.finishIframeAttempt()?.reject(Error(`POFSIS Auth iframe timed out.`))},this.config.popup.timeoutMs);this.iframeAttempt={frame:t,state:r,verifier:i,correlationId:n,returnUrl:a,resolve:o,reject:s,timeout:c},this.authorizationUrl(e,r,i).then(e=>t.contentWindow?.location.replace(e)).catch(e=>{this.finishIframeAttempt()?.reject(e instanceof Error?e:Error(String(e)))})})}async authorizationUrl(e,t,n){let r=await this.loadClient(),i=new URLSearchParams({app:this.config.appName.toUpperCase(),client_id:r.client_id,redirect_uri:r.redirect_uri,response_type:`code`,scope:this.config.scope,state:t,code_challenge:await D(n),code_challenge_method:`S256`});return x({authUrl:this.config.authUrl,appName:this.config.appName.toUpperCase(),query:i,options:e})}storageKey(e){return`${this.config.appName.toLowerCase()}.auth.${e}`}async startRedirect(e){let t=E(),n=E();sessionStorage.setItem(this.storageKey(`state`),t),sessionStorage.setItem(this.storageKey(`verifier`),n);let r=O(e.returnUrl);return r?sessionStorage.setItem(this.storageKey(`return-path`),r):sessionStorage.removeItem(this.storageKey(`return-path`)),window.location.assign(await this.authorizationUrl(e,t,n)),{status:`redirecting`}}async openPopup(e){if(this.attempt&&!this.attempt.popup.closed)return this.attempt.popup.focus(),new Promise((e,t)=>{let n=this.attempt,r=n.resolve,i=n.reject;n.resolve=t=>{r(t),e(t)},n.reject=e=>{i(e),t(e)}});let{width:t,height:n,name:r,timeoutMs:i}=this.config.popup,a=Math.max(0,window.screenX+(window.outerWidth-t)/2),o=Math.max(0,window.screenY+(window.outerHeight-n)/2),s=window.open(`about:blank`,r,`popup=yes,width=${t},height=${n},left=${Math.round(a)},top=${Math.round(o)}`);if(!s)return this.startRedirect({...e,presentation:`redirect`});let c=E(),l=`${c}.${E()}`,u=E(),d=O(e.returnUrl);return new Promise((t,n)=>{let r=setInterval(()=>{s.closed&&this.finishAttempt()?.resolve({status:`cancelled`})},250),a=setTimeout(()=>{let e=this.finishAttempt();s.close(),e?.reject(Error(`POFSIS Auth popup timed out.`))},i);this.attempt={popup:s,state:l,verifier:u,correlationId:c,returnUrl:d,resolve:t,reject:n,timer:r,timeout:a},this.authorizationUrl(e,l,u).then(e=>s.location.replace(e)).catch(e=>{let t=this.finishAttempt();s.close(),t?.reject(e instanceof Error?e:Error(String(e)))})})}finishAttempt(){let e=this.attempt;return e?(clearInterval(e.timer),clearTimeout(e.timeout),this.attempt=null,e):null}finishIframeAttempt(){let e=this.iframeAttempt;return e?(clearTimeout(e.timeout),this.iframeAttempt=null,e):null}onPopupMessage=e=>{let t=this.iframeAttempt;if(t&&e.origin===window.location.origin&&e.source===t.frame.contentWindow&&e.data?.type===`pofsis-auth:callback`&&e.data.correlationId===t.correlationId&&C(e.data.state||null)===t.correlationId&&e.data.state===t.state){let t=this.finishIframeAttempt();if(e.data.error||!e.data.code){t.reject(Error(e.data.error||`POFSIS Auth callback was incomplete.`));return}this.completeCode(e.data.code,e.data.state,t.verifier).then(()=>t.resolve({status:`authenticated`,user:this.getUser()})).catch(e=>t.reject(e instanceof Error?e:Error(String(e))));return}let n=this.attempt,r=e.data;if(!n||e.origin!==window.location.origin||e.source!==n.popup||r?.type!==`pofsis-auth:callback`||r.correlationId!==n.correlationId||C(r.state||null)!==n.correlationId||r.state!==n.state)return;let i=this.finishAttempt();if(i){if(r.error||!r.code){i.popup.close(),i.reject(Error(r.error||`POFSIS Auth callback was incomplete.`));return}this.completeCode(r.code,r.state,i.verifier).then(()=>{i.popup.close(),i.returnUrl&&window.history.replaceState(null,``,i.returnUrl),i.resolve({status:`authenticated`,user:this.getUser()})}).catch(e=>{i.popup.close(),i.reject(e instanceof Error?e:Error(String(e)))})}};async completeCode(e,t,n){if(!t||!n)throw Error(`Authentication state could not be verified.`);let i=await this.loadClient();this.accept(await r(this.config,e,n,i))}async completeRedirectCallback(e,t){let n=sessionStorage.getItem(this.storageKey(`state`)),r=sessionStorage.getItem(this.storageKey(`verifier`));if(sessionStorage.removeItem(this.storageKey(`state`)),sessionStorage.removeItem(this.storageKey(`verifier`)),!n||!r||t!==n)throw Error(`Authentication state could not be verified.`);await this.completeCode(e,t,r)}};function j(e){return new A(e)}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return A}});
|
|
2
|
+
//# sourceMappingURL=PofsisAuthClient-CRYYsJYc.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PofsisAuthClient-CRYYsJYc.cjs","names":[],"sources":["../src/auth/api.ts","../src/auth/config.ts","../src/auth/authLaunch.ts","../src/core/popupProtocol.ts","../src/auth/pkce.ts","../src/core/PofsisAuthClient.ts"],"sourcesContent":["import type { AccountProfile, OAuthClientConfig, PofsisAuthConfig, TokenResponse } from '../types'\n\nasync function parseJson<T>(response: Response): Promise<T> {\n if (response.status === 204) return null as T\n const text = await response.text()\n if (!text) return null as T\n return JSON.parse(text) as T\n}\n\nasync function request<T>(\n config: PofsisAuthConfig,\n path: string,\n init?: RequestInit,\n): Promise<{ status: number; data: T }> {\n const response = await fetch(`${config.apiBaseUrl}${path}`, {\n credentials: 'include',\n ...init,\n headers: {\n Accept: 'application/json',\n ...(init?.body && !(init.body instanceof FormData)\n ? { 'Content-Type': 'application/json' }\n : {}),\n ...init?.headers,\n },\n })\n if (!response.ok) {\n const error = new Error(`Auth API ${path} failed (${response.status})`)\n ;(error as Error & { status?: number }).status = response.status\n throw error\n }\n return { status: response.status, data: await parseJson<T>(response) }\n}\n\nexport async function fetchOAuthClient(config: PofsisAuthConfig) {\n const identity = encodeURIComponent(config.appName.toUpperCase())\n const origin = encodeURIComponent(window.location.origin)\n const { data } = await request<OAuthClientConfig>(\n config,\n `/oauth/clients/${identity}?origin=${origin}`,\n )\n return data\n}\n\nexport async function exchangeCode(\n config: PofsisAuthConfig,\n code: string,\n verifier: string,\n client: Pick<OAuthClientConfig, 'client_id' | 'redirect_uri'>,\n) {\n const { data } = await request<TokenResponse>(config, '/oauth/token', {\n method: 'POST',\n body: JSON.stringify({\n grant_type: 'authorization_code',\n client_id: client.client_id,\n redirect_uri: client.redirect_uri,\n code,\n code_verifier: verifier,\n }),\n })\n return data\n}\n\nexport async function refresh(config: PofsisAuthConfig, clientId: string) {\n const { data } = await request<TokenResponse | null>(config, '/oauth/token', {\n method: 'POST',\n body: JSON.stringify({\n grant_type: 'refresh_token',\n client_id: clientId,\n }),\n })\n return data || null\n}\n\nexport async function checkSession(config: PofsisAuthConfig) {\n try {\n await request(config, '/auth/session')\n return true\n } catch {\n return false\n }\n}\n\nexport async function signOut(config: PofsisAuthConfig) {\n await request(config, '/auth/logout', { method: 'POST' })\n}\n\nexport async function getAccountProfile(config: PofsisAuthConfig, accessToken: string) {\n const { data } = await request<AccountProfile>(config, '/auth/profile/me', {\n headers: { Authorization: `Bearer ${accessToken}` },\n })\n return data\n}\n\nexport async function updateAccountProfile(\n config: PofsisAuthConfig,\n accessToken: string,\n profile: { firstName?: string | null; lastName?: string | null },\n) {\n const { data } = await request<AccountProfile>(config, '/auth/profile/me', {\n method: 'PATCH',\n headers: { Authorization: `Bearer ${accessToken}` },\n body: JSON.stringify(profile),\n })\n return data\n}\n\nexport async function uploadAccountProfileImage(\n config: PofsisAuthConfig,\n accessToken: string,\n kind: 'profile' | 'cover',\n file: File,\n) {\n const body = new FormData()\n body.append('file', file)\n const { data } = await request<AccountProfile>(config, `/auth/profile/me/images/${kind}`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${accessToken}` },\n body,\n })\n return data\n}\n\nexport async function deleteAccountProfileImage(\n config: PofsisAuthConfig,\n accessToken: string,\n kind: 'profile' | 'cover',\n) {\n const { data } = await request<AccountProfile>(config, `/auth/profile/me/images/${kind}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${accessToken}` },\n })\n return data\n}\n","import type { PofsisAuthClientConfig, ResolvedPofsisAuthConfig } from '../types'\n\nfunction stripTrailingSlash(value: string) {\n return value.replace(/\\/$/, '')\n}\n\nexport type ConfigOverrides = Partial<PofsisAuthClientConfig>\n\n/**\n * Validate and normalize explicitly supplied runtime configuration.\n */\nexport function resolveConfig(overrides: ConfigOverrides = {}): ResolvedPofsisAuthConfig {\n const appName = overrides.appName?.trim()\n const apiBaseUrl = overrides.apiBaseUrl?.trim()\n const authUrl = overrides.authUrl?.trim()\n const scope = overrides.scope?.trim() || 'openid profile email'\n const callbackPath = overrides.callbackPath?.trim() || '/auth/callback'\n const popup = {\n width: overrides.popup?.width ?? 480,\n height: overrides.popup?.height ?? 720,\n name: overrides.popup?.name?.trim() || 'pofsis-auth',\n timeoutMs: overrides.popup?.timeoutMs ?? 300_000,\n }\n\n const missing: string[] = []\n if (!appName) missing.push('appName')\n if (!apiBaseUrl) missing.push('apiBaseUrl')\n if (!authUrl) missing.push('authUrl')\n if (missing.length) {\n throw new Error(`@pofsis-nbt/pofsis-auth missing config: ${missing.join(', ')}`)\n }\n if (!appName || !apiBaseUrl || !authUrl) {\n throw new Error('@pofsis-nbt/pofsis-auth missing config')\n }\n if (!callbackPath.startsWith('/') || callbackPath.startsWith('//')) {\n throw new Error('@pofsis-nbt/pofsis-auth callbackPath must be application-relative')\n }\n if (popup.width <= 0 || popup.height <= 0 || popup.timeoutMs <= 0) {\n throw new Error('@pofsis-nbt/pofsis-auth popup dimensions and timeout must be positive')\n }\n\n return {\n appName,\n apiBaseUrl: stripTrailingSlash(apiBaseUrl),\n authUrl: stripTrailingSlash(authUrl),\n scope,\n callbackPath,\n popup,\n }\n}\n","import type { AuthLaunchOptions, AuthMethod, AuthScreen } from '../types'\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst PHILIPPINE_MOBILE = /^(?:\\+63|63|0)?9\\d{9}$/\nconst METHODS = new Set<AuthMethod>(['password', 'passkey', 'otp'])\nconst SCREENS = new Set<AuthScreen>(['login', 'signup', 'reset'])\nconst MAX_HINT_LENGTH = 320\n\nfunction normalizeHint(value: unknown, emailOnly = false): string | undefined {\n const candidate = typeof value === 'string' ? value.trim() : ''\n if (!candidate || candidate.length > MAX_HINT_LENGTH) return undefined\n if (EMAIL.test(candidate)) return candidate.toLowerCase()\n const compact = candidate.replace(/[\\s()-]/g, '')\n if (emailOnly || !PHILIPPINE_MOBILE.test(compact)) return undefined\n return `+63${compact.replace(/^(?:\\+63|63|0)/, '')}`\n}\n\nexport function normalizeAuthLaunchOptions(\n value?: AuthLaunchOptions | string | null,\n defaultScreen: AuthScreen = 'login',\n) {\n const options = typeof value === 'string' ? { returnUrl: value } : value || {}\n const requestedScreen = options.screen === 'register' ? 'signup' : options.screen\n const screen = SCREENS.has(requestedScreen as AuthScreen)\n ? (requestedScreen as AuthScreen)\n : defaultScreen\n const requestedMethod = METHODS.has(options.method as AuthMethod)\n ? (options.method as AuthMethod)\n : undefined\n const method =\n screen === 'login' ||\n (screen === 'signup' && (requestedMethod === 'password' || requestedMethod === 'otp'))\n ? requestedMethod\n : undefined\n return {\n returnUrl: options.returnUrl,\n screen,\n loginHint: normalizeHint(options.loginHint),\n method,\n }\n}\n\nexport function authLaunchOptionsFromSearch(search: string) {\n const params = new URLSearchParams(search)\n const canonicalHint = params.get('login_hint')\n const loginHint =\n canonicalHint !== null\n ? normalizeHint(canonicalHint)\n : normalizeHint(params.get('email'), true)\n return normalizeAuthLaunchOptions({\n screen: (params.get('screen') || undefined) as AuthLaunchOptions['screen'],\n loginHint,\n method: (params.get('method') || undefined) as AuthLaunchOptions['method'],\n })\n}\n\nexport function buildAuthDestination({\n authUrl,\n appName,\n query,\n options,\n}: {\n authUrl: string\n appName: string\n query: URLSearchParams\n options?: AuthLaunchOptions\n}) {\n const launch = normalizeAuthLaunchOptions(options)\n const authorizationUrl = new URL(authUrl)\n authorizationUrl.search = query.toString()\n if (launch.loginHint) authorizationUrl.searchParams.set('login_hint', launch.loginHint)\n if (launch.screen === 'login' && launch.method) {\n authorizationUrl.searchParams.set('method', launch.method)\n }\n if (launch.screen === 'login') return authorizationUrl.toString()\n\n const pathname = launch.screen === 'signup' ? '/signup' : '/forgot-password'\n const destination = new URL(pathname, authorizationUrl)\n destination.searchParams.set('app', appName)\n destination.searchParams.set(\n 'return_to',\n `${authorizationUrl.pathname}${authorizationUrl.search}`,\n )\n if (launch.loginHint) destination.searchParams.set('login_hint', launch.loginHint)\n if (launch.screen === 'signup') {\n destination.searchParams.set('method', launch.method || 'password')\n }\n return destination.toString()\n}\n","export const POPUP_MESSAGE_TYPE = 'pofsis-auth:callback'\n\nexport type PopupCallbackMessage = {\n type: typeof POPUP_MESSAGE_TYPE\n code?: string\n state?: string\n error?: string\n correlationId?: string\n}\n\nexport function correlationFromState(state: string | null) {\n if (!state) return undefined\n const separator = state.indexOf('.')\n return separator > 0 ? state.slice(0, separator) : undefined\n}\n\nexport function relayPopupCallback(targetOrigin = window.location.origin) {\n const target =\n window.opener && !window.opener.closed\n ? window.opener\n : window.parent !== window\n ? window.parent\n : null\n if (!target) return false\n const params = new URLSearchParams(window.location.search)\n const state = params.get('state') || undefined\n const message: PopupCallbackMessage = {\n type: POPUP_MESSAGE_TYPE,\n code: params.get('code') || undefined,\n state,\n error: params.get('error') || undefined,\n correlationId: correlationFromState(state || null),\n }\n target.postMessage(message, targetOrigin)\n if (target === window.opener) window.close()\n return true\n}\n","const encode = (bytes: Uint8Array) =>\n btoa(String.fromCharCode(...bytes))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '')\n\nexport const randomValue = () => encode(crypto.getRandomValues(new Uint8Array(32)))\n\nexport async function pkceChallenge(verifier: string) {\n return encode(\n new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))),\n )\n}\n","import { checkSession, exchangeCode, fetchOAuthClient, refresh, signOut } from '../auth/api'\nimport { buildAuthDestination, normalizeAuthLaunchOptions } from '../auth/authLaunch'\nimport { resolveConfig } from '../auth/config'\nimport { pkceChallenge, randomValue } from '../auth/pkce'\nimport type {\n AuthLaunchOptions,\n AuthResult,\n OAuthClientConfig,\n PofsisAuthClientConfig,\n ResolvedPofsisAuthConfig,\n PofsisUser,\n SessionPayload,\n} from '../types'\nimport {\n correlationFromState,\n POPUP_MESSAGE_TYPE,\n type PopupCallbackMessage,\n} from './popupProtocol'\n\ntype Subscriber = (session: SessionPayload | null) => void\ntype PopupAttempt = {\n popup: Window\n state: string\n verifier: string\n correlationId: string\n returnUrl?: string\n resolve: (result: AuthResult) => void\n reject: (error: Error) => void\n timer: ReturnType<typeof setInterval>\n timeout: ReturnType<typeof setTimeout>\n}\n\ntype IframeAttempt = Omit<PopupAttempt, 'popup' | 'timer'> & { frame: HTMLIFrameElement }\n\nconst safeLocalPath = (value?: string) =>\n value?.startsWith('/') && !value.startsWith('//') ? value : undefined\n\nconst toSession = (result: { token_type: string; expires_in: number; user: PofsisUser }) => ({\n token_type: result.token_type,\n expires_in: result.expires_in,\n user: result.user,\n})\n\nexport class PofsisAuthClient {\n readonly config: ResolvedPofsisAuthConfig\n private token: string | null = null\n private session: SessionPayload | null = null\n private client: OAuthClientConfig | null = null\n private clientPromise: Promise<OAuthClientConfig> | null = null\n private refreshPromise: Promise<void> | null = null\n private subscribers = new Set<Subscriber>()\n private attempt: PopupAttempt | null = null\n private iframeAttempt: IframeAttempt | null = null\n private listening = false\n\n constructor(config: PofsisAuthClientConfig) {\n this.config = resolveConfig(config)\n this.attach()\n }\n\n private attach() {\n if (this.listening) return\n window.addEventListener('message', this.onPopupMessage)\n this.listening = true\n }\n\n destroy() {\n window.removeEventListener('message', this.onPopupMessage)\n this.listening = false\n const attempt = this.finishAttempt()\n if (attempt) {\n attempt.popup.close()\n attempt.resolve({ status: 'cancelled' })\n }\n this.cancelIframeLogin()\n this.subscribers.clear()\n }\n\n getUser() {\n return this.session?.user ?? null\n }\n\n getSession() {\n return this.session\n }\n\n getAccessToken() {\n return this.token\n }\n\n subscribe(listener: Subscriber) {\n this.attach()\n this.subscribers.add(listener)\n listener(this.session)\n return () => {\n this.subscribers.delete(listener)\n }\n }\n\n private emit() {\n for (const listener of this.subscribers) listener(this.session)\n }\n\n private accept(result: Awaited<ReturnType<typeof exchangeCode>>) {\n this.token = result.access_token\n this.session = toSession(result)\n this.emit()\n }\n\n private loadClient() {\n if (!this.clientPromise) {\n this.clientPromise = fetchOAuthClient(this.config)\n .then((client) => (this.client = client))\n .catch((error) => {\n this.clientPromise = null\n throw error\n })\n }\n return this.clientPromise\n }\n\n getOAuthClient() {\n return this.loadClient()\n }\n\n async refreshSession() {\n const client = await this.loadClient()\n if (!this.refreshPromise) {\n this.refreshPromise = refresh(this.config, client.client_id)\n .then((result) => {\n if (result) this.accept(result)\n else this.clearSession()\n })\n .finally(() => (this.refreshPromise = null))\n }\n return this.refreshPromise\n }\n\n async isRemoteSessionActive() {\n return checkSession(this.config)\n }\n\n clearSession() {\n this.token = null\n this.session = null\n this.emit()\n }\n\n replaceUser(user: PofsisUser) {\n if (!this.session) return\n this.session = { ...this.session, user }\n this.emit()\n }\n\n async logout() {\n try {\n await signOut(this.config)\n } finally {\n this.clearSession()\n }\n }\n\n signup(options: Omit<AuthLaunchOptions, 'screen'> = {}) {\n return this.login({ ...options, screen: 'signup' })\n }\n\n resetPassword(options: Omit<AuthLaunchOptions, 'screen'> = {}) {\n return this.login({ ...options, screen: 'reset' })\n }\n\n async login(options: AuthLaunchOptions = {}): Promise<AuthResult> {\n const launch = normalizeAuthLaunchOptions(options)\n const presentation = options.presentation ?? 'popup'\n if (presentation === 'popup') return this.openPopup({ ...options, ...launch })\n if (presentation === 'iframe') return this.openIframe({ ...options, ...launch })\n return this.startRedirect({ ...options, ...launch })\n }\n\n cancelIframeLogin() {\n const attempt = this.finishIframeAttempt()\n attempt?.resolve({ status: 'cancelled' })\n }\n\n private openIframe(options: AuthLaunchOptions): Promise<AuthResult> {\n const frame = options.target\n if (!frame) return Promise.reject(new Error('POFSIS Auth iframe target is required.'))\n this.cancelIframeLogin()\n const correlationId = randomValue()\n const state = `${correlationId}.${randomValue()}`\n const verifier = randomValue()\n const returnUrl = safeLocalPath(options.returnUrl)\n return new Promise<AuthResult>((resolve, reject) => {\n const timeout = setTimeout(() => {\n const attempt = this.finishIframeAttempt()\n attempt?.reject(new Error('POFSIS Auth iframe timed out.'))\n }, this.config.popup.timeoutMs)\n this.iframeAttempt = {\n frame,\n state,\n verifier,\n correlationId,\n returnUrl,\n resolve,\n reject,\n timeout,\n }\n void this.authorizationUrl(options, state, verifier)\n .then((url) => frame.contentWindow?.location.replace(url))\n .catch((error) => {\n const attempt = this.finishIframeAttempt()\n attempt?.reject(error instanceof Error ? error : new Error(String(error)))\n })\n })\n }\n\n private async authorizationUrl(options: AuthLaunchOptions, state: string, verifier: string) {\n const client = await this.loadClient()\n const query = new URLSearchParams({\n app: this.config.appName.toUpperCase(),\n client_id: client.client_id,\n redirect_uri: client.redirect_uri,\n response_type: 'code',\n scope: this.config.scope,\n state,\n code_challenge: await pkceChallenge(verifier),\n code_challenge_method: 'S256',\n })\n return buildAuthDestination({\n authUrl: this.config.authUrl,\n appName: this.config.appName.toUpperCase(),\n query,\n options,\n })\n }\n\n private storageKey(suffix: string) {\n return `${this.config.appName.toLowerCase()}.auth.${suffix}`\n }\n\n private async startRedirect(options: AuthLaunchOptions): Promise<AuthResult> {\n const state = randomValue()\n const verifier = randomValue()\n sessionStorage.setItem(this.storageKey('state'), state)\n sessionStorage.setItem(this.storageKey('verifier'), verifier)\n const returnUrl = safeLocalPath(options.returnUrl)\n if (returnUrl) sessionStorage.setItem(this.storageKey('return-path'), returnUrl)\n else sessionStorage.removeItem(this.storageKey('return-path'))\n window.location.assign(await this.authorizationUrl(options, state, verifier))\n return { status: 'redirecting' }\n }\n\n private async openPopup(options: AuthLaunchOptions): Promise<AuthResult> {\n if (this.attempt && !this.attempt.popup.closed) {\n this.attempt.popup.focus()\n return new Promise((resolve, reject) => {\n const current = this.attempt!\n const originalResolve = current.resolve\n const originalReject = current.reject\n current.resolve = (value) => {\n originalResolve(value)\n resolve(value)\n }\n current.reject = (error) => {\n originalReject(error)\n reject(error)\n }\n })\n }\n const { width, height, name, timeoutMs } = this.config.popup\n const left = Math.max(0, window.screenX + (window.outerWidth - width) / 2)\n const top = Math.max(0, window.screenY + (window.outerHeight - height) / 2)\n const popup = window.open(\n 'about:blank',\n name,\n `popup=yes,width=${width},height=${height},left=${Math.round(left)},top=${Math.round(top)}`,\n )\n if (!popup) return this.startRedirect({ ...options, presentation: 'redirect' })\n\n const correlationId = randomValue()\n const state = `${correlationId}.${randomValue()}`\n const verifier = randomValue()\n const returnUrl = safeLocalPath(options.returnUrl)\n return new Promise<AuthResult>((resolve, reject) => {\n const timer = setInterval(() => {\n if (!popup.closed) return\n const attempt = this.finishAttempt()\n attempt?.resolve({ status: 'cancelled' })\n }, 250)\n const timeout = setTimeout(() => {\n const attempt = this.finishAttempt()\n popup.close()\n attempt?.reject(new Error('POFSIS Auth popup timed out.'))\n }, timeoutMs)\n this.attempt = {\n popup,\n state,\n verifier,\n correlationId,\n returnUrl,\n resolve,\n reject,\n timer,\n timeout,\n }\n void this.authorizationUrl(options, state, verifier)\n .then((url) => popup.location.replace(url))\n .catch((error) => {\n const attempt = this.finishAttempt()\n popup.close()\n attempt?.reject(error instanceof Error ? error : new Error(String(error)))\n })\n })\n }\n\n private finishAttempt() {\n const attempt = this.attempt\n if (!attempt) return null\n clearInterval(attempt.timer)\n clearTimeout(attempt.timeout)\n this.attempt = null\n return attempt\n }\n\n private finishIframeAttempt() {\n const attempt = this.iframeAttempt\n if (!attempt) return null\n clearTimeout(attempt.timeout)\n this.iframeAttempt = null\n return attempt\n }\n\n private onPopupMessage = (event: MessageEvent<PopupCallbackMessage>) => {\n const iframeAttempt = this.iframeAttempt\n if (\n iframeAttempt &&\n event.origin === window.location.origin &&\n event.source === iframeAttempt.frame.contentWindow &&\n event.data?.type === POPUP_MESSAGE_TYPE &&\n event.data.correlationId === iframeAttempt.correlationId &&\n correlationFromState(event.data.state || null) === iframeAttempt.correlationId &&\n event.data.state === iframeAttempt.state\n ) {\n const completed = this.finishIframeAttempt()!\n if (event.data.error || !event.data.code) {\n completed.reject(\n new Error(event.data.error || 'POFSIS Auth callback was incomplete.'),\n )\n return\n }\n void this.completeCode(event.data.code, event.data.state, completed.verifier)\n .then(() => completed.resolve({ status: 'authenticated', user: this.getUser()! }))\n .catch((error) =>\n completed.reject(error instanceof Error ? error : new Error(String(error))),\n )\n return\n }\n const attempt = this.attempt\n const message = event.data\n if (\n !attempt ||\n event.origin !== window.location.origin ||\n event.source !== attempt.popup ||\n message?.type !== POPUP_MESSAGE_TYPE ||\n message.correlationId !== attempt.correlationId ||\n correlationFromState(message.state || null) !== attempt.correlationId ||\n message.state !== attempt.state\n )\n return\n\n const completed = this.finishAttempt()\n if (!completed) return\n if (message.error || !message.code) {\n completed.popup.close()\n completed.reject(new Error(message.error || 'POFSIS Auth callback was incomplete.'))\n return\n }\n void this.completeCode(message.code, message.state, completed.verifier)\n .then(() => {\n completed.popup.close()\n if (completed.returnUrl) window.history.replaceState(null, '', completed.returnUrl)\n completed.resolve({ status: 'authenticated', user: this.getUser()! })\n })\n .catch((error) => {\n completed.popup.close()\n completed.reject(error instanceof Error ? error : new Error(String(error)))\n })\n }\n\n private async completeCode(code: string, state: string, verifier: string) {\n if (!state || !verifier) throw new Error('Authentication state could not be verified.')\n const client = await this.loadClient()\n this.accept(await exchangeCode(this.config, code, verifier, client))\n }\n\n async completeRedirectCallback(code: string, state: string) {\n const expected = sessionStorage.getItem(this.storageKey('state'))\n const verifier = sessionStorage.getItem(this.storageKey('verifier'))\n sessionStorage.removeItem(this.storageKey('state'))\n sessionStorage.removeItem(this.storageKey('verifier'))\n if (!expected || !verifier || state !== expected) {\n throw new Error('Authentication state could not be verified.')\n }\n await this.completeCode(code, state, verifier)\n }\n}\n\nexport function createPofsisAuth(config: PofsisAuthClientConfig) {\n return new PofsisAuthClient(config)\n}\n"],"mappings":"AAEA,eAAe,EAAa,EAAgC,CACxD,GAAI,EAAS,SAAW,IAAK,OAAO,KACpC,IAAM,EAAO,MAAM,EAAS,KAAK,EAEjC,OADK,EACE,KAAK,MAAM,CAAI,EADJ,IAEtB,CAEA,eAAe,EACX,EACA,EACA,EACoC,CACpC,IAAM,EAAW,MAAM,MAAM,GAAG,EAAO,aAAa,IAAQ,CACxD,YAAa,UACb,GAAG,EACH,QAAS,CACL,OAAQ,mBACR,GAAI,GAAM,MAAQ,EAAE,EAAK,gBAAgB,UACnC,CAAE,eAAgB,kBAAmB,EACrC,CAAC,EACP,GAAG,GAAM,OACb,CACJ,CAAC,EACD,GAAI,CAAC,EAAS,GAAI,CACd,IAAM,EAAY,MAAM,YAAY,EAAK,WAAW,EAAS,OAAO,EAAE,EAEtE,KADC,GAAuC,OAAS,EAAS,OACpD,CACV,CACA,MAAO,CAAE,OAAQ,EAAS,OAAQ,KAAM,MAAM,EAAa,CAAQ,CAAE,CACzE,CAEA,eAAsB,EAAiB,EAA0B,CAG7D,GAAM,CAAE,QAAS,MAAM,EACnB,EACA,kBAJa,mBAAmB,EAAO,QAAQ,YAAY,CAIzC,EAAS,UAHhB,mBAAmB,OAAO,SAAS,MAGT,GACzC,EACA,OAAO,CACX,CAE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U,MAAM,MAAM,EAClB,EAAU,WAAW,OAAO,QAAQ,aAAa,KAAM,GAAI,EAAU,SAAS,EAClF,EAAU,QAAQ,CAAE,OAAQ,gBAAiB,KAAM,KAAK,QAAQ,CAAG,CAAC,CACxE,CAAC,CAAC,CACD,MAAO,GAAU,CACd,EAAU,MAAM,MAAM,EACtB,EAAU,OAAO,aAAiB,MAAQ,EAAY,MAAM,OAAO,CAAK,CAAC,CAAC,CAC9E,CAAC,CAVL,CAWJ,EAEA,MAAc,aAAa,EAAc,EAAe,EAAkB,CACtE,GAAI,CAAC,GAAS,CAAC,EAAU,MAAU,MAAM,6CAA6C,EACtF,IAAM,EAAS,MAAM,KAAK,WAAW,EACrC,KAAK,OAAO,MAAM,EAAa,KAAK,OAAQ,EAAM,EAAU,CAAM,CAAC,CACvE,CAEA,MAAM,yBAAyB,EAAc,EAAe,CACxD,IAAM,EAAW,eAAe,QAAQ,KAAK,WAAW,OAAO,CAAC,EAC1D,EAAW,eAAe,QAAQ,KAAK,WAAW,UAAU,CAAC,EAGnE,GAFA,eAAe,WAAW,KAAK,WAAW,OAAO,CAAC,EAClD,eAAe,WAAW,KAAK,WAAW,UAAU,CAAC,EACjD,CAAC,GAAY,CAAC,GAAY,IAAU,EACpC,MAAU,MAAM,6CAA6C,EAEjE,MAAM,KAAK,aAAa,EAAM,EAAO,CAAQ,CACjD,CACJ,EAEA,SAAgB,EAAiB,EAAgC,CAC7D,OAAO,IAAI,EAAiB,CAAM,CACtC"}
|
|
@@ -164,15 +164,16 @@ function C(e) {
|
|
|
164
164
|
return t > 0 ? e.slice(0, t) : void 0;
|
|
165
165
|
}
|
|
166
166
|
function w(e = window.location.origin) {
|
|
167
|
-
|
|
168
|
-
|
|
167
|
+
let t = window.opener && !window.opener.closed ? window.opener : window.parent === window ? null : window.parent;
|
|
168
|
+
if (!t) return !1;
|
|
169
|
+
let n = new URLSearchParams(window.location.search), r = n.get("state") || void 0, i = {
|
|
169
170
|
type: S,
|
|
170
|
-
code:
|
|
171
|
-
state:
|
|
172
|
-
error:
|
|
173
|
-
correlationId: C(
|
|
171
|
+
code: n.get("code") || void 0,
|
|
172
|
+
state: r,
|
|
173
|
+
error: n.get("error") || void 0,
|
|
174
|
+
correlationId: C(r || null)
|
|
174
175
|
};
|
|
175
|
-
return
|
|
176
|
+
return t.postMessage(i, e), t === window.opener && window.close(), !0;
|
|
176
177
|
}
|
|
177
178
|
//#endregion
|
|
178
179
|
//#region src/auth/pkce.ts
|
|
@@ -195,6 +196,7 @@ var O = (e) => e?.startsWith("/") && !e.startsWith("//") ? e : void 0, k = (e) =
|
|
|
195
196
|
refreshPromise = null;
|
|
196
197
|
subscribers = /* @__PURE__ */ new Set();
|
|
197
198
|
attempt = null;
|
|
199
|
+
iframeAttempt = null;
|
|
198
200
|
listening = !1;
|
|
199
201
|
constructor(e) {
|
|
200
202
|
this.config = f(e), this.attach();
|
|
@@ -205,7 +207,7 @@ var O = (e) => e?.startsWith("/") && !e.startsWith("//") ? e : void 0, k = (e) =
|
|
|
205
207
|
destroy() {
|
|
206
208
|
window.removeEventListener("message", this.onPopupMessage), this.listening = !1;
|
|
207
209
|
let e = this.finishAttempt();
|
|
208
|
-
e && (e.popup.close(), e.resolve({ status: "cancelled" })), this.subscribers.clear();
|
|
210
|
+
e && (e.popup.close(), e.resolve({ status: "cancelled" })), this.cancelIframeLogin(), this.subscribers.clear();
|
|
209
211
|
}
|
|
210
212
|
getUser() {
|
|
211
213
|
return this.session?.user ?? null;
|
|
@@ -273,8 +275,11 @@ var O = (e) => e?.startsWith("/") && !e.startsWith("//") ? e : void 0, k = (e) =
|
|
|
273
275
|
});
|
|
274
276
|
}
|
|
275
277
|
async login(e = {}) {
|
|
276
|
-
let t = y(e);
|
|
277
|
-
return
|
|
278
|
+
let t = y(e), n = e.presentation ?? "popup";
|
|
279
|
+
return n === "popup" ? this.openPopup({
|
|
280
|
+
...e,
|
|
281
|
+
...t
|
|
282
|
+
}) : n === "iframe" ? this.openIframe({
|
|
278
283
|
...e,
|
|
279
284
|
...t
|
|
280
285
|
}) : this.startRedirect({
|
|
@@ -282,6 +287,32 @@ var O = (e) => e?.startsWith("/") && !e.startsWith("//") ? e : void 0, k = (e) =
|
|
|
282
287
|
...t
|
|
283
288
|
});
|
|
284
289
|
}
|
|
290
|
+
cancelIframeLogin() {
|
|
291
|
+
this.finishIframeAttempt()?.resolve({ status: "cancelled" });
|
|
292
|
+
}
|
|
293
|
+
openIframe(e) {
|
|
294
|
+
let t = e.target;
|
|
295
|
+
if (!t) return Promise.reject(/* @__PURE__ */ Error("POFSIS Auth iframe target is required."));
|
|
296
|
+
this.cancelIframeLogin();
|
|
297
|
+
let n = E(), r = `${n}.${E()}`, i = E(), a = O(e.returnUrl);
|
|
298
|
+
return new Promise((o, s) => {
|
|
299
|
+
let c = setTimeout(() => {
|
|
300
|
+
this.finishIframeAttempt()?.reject(/* @__PURE__ */ Error("POFSIS Auth iframe timed out."));
|
|
301
|
+
}, this.config.popup.timeoutMs);
|
|
302
|
+
this.iframeAttempt = {
|
|
303
|
+
frame: t,
|
|
304
|
+
state: r,
|
|
305
|
+
verifier: i,
|
|
306
|
+
correlationId: n,
|
|
307
|
+
returnUrl: a,
|
|
308
|
+
resolve: o,
|
|
309
|
+
reject: s,
|
|
310
|
+
timeout: c
|
|
311
|
+
}, this.authorizationUrl(e, r, i).then((e) => t.contentWindow?.location.replace(e)).catch((e) => {
|
|
312
|
+
this.finishIframeAttempt()?.reject(e instanceof Error ? e : Error(String(e)));
|
|
313
|
+
});
|
|
314
|
+
});
|
|
315
|
+
}
|
|
285
316
|
async authorizationUrl(e, t, n) {
|
|
286
317
|
let r = await this.loadClient(), i = new URLSearchParams({
|
|
287
318
|
app: this.config.appName.toUpperCase(),
|
|
@@ -351,22 +382,39 @@ var O = (e) => e?.startsWith("/") && !e.startsWith("//") ? e : void 0, k = (e) =
|
|
|
351
382
|
let e = this.attempt;
|
|
352
383
|
return e ? (clearInterval(e.timer), clearTimeout(e.timeout), this.attempt = null, e) : null;
|
|
353
384
|
}
|
|
385
|
+
finishIframeAttempt() {
|
|
386
|
+
let e = this.iframeAttempt;
|
|
387
|
+
return e ? (clearTimeout(e.timeout), this.iframeAttempt = null, e) : null;
|
|
388
|
+
}
|
|
354
389
|
onPopupMessage = (e) => {
|
|
355
|
-
let t = this.
|
|
356
|
-
if (
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
390
|
+
let t = this.iframeAttempt;
|
|
391
|
+
if (t && e.origin === window.location.origin && e.source === t.frame.contentWindow && e.data?.type === "pofsis-auth:callback" && e.data.correlationId === t.correlationId && C(e.data.state || null) === t.correlationId && e.data.state === t.state) {
|
|
392
|
+
let t = this.finishIframeAttempt();
|
|
393
|
+
if (e.data.error || !e.data.code) {
|
|
394
|
+
t.reject(Error(e.data.error || "POFSIS Auth callback was incomplete."));
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
this.completeCode(e.data.code, e.data.state, t.verifier).then(() => t.resolve({
|
|
398
|
+
status: "authenticated",
|
|
399
|
+
user: this.getUser()
|
|
400
|
+
})).catch((e) => t.reject(e instanceof Error ? e : Error(String(e))));
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
let n = this.attempt, r = e.data;
|
|
404
|
+
if (!n || e.origin !== window.location.origin || e.source !== n.popup || r?.type !== "pofsis-auth:callback" || r.correlationId !== n.correlationId || C(r.state || null) !== n.correlationId || r.state !== n.state) return;
|
|
405
|
+
let i = this.finishAttempt();
|
|
406
|
+
if (i) {
|
|
407
|
+
if (r.error || !r.code) {
|
|
408
|
+
i.popup.close(), i.reject(Error(r.error || "POFSIS Auth callback was incomplete."));
|
|
361
409
|
return;
|
|
362
410
|
}
|
|
363
|
-
this.completeCode(
|
|
364
|
-
|
|
411
|
+
this.completeCode(r.code, r.state, i.verifier).then(() => {
|
|
412
|
+
i.popup.close(), i.returnUrl && window.history.replaceState(null, "", i.returnUrl), i.resolve({
|
|
365
413
|
status: "authenticated",
|
|
366
414
|
user: this.getUser()
|
|
367
415
|
});
|
|
368
416
|
}).catch((e) => {
|
|
369
|
-
|
|
417
|
+
i.popup.close(), i.reject(e instanceof Error ? e : Error(String(e)));
|
|
370
418
|
});
|
|
371
419
|
}
|
|
372
420
|
};
|
|
@@ -387,4 +435,4 @@ function j(e) {
|
|
|
387
435
|
//#endregion
|
|
388
436
|
export { f as a, c, b as i, l, j as n, u as o, w as r, s, A as t };
|
|
389
437
|
|
|
390
|
-
//# sourceMappingURL=PofsisAuthClient-
|
|
438
|
+
//# sourceMappingURL=PofsisAuthClient-c9BY8iNp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PofsisAuthClient-c9BY8iNp.js","names":[],"sources":["../src/auth/api.ts","../src/auth/config.ts","../src/auth/authLaunch.ts","../src/core/popupProtocol.ts","../src/auth/pkce.ts","../src/core/PofsisAuthClient.ts"],"sourcesContent":["import type { AccountProfile, OAuthClientConfig, PofsisAuthConfig, TokenResponse } from '../types'\n\nasync function parseJson<T>(response: Response): Promise<T> {\n if (response.status === 204) return null as T\n const text = await response.text()\n if (!text) return null as T\n return JSON.parse(text) as T\n}\n\nasync function request<T>(\n config: PofsisAuthConfig,\n path: string,\n init?: RequestInit,\n): Promise<{ status: number; data: T }> {\n const response = await fetch(`${config.apiBaseUrl}${path}`, {\n credentials: 'include',\n ...init,\n headers: {\n Accept: 'application/json',\n ...(init?.body && !(init.body instanceof FormData)\n ? { 'Content-Type': 'application/json' }\n : {}),\n ...init?.headers,\n },\n })\n if (!response.ok) {\n const error = new Error(`Auth API ${path} failed (${response.status})`)\n ;(error as Error & { status?: number }).status = response.status\n throw error\n }\n return { status: response.status, data: await parseJson<T>(response) }\n}\n\nexport async function fetchOAuthClient(config: PofsisAuthConfig) {\n const identity = encodeURIComponent(config.appName.toUpperCase())\n const origin = encodeURIComponent(window.location.origin)\n const { data } = await request<OAuthClientConfig>(\n config,\n `/oauth/clients/${identity}?origin=${origin}`,\n )\n return data\n}\n\nexport async function exchangeCode(\n config: PofsisAuthConfig,\n code: string,\n verifier: string,\n client: Pick<OAuthClientConfig, 'client_id' | 'redirect_uri'>,\n) {\n const { data } = await request<TokenResponse>(config, '/oauth/token', {\n method: 'POST',\n body: JSON.stringify({\n grant_type: 'authorization_code',\n client_id: client.client_id,\n redirect_uri: client.redirect_uri,\n code,\n code_verifier: verifier,\n }),\n })\n return data\n}\n\nexport async function refresh(config: PofsisAuthConfig, clientId: string) {\n const { data } = await request<TokenResponse | null>(config, '/oauth/token', {\n method: 'POST',\n body: JSON.stringify({\n grant_type: 'refresh_token',\n client_id: clientId,\n }),\n })\n return data || null\n}\n\nexport async function checkSession(config: PofsisAuthConfig) {\n try {\n await request(config, '/auth/session')\n return true\n } catch {\n return false\n }\n}\n\nexport async function signOut(config: PofsisAuthConfig) {\n await request(config, '/auth/logout', { method: 'POST' })\n}\n\nexport async function getAccountProfile(config: PofsisAuthConfig, accessToken: string) {\n const { data } = await request<AccountProfile>(config, '/auth/profile/me', {\n headers: { Authorization: `Bearer ${accessToken}` },\n })\n return data\n}\n\nexport async function updateAccountProfile(\n config: PofsisAuthConfig,\n accessToken: string,\n profile: { firstName?: string | null; lastName?: string | null },\n) {\n const { data } = await request<AccountProfile>(config, '/auth/profile/me', {\n method: 'PATCH',\n headers: { Authorization: `Bearer ${accessToken}` },\n body: JSON.stringify(profile),\n })\n return data\n}\n\nexport async function uploadAccountProfileImage(\n config: PofsisAuthConfig,\n accessToken: string,\n kind: 'profile' | 'cover',\n file: File,\n) {\n const body = new FormData()\n body.append('file', file)\n const { data } = await request<AccountProfile>(config, `/auth/profile/me/images/${kind}`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${accessToken}` },\n body,\n })\n return data\n}\n\nexport async function deleteAccountProfileImage(\n config: PofsisAuthConfig,\n accessToken: string,\n kind: 'profile' | 'cover',\n) {\n const { data } = await request<AccountProfile>(config, `/auth/profile/me/images/${kind}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${accessToken}` },\n })\n return data\n}\n","import type { PofsisAuthClientConfig, ResolvedPofsisAuthConfig } from '../types'\n\nfunction stripTrailingSlash(value: string) {\n return value.replace(/\\/$/, '')\n}\n\nexport type ConfigOverrides = Partial<PofsisAuthClientConfig>\n\n/**\n * Validate and normalize explicitly supplied runtime configuration.\n */\nexport function resolveConfig(overrides: ConfigOverrides = {}): ResolvedPofsisAuthConfig {\n const appName = overrides.appName?.trim()\n const apiBaseUrl = overrides.apiBaseUrl?.trim()\n const authUrl = overrides.authUrl?.trim()\n const scope = overrides.scope?.trim() || 'openid profile email'\n const callbackPath = overrides.callbackPath?.trim() || '/auth/callback'\n const popup = {\n width: overrides.popup?.width ?? 480,\n height: overrides.popup?.height ?? 720,\n name: overrides.popup?.name?.trim() || 'pofsis-auth',\n timeoutMs: overrides.popup?.timeoutMs ?? 300_000,\n }\n\n const missing: string[] = []\n if (!appName) missing.push('appName')\n if (!apiBaseUrl) missing.push('apiBaseUrl')\n if (!authUrl) missing.push('authUrl')\n if (missing.length) {\n throw new Error(`@pofsis-nbt/pofsis-auth missing config: ${missing.join(', ')}`)\n }\n if (!appName || !apiBaseUrl || !authUrl) {\n throw new Error('@pofsis-nbt/pofsis-auth missing config')\n }\n if (!callbackPath.startsWith('/') || callbackPath.startsWith('//')) {\n throw new Error('@pofsis-nbt/pofsis-auth callbackPath must be application-relative')\n }\n if (popup.width <= 0 || popup.height <= 0 || popup.timeoutMs <= 0) {\n throw new Error('@pofsis-nbt/pofsis-auth popup dimensions and timeout must be positive')\n }\n\n return {\n appName,\n apiBaseUrl: stripTrailingSlash(apiBaseUrl),\n authUrl: stripTrailingSlash(authUrl),\n scope,\n callbackPath,\n popup,\n }\n}\n","import type { AuthLaunchOptions, AuthMethod, AuthScreen } from '../types'\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst PHILIPPINE_MOBILE = /^(?:\\+63|63|0)?9\\d{9}$/\nconst METHODS = new Set<AuthMethod>(['password', 'passkey', 'otp'])\nconst SCREENS = new Set<AuthScreen>(['login', 'signup', 'reset'])\nconst MAX_HINT_LENGTH = 320\n\nfunction normalizeHint(value: unknown, emailOnly = false): string | undefined {\n const candidate = typeof value === 'string' ? value.trim() : ''\n if (!candidate || candidate.length > MAX_HINT_LENGTH) return undefined\n if (EMAIL.test(candidate)) return candidate.toLowerCase()\n const compact = candidate.replace(/[\\s()-]/g, '')\n if (emailOnly || !PHILIPPINE_MOBILE.test(compact)) return undefined\n return `+63${compact.replace(/^(?:\\+63|63|0)/, '')}`\n}\n\nexport function normalizeAuthLaunchOptions(\n value?: AuthLaunchOptions | string | null,\n defaultScreen: AuthScreen = 'login',\n) {\n const options = typeof value === 'string' ? { returnUrl: value } : value || {}\n const requestedScreen = options.screen === 'register' ? 'signup' : options.screen\n const screen = SCREENS.has(requestedScreen as AuthScreen)\n ? (requestedScreen as AuthScreen)\n : defaultScreen\n const requestedMethod = METHODS.has(options.method as AuthMethod)\n ? (options.method as AuthMethod)\n : undefined\n const method =\n screen === 'login' ||\n (screen === 'signup' && (requestedMethod === 'password' || requestedMethod === 'otp'))\n ? requestedMethod\n : undefined\n return {\n returnUrl: options.returnUrl,\n screen,\n loginHint: normalizeHint(options.loginHint),\n method,\n }\n}\n\nexport function authLaunchOptionsFromSearch(search: string) {\n const params = new URLSearchParams(search)\n const canonicalHint = params.get('login_hint')\n const loginHint =\n canonicalHint !== null\n ? normalizeHint(canonicalHint)\n : normalizeHint(params.get('email'), true)\n return normalizeAuthLaunchOptions({\n screen: (params.get('screen') || undefined) as AuthLaunchOptions['screen'],\n loginHint,\n method: (params.get('method') || undefined) as AuthLaunchOptions['method'],\n })\n}\n\nexport function buildAuthDestination({\n authUrl,\n appName,\n query,\n options,\n}: {\n authUrl: string\n appName: string\n query: URLSearchParams\n options?: AuthLaunchOptions\n}) {\n const launch = normalizeAuthLaunchOptions(options)\n const authorizationUrl = new URL(authUrl)\n authorizationUrl.search = query.toString()\n if (launch.loginHint) authorizationUrl.searchParams.set('login_hint', launch.loginHint)\n if (launch.screen === 'login' && launch.method) {\n authorizationUrl.searchParams.set('method', launch.method)\n }\n if (launch.screen === 'login') return authorizationUrl.toString()\n\n const pathname = launch.screen === 'signup' ? '/signup' : '/forgot-password'\n const destination = new URL(pathname, authorizationUrl)\n destination.searchParams.set('app', appName)\n destination.searchParams.set(\n 'return_to',\n `${authorizationUrl.pathname}${authorizationUrl.search}`,\n )\n if (launch.loginHint) destination.searchParams.set('login_hint', launch.loginHint)\n if (launch.screen === 'signup') {\n destination.searchParams.set('method', launch.method || 'password')\n }\n return destination.toString()\n}\n","export const POPUP_MESSAGE_TYPE = 'pofsis-auth:callback'\n\nexport type PopupCallbackMessage = {\n type: typeof POPUP_MESSAGE_TYPE\n code?: string\n state?: string\n error?: string\n correlationId?: string\n}\n\nexport function correlationFromState(state: string | null) {\n if (!state) return undefined\n const separator = state.indexOf('.')\n return separator > 0 ? state.slice(0, separator) : undefined\n}\n\nexport function relayPopupCallback(targetOrigin = window.location.origin) {\n const target =\n window.opener && !window.opener.closed\n ? window.opener\n : window.parent !== window\n ? window.parent\n : null\n if (!target) return false\n const params = new URLSearchParams(window.location.search)\n const state = params.get('state') || undefined\n const message: PopupCallbackMessage = {\n type: POPUP_MESSAGE_TYPE,\n code: params.get('code') || undefined,\n state,\n error: params.get('error') || undefined,\n correlationId: correlationFromState(state || null),\n }\n target.postMessage(message, targetOrigin)\n if (target === window.opener) window.close()\n return true\n}\n","const encode = (bytes: Uint8Array) =>\n btoa(String.fromCharCode(...bytes))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '')\n\nexport const randomValue = () => encode(crypto.getRandomValues(new Uint8Array(32)))\n\nexport async function pkceChallenge(verifier: string) {\n return encode(\n new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))),\n )\n}\n","import { checkSession, exchangeCode, fetchOAuthClient, refresh, signOut } from '../auth/api'\nimport { buildAuthDestination, normalizeAuthLaunchOptions } from '../auth/authLaunch'\nimport { resolveConfig } from '../auth/config'\nimport { pkceChallenge, randomValue } from '../auth/pkce'\nimport type {\n AuthLaunchOptions,\n AuthResult,\n OAuthClientConfig,\n PofsisAuthClientConfig,\n ResolvedPofsisAuthConfig,\n PofsisUser,\n SessionPayload,\n} from '../types'\nimport {\n correlationFromState,\n POPUP_MESSAGE_TYPE,\n type PopupCallbackMessage,\n} from './popupProtocol'\n\ntype Subscriber = (session: SessionPayload | null) => void\ntype PopupAttempt = {\n popup: Window\n state: string\n verifier: string\n correlationId: string\n returnUrl?: string\n resolve: (result: AuthResult) => void\n reject: (error: Error) => void\n timer: ReturnType<typeof setInterval>\n timeout: ReturnType<typeof setTimeout>\n}\n\ntype IframeAttempt = Omit<PopupAttempt, 'popup' | 'timer'> & { frame: HTMLIFrameElement }\n\nconst safeLocalPath = (value?: string) =>\n value?.startsWith('/') && !value.startsWith('//') ? value : undefined\n\nconst toSession = (result: { token_type: string; expires_in: number; user: PofsisUser }) => ({\n token_type: result.token_type,\n expires_in: result.expires_in,\n user: result.user,\n})\n\nexport class PofsisAuthClient {\n readonly config: ResolvedPofsisAuthConfig\n private token: string | null = null\n private session: SessionPayload | null = null\n private client: OAuthClientConfig | null = null\n private clientPromise: Promise<OAuthClientConfig> | null = null\n private refreshPromise: Promise<void> | null = null\n private subscribers = new Set<Subscriber>()\n private attempt: PopupAttempt | null = null\n private iframeAttempt: IframeAttempt | null = null\n private listening = false\n\n constructor(config: PofsisAuthClientConfig) {\n this.config = resolveConfig(config)\n this.attach()\n }\n\n private attach() {\n if (this.listening) return\n window.addEventListener('message', this.onPopupMessage)\n this.listening = true\n }\n\n destroy() {\n window.removeEventListener('message', this.onPopupMessage)\n this.listening = false\n const attempt = this.finishAttempt()\n if (attempt) {\n attempt.popup.close()\n attempt.resolve({ status: 'cancelled' })\n }\n this.cancelIframeLogin()\n this.subscribers.clear()\n }\n\n getUser() {\n return this.session?.user ?? null\n }\n\n getSession() {\n return this.session\n }\n\n getAccessToken() {\n return this.token\n }\n\n subscribe(listener: Subscriber) {\n this.attach()\n this.subscribers.add(listener)\n listener(this.session)\n return () => {\n this.subscribers.delete(listener)\n }\n }\n\n private emit() {\n for (const listener of this.subscribers) listener(this.session)\n }\n\n private accept(result: Awaited<ReturnType<typeof exchangeCode>>) {\n this.token = result.access_token\n this.session = toSession(result)\n this.emit()\n }\n\n private loadClient() {\n if (!this.clientPromise) {\n this.clientPromise = fetchOAuthClient(this.config)\n .then((client) => (this.client = client))\n .catch((error) => {\n this.clientPromise = null\n throw error\n })\n }\n return this.clientPromise\n }\n\n getOAuthClient() {\n return this.loadClient()\n }\n\n async refreshSession() {\n const client = await this.loadClient()\n if (!this.refreshPromise) {\n this.refreshPromise = refresh(this.config, client.client_id)\n .then((result) => {\n if (result) this.accept(result)\n else this.clearSession()\n })\n .finally(() => (this.refreshPromise = null))\n }\n return this.refreshPromise\n }\n\n async isRemoteSessionActive() {\n return checkSession(this.config)\n }\n\n clearSession() {\n this.token = null\n this.session = null\n this.emit()\n }\n\n replaceUser(user: PofsisUser) {\n if (!this.session) return\n this.session = { ...this.session, user }\n this.emit()\n }\n\n async logout() {\n try {\n await signOut(this.config)\n } finally {\n this.clearSession()\n }\n }\n\n signup(options: Omit<AuthLaunchOptions, 'screen'> = {}) {\n return this.login({ ...options, screen: 'signup' })\n }\n\n resetPassword(options: Omit<AuthLaunchOptions, 'screen'> = {}) {\n return this.login({ ...options, screen: 'reset' })\n }\n\n async login(options: AuthLaunchOptions = {}): Promise<AuthResult> {\n const launch = normalizeAuthLaunchOptions(options)\n const presentation = options.presentation ?? 'popup'\n if (presentation === 'popup') return this.openPopup({ ...options, ...launch })\n if (presentation === 'iframe') return this.openIframe({ ...options, ...launch })\n return this.startRedirect({ ...options, ...launch })\n }\n\n cancelIframeLogin() {\n const attempt = this.finishIframeAttempt()\n attempt?.resolve({ status: 'cancelled' })\n }\n\n private openIframe(options: AuthLaunchOptions): Promise<AuthResult> {\n const frame = options.target\n if (!frame) return Promise.reject(new Error('POFSIS Auth iframe target is required.'))\n this.cancelIframeLogin()\n const correlationId = randomValue()\n const state = `${correlationId}.${randomValue()}`\n const verifier = randomValue()\n const returnUrl = safeLocalPath(options.returnUrl)\n return new Promise<AuthResult>((resolve, reject) => {\n const timeout = setTimeout(() => {\n const attempt = this.finishIframeAttempt()\n attempt?.reject(new Error('POFSIS Auth iframe timed out.'))\n }, this.config.popup.timeoutMs)\n this.iframeAttempt = {\n frame,\n state,\n verifier,\n correlationId,\n returnUrl,\n resolve,\n reject,\n timeout,\n }\n void this.authorizationUrl(options, state, verifier)\n .then((url) => frame.contentWindow?.location.replace(url))\n .catch((error) => {\n const attempt = this.finishIframeAttempt()\n attempt?.reject(error instanceof Error ? error : new Error(String(error)))\n })\n })\n }\n\n private async authorizationUrl(options: AuthLaunchOptions, state: string, verifier: string) {\n const client = await this.loadClient()\n const query = new URLSearchParams({\n app: this.config.appName.toUpperCase(),\n client_id: client.client_id,\n redirect_uri: client.redirect_uri,\n response_type: 'code',\n scope: this.config.scope,\n state,\n code_challenge: await pkceChallenge(verifier),\n code_challenge_method: 'S256',\n })\n return buildAuthDestination({\n authUrl: this.config.authUrl,\n appName: this.config.appName.toUpperCase(),\n query,\n options,\n })\n }\n\n private storageKey(suffix: string) {\n return `${this.config.appName.toLowerCase()}.auth.${suffix}`\n }\n\n private async startRedirect(options: AuthLaunchOptions): Promise<AuthResult> {\n const state = randomValue()\n const verifier = randomValue()\n sessionStorage.setItem(this.storageKey('state'), state)\n sessionStorage.setItem(this.storageKey('verifier'), verifier)\n const returnUrl = safeLocalPath(options.returnUrl)\n if (returnUrl) sessionStorage.setItem(this.storageKey('return-path'), returnUrl)\n else sessionStorage.removeItem(this.storageKey('return-path'))\n window.location.assign(await this.authorizationUrl(options, state, verifier))\n return { status: 'redirecting' }\n }\n\n private async openPopup(options: AuthLaunchOptions): Promise<AuthResult> {\n if (this.attempt && !this.attempt.popup.closed) {\n this.attempt.popup.focus()\n return new Promise((resolve, reject) => {\n const current = this.attempt!\n const originalResolve = current.resolve\n const originalReject = current.reject\n current.resolve = (value) => {\n originalResolve(value)\n resolve(value)\n }\n current.reject = (error) => {\n originalReject(error)\n reject(error)\n }\n })\n }\n const { width, height, name, timeoutMs } = this.config.popup\n const left = Math.max(0, window.screenX + (window.outerWidth - width) / 2)\n const top = Math.max(0, window.screenY + (window.outerHeight - height) / 2)\n const popup = window.open(\n 'about:blank',\n name,\n `popup=yes,width=${width},height=${height},left=${Math.round(left)},top=${Math.round(top)}`,\n )\n if (!popup) return this.startRedirect({ ...options, presentation: 'redirect' })\n\n const correlationId = randomValue()\n const state = `${correlationId}.${randomValue()}`\n const verifier = randomValue()\n const returnUrl = safeLocalPath(options.returnUrl)\n return new Promise<AuthResult>((resolve, reject) => {\n const timer = setInterval(() => {\n if (!popup.closed) return\n const attempt = this.finishAttempt()\n attempt?.resolve({ status: 'cancelled' })\n }, 250)\n const timeout = setTimeout(() => {\n const attempt = this.finishAttempt()\n popup.close()\n attempt?.reject(new Error('POFSIS Auth popup timed out.'))\n }, timeoutMs)\n this.attempt = {\n popup,\n state,\n verifier,\n correlationId,\n returnUrl,\n resolve,\n reject,\n timer,\n timeout,\n }\n void this.authorizationUrl(options, state, verifier)\n .then((url) => popup.location.replace(url))\n .catch((error) => {\n const attempt = this.finishAttempt()\n popup.close()\n attempt?.reject(error instanceof Error ? error : new Error(String(error)))\n })\n })\n }\n\n private finishAttempt() {\n const attempt = this.attempt\n if (!attempt) return null\n clearInterval(attempt.timer)\n clearTimeout(attempt.timeout)\n this.attempt = null\n return attempt\n }\n\n private finishIframeAttempt() {\n const attempt = this.iframeAttempt\n if (!attempt) return null\n clearTimeout(attempt.timeout)\n this.iframeAttempt = null\n return attempt\n }\n\n private onPopupMessage = (event: MessageEvent<PopupCallbackMessage>) => {\n const iframeAttempt = this.iframeAttempt\n if (\n iframeAttempt &&\n event.origin === window.location.origin &&\n event.source === iframeAttempt.frame.contentWindow &&\n event.data?.type === POPUP_MESSAGE_TYPE &&\n event.data.correlationId === iframeAttempt.correlationId &&\n correlationFromState(event.data.state || null) === iframeAttempt.correlationId &&\n event.data.state === iframeAttempt.state\n ) {\n const completed = this.finishIframeAttempt()!\n if (event.data.error || !event.data.code) {\n completed.reject(\n new Error(event.data.error || 'POFSIS Auth callback was incomplete.'),\n )\n return\n }\n void this.completeCode(event.data.code, event.data.state, completed.verifier)\n .then(() => completed.resolve({ status: 'authenticated', user: this.getUser()! }))\n .catch((error) =>\n completed.reject(error instanceof Error ? error : new Error(String(error))),\n )\n return\n }\n const attempt = this.attempt\n const message = event.data\n if (\n !attempt ||\n event.origin !== window.location.origin ||\n event.source !== attempt.popup ||\n message?.type !== POPUP_MESSAGE_TYPE ||\n message.correlationId !== attempt.correlationId ||\n correlationFromState(message.state || null) !== attempt.correlationId ||\n message.state !== attempt.state\n )\n return\n\n const completed = this.finishAttempt()\n if (!completed) return\n if (message.error || !message.code) {\n completed.popup.close()\n completed.reject(new Error(message.error || 'POFSIS Auth callback was incomplete.'))\n return\n }\n void this.completeCode(message.code, message.state, completed.verifier)\n .then(() => {\n completed.popup.close()\n if (completed.returnUrl) window.history.replaceState(null, '', completed.returnUrl)\n completed.resolve({ status: 'authenticated', user: this.getUser()! })\n })\n .catch((error) => {\n completed.popup.close()\n completed.reject(error instanceof Error ? error : new Error(String(error)))\n })\n }\n\n private async completeCode(code: string, state: string, verifier: string) {\n if (!state || !verifier) throw new Error('Authentication state could not be verified.')\n const client = await this.loadClient()\n this.accept(await exchangeCode(this.config, code, verifier, client))\n }\n\n async completeRedirectCallback(code: string, state: string) {\n const expected = sessionStorage.getItem(this.storageKey('state'))\n const verifier = sessionStorage.getItem(this.storageKey('verifier'))\n sessionStorage.removeItem(this.storageKey('state'))\n sessionStorage.removeItem(this.storageKey('verifier'))\n if (!expected || !verifier || state !== expected) {\n throw new Error('Authentication state could not be verified.')\n }\n await this.completeCode(code, state, verifier)\n }\n}\n\nexport function createPofsisAuth(config: Pofsis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EAAU,OAAO,aAAiB,QAAQ,IAAY,MAAM,OAAO,CAAK,CAAC,CAAC;GAC9E,CAAC;EAVL;CAWJ;CAEA,MAAc,aAAa,GAAc,GAAe,GAAkB;EACtE,IAAI,CAAC,KAAS,CAAC,GAAU,MAAU,MAAM,6CAA6C;EACtF,IAAM,IAAS,MAAM,KAAK,WAAW;EACrC,KAAK,OAAO,MAAM,EAAa,KAAK,QAAQ,GAAM,GAAU,CAAM,CAAC;CACvE;CAEA,MAAM,yBAAyB,GAAc,GAAe;EACxD,IAAM,IAAW,eAAe,QAAQ,KAAK,WAAW,OAAO,CAAC,GAC1D,IAAW,eAAe,QAAQ,KAAK,WAAW,UAAU,CAAC;EAGnE,IAFA,eAAe,WAAW,KAAK,WAAW,OAAO,CAAC,GAClD,eAAe,WAAW,KAAK,WAAW,UAAU,CAAC,GACjD,CAAC,KAAY,CAAC,KAAY,MAAU,GACpC,MAAU,MAAM,6CAA6C;EAEjE,MAAM,KAAK,aAAa,GAAM,GAAO,CAAQ;CACjD;AACJ;AAEA,SAAgB,EAAiB,GAAgC;CAC7D,OAAO,IAAI,EAAiB,CAAM;AACtC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as e, c as t, i as n, l as r, o as i, r as a, s as o, t as s } from "./PofsisAuthClient-
|
|
1
|
+
import { a as e, c as t, i as n, l as r, o as i, r as a, s as o, t as s } from "./PofsisAuthClient-c9BY8iNp.js";
|
|
2
2
|
import { createContext as c, useCallback as l, useContext as u, useEffect as d, useMemo as f, useRef as p, useState as m } from "react";
|
|
3
3
|
import { Fragment as h, jsx as g, jsxs as _ } from "react/jsx-runtime";
|
|
4
4
|
//#region src/assets/auth-error-illustration.png
|
|
@@ -293,6 +293,7 @@ function z({ children: e, client: n, postLoginPath: a, components: s }) {
|
|
|
293
293
|
login: n.login.bind(n),
|
|
294
294
|
signup: n.signup.bind(n),
|
|
295
295
|
resetPassword: n.resetPassword.bind(n),
|
|
296
|
+
cancelIframeLogin: () => n.cancelIframeLogin(),
|
|
296
297
|
logout: v,
|
|
297
298
|
refreshSession: () => n.refreshSession(),
|
|
298
299
|
getAccessToken: () => n.getAccessToken(),
|
|
@@ -398,6 +399,97 @@ function U({ children: e, fallback: t, onUnauthenticated: n }) {
|
|
|
398
399
|
]), r || !i ? /* @__PURE__ */ g(h, { children: t ?? (o ? /* @__PURE__ */ g(o, {}) : null) }) : /* @__PURE__ */ g(h, { children: e });
|
|
399
400
|
}
|
|
400
401
|
//#endregion
|
|
401
|
-
|
|
402
|
+
//#region src/components/PofsisAuthModal.tsx
|
|
403
|
+
function W({ open: e, screen: t = "login", method: n, loginHint: r, returnUrl: i, title: a = t === "signup" ? "Create your account" : "Sign in", onClose: o, onAuthenticated: s, onError: c }) {
|
|
404
|
+
let l = H(), u = p(null);
|
|
405
|
+
return d(() => {
|
|
406
|
+
if (!e || !u.current) return;
|
|
407
|
+
let a = !0;
|
|
408
|
+
return l.login({
|
|
409
|
+
presentation: "iframe",
|
|
410
|
+
target: u.current,
|
|
411
|
+
screen: t,
|
|
412
|
+
method: n,
|
|
413
|
+
loginHint: r,
|
|
414
|
+
returnUrl: i
|
|
415
|
+
}).then((e) => {
|
|
416
|
+
a && e.status === "authenticated" && s?.(e.user);
|
|
417
|
+
}).catch((e) => {
|
|
418
|
+
a && c?.(e instanceof Error ? e : Error(String(e)));
|
|
419
|
+
}), () => {
|
|
420
|
+
a = !1, l.cancelIframeLogin();
|
|
421
|
+
};
|
|
422
|
+
}, [
|
|
423
|
+
l,
|
|
424
|
+
r,
|
|
425
|
+
n,
|
|
426
|
+
s,
|
|
427
|
+
c,
|
|
428
|
+
e,
|
|
429
|
+
i,
|
|
430
|
+
t
|
|
431
|
+
]), e ? /* @__PURE__ */ g("div", {
|
|
432
|
+
role: "presentation",
|
|
433
|
+
style: G,
|
|
434
|
+
children: /* @__PURE__ */ _("section", {
|
|
435
|
+
role: "dialog",
|
|
436
|
+
"aria-modal": "true",
|
|
437
|
+
"aria-label": a,
|
|
438
|
+
style: K,
|
|
439
|
+
children: [/* @__PURE__ */ _("div", {
|
|
440
|
+
style: q,
|
|
441
|
+
children: [/* @__PURE__ */ g("strong", { children: a }), /* @__PURE__ */ g("button", {
|
|
442
|
+
type: "button",
|
|
443
|
+
onClick: o,
|
|
444
|
+
"aria-label": "Close authentication",
|
|
445
|
+
style: J,
|
|
446
|
+
children: "×"
|
|
447
|
+
})]
|
|
448
|
+
}), /* @__PURE__ */ g("iframe", {
|
|
449
|
+
ref: u,
|
|
450
|
+
title: a,
|
|
451
|
+
allow: "publickey-credentials-get; publickey-credentials-create",
|
|
452
|
+
style: Y
|
|
453
|
+
})]
|
|
454
|
+
})
|
|
455
|
+
}) : null;
|
|
456
|
+
}
|
|
457
|
+
var G = {
|
|
458
|
+
position: "fixed",
|
|
459
|
+
inset: 0,
|
|
460
|
+
zIndex: 1400,
|
|
461
|
+
display: "grid",
|
|
462
|
+
placeItems: "center",
|
|
463
|
+
padding: 16,
|
|
464
|
+
background: "rgba(10, 10, 10, 0.45)"
|
|
465
|
+
}, K = {
|
|
466
|
+
width: "min(560px, 100%)",
|
|
467
|
+
height: "min(780px, calc(100dvh - 32px))",
|
|
468
|
+
background: "#fff",
|
|
469
|
+
borderRadius: 12,
|
|
470
|
+
overflow: "hidden",
|
|
471
|
+
boxShadow: "0 24px 64px rgba(0,0,0,.24)",
|
|
472
|
+
display: "flex",
|
|
473
|
+
flexDirection: "column"
|
|
474
|
+
}, q = {
|
|
475
|
+
height: 48,
|
|
476
|
+
padding: "0 12px 0 18px",
|
|
477
|
+
display: "flex",
|
|
478
|
+
alignItems: "center",
|
|
479
|
+
justifyContent: "space-between",
|
|
480
|
+
fontFamily: "Inter, sans-serif"
|
|
481
|
+
}, J = {
|
|
482
|
+
border: 0,
|
|
483
|
+
background: "transparent",
|
|
484
|
+
fontSize: 28,
|
|
485
|
+
lineHeight: 1,
|
|
486
|
+
cursor: "pointer"
|
|
487
|
+
}, Y = {
|
|
488
|
+
width: "100%",
|
|
489
|
+
flex: 1,
|
|
490
|
+
border: 0
|
|
491
|
+
};
|
|
492
|
+
//#endregion
|
|
493
|
+
export { B as a, V as i, U as n, A as o, H as r, E as s, W as t };
|
|
402
494
|
|
|
403
|
-
//# sourceMappingURL=
|
|
495
|
+
//# sourceMappingURL=PofsisAuthModal-DGbtRZ4f.js.map
|