@pofsis-nbt/pofsis-auth 1.0.3 → 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.
Files changed (50) hide show
  1. package/Documentation.md +143 -141
  2. package/README.md +130 -119
  3. package/dist/PofsisAuth.d.ts +1 -5
  4. package/dist/PofsisAuth.d.ts.map +1 -1
  5. package/dist/PofsisAuthClient-CRYYsJYc.cjs +2 -0
  6. package/dist/PofsisAuthClient-CRYYsJYc.cjs.map +1 -0
  7. package/dist/PofsisAuthClient-c9BY8iNp.js +438 -0
  8. package/dist/PofsisAuthClient-c9BY8iNp.js.map +1 -0
  9. package/dist/PofsisAuthModal-DGbtRZ4f.js +495 -0
  10. package/dist/PofsisAuthModal-DGbtRZ4f.js.map +1 -0
  11. package/dist/PofsisAuthModal-DIzzLJSP.cjs +2 -0
  12. package/dist/PofsisAuthModal-DIzzLJSP.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/components/PofsisAuthModal.d.ts +3 -0
  18. package/dist/components/PofsisAuthModal.d.ts.map +1 -0
  19. package/dist/components/index.d.ts +1 -0
  20. package/dist/components/index.d.ts.map +1 -1
  21. package/dist/core/PofsisAuthClient.d.ts +47 -0
  22. package/dist/core/PofsisAuthClient.d.ts.map +1 -0
  23. package/dist/core/index.d.ts +4 -0
  24. package/dist/core/index.d.ts.map +1 -0
  25. package/dist/core/popupProtocol.d.ts +11 -0
  26. package/dist/core/popupProtocol.d.ts.map +1 -0
  27. package/dist/core.cjs +1 -0
  28. package/dist/core.js +2 -0
  29. package/dist/elements/index.d.ts +12 -0
  30. package/dist/elements/index.d.ts.map +1 -0
  31. package/dist/elements.cjs +2 -0
  32. package/dist/elements.cjs.map +1 -0
  33. package/dist/elements.js +75 -0
  34. package/dist/elements.js.map +1 -0
  35. package/dist/index.cjs +1 -2
  36. package/dist/index.d.ts +3 -2
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +4 -623
  39. package/dist/pofsis-auth-elements.js +2 -0
  40. package/dist/pofsis-auth-elements.js.map +1 -0
  41. package/dist/react/index.d.ts +7 -0
  42. package/dist/react/index.d.ts.map +1 -0
  43. package/dist/react.cjs +1 -0
  44. package/dist/react.js +2 -0
  45. package/dist/types.d.ts +51 -1
  46. package/dist/types.d.ts.map +1 -1
  47. package/docs/popup-integration.md +178 -0
  48. package/package.json +87 -62
  49. package/dist/index.cjs.map +0 -1
  50. package/dist/index.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ var PofsisAuthElements=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});async function t(e){if(e.status===204)return null;let t=await e.text();return t?JSON.parse(t):null}async function n(e,n,r){let i=await fetch(`${e.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 t(i)}}async function r(e){let{data:t}=await n(e,`/oauth/clients/${encodeURIComponent(e.appName.toUpperCase())}?origin=${encodeURIComponent(window.location.origin)}`);return t}async function i(e,t,r,i){let{data:a}=await n(e,`/oauth/token`,{method:`POST`,body:JSON.stringify({grant_type:`authorization_code`,client_id:i.client_id,redirect_uri:i.redirect_uri,code:t,code_verifier:r})});return a}async function a(e,t){let{data:r}=await n(e,`/oauth/token`,{method:`POST`,body:JSON.stringify({grant_type:`refresh_token`,client_id:t})});return r||null}async function o(e){try{return await n(e,`/auth/session`),!0}catch{return!1}}async function s(e){await n(e,`/auth/logout`,{method:`POST`})}var c=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,l=/^(?:\+63|63|0)?9\d{9}$/,u=new Set([`password`,`passkey`,`otp`]),d=new Set([`login`,`signup`,`reset`]),f=320;function p(e,t=!1){let n=typeof e==`string`?e.trim():``;if(!n||n.length>f)return;if(c.test(n))return n.toLowerCase();let r=n.replace(/[\s()-]/g,``);if(!t&&l.test(r))return`+63${r.replace(/^(?:\+63|63|0)/,``)}`}function m(e,t=`login`){let n=typeof e==`string`?{returnUrl:e}:e||{},r=n.screen===`register`?`signup`:n.screen,i=d.has(r)?r:t,a=u.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:p(n.loginHint),method:o}}function h({authUrl:e,appName:t,query:n,options:r}){let i=m(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()}function g(e){return e.replace(/\/$/,``)}function _(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:g(n),authUrl:g(r),scope:i,callbackPath:a,popup:o}}var v=e=>btoa(String.fromCharCode(...e)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``),y=()=>v(crypto.getRandomValues(new Uint8Array(32)));async function b(e){return v(new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))))}function x(e){if(!e)return;let t=e.indexOf(`.`);return t>0?e.slice(0,t):void 0}var S=e=>e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0,C=e=>({token_type:e.token_type,expires_in:e.expires_in,user:e.user}),w=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=_(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=C(e),this.emit()}loadClient(){return this.clientPromise||=r(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||=a(this.config,e.client_id).then(e=>{e?this.accept(e):this.clearSession()}).finally(()=>this.refreshPromise=null),this.refreshPromise}async isRemoteSessionActive(){return o(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 s(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=m(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=y(),r=`${n}.${y()}`,i=y(),a=S(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 b(n),code_challenge_method:`S256`});return h({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=y(),n=y();sessionStorage.setItem(this.storageKey(`state`),t),sessionStorage.setItem(this.storageKey(`verifier`),n);let r=S(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=y(),l=`${c}.${y()}`,u=y(),d=S(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&&x(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||x(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 r=await this.loadClient();this.accept(await i(this.config,e,n,r))}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 T(e){return new w(e)}var E=[`app-name`,`api-base-url`,`auth-url`,`scope`,`return-url`,`screen`,`method`,`login-hint`],D=class extends HTMLElement{static get observedAttributes(){return E}client=null;button=null;connectedCallback(){this.render()}disconnectedCallback(){this.client?.destroy()}attributeChangedCallback(){this.isConnected&&this.render()}required(e){let t=this.getAttribute(e)?.trim();if(!t)throw Error(`<pofsis-sign-in> requires ${e}`);return t}render(){this.client?.destroy(),this.client=T({appName:this.required(`app-name`),apiBaseUrl:this.required(`api-base-url`),authUrl:this.required(`auth-url`),scope:this.getAttribute(`scope`)||void 0});let e=this.textContent?.trim()||`Sign in`;this.replaceChildren(),this.button=document.createElement(`button`),this.button.type=`button`,this.button.part.add(`button`),this.button.textContent=e,this.button.addEventListener(`click`,()=>void this.launch()),this.append(this.button)}async launch(){if(!this.client||!this.button)return;this.button.disabled=!0;let e={presentation:`popup`,returnUrl:this.getAttribute(`return-url`)||void 0,screen:this.getAttribute(`screen`)||`login`,method:this.getAttribute(`method`)||void 0,loginHint:this.getAttribute(`login-hint`)||void 0};try{let t=await this.client.login(e);this.dispatchEvent(new CustomEvent(`pofsis-auth-${t.status}`,{bubbles:!0,composed:!0,detail:t}))}catch(e){this.dispatchEvent(new CustomEvent(`pofsis-auth-error`,{bubbles:!0,composed:!0,detail:{error:e}}))}finally{this.button.disabled=!1}}};return customElements.get(`pofsis-sign-in`)||customElements.define(`pofsis-sign-in`,D),e.PofsisSignInElement=D,e})({});
2
+ //# sourceMappingURL=pofsis-auth-elements.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pofsis-auth-elements.js","names":[],"sources":["../src/auth/api.ts","../src/auth/authLaunch.ts","../src/auth/config.ts","../src/auth/pkce.ts","../src/core/popupProtocol.ts","../src/core/PofsisAuthClient.ts","../src/elements/index.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 { 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","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","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","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","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","import { createPofsisAuth, type PofsisAuthClient } from '../core'\nimport type { AuthLaunchOptions } from '../types'\n\nconst observed = [\n 'app-name',\n 'api-base-url',\n 'auth-url',\n 'scope',\n 'return-url',\n 'screen',\n 'method',\n 'login-hint',\n]\n\nexport class PofsisSignInElement extends HTMLElement {\n static get observedAttributes() {\n return observed\n }\n private client: PofsisAuthClient | null = null\n private button: HTMLButtonElement | null = null\n\n connectedCallback() {\n this.render()\n }\n disconnectedCallback() {\n this.client?.destroy()\n }\n attributeChangedCallback() {\n if (this.isConnected) this.render()\n }\n\n private required(name: string) {\n const value = this.getAttribute(name)?.trim()\n if (!value) throw new Error(`<pofsis-sign-in> requires ${name}`)\n return value\n }\n\n private render() {\n this.client?.destroy()\n this.client = createPofsisAuth({\n appName: this.required('app-name'),\n apiBaseUrl: this.required('api-base-url'),\n authUrl: this.required('auth-url'),\n scope: this.getAttribute('scope') || undefined,\n })\n const label = this.textContent?.trim() || 'Sign in'\n this.replaceChildren()\n this.button = document.createElement('button')\n this.button.type = 'button'\n this.button.part.add('button')\n this.button.textContent = label\n this.button.addEventListener('click', () => void this.launch())\n this.append(this.button)\n }\n\n private async launch() {\n if (!this.client || !this.button) return\n this.button.disabled = true\n const options: AuthLaunchOptions = {\n presentation: 'popup',\n returnUrl: this.getAttribute('return-url') || undefined,\n screen: (this.getAttribute('screen') || 'login') as AuthLaunchOptions['screen'],\n method: (this.getAttribute('method') || undefined) as AuthLaunchOptions['method'],\n loginHint: this.getAttribute('login-hint') || undefined,\n }\n try {\n const result = await this.client.login(options)\n this.dispatchEvent(\n new CustomEvent(`pofsis-auth-${result.status}`, {\n bubbles: true,\n composed: true,\n detail: result,\n }),\n )\n } catch (error) {\n this.dispatchEvent(\n new CustomEvent('pofsis-auth-error', {\n bubbles: true,\n composed: true,\n detail: { error },\n }),\n )\n } finally {\n this.button.disabled = false\n }\n }\n}\n\nif (!customElements.get('pofsis-sign-in')) {\n customElements.define('pofsis-sign-in', PofsisSignInElement)\n}\n"],"mappings":"iGAEA,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,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,QAAS,GACT,SAAU,GACV,OAAQ,CAAE,OAAM,CACpB,CAAC,CACL,CACJ,QAAU,CACN,KAAK,OAAO,SAAW,EAC3B,CACJ,CACJ,SAEK,eAAe,IAAI,gBAAgB,GACpC,eAAe,OAAO,iBAAkB,CAAmB"}
@@ -0,0 +1,7 @@
1
+ export { PofsisAuth } from '../PofsisAuth';
2
+ export { attachAuthInterceptor } from '../attachAuthInterceptor';
3
+ export { AuthErrorScreen, AuthLoadingScreen, PofsisAuthModal, RequireAuth } from '../components';
4
+ export type { RequireAuthProps } from '../components';
5
+ export { useAuth } from '../context/useAuth';
6
+ export type { AccountProfile, AuthComponentOverrides, AuthContextValue, AuthErrorScreenProps, AuthLaunchOptions, AuthLoadingScreenProps, AuthMethod, AuthPopupOptions, AuthResult, AuthScreen, OAuthClientConfig, PofsisAuthConfig, PofsisAuthProps, PofsisAuthModalProps, PofsisUser, SessionPayload, TokenResponse, } from '../types';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAA;AAChE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAChG,YAAY,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAC5C,YAAY,EACR,cAAc,EACd,sBAAsB,EACtB,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EACjB,sBAAsB,EACtB,UAAU,EACV,gBAAgB,EAChB,UAAU,EACV,UAAU,EACV,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,UAAU,EACV,cAAc,EACd,aAAa,GAChB,MAAM,UAAU,CAAA"}
package/dist/react.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./PofsisAuthModal-DIzzLJSP.cjs");exports.AuthErrorScreen=e.s,exports.AuthLoadingScreen=e.o,exports.PofsisAuth=e.a,exports.PofsisAuthModal=e.t,exports.RequireAuth=e.n,exports.attachAuthInterceptor=e.i,exports.useAuth=e.r;
package/dist/react.js ADDED
@@ -0,0 +1,2 @@
1
+ import { a as e, i as t, n, o as r, r as i, s as a, t as o } from "./PofsisAuthModal-DGbtRZ4f.js";
2
+ export { a as AuthErrorScreen, r as AuthLoadingScreen, e as PofsisAuth, o as PofsisAuthModal, n as RequireAuth, t as attachAuthInterceptor, i as useAuth };
package/dist/types.d.ts CHANGED
@@ -38,7 +38,19 @@ export interface PofsisAuthConfig {
38
38
  apiBaseUrl: string;
39
39
  authUrl: string;
40
40
  scope: string;
41
+ callbackPath?: string;
42
+ popup?: AuthPopupOptions;
41
43
  }
44
+ export interface ResolvedPofsisAuthConfig extends PofsisAuthConfig {
45
+ callbackPath: string;
46
+ popup: Required<AuthPopupOptions>;
47
+ }
48
+ export type AuthPopupOptions = {
49
+ width?: number;
50
+ height?: number;
51
+ name?: string;
52
+ timeoutMs?: number;
53
+ };
42
54
  export type AuthLoadingScreenProps = {
43
55
  callback?: boolean;
44
56
  };
@@ -57,13 +69,36 @@ export type AuthLaunchOptions = {
57
69
  screen?: AuthScreen | 'register';
58
70
  loginHint?: string;
59
71
  method?: AuthMethod;
72
+ /** Popup for explicit user actions; redirect for route guards and fallback. */
73
+ presentation?: 'popup' | 'redirect' | 'iframe';
74
+ /** Required only for `presentation: 'iframe'`. */
75
+ target?: HTMLIFrameElement;
76
+ };
77
+ export type AuthResult = {
78
+ status: 'authenticated';
79
+ user: PofsisUser;
80
+ } | {
81
+ status: 'cancelled';
82
+ } | {
83
+ status: 'redirecting';
84
+ };
85
+ export type PofsisAuthClientConfig = {
86
+ appName: string;
87
+ apiBaseUrl: string;
88
+ authUrl: string;
89
+ scope?: string;
90
+ callbackPath?: string;
91
+ popup?: AuthPopupOptions;
60
92
  };
61
93
  export interface AuthContextValue {
62
94
  user: PofsisUser | null;
63
95
  session: SessionPayload | null;
64
96
  isAuthenticated: boolean;
65
97
  isLoading: boolean;
66
- login: (options?: AuthLaunchOptions) => Promise<void>;
98
+ login: (options?: AuthLaunchOptions) => Promise<AuthResult>;
99
+ signup: (options?: Omit<AuthLaunchOptions, 'screen'>) => Promise<AuthResult>;
100
+ resetPassword: (options?: Omit<AuthLaunchOptions, 'screen'>) => Promise<AuthResult>;
101
+ cancelIframeLogin: () => void;
67
102
  logout: () => Promise<void>;
68
103
  refreshSession: () => Promise<void>;
69
104
  getAccessToken: () => string | null;
@@ -86,9 +121,24 @@ export type PofsisAuthProps = {
86
121
  authUrl: string;
87
122
  /** OAuth scope. Defaults to `openid profile email`. */
88
123
  scope?: string;
124
+ /** Tool callback path. Defaults to `/auth/callback`. */
125
+ callbackPath?: string;
126
+ /** Popup dimensions, name, and timeout. */
127
+ popup?: AuthPopupOptions;
89
128
  /** Where to send the user after a successful callback. Default `/`. */
90
129
  postLoginPath?: string;
91
130
  /** Override the package's default loading and error screens. */
92
131
  components?: AuthComponentOverrides;
93
132
  };
133
+ export type PofsisAuthModalProps = {
134
+ open: boolean;
135
+ screen?: AuthScreen;
136
+ method?: AuthMethod;
137
+ loginHint?: string;
138
+ returnUrl?: string;
139
+ title?: string;
140
+ onClose: () => void;
141
+ onAuthenticated?: (user: PofsisUser) => void;
142
+ onError?: (error: Error) => void;
143
+ };
94
144
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACvB,EAAE,EAAE,MAAM,CAAA;IACV,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,KAAK,EAAE,MAAM,CAAA;IACb,WAAW,EAAE,MAAM,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AyB;IACzB,UAAU,EAAE,MAAM,CAAA;IAClB,2BAA2B;IAC3B,OAAO,EAAE,MAAM,CAAA;IACf,uDAAuD;IACvD,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,wDAAwD;IACxD,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,2CAA2C;IAC3C,KAAK,CAAC,EAAE,gBAAgB,CAAA;IACxB,uEAAuE;IACvE,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,gEAAgE;IAChE,UAAU,CAAC,EAAE,sBAAsB,CAAA;CACtC,CAAA;AAED,MAAM,MAAM,oBAAoB,GAAG;IAC/B,IAAI,EAAE,OAAO,CAAA;IACb,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,eAAe,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,IAAI,CAAA;IAC5C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CACnC,CAAA"}
@@ -0,0 +1,178 @@
1
+ # POFSIS Auth popup integration
2
+
3
+ `@pofsis-nbt/pofsis-auth` opens the hosted POFSIS Auth UI in a popup and completes OAuth 2.0 Authorization Code with PKCE in the calling tool. Passwords, OTPs, passkeys, refresh tokens, and Cognito credentials remain owned by POFSIS Auth.
4
+
5
+ ## Prerequisites
6
+
7
+ - Register the tool's exact origin, callback URI, and logout URI with POFSIS Auth for each environment.
8
+ - Use HTTPS outside local development and allow the tool origin in Auth CORS configuration.
9
+ - Obtain the registered application code and allowed public scopes.
10
+ - Never put an OAuth client secret or organization service credential in a browser application.
11
+
12
+ ## Package entry points
13
+
14
+ ```bash
15
+ npm install @pofsis-nbt/pofsis-auth
16
+ ```
17
+
18
+ | Import | Use |
19
+ | ---------------------------------- | ----------------------------------------------- |
20
+ | `@pofsis-nbt/pofsis-auth/core` | Framework-neutral browser SDK |
21
+ | `@pofsis-nbt/pofsis-auth/react` | React provider, hooks, guards, and API helper |
22
+ | `@pofsis-nbt/pofsis-auth/elements` | Optional `<pofsis-sign-in>` Web Component |
23
+ | `@pofsis-nbt/pofsis-auth` | Backward-compatible React API plus core exports |
24
+
25
+ ## Framework-neutral setup
26
+
27
+ ```js
28
+ import { createPofsisAuth, relayPopupCallback } from '@pofsis-nbt/pofsis-auth/core'
29
+
30
+ const auth = createPofsisAuth({
31
+ appName: 'POFBUSINESS',
32
+ apiBaseUrl: 'https://auth-api.example.com',
33
+ authUrl: 'https://auth.example.com/authorize',
34
+ })
35
+
36
+ // Run this before rendering the normal app on /auth/callback.
37
+ if (location.pathname === '/auth/callback') {
38
+ const relayed = relayPopupCallback()
39
+ if (!relayed) {
40
+ const params = new URLSearchParams(location.search)
41
+ await auth.completeRedirectCallback(params.get('code'), params.get('state'))
42
+ }
43
+ }
44
+ ```
45
+
46
+ Call popup authentication directly from a click or other user gesture:
47
+
48
+ ```js
49
+ document.querySelector('#login').addEventListener('click', async () => {
50
+ const result = await auth.login({
51
+ presentation: 'popup',
52
+ screen: 'login',
53
+ returnUrl: location.pathname + location.search,
54
+ })
55
+ if (result.status === 'authenticated') renderUser(result.user)
56
+ })
57
+ ```
58
+
59
+ The SDK calls `window.open()` itself. A blocked popup falls back to a full-page redirect. Route guards should explicitly use `presentation: 'redirect'` because they may not run during a user gesture.
60
+
61
+ ## Initialization parameters
62
+
63
+ | Parameter | Required | Default | Meaning |
64
+ | ----------------- | -------: | ---------------------- | ---------------------------------- |
65
+ | `appName` | yes | - | Registered POFSIS application code |
66
+ | `apiBaseUrl` | yes | - | Public POFSIS Auth API base URL |
67
+ | `authUrl` | yes | - | Hosted Auth `/authorize` URL |
68
+ | `scope` | no | `openid profile email` | Registered OAuth scopes |
69
+ | `callbackPath` | no | `/auth/callback` | Local tool callback route |
70
+ | `popup.width` | no | `480` | Popup width in pixels |
71
+ | `popup.height` | no | `720` | Popup height in pixels |
72
+ | `popup.name` | no | `pofsis-auth` | Reused browser window name |
73
+ | `popup.timeoutMs` | no | `300000` | Authentication timeout |
74
+
75
+ ## Launch parameters
76
+
77
+ | Parameter | Required | Default | Meaning |
78
+ | -------------- | -------: | ------------ | ---------------------------------------------------- |
79
+ | `presentation` | no | `popup` | `popup` or full-page `redirect` |
80
+ | `screen` | no | `login` | `login`, `signup`, or `reset` |
81
+ | `method` | no | Auth default | `password`, `passkey`, or `otp` |
82
+ | `loginHint` | no | - | Editable email or Philippine mobile hint |
83
+ | `returnUrl` | no | - | Safe application-relative route restored after login |
84
+
85
+ `returnUrl` must start with one `/` and must not start with `//`. Do not put invitation secrets or external URLs in it.
86
+
87
+ Convenience methods use the same protocol:
88
+
89
+ ```js
90
+ await auth.signup({ loginHint: 'employee@example.com', method: 'otp' })
91
+ await auth.resetPassword({ loginHint: 'employee@example.com' })
92
+ await auth.login({ method: 'password' })
93
+ await auth.login({ method: 'passkey' })
94
+ ```
95
+
96
+ ## React
97
+
98
+ ```tsx
99
+ import { PofsisAuth, useAuth } from '@pofsis-nbt/pofsis-auth/react'
100
+ import '@pofsis-nbt/pofsis-auth/style.css'
101
+
102
+ function SignInButton() {
103
+ const { login } = useAuth()
104
+ return <button onClick={() => void login({ presentation: 'popup' })}>Sign in</button>
105
+ }
106
+
107
+ export function App() {
108
+ return (
109
+ <PofsisAuth
110
+ appName="POFBUSINESS"
111
+ apiBaseUrl="https://auth-api.example.com"
112
+ authUrl="https://auth.example.com/authorize"
113
+ >
114
+ <SignInButton />
115
+ </PofsisAuth>
116
+ )
117
+ }
118
+ ```
119
+
120
+ `RequireAuth` deliberately uses redirect presentation. The provider handles popup and full-page callbacks at `callbackPath`.
121
+
122
+ ### Iframe modal
123
+
124
+ `PofsisAuthModal` keeps hosted Auth inside the current tool while the parent SDK retains PKCE state:
125
+
126
+ ```tsx
127
+ <PofsisAuthModal
128
+ open={authOpen}
129
+ screen="login"
130
+ returnUrl="/apps/submit"
131
+ onClose={() => setAuthOpen(false)}
132
+ onAuthenticated={() => setAuthOpen(false)}
133
+ />
134
+ ```
135
+
136
+ The Auth hosting response must allow the registered tool origin through CSP `frame-ancestors` and must not send a conflicting `X-Frame-Options` header. Passkeys require the component's included `publickey-credentials-get` and `publickey-credentials-create` iframe permissions. Browsers that reject the embedded Auth cookie or WebAuthn flow should use popup or redirect presentation instead.
137
+
138
+ ## Web Component
139
+
140
+ Import the package entry or host the generated standalone `dist/pofsis-auth-elements.js` bundle:
141
+
142
+ ```html
143
+ <script type="module" src="https://auth.pofsis.com/sdk/pofsis-auth-elements.js"></script>
144
+
145
+ <pofsis-sign-in
146
+ app-name="POFBUSINESS"
147
+ api-base-url="https://auth-api.example.com"
148
+ auth-url="https://auth.example.com/authorize"
149
+ return-url="/dashboard"
150
+ >Sign in</pofsis-sign-in
151
+ >
152
+ ```
153
+
154
+ The element dispatches `pofsis-auth-authenticated`, `pofsis-auth-cancelled`, `pofsis-auth-redirecting`, and `pofsis-auth-error`. It is only a launch control; credential fields always render on the hosted Auth origin.
155
+
156
+ ## Session and API calls
157
+
158
+ ```js
159
+ const unsubscribe = auth.subscribe((session) => updateHeader(session?.user))
160
+ const token = auth.getAccessToken()
161
+ await auth.refreshSession()
162
+ await auth.logout()
163
+ unsubscribe()
164
+ ```
165
+
166
+ Access tokens are held in memory. Use `getAccessToken()` to add a bearer token to the tool's own API calls. Do not write access tokens to URLs or browser storage.
167
+
168
+ ## Results and failures
169
+
170
+ - `authenticated`: code exchange succeeded and includes the user.
171
+ - `cancelled`: the user closed the popup; this is not an authentication error.
172
+ - `redirecting`: the SDK started full-page navigation, including popup-blocked fallback.
173
+ - Invalid state, origin, popup source, or correlation messages are ignored or rejected.
174
+ - A timeout rejects the launch and closes the popup.
175
+
176
+ For callback URI mismatches, verify the exact deployed origin and registered URI. For CORS or silent-session failures, verify Auth's origin registry and credentialed cookie configuration. A cancelled or unavailable passkey remains an Auth-screen concern and must retain the password fallback.
177
+
178
+ The frontend SDK must never call `/api/internal`, Cognito administration APIs, or organization provisioning APIs. Those flows remain tool-backend to Auth-backend operations.
package/package.json CHANGED
@@ -1,62 +1,87 @@
1
- {
2
- "name": "@pofsis-nbt/pofsis-auth",
3
- "version": "1.0.3",
4
- "description": "POFSIS OAuth/PKCE authentication client for React applications.",
5
- "type": "module",
6
- "main": "./dist/index.cjs",
7
- "module": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
9
- "exports": {
10
- ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.cjs",
14
- "default": "./dist/index.js"
15
- },
16
- "./style.css": "./dist/style.css"
17
- },
18
- "files": [
19
- "dist",
20
- "README.md",
21
- "Documentation.md"
22
- ],
23
- "sideEffects": [
24
- "**/*.css"
25
- ],
26
- "engines": {
27
- "node": "^20.19.0 || >=22.12.0"
28
- },
29
- "scripts": {
30
- "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
31
- "typecheck": "tsc --noEmit -p tsconfig.json",
32
- "test": "tsx --test src/**/*.test.ts",
33
- "check": "npm run typecheck && npm test",
34
- "build": "npm run clean && vite build && tsc -p tsconfig.build.json",
35
- "prepack": "npm run check && npm run build",
36
- "pack:check": "npm pack --dry-run --json",
37
- "format": "prettier --write .",
38
- "format:check": "prettier --check ."
39
- },
40
- "peerDependencies": {
41
- "axios": ">=1",
42
- "react": ">=18",
43
- "react-dom": ">=18"
44
- },
45
- "peerDependenciesMeta": {
46
- "axios": {
47
- "optional": true
48
- }
49
- },
50
- "devDependencies": {
51
- "@types/node": "^26.0.0",
52
- "@types/react": "^19.2.0",
53
- "@types/react-dom": "^19.2.0",
54
- "axios": "^1.19.0",
55
- "prettier": "^3.6.0",
56
- "react": "^19.2.0",
57
- "react-dom": "^19.2.0",
58
- "tsx": "^4.20.0",
59
- "typescript": "^5.9.0",
60
- "vite": "^8.2.0"
61
- }
62
- }
1
+ {
2
+ "name": "@pofsis-nbt/pofsis-auth",
3
+ "version": "1.2.0",
4
+ "description": "POFSIS OAuth/PKCE authentication SDK for browser applications.",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./core": {
17
+ "types": "./dist/core/index.d.ts",
18
+ "import": "./dist/core.js",
19
+ "require": "./dist/core.cjs",
20
+ "default": "./dist/core.js"
21
+ },
22
+ "./react": {
23
+ "types": "./dist/react/index.d.ts",
24
+ "import": "./dist/react.js",
25
+ "require": "./dist/react.cjs",
26
+ "default": "./dist/react.js"
27
+ },
28
+ "./elements": {
29
+ "types": "./dist/elements/index.d.ts",
30
+ "import": "./dist/elements.js",
31
+ "require": "./dist/elements.cjs",
32
+ "default": "./dist/elements.js"
33
+ },
34
+ "./style.css": "./dist/style.css"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "README.md",
39
+ "Documentation.md",
40
+ "docs"
41
+ ],
42
+ "sideEffects": [
43
+ "**/*.css"
44
+ ],
45
+ "engines": {
46
+ "node": "^20.19.0 || >=22.12.0"
47
+ },
48
+ "scripts": {
49
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
50
+ "typecheck": "tsc --noEmit -p tsconfig.json",
51
+ "test": "tsx --test src/**/*.test.ts",
52
+ "check": "npm run typecheck && npm test",
53
+ "build": "npm run clean && vite build && vite build --config vite.elements.config.ts && tsc -p tsconfig.build.json",
54
+ "prepack": "npm run check && npm run build",
55
+ "pack:check": "npm pack --dry-run --json",
56
+ "format": "prettier --write .",
57
+ "format:check": "prettier --check ."
58
+ },
59
+ "peerDependencies": {
60
+ "axios": ">=1",
61
+ "react": ">=18",
62
+ "react-dom": ">=18"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "axios": {
66
+ "optional": true
67
+ },
68
+ "react": {
69
+ "optional": true
70
+ },
71
+ "react-dom": {
72
+ "optional": true
73
+ }
74
+ },
75
+ "devDependencies": {
76
+ "@types/node": "^26.0.0",
77
+ "@types/react": "^19.2.0",
78
+ "@types/react-dom": "^19.2.0",
79
+ "axios": "^1.19.0",
80
+ "prettier": "^3.6.0",
81
+ "react": "^19.2.0",
82
+ "react-dom": "^19.2.0",
83
+ "tsx": "^4.20.0",
84
+ "typescript": "^5.9.0",
85
+ "vite": "^8.2.0"
86
+ }
87
+ }