@pofsis-nbt/pofsis-auth 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Documentation.md +143 -141
- package/README.md +130 -119
- package/dist/PofsisAuth.d.ts +1 -5
- package/dist/PofsisAuth.d.ts.map +1 -1
- package/dist/PofsisAuthClient-B-07-cNX.cjs +2 -0
- package/dist/PofsisAuthClient-B-07-cNX.cjs.map +1 -0
- package/dist/PofsisAuthClient-DJSQb0qq.js +390 -0
- package/dist/PofsisAuthClient-DJSQb0qq.js.map +1 -0
- package/dist/RequireAuth-BFjNqM_v.js +403 -0
- package/dist/RequireAuth-BFjNqM_v.js.map +1 -0
- package/dist/RequireAuth-n5Hb1WL9.cjs +2 -0
- package/dist/RequireAuth-n5Hb1WL9.cjs.map +1 -0
- package/dist/auth/config.d.ts +3 -5
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/components/AuthPathShell.d.ts +2 -1
- package/dist/components/AuthPathShell.d.ts.map +1 -1
- package/dist/core/PofsisAuthClient.d.ts +43 -0
- package/dist/core/PofsisAuthClient.d.ts.map +1 -0
- package/dist/core/index.d.ts +4 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/popupProtocol.d.ts +11 -0
- package/dist/core/popupProtocol.d.ts.map +1 -0
- package/dist/core.cjs +1 -0
- package/dist/core.js +2 -0
- package/dist/elements/index.d.ts +12 -0
- package/dist/elements/index.d.ts.map +1 -0
- package/dist/elements.cjs +2 -0
- package/dist/elements.cjs.map +1 -0
- package/dist/elements.js +75 -0
- package/dist/elements.js.map +1 -0
- package/dist/index.cjs +1 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -623
- package/dist/pofsis-auth-elements.js +2 -0
- package/dist/pofsis-auth-elements.js.map +1 -0
- package/dist/react/index.d.ts +7 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react.cjs +1 -0
- package/dist/react.js +2 -0
- package/dist/types.d.ts +37 -1
- package/dist/types.d.ts.map +1 -1
- package/docs/popup-integration.md +162 -0
- package/package.json +87 -62
- package/dist/index.cjs.map +0 -1
- 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;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.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);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 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}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||x(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 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 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","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","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,CAAE,eA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KAAK,GAAK,UAC1C,KAAK,gBAAgB,EACrB,KAAK,OAAS,SAAS,cAAc,QAAQ,EAC7C,KAAK,OAAO,KAAO,SACnB,KAAK,OAAO,KAAK,IAAI,QAAQ,EAC7B,KAAK,OAAO,YAAc,EAC1B,KAAK,OAAO,iBAAiB,YAAe,KAAK,KAAK,OAAO,CAAC,EAC9D,KAAK,OAAO,KAAK,MAAM,CAC3B,CAEA,MAAc,QAAS,CACnB,GAAI,CAAC,KAAK,QAAU,CAAC,KAAK,OAAQ,OAClC,KAAK,OAAO,SAAW,GACvB,IAAM,EAA6B,CAC/B,aAAc,QACd,UAAW,KAAK,aAAa,YAAY,GAAK,IAAA,GAC9C,OAAS,KAAK,aAAa,QAAQ,GAAK,QACxC,OAAS,KAAK,aAAa,QAAQ,GAAK,IAAA,GACxC,UAAW,KAAK,aAAa,YAAY,GAAK,IAAA,EAClD,EACA,GAAI,CACA,IAAM,EAAS,MAAM,KAAK,OAAO,MAAM,CAAO,EAC9C,KAAK,cACD,IAAI,YAAY,eAAe,EAAO,SAAU,CAC5C,QAAS,GACT,SAAU,GACV,OAAQ,CACZ,CAAC,CACL,CACJ,OAAS,EAAO,CACZ,KAAK,cACD,IAAI,YAAY,oBAAqB,CACjC,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, 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, 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,WAAW,EAAE,MAAM,eAAe,CAAA;AAC/E,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,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("./RequireAuth-n5Hb1WL9.cjs");exports.AuthErrorScreen=e.o,exports.AuthLoadingScreen=e.a,exports.PofsisAuth=e.i,exports.RequireAuth=e.t,exports.attachAuthInterceptor=e.r,exports.useAuth=e.n;
|
package/dist/react.js
ADDED
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,33 @@ 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';
|
|
74
|
+
};
|
|
75
|
+
export type AuthResult = {
|
|
76
|
+
status: 'authenticated';
|
|
77
|
+
user: PofsisUser;
|
|
78
|
+
} | {
|
|
79
|
+
status: 'cancelled';
|
|
80
|
+
} | {
|
|
81
|
+
status: 'redirecting';
|
|
82
|
+
};
|
|
83
|
+
export type PofsisAuthClientConfig = {
|
|
84
|
+
appName: string;
|
|
85
|
+
apiBaseUrl: string;
|
|
86
|
+
authUrl: string;
|
|
87
|
+
scope?: string;
|
|
88
|
+
callbackPath?: string;
|
|
89
|
+
popup?: AuthPopupOptions;
|
|
60
90
|
};
|
|
61
91
|
export interface AuthContextValue {
|
|
62
92
|
user: PofsisUser | null;
|
|
63
93
|
session: SessionPayload | null;
|
|
64
94
|
isAuthenticated: boolean;
|
|
65
95
|
isLoading: boolean;
|
|
66
|
-
login: (options?: AuthLaunchOptions) => Promise<
|
|
96
|
+
login: (options?: AuthLaunchOptions) => Promise<AuthResult>;
|
|
97
|
+
signup: (options?: Omit<AuthLaunchOptions, 'screen'>) => Promise<AuthResult>;
|
|
98
|
+
resetPassword: (options?: Omit<AuthLaunchOptions, 'screen'>) => Promise<AuthResult>;
|
|
67
99
|
logout: () => Promise<void>;
|
|
68
100
|
refreshSession: () => Promise<void>;
|
|
69
101
|
getAccessToken: () => string | null;
|
|
@@ -86,6 +118,10 @@ export type PofsisAuthProps = {
|
|
|
86
118
|
authUrl: string;
|
|
87
119
|
/** OAuth scope. Defaults to `openid profile email`. */
|
|
88
120
|
scope?: string;
|
|
121
|
+
/** Tool callback path. Defaults to `/auth/callback`. */
|
|
122
|
+
callbackPath?: string;
|
|
123
|
+
/** Popup dimensions, name, and timeout. */
|
|
124
|
+
popup?: AuthPopupOptions;
|
|
89
125
|
/** Where to send the user after a successful callback. Default `/`. */
|
|
90
126
|
postLoginPath?: string;
|
|
91
127
|
/** Override the package's default loading and error screens. */
|
package/dist/types.d.ts.map
CHANGED
|
@@ -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,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;CACnB;AAED,MAAM,WAAW,cAAc;IAC3B,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC/B,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC7B,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EA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AC3C,KAAK,CAAC,EAAE,gBAAgB,CAAA;IACxB,uEAAuE;IACvE,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,gEAAgE;IAChE,UAAU,CAAC,EAAE,sBAAsB,CAAA;CACtC,CAAA"}
|
|
@@ -0,0 +1,162 @@
|
|
|
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
|
+
## Web Component
|
|
123
|
+
|
|
124
|
+
Import the package entry or host the generated standalone `dist/pofsis-auth-elements.js` bundle:
|
|
125
|
+
|
|
126
|
+
```html
|
|
127
|
+
<script type="module" src="https://auth.pofsis.com/sdk/pofsis-auth-elements.js"></script>
|
|
128
|
+
|
|
129
|
+
<pofsis-sign-in
|
|
130
|
+
app-name="POFBUSINESS"
|
|
131
|
+
api-base-url="https://auth-api.example.com"
|
|
132
|
+
auth-url="https://auth.example.com/authorize"
|
|
133
|
+
return-url="/dashboard"
|
|
134
|
+
>Sign in</pofsis-sign-in
|
|
135
|
+
>
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
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.
|
|
139
|
+
|
|
140
|
+
## Session and API calls
|
|
141
|
+
|
|
142
|
+
```js
|
|
143
|
+
const unsubscribe = auth.subscribe((session) => updateHeader(session?.user))
|
|
144
|
+
const token = auth.getAccessToken()
|
|
145
|
+
await auth.refreshSession()
|
|
146
|
+
await auth.logout()
|
|
147
|
+
unsubscribe()
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
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.
|
|
151
|
+
|
|
152
|
+
## Results and failures
|
|
153
|
+
|
|
154
|
+
- `authenticated`: code exchange succeeded and includes the user.
|
|
155
|
+
- `cancelled`: the user closed the popup; this is not an authentication error.
|
|
156
|
+
- `redirecting`: the SDK started full-page navigation, including popup-blocked fallback.
|
|
157
|
+
- Invalid state, origin, popup source, or correlation messages are ignored or rejected.
|
|
158
|
+
- A timeout rejects the launch and closes the popup.
|
|
159
|
+
|
|
160
|
+
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.
|
|
161
|
+
|
|
162
|
+
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
|
|
4
|
-
"description": "POFSIS OAuth/PKCE authentication
|
|
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
|
-
"./
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
"
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
"
|
|
44
|
-
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
"
|
|
52
|
-
"
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"
|
|
57
|
-
"
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
"
|
|
61
|
-
|
|
62
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@pofsis-nbt/pofsis-auth",
|
|
3
|
+
"version": "1.1.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
|
+
}
|