@pofsis-nbt/pofsis-auth 1.0.2 → 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.
Files changed (46) hide show
  1. package/Documentation.md +3 -1
  2. package/README.md +11 -0
  3. package/dist/PofsisAuth.d.ts +1 -5
  4. package/dist/PofsisAuth.d.ts.map +1 -1
  5. package/dist/PofsisAuthClient-B-07-cNX.cjs +2 -0
  6. package/dist/PofsisAuthClient-B-07-cNX.cjs.map +1 -0
  7. package/dist/PofsisAuthClient-DJSQb0qq.js +390 -0
  8. package/dist/PofsisAuthClient-DJSQb0qq.js.map +1 -0
  9. package/dist/RequireAuth-BFjNqM_v.js +403 -0
  10. package/dist/RequireAuth-BFjNqM_v.js.map +1 -0
  11. package/dist/RequireAuth-n5Hb1WL9.cjs +2 -0
  12. package/dist/RequireAuth-n5Hb1WL9.cjs.map +1 -0
  13. package/dist/auth/config.d.ts +3 -5
  14. package/dist/auth/config.d.ts.map +1 -1
  15. package/dist/components/AuthPathShell.d.ts +2 -1
  16. package/dist/components/AuthPathShell.d.ts.map +1 -1
  17. package/dist/core/PofsisAuthClient.d.ts +43 -0
  18. package/dist/core/PofsisAuthClient.d.ts.map +1 -0
  19. package/dist/core/index.d.ts +4 -0
  20. package/dist/core/index.d.ts.map +1 -0
  21. package/dist/core/popupProtocol.d.ts +11 -0
  22. package/dist/core/popupProtocol.d.ts.map +1 -0
  23. package/dist/core.cjs +1 -0
  24. package/dist/core.js +2 -0
  25. package/dist/elements/index.d.ts +12 -0
  26. package/dist/elements/index.d.ts.map +1 -0
  27. package/dist/elements.cjs +2 -0
  28. package/dist/elements.cjs.map +1 -0
  29. package/dist/elements.js +75 -0
  30. package/dist/elements.js.map +1 -0
  31. package/dist/index.cjs +1 -2
  32. package/dist/index.d.ts +2 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +4 -623
  35. package/dist/pofsis-auth-elements.js +2 -0
  36. package/dist/pofsis-auth-elements.js.map +1 -0
  37. package/dist/react/index.d.ts +7 -0
  38. package/dist/react/index.d.ts.map +1 -0
  39. package/dist/react.cjs +1 -0
  40. package/dist/react.js +2 -0
  41. package/dist/types.d.ts +37 -1
  42. package/dist/types.d.ts.map +1 -1
  43. package/docs/popup-integration.md +162 -0
  44. package/package.json +29 -4
  45. package/dist/index.cjs.map +0 -1
  46. package/dist/index.js.map +0 -1
package/Documentation.md CHANGED
@@ -1,9 +1,11 @@
1
1
  # POFSIS Auth Documentation
2
2
 
3
- This is the complete public API and integration reference for `@pofsis-nbt/pofsis-auth@1.0.1`.
3
+ This is the complete public API and integration reference for `@pofsis-nbt/pofsis-auth@1.1.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
 
7
+ The [popup integration guide](./docs/popup-integration.md) is the canonical consumer reference for framework-neutral, React, and Web Component popup launches.
8
+
7
9
  ## Integration process
8
10
 
9
11
  1. Install `@pofsis-nbt/pofsis-auth` with its React, React DOM, and optional Axios peers.
package/README.md CHANGED
@@ -4,6 +4,8 @@ React OAuth 2.0/PKCE authentication for POFSIS applications. One package serves
4
4
 
5
5
  For guided setup and authentication scenarios, open the repository's interactive [POFSIS Auth documentation portal](./index.html). It validates consumer-supplied environment values and generates safe `/login` launch links without storing them.
6
6
 
7
+ For hosted popup setup, parameters, callback handling, React usage, and the optional Web Component, see the [popup integration guide](./docs/popup-integration.md).
8
+
7
9
  ## Install
8
10
 
9
11
  ```bash
@@ -64,6 +66,15 @@ function AccountMenu() {
64
66
  }
65
67
  ```
66
68
 
69
+ Explicit user actions open hosted Auth in a popup:
70
+
71
+ ```tsx
72
+ const { login } = useAuth()
73
+ <button onClick={() => void login({ presentation: 'popup', returnUrl: location.pathname })}>
74
+ Sign in
75
+ </button>
76
+ ```
77
+
67
78
  The provider handles `/login`, `/auth/callback`, and `/auth/error`. Login supports `screen`, `loginHint`, `method`, and a safe application-relative `returnUrl`. An OTP signup opens the signup page and continues to account verification after the identifier is submitted. See [Documentation.md](./Documentation.md) for the complete API.
68
79
 
69
80
  ## Axios
@@ -1,7 +1,3 @@
1
1
  import type { PofsisAuthProps } from './types';
2
- /**
3
- * Single integration surface for tool apps.
4
- * Handles session restore, PKCE login, and fixed paths `/login`, `/auth/callback`, `/auth/error`.
5
- */
6
- export declare function PofsisAuth({ children, appName, apiBaseUrl, authUrl, scope, postLoginPath, components, }: PofsisAuthProps): import("react").JSX.Element;
2
+ export declare function PofsisAuth({ children, appName, apiBaseUrl, authUrl, scope, callbackPath, popup, postLoginPath, components, }: PofsisAuthProps): import("react").JSX.Element;
7
3
  //# sourceMappingURL=PofsisAuth.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"PofsisAuth.d.ts","sourceRoot":"","sources":["../src/PofsisAuth.tsx"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAIR,eAAe,EAElB,MAAM,SAAS,CAAA;AAmVhB;;;GAGG;AACH,wBAAgB,UAAU,CAAC,EACvB,QAAQ,EACR,OAAO,EACP,UAAU,EACV,OAAO,EACP,KAAK,EACL,aAAmB,EACnB,UAAU,GACb,EAAE,eAAe,+BA4BjB"}
1
+ {"version":3,"file":"PofsisAuth.d.ts","sourceRoot":"","sources":["../src/PofsisAuth.tsx"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAGR,eAAe,EAGlB,MAAM,SAAS,CAAA;AAgMhB,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){if(!window.opener||window.opener.closed)return!1;let t=new URLSearchParams(window.location.search),n=t.get(`state`)||void 0,r={type:S,code:t.get(`code`)||void 0,state:n,error:t.get(`error`)||void 0,correlationId:C(n||null)};return window.opener.postMessage(r,e),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;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.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);return(e.presentation??`popup`)===`popup`?this.openPopup({...e,...t}):this.startRedirect({...e,...t})}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}onPopupMessage=e=>{let t=this.attempt,n=e.data;if(!t||e.origin!==window.location.origin||e.source!==t.popup||n?.type!==`pofsis-auth:callback`||n.correlationId!==t.correlationId||C(n.state||null)!==t.correlationId||n.state!==t.state)return;let r=this.finishAttempt();if(r){if(n.error||!n.code){r.popup.close(),r.reject(Error(n.error||`POFSIS Auth callback was incomplete.`));return}this.completeCode(n.code,n.state,r.verifier).then(()=>{r.popup.close(),r.returnUrl&&window.history.replaceState(null,``,r.returnUrl),r.resolve({status:`authenticated`,user:this.getUser()})}).catch(e=>{r.popup.close(),r.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-B-07-cNX.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PofsisAuthClient-B-07-cNX.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 if (!window.opener || window.opener.closed) 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 window.opener.postMessage(message, targetOrigin)\n 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\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 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.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 return this.startRedirect({ ...options, ...launch })\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 onPopupMessage = (event: MessageEvent<PopupCallbackMessage>) => {\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,EA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Aa,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"}
@@ -0,0 +1,390 @@
1
+ //#region src/auth/api.ts
2
+ async function e(e) {
3
+ if (e.status === 204) return null;
4
+ let t = await e.text();
5
+ return t ? JSON.parse(t) : null;
6
+ }
7
+ async function t(t, n, r) {
8
+ let i = await fetch(`${t.apiBaseUrl}${n}`, {
9
+ credentials: "include",
10
+ ...r,
11
+ headers: {
12
+ Accept: "application/json",
13
+ ...r?.body && !(r.body instanceof FormData) ? { "Content-Type": "application/json" } : {},
14
+ ...r?.headers
15
+ }
16
+ });
17
+ if (!i.ok) {
18
+ let e = /* @__PURE__ */ Error(`Auth API ${n} failed (${i.status})`);
19
+ throw e.status = i.status, e;
20
+ }
21
+ return {
22
+ status: i.status,
23
+ data: await e(i)
24
+ };
25
+ }
26
+ async function n(e) {
27
+ let { data: n } = await t(e, `/oauth/clients/${encodeURIComponent(e.appName.toUpperCase())}?origin=${encodeURIComponent(window.location.origin)}`);
28
+ return n;
29
+ }
30
+ async function r(e, n, r, i) {
31
+ let { data: a } = await t(e, "/oauth/token", {
32
+ method: "POST",
33
+ body: JSON.stringify({
34
+ grant_type: "authorization_code",
35
+ client_id: i.client_id,
36
+ redirect_uri: i.redirect_uri,
37
+ code: n,
38
+ code_verifier: r
39
+ })
40
+ });
41
+ return a;
42
+ }
43
+ async function i(e, n) {
44
+ let { data: r } = await t(e, "/oauth/token", {
45
+ method: "POST",
46
+ body: JSON.stringify({
47
+ grant_type: "refresh_token",
48
+ client_id: n
49
+ })
50
+ });
51
+ return r || null;
52
+ }
53
+ async function a(e) {
54
+ try {
55
+ return await t(e, "/auth/session"), !0;
56
+ } catch {
57
+ return !1;
58
+ }
59
+ }
60
+ async function o(e) {
61
+ await t(e, "/auth/logout", { method: "POST" });
62
+ }
63
+ async function s(e, n) {
64
+ let { data: r } = await t(e, "/auth/profile/me", { headers: { Authorization: `Bearer ${n}` } });
65
+ return r;
66
+ }
67
+ async function c(e, n, r) {
68
+ let { data: i } = await t(e, "/auth/profile/me", {
69
+ method: "PATCH",
70
+ headers: { Authorization: `Bearer ${n}` },
71
+ body: JSON.stringify(r)
72
+ });
73
+ return i;
74
+ }
75
+ async function l(e, n, r, i) {
76
+ let a = new FormData();
77
+ a.append("file", i);
78
+ let { data: o } = await t(e, `/auth/profile/me/images/${r}`, {
79
+ method: "POST",
80
+ headers: { Authorization: `Bearer ${n}` },
81
+ body: a
82
+ });
83
+ return o;
84
+ }
85
+ async function u(e, n, r) {
86
+ let { data: i } = await t(e, `/auth/profile/me/images/${r}`, {
87
+ method: "DELETE",
88
+ headers: { Authorization: `Bearer ${n}` }
89
+ });
90
+ return i;
91
+ }
92
+ //#endregion
93
+ //#region src/auth/config.ts
94
+ function d(e) {
95
+ return e.replace(/\/$/, "");
96
+ }
97
+ function f(e = {}) {
98
+ 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 = {
99
+ width: e.popup?.width ?? 480,
100
+ height: e.popup?.height ?? 720,
101
+ name: e.popup?.name?.trim() || "pofsis-auth",
102
+ timeoutMs: e.popup?.timeoutMs ?? 3e5
103
+ }, s = [];
104
+ 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(", ")}`);
105
+ if (!t || !n || !r) throw Error("@pofsis-nbt/pofsis-auth missing config");
106
+ if (!a.startsWith("/") || a.startsWith("//")) throw Error("@pofsis-nbt/pofsis-auth callbackPath must be application-relative");
107
+ if (o.width <= 0 || o.height <= 0 || o.timeoutMs <= 0) throw Error("@pofsis-nbt/pofsis-auth popup dimensions and timeout must be positive");
108
+ return {
109
+ appName: t,
110
+ apiBaseUrl: d(n),
111
+ authUrl: d(r),
112
+ scope: i,
113
+ callbackPath: a,
114
+ popup: o
115
+ };
116
+ }
117
+ //#endregion
118
+ //#region src/auth/authLaunch.ts
119
+ var p = /^[^\s@]+@[^\s@]+\.[^\s@]+$/, m = /^(?:\+63|63|0)?9\d{9}$/, h = /* @__PURE__ */ new Set([
120
+ "password",
121
+ "passkey",
122
+ "otp"
123
+ ]), g = /* @__PURE__ */ new Set([
124
+ "login",
125
+ "signup",
126
+ "reset"
127
+ ]), _ = 320;
128
+ function v(e, t = !1) {
129
+ let n = typeof e == "string" ? e.trim() : "";
130
+ if (!n || n.length > _) return;
131
+ if (p.test(n)) return n.toLowerCase();
132
+ let r = n.replace(/[\s()-]/g, "");
133
+ if (!t && m.test(r)) return `+63${r.replace(/^(?:\+63|63|0)/, "")}`;
134
+ }
135
+ function y(e, t = "login") {
136
+ 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;
137
+ return {
138
+ returnUrl: n.returnUrl,
139
+ screen: i,
140
+ loginHint: v(n.loginHint),
141
+ method: o
142
+ };
143
+ }
144
+ function b(e) {
145
+ let t = new URLSearchParams(e), n = t.get("login_hint"), r = n === null ? v(t.get("email"), !0) : v(n);
146
+ return y({
147
+ screen: t.get("screen") || void 0,
148
+ loginHint: r,
149
+ method: t.get("method") || void 0
150
+ });
151
+ }
152
+ function x({ authUrl: e, appName: t, query: n, options: r }) {
153
+ let i = y(r), a = new URL(e);
154
+ 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();
155
+ let o = i.screen === "signup" ? "/signup" : "/forgot-password", s = new URL(o, a);
156
+ 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();
157
+ }
158
+ //#endregion
159
+ //#region src/core/popupProtocol.ts
160
+ var S = "pofsis-auth:callback";
161
+ function C(e) {
162
+ if (!e) return;
163
+ let t = e.indexOf(".");
164
+ return t > 0 ? e.slice(0, t) : void 0;
165
+ }
166
+ function w(e = window.location.origin) {
167
+ if (!window.opener || window.opener.closed) return !1;
168
+ let t = new URLSearchParams(window.location.search), n = t.get("state") || void 0, r = {
169
+ type: S,
170
+ code: t.get("code") || void 0,
171
+ state: n,
172
+ error: t.get("error") || void 0,
173
+ correlationId: C(n || null)
174
+ };
175
+ return window.opener.postMessage(r, e), window.close(), !0;
176
+ }
177
+ //#endregion
178
+ //#region src/auth/pkce.ts
179
+ var T = (e) => btoa(String.fromCharCode(...e)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""), E = () => T(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
180
+ async function D(e) {
181
+ return T(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(e))));
182
+ }
183
+ //#endregion
184
+ //#region src/core/PofsisAuthClient.ts
185
+ var O = (e) => e?.startsWith("/") && !e.startsWith("//") ? e : void 0, k = (e) => ({
186
+ token_type: e.token_type,
187
+ expires_in: e.expires_in,
188
+ user: e.user
189
+ }), A = class {
190
+ config;
191
+ token = null;
192
+ session = null;
193
+ client = null;
194
+ clientPromise = null;
195
+ refreshPromise = null;
196
+ subscribers = /* @__PURE__ */ new Set();
197
+ attempt = null;
198
+ listening = !1;
199
+ constructor(e) {
200
+ this.config = f(e), this.attach();
201
+ }
202
+ attach() {
203
+ this.listening ||= (window.addEventListener("message", this.onPopupMessage), !0);
204
+ }
205
+ destroy() {
206
+ window.removeEventListener("message", this.onPopupMessage), this.listening = !1;
207
+ let e = this.finishAttempt();
208
+ e && (e.popup.close(), e.resolve({ status: "cancelled" })), this.subscribers.clear();
209
+ }
210
+ getUser() {
211
+ return this.session?.user ?? null;
212
+ }
213
+ getSession() {
214
+ return this.session;
215
+ }
216
+ getAccessToken() {
217
+ return this.token;
218
+ }
219
+ subscribe(e) {
220
+ return this.attach(), this.subscribers.add(e), e(this.session), () => {
221
+ this.subscribers.delete(e);
222
+ };
223
+ }
224
+ emit() {
225
+ for (let e of this.subscribers) e(this.session);
226
+ }
227
+ accept(e) {
228
+ this.token = e.access_token, this.session = k(e), this.emit();
229
+ }
230
+ loadClient() {
231
+ return this.clientPromise ||= n(this.config).then((e) => this.client = e).catch((e) => {
232
+ throw this.clientPromise = null, e;
233
+ }), this.clientPromise;
234
+ }
235
+ getOAuthClient() {
236
+ return this.loadClient();
237
+ }
238
+ async refreshSession() {
239
+ let e = await this.loadClient();
240
+ return this.refreshPromise ||= i(this.config, e.client_id).then((e) => {
241
+ e ? this.accept(e) : this.clearSession();
242
+ }).finally(() => this.refreshPromise = null), this.refreshPromise;
243
+ }
244
+ async isRemoteSessionActive() {
245
+ return a(this.config);
246
+ }
247
+ clearSession() {
248
+ this.token = null, this.session = null, this.emit();
249
+ }
250
+ replaceUser(e) {
251
+ this.session && (this.session = {
252
+ ...this.session,
253
+ user: e
254
+ }, this.emit());
255
+ }
256
+ async logout() {
257
+ try {
258
+ await o(this.config);
259
+ } finally {
260
+ this.clearSession();
261
+ }
262
+ }
263
+ signup(e = {}) {
264
+ return this.login({
265
+ ...e,
266
+ screen: "signup"
267
+ });
268
+ }
269
+ resetPassword(e = {}) {
270
+ return this.login({
271
+ ...e,
272
+ screen: "reset"
273
+ });
274
+ }
275
+ async login(e = {}) {
276
+ let t = y(e);
277
+ return (e.presentation ?? "popup") === "popup" ? this.openPopup({
278
+ ...e,
279
+ ...t
280
+ }) : this.startRedirect({
281
+ ...e,
282
+ ...t
283
+ });
284
+ }
285
+ async authorizationUrl(e, t, n) {
286
+ let r = await this.loadClient(), i = new URLSearchParams({
287
+ app: this.config.appName.toUpperCase(),
288
+ client_id: r.client_id,
289
+ redirect_uri: r.redirect_uri,
290
+ response_type: "code",
291
+ scope: this.config.scope,
292
+ state: t,
293
+ code_challenge: await D(n),
294
+ code_challenge_method: "S256"
295
+ });
296
+ return x({
297
+ authUrl: this.config.authUrl,
298
+ appName: this.config.appName.toUpperCase(),
299
+ query: i,
300
+ options: e
301
+ });
302
+ }
303
+ storageKey(e) {
304
+ return `${this.config.appName.toLowerCase()}.auth.${e}`;
305
+ }
306
+ async startRedirect(e) {
307
+ let t = E(), n = E();
308
+ sessionStorage.setItem(this.storageKey("state"), t), sessionStorage.setItem(this.storageKey("verifier"), n);
309
+ let r = O(e.returnUrl);
310
+ 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" };
311
+ }
312
+ async openPopup(e) {
313
+ if (this.attempt && !this.attempt.popup.closed) return this.attempt.popup.focus(), new Promise((e, t) => {
314
+ let n = this.attempt, r = n.resolve, i = n.reject;
315
+ n.resolve = (t) => {
316
+ r(t), e(t);
317
+ }, n.reject = (e) => {
318
+ i(e), t(e);
319
+ };
320
+ });
321
+ 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)}`);
322
+ if (!s) return this.startRedirect({
323
+ ...e,
324
+ presentation: "redirect"
325
+ });
326
+ let c = E(), l = `${c}.${E()}`, u = E(), d = O(e.returnUrl);
327
+ return new Promise((t, n) => {
328
+ let r = setInterval(() => {
329
+ s.closed && this.finishAttempt()?.resolve({ status: "cancelled" });
330
+ }, 250), a = setTimeout(() => {
331
+ let e = this.finishAttempt();
332
+ s.close(), e?.reject(/* @__PURE__ */ Error("POFSIS Auth popup timed out."));
333
+ }, i);
334
+ this.attempt = {
335
+ popup: s,
336
+ state: l,
337
+ verifier: u,
338
+ correlationId: c,
339
+ returnUrl: d,
340
+ resolve: t,
341
+ reject: n,
342
+ timer: r,
343
+ timeout: a
344
+ }, this.authorizationUrl(e, l, u).then((e) => s.location.replace(e)).catch((e) => {
345
+ let t = this.finishAttempt();
346
+ s.close(), t?.reject(e instanceof Error ? e : Error(String(e)));
347
+ });
348
+ });
349
+ }
350
+ finishAttempt() {
351
+ let e = this.attempt;
352
+ return e ? (clearInterval(e.timer), clearTimeout(e.timeout), this.attempt = null, e) : null;
353
+ }
354
+ onPopupMessage = (e) => {
355
+ let t = this.attempt, n = e.data;
356
+ if (!t || e.origin !== window.location.origin || e.source !== t.popup || n?.type !== "pofsis-auth:callback" || n.correlationId !== t.correlationId || C(n.state || null) !== t.correlationId || n.state !== t.state) return;
357
+ let r = this.finishAttempt();
358
+ if (r) {
359
+ if (n.error || !n.code) {
360
+ r.popup.close(), r.reject(Error(n.error || "POFSIS Auth callback was incomplete."));
361
+ return;
362
+ }
363
+ this.completeCode(n.code, n.state, r.verifier).then(() => {
364
+ r.popup.close(), r.returnUrl && window.history.replaceState(null, "", r.returnUrl), r.resolve({
365
+ status: "authenticated",
366
+ user: this.getUser()
367
+ });
368
+ }).catch((e) => {
369
+ r.popup.close(), r.reject(e instanceof Error ? e : Error(String(e)));
370
+ });
371
+ }
372
+ };
373
+ async completeCode(e, t, n) {
374
+ if (!t || !n) throw Error("Authentication state could not be verified.");
375
+ let i = await this.loadClient();
376
+ this.accept(await r(this.config, e, n, i));
377
+ }
378
+ async completeRedirectCallback(e, t) {
379
+ let n = sessionStorage.getItem(this.storageKey("state")), r = sessionStorage.getItem(this.storageKey("verifier"));
380
+ if (sessionStorage.removeItem(this.storageKey("state")), sessionStorage.removeItem(this.storageKey("verifier")), !n || !r || t !== n) throw Error("Authentication state could not be verified.");
381
+ await this.completeCode(e, t, r);
382
+ }
383
+ };
384
+ function j(e) {
385
+ return new A(e);
386
+ }
387
+ //#endregion
388
+ export { f as a, c, b as i, l, j as n, u as o, w as r, s, A as t };
389
+
390
+ //# sourceMappingURL=PofsisAuthClient-DJSQb0qq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PofsisAuthClient-DJSQb0qq.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 if (!window.opener || window.opener.closed) 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 window.opener.postMessage(message, targetOrigin)\n 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\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 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.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 return this.startRedirect({ ...options, ...launch })\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 onPopupMessage = (event: MessageEvent<PopupCallbackMessage>) => {\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"],"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