@pofsis-nbt/pofsis-auth 1.2.0 → 2.0.1
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 +147 -143
- package/README.md +133 -130
- package/dist/PofsisAuth.d.ts +1 -1
- package/dist/PofsisAuth.d.ts.map +1 -1
- package/dist/PofsisAuthClient-B3YHqgZL.cjs +2 -0
- package/dist/PofsisAuthClient-B3YHqgZL.cjs.map +1 -0
- package/dist/{PofsisAuthClient-c9BY8iNp.js → PofsisAuthClient-CEw_lL5S.js} +31 -80
- package/dist/PofsisAuthClient-CEw_lL5S.js.map +1 -0
- package/dist/{PofsisAuthModal-DIzzLJSP.cjs → RequireAuth-CPhXupYh.cjs} +2 -2
- package/dist/RequireAuth-CPhXupYh.cjs.map +1 -0
- package/dist/{PofsisAuthModal-DGbtRZ4f.js → RequireAuth-DFa8_MR1.js} +6 -98
- package/dist/RequireAuth-DFa8_MR1.js.map +1 -0
- package/dist/auth/authLaunch.d.ts +1 -2
- package/dist/auth/authLaunch.d.ts.map +1 -1
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/components/index.d.ts +0 -1
- package/dist/components/index.d.ts.map +1 -1
- package/dist/core/PofsisAuthClient.d.ts +0 -4
- package/dist/core/PofsisAuthClient.d.ts.map +1 -1
- package/dist/core/popupProtocol.d.ts.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/elements.cjs +1 -1
- package/dist/elements.cjs.map +1 -1
- package/dist/elements.js +3 -3
- package/dist/elements.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/pofsis-auth-elements.js +1 -1
- package/dist/pofsis-auth-elements.js.map +1 -1
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.js +2 -2
- package/dist/types.d.ts +7 -21
- package/dist/types.d.ts.map +1 -1
- package/docs/application-id-consumer-migration.md +180 -0
- package/docs/popup-integration.md +162 -178
- package/package.json +87 -87
- package/dist/PofsisAuthClient-CRYYsJYc.cjs +0 -2
- package/dist/PofsisAuthClient-CRYYsJYc.cjs.map +0 -1
- package/dist/PofsisAuthClient-c9BY8iNp.js.map +0 -1
- package/dist/PofsisAuthModal-DGbtRZ4f.js.map +0 -1
- package/dist/PofsisAuthModal-DIzzLJSP.cjs.map +0 -1
- package/dist/components/PofsisAuthModal.d.ts +0 -3
- package/dist/components/PofsisAuthModal.d.ts.map +0 -1
|
@@ -1 +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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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"}
|
|
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'\r\n\r\nasync function parseJson<T>(response: Response): Promise<T> {\r\n if (response.status === 204) return null as T\r\n const text = await response.text()\r\n if (!text) return null as T\r\n return JSON.parse(text) as T\r\n}\r\n\r\nasync function request<T>(\r\n config: PofsisAuthConfig,\r\n path: string,\r\n init?: RequestInit,\r\n): Promise<{ status: number; data: T }> {\r\n const response = await fetch(`${config.apiBaseUrl}${path}`, {\r\n credentials: 'include',\r\n ...init,\r\n headers: {\r\n Accept: 'application/json',\r\n ...(init?.body && !(init.body instanceof FormData)\r\n ? { 'Content-Type': 'application/json' }\r\n : {}),\r\n ...init?.headers,\r\n },\r\n })\r\n if (!response.ok) {\r\n const error = new Error(`Auth API ${path} failed (${response.status})`)\r\n ;(error as Error & { status?: number }).status = response.status\r\n throw error\r\n }\r\n return { status: response.status, data: await parseJson<T>(response) }\r\n}\r\n\r\nexport async function fetchOAuthClient(config: PofsisAuthConfig) {\r\n const applicationId = encodeURIComponent(config.applicationId)\r\n const origin = encodeURIComponent(window.location.origin)\r\n const { data } = await request<OAuthClientConfig>(\r\n config,\r\n `/oauth/applications/${applicationId}/client?origin=${origin}`,\r\n )\r\n return data\r\n}\r\n\r\nexport async function exchangeCode(\r\n config: PofsisAuthConfig,\r\n code: string,\r\n verifier: string,\r\n client: Pick<OAuthClientConfig, 'client_id' | 'redirect_uri'>,\r\n) {\r\n const { data } = await request<TokenResponse>(config, '/oauth/token', {\r\n method: 'POST',\r\n body: JSON.stringify({\r\n grant_type: 'authorization_code',\r\n client_id: client.client_id,\r\n redirect_uri: client.redirect_uri,\r\n code,\r\n code_verifier: verifier,\r\n }),\r\n })\r\n return data\r\n}\r\n\r\nexport async function refresh(config: PofsisAuthConfig, clientId: string) {\r\n const { data } = await request<TokenResponse | null>(config, '/oauth/token', {\r\n method: 'POST',\r\n body: JSON.stringify({\r\n grant_type: 'refresh_token',\r\n client_id: clientId,\r\n }),\r\n })\r\n return data || null\r\n}\r\n\r\nexport async function checkSession(config: PofsisAuthConfig) {\r\n try {\r\n await request(config, '/auth/session')\r\n return true\r\n } catch {\r\n return false\r\n }\r\n}\r\n\r\nexport async function signOut(config: PofsisAuthConfig) {\r\n await request(config, '/auth/logout', { method: 'POST' })\r\n}\r\n\r\nexport async function getAccountProfile(config: PofsisAuthConfig, accessToken: string) {\r\n const { data } = await request<AccountProfile>(config, '/auth/profile/me', {\r\n headers: { Authorization: `Bearer ${accessToken}` },\r\n })\r\n return data\r\n}\r\n\r\nexport async function updateAccountProfile(\r\n config: PofsisAuthConfig,\r\n accessToken: string,\r\n profile: { firstName?: string | null; lastName?: string | null },\r\n) {\r\n const { data } = await request<AccountProfile>(config, '/auth/profile/me', {\r\n method: 'PATCH',\r\n headers: { Authorization: `Bearer ${accessToken}` },\r\n body: JSON.stringify(profile),\r\n })\r\n return data\r\n}\r\n\r\nexport async function uploadAccountProfileImage(\r\n config: PofsisAuthConfig,\r\n accessToken: string,\r\n kind: 'profile' | 'cover',\r\n file: File,\r\n) {\r\n const body = new FormData()\r\n body.append('file', file)\r\n const { data } = await request<AccountProfile>(config, `/auth/profile/me/images/${kind}`, {\r\n method: 'POST',\r\n headers: { Authorization: `Bearer ${accessToken}` },\r\n body,\r\n })\r\n return data\r\n}\r\n\r\nexport async function deleteAccountProfileImage(\r\n config: PofsisAuthConfig,\r\n accessToken: string,\r\n kind: 'profile' | 'cover',\r\n) {\r\n const { data } = await request<AccountProfile>(config, `/auth/profile/me/images/${kind}`, {\r\n method: 'DELETE',\r\n headers: { Authorization: `Bearer ${accessToken}` },\r\n })\r\n return data\r\n}\r\n","import type { AuthLaunchOptions, AuthMethod, AuthScreen } from '../types'\r\n\r\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\r\nconst PHILIPPINE_MOBILE = /^(?:\\+63|63|0)?9\\d{9}$/\r\nconst METHODS = new Set<AuthMethod>(['password', 'passkey', 'otp'])\r\nconst SCREENS = new Set<AuthScreen>(['login', 'signup', 'reset'])\r\nconst MAX_HINT_LENGTH = 320\r\n\r\nfunction normalizeHint(value: unknown, emailOnly = false): string | undefined {\r\n const candidate = typeof value === 'string' ? value.trim() : ''\r\n if (!candidate || candidate.length > MAX_HINT_LENGTH) return undefined\r\n if (EMAIL.test(candidate)) return candidate.toLowerCase()\r\n const compact = candidate.replace(/[\\s()-]/g, '')\r\n if (emailOnly || !PHILIPPINE_MOBILE.test(compact)) return undefined\r\n return `+63${compact.replace(/^(?:\\+63|63|0)/, '')}`\r\n}\r\n\r\nexport function normalizeAuthLaunchOptions(\r\n value?: AuthLaunchOptions | string | null,\r\n defaultScreen: AuthScreen = 'login',\r\n) {\r\n const options = typeof value === 'string' ? { returnUrl: value } : value || {}\r\n const requestedScreen = options.screen === 'register' ? 'signup' : options.screen\r\n const screen = SCREENS.has(requestedScreen as AuthScreen)\r\n ? (requestedScreen as AuthScreen)\r\n : defaultScreen\r\n const requestedMethod = METHODS.has(options.method as AuthMethod)\r\n ? (options.method as AuthMethod)\r\n : undefined\r\n const method =\r\n screen === 'login' ||\r\n (screen === 'signup' && (requestedMethod === 'password' || requestedMethod === 'otp'))\r\n ? requestedMethod\r\n : undefined\r\n return {\r\n returnUrl: options.returnUrl,\r\n screen,\r\n loginHint: normalizeHint(options.loginHint),\r\n method,\r\n }\r\n}\r\n\r\nexport function authLaunchOptionsFromSearch(search: string) {\r\n const params = new URLSearchParams(search)\r\n const canonicalHint = params.get('login_hint')\r\n const loginHint =\r\n canonicalHint !== null\r\n ? normalizeHint(canonicalHint)\r\n : normalizeHint(params.get('email'), true)\r\n return normalizeAuthLaunchOptions({\r\n screen: (params.get('screen') || undefined) as AuthLaunchOptions['screen'],\r\n loginHint,\r\n method: (params.get('method') || undefined) as AuthLaunchOptions['method'],\r\n })\r\n}\r\n\r\nexport function buildAuthDestination({\r\n authUrl,\r\n query,\r\n options,\r\n}: {\r\n authUrl: string\r\n query: URLSearchParams\r\n options?: AuthLaunchOptions\r\n}) {\r\n const launch = normalizeAuthLaunchOptions(options)\r\n const authorizationUrl = new URL(authUrl)\r\n authorizationUrl.search = query.toString()\r\n if (launch.loginHint) authorizationUrl.searchParams.set('login_hint', launch.loginHint)\r\n if (launch.screen === 'login' && launch.method) {\r\n authorizationUrl.searchParams.set('method', launch.method)\r\n }\r\n if (launch.screen === 'login') return authorizationUrl.toString()\r\n\r\n const pathname = launch.screen === 'signup' ? '/signup' : '/forgot-password'\r\n const destination = new URL(pathname, authorizationUrl)\r\n const clientId = query.get('client_id')\r\n if (clientId) destination.searchParams.set('client_id', clientId)\r\n destination.searchParams.set(\r\n 'return_to',\r\n `${authorizationUrl.pathname}${authorizationUrl.search}`,\r\n )\r\n if (launch.loginHint) destination.searchParams.set('login_hint', launch.loginHint)\r\n if (launch.screen === 'signup') {\r\n destination.searchParams.set('method', launch.method || 'password')\r\n }\r\n return destination.toString()\r\n}\r\n","import type { PofsisAuthClientConfig, ResolvedPofsisAuthConfig } from '../types'\r\n\r\nfunction stripTrailingSlash(value: string) {\r\n return value.replace(/\\/$/, '')\r\n}\r\n\r\nexport type ConfigOverrides = Partial<PofsisAuthClientConfig>\r\n\r\n/**\r\n * Validate and normalize explicitly supplied runtime configuration.\r\n */\r\nexport function resolveConfig(overrides: ConfigOverrides = {}): ResolvedPofsisAuthConfig {\r\n const applicationId = overrides.applicationId?.trim()\r\n const apiBaseUrl = overrides.apiBaseUrl?.trim()\r\n const authUrl = overrides.authUrl?.trim()\r\n const scope = overrides.scope?.trim() || 'openid profile email'\r\n const callbackPath = overrides.callbackPath?.trim() || '/auth/callback'\r\n const popup = {\r\n width: overrides.popup?.width ?? 480,\r\n height: overrides.popup?.height ?? 720,\r\n name: overrides.popup?.name?.trim() || 'pofsis-auth',\r\n timeoutMs: overrides.popup?.timeoutMs ?? 300_000,\r\n }\r\n\r\n const missing: string[] = []\r\n if (!applicationId) missing.push('applicationId')\r\n if (!apiBaseUrl) missing.push('apiBaseUrl')\r\n if (!authUrl) missing.push('authUrl')\r\n if (missing.length) {\r\n throw new Error(`@pofsis-nbt/pofsis-auth missing config: ${missing.join(', ')}`)\r\n }\r\n if (!applicationId || !apiBaseUrl || !authUrl) {\r\n throw new Error('@pofsis-nbt/pofsis-auth missing config')\r\n }\r\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(applicationId)) {\r\n throw new Error('@pofsis-nbt/pofsis-auth applicationId must be a UUID')\r\n }\r\n if (!callbackPath.startsWith('/') || callbackPath.startsWith('//')) {\r\n throw new Error('@pofsis-nbt/pofsis-auth callbackPath must be application-relative')\r\n }\r\n if (popup.width <= 0 || popup.height <= 0 || popup.timeoutMs <= 0) {\r\n throw new Error('@pofsis-nbt/pofsis-auth popup dimensions and timeout must be positive')\r\n }\r\n\r\n return {\r\n applicationId: applicationId.toLowerCase(),\r\n apiBaseUrl: stripTrailingSlash(apiBaseUrl),\r\n authUrl: stripTrailingSlash(authUrl),\r\n scope,\r\n callbackPath,\r\n popup,\r\n }\r\n}\r\n","const encode = (bytes: Uint8Array) =>\r\n btoa(String.fromCharCode(...bytes))\r\n .replace(/\\+/g, '-')\r\n .replace(/\\//g, '_')\r\n .replace(/=+$/, '')\r\n\r\nexport const randomValue = () => encode(crypto.getRandomValues(new Uint8Array(32)))\r\n\r\nexport async function pkceChallenge(verifier: string) {\r\n return encode(\r\n new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))),\r\n )\r\n}\r\n","export const POPUP_MESSAGE_TYPE = 'pofsis-auth:callback'\r\n\r\nexport type PopupCallbackMessage = {\r\n type: typeof POPUP_MESSAGE_TYPE\r\n code?: string\r\n state?: string\r\n error?: string\r\n correlationId?: string\r\n}\r\n\r\nexport function correlationFromState(state: string | null) {\r\n if (!state) return undefined\r\n const separator = state.indexOf('.')\r\n return separator > 0 ? state.slice(0, separator) : undefined\r\n}\r\n\r\nexport function relayPopupCallback(targetOrigin = window.location.origin) {\r\n if (!window.opener || window.opener.closed) return false\r\n const params = new URLSearchParams(window.location.search)\r\n const state = params.get('state') || undefined\r\n const message: PopupCallbackMessage = {\r\n type: POPUP_MESSAGE_TYPE,\r\n code: params.get('code') || undefined,\r\n state,\r\n error: params.get('error') || undefined,\r\n correlationId: correlationFromState(state || null),\r\n }\r\n window.opener.postMessage(message, targetOrigin)\r\n window.close()\r\n return true\r\n}\r\n","import { checkSession, exchangeCode, fetchOAuthClient, refresh, signOut } from '../auth/api'\r\nimport { buildAuthDestination, normalizeAuthLaunchOptions } from '../auth/authLaunch'\r\nimport { resolveConfig } from '../auth/config'\r\nimport { pkceChallenge, randomValue } from '../auth/pkce'\r\nimport type {\r\n AuthLaunchOptions,\r\n AuthResult,\r\n OAuthClientConfig,\r\n PofsisAuthClientConfig,\r\n ResolvedPofsisAuthConfig,\r\n PofsisUser,\r\n SessionPayload,\r\n} from '../types'\r\nimport {\r\n correlationFromState,\r\n POPUP_MESSAGE_TYPE,\r\n type PopupCallbackMessage,\r\n} from './popupProtocol'\r\n\r\ntype Subscriber = (session: SessionPayload | null) => void\r\ntype PopupAttempt = {\r\n popup: Window\r\n state: string\r\n verifier: string\r\n correlationId: string\r\n returnUrl?: string\r\n resolve: (result: AuthResult) => void\r\n reject: (error: Error) => void\r\n timer: ReturnType<typeof setInterval>\r\n timeout: ReturnType<typeof setTimeout>\r\n}\r\n\r\nconst safeLocalPath = (value?: string) =>\r\n value?.startsWith('/') && !value.startsWith('//') ? value : undefined\r\n\r\nconst toSession = (result: { token_type: string; expires_in: number; user: PofsisUser }) => ({\r\n token_type: result.token_type,\r\n expires_in: result.expires_in,\r\n user: result.user,\r\n})\r\n\r\nexport class PofsisAuthClient {\r\n readonly config: ResolvedPofsisAuthConfig\r\n private token: string | null = null\r\n private session: SessionPayload | null = null\r\n private client: OAuthClientConfig | null = null\r\n private clientPromise: Promise<OAuthClientConfig> | null = null\r\n private refreshPromise: Promise<void> | null = null\r\n private subscribers = new Set<Subscriber>()\r\n private attempt: PopupAttempt | null = null\r\n private listening = false\r\n\r\n constructor(config: PofsisAuthClientConfig) {\r\n this.config = resolveConfig(config)\r\n this.attach()\r\n }\r\n\r\n private attach() {\r\n if (this.listening) return\r\n window.addEventListener('message', this.onPopupMessage)\r\n this.listening = true\r\n }\r\n\r\n destroy() {\r\n window.removeEventListener('message', this.onPopupMessage)\r\n this.listening = false\r\n const attempt = this.finishAttempt()\r\n if (attempt) {\r\n attempt.popup.close()\r\n attempt.resolve({ status: 'cancelled' })\r\n }\r\n this.subscribers.clear()\r\n }\r\n\r\n getUser() {\r\n return this.session?.user ?? null\r\n }\r\n\r\n getSession() {\r\n return this.session\r\n }\r\n\r\n getAccessToken() {\r\n return this.token\r\n }\r\n\r\n subscribe(listener: Subscriber) {\r\n this.attach()\r\n this.subscribers.add(listener)\r\n listener(this.session)\r\n return () => {\r\n this.subscribers.delete(listener)\r\n }\r\n }\r\n\r\n private emit() {\r\n for (const listener of this.subscribers) listener(this.session)\r\n }\r\n\r\n private accept(result: Awaited<ReturnType<typeof exchangeCode>>) {\r\n this.token = result.access_token\r\n this.session = toSession(result)\r\n this.emit()\r\n }\r\n\r\n private loadClient() {\r\n if (!this.clientPromise) {\r\n this.clientPromise = fetchOAuthClient(this.config)\r\n .then((client) => (this.client = client))\r\n .catch((error) => {\r\n this.clientPromise = null\r\n throw error\r\n })\r\n }\r\n return this.clientPromise\r\n }\r\n\r\n getOAuthClient() {\r\n return this.loadClient()\r\n }\r\n\r\n async refreshSession() {\r\n const client = await this.loadClient()\r\n if (!this.refreshPromise) {\r\n this.refreshPromise = refresh(this.config, client.client_id)\r\n .then((result) => {\r\n if (result) this.accept(result)\r\n else this.clearSession()\r\n })\r\n .finally(() => (this.refreshPromise = null))\r\n }\r\n return this.refreshPromise\r\n }\r\n\r\n async isRemoteSessionActive() {\r\n return checkSession(this.config)\r\n }\r\n\r\n clearSession() {\r\n this.token = null\r\n this.session = null\r\n this.emit()\r\n }\r\n\r\n replaceUser(user: PofsisUser) {\r\n if (!this.session) return\r\n this.session = { ...this.session, user }\r\n this.emit()\r\n }\r\n\r\n async logout() {\r\n try {\r\n await signOut(this.config)\r\n } finally {\r\n this.clearSession()\r\n }\r\n }\r\n\r\n signup(options: Omit<AuthLaunchOptions, 'screen'> = {}) {\r\n return this.login({ ...options, screen: 'signup' })\r\n }\r\n\r\n resetPassword(options: Omit<AuthLaunchOptions, 'screen'> = {}) {\r\n return this.login({ ...options, screen: 'reset' })\r\n }\r\n\r\n async login(options: AuthLaunchOptions = {}): Promise<AuthResult> {\r\n const launch = normalizeAuthLaunchOptions(options)\r\n const presentation = options.presentation ?? 'popup'\r\n if (presentation === 'popup') return this.openPopup({ ...options, ...launch })\r\n return this.startRedirect({ ...options, ...launch })\r\n }\r\n\r\n private async authorizationUrl(options: AuthLaunchOptions, state: string, verifier: string) {\r\n const client = await this.loadClient()\r\n const query = new URLSearchParams({\r\n client_id: client.client_id,\r\n redirect_uri: client.redirect_uri,\r\n response_type: 'code',\r\n scope: this.config.scope,\r\n state,\r\n code_challenge: await pkceChallenge(verifier),\r\n code_challenge_method: 'S256',\r\n })\r\n return buildAuthDestination({\r\n authUrl: this.config.authUrl,\r\n query,\r\n options,\r\n })\r\n }\r\n\r\n private storageKey(suffix: string) {\r\n return `${this.config.applicationId}.auth.${suffix}`\r\n }\r\n\r\n private async startRedirect(options: AuthLaunchOptions): Promise<AuthResult> {\r\n const state = randomValue()\r\n const verifier = randomValue()\r\n sessionStorage.setItem(this.storageKey('state'), state)\r\n sessionStorage.setItem(this.storageKey('verifier'), verifier)\r\n const returnUrl = safeLocalPath(options.returnUrl)\r\n if (returnUrl) sessionStorage.setItem(this.storageKey('return-path'), returnUrl)\r\n else sessionStorage.removeItem(this.storageKey('return-path'))\r\n window.location.assign(await this.authorizationUrl(options, state, verifier))\r\n return { status: 'redirecting' }\r\n }\r\n\r\n private async openPopup(options: AuthLaunchOptions): Promise<AuthResult> {\r\n if (this.attempt && !this.attempt.popup.closed) {\r\n this.attempt.popup.focus()\r\n return new Promise((resolve, reject) => {\r\n const current = this.attempt!\r\n const originalResolve = current.resolve\r\n const originalReject = current.reject\r\n current.resolve = (value) => {\r\n originalResolve(value)\r\n resolve(value)\r\n }\r\n current.reject = (error) => {\r\n originalReject(error)\r\n reject(error)\r\n }\r\n })\r\n }\r\n const { width, height, name, timeoutMs } = this.config.popup\r\n const left = Math.max(0, window.screenX + (window.outerWidth - width) / 2)\r\n const top = Math.max(0, window.screenY + (window.outerHeight - height) / 2)\r\n const popup = window.open(\r\n 'about:blank',\r\n name,\r\n `popup=yes,width=${width},height=${height},left=${Math.round(left)},top=${Math.round(top)}`,\r\n )\r\n if (!popup) return this.startRedirect({ ...options, presentation: 'redirect' })\r\n\r\n const correlationId = randomValue()\r\n const state = `${correlationId}.${randomValue()}`\r\n const verifier = randomValue()\r\n const returnUrl = safeLocalPath(options.returnUrl)\r\n return new Promise<AuthResult>((resolve, reject) => {\r\n const timer = setInterval(() => {\r\n if (!popup.closed) return\r\n const attempt = this.finishAttempt()\r\n attempt?.resolve({ status: 'cancelled' })\r\n }, 250)\r\n const timeout = setTimeout(() => {\r\n const attempt = this.finishAttempt()\r\n popup.close()\r\n attempt?.reject(new Error('POFSIS Auth popup timed out.'))\r\n }, timeoutMs)\r\n this.attempt = {\r\n popup,\r\n state,\r\n verifier,\r\n correlationId,\r\n returnUrl,\r\n resolve,\r\n reject,\r\n timer,\r\n timeout,\r\n }\r\n void this.authorizationUrl(options, state, verifier)\r\n .then((url) => popup.location.replace(url))\r\n .catch((error) => {\r\n const attempt = this.finishAttempt()\r\n popup.close()\r\n attempt?.reject(error instanceof Error ? error : new Error(String(error)))\r\n })\r\n })\r\n }\r\n\r\n private finishAttempt() {\r\n const attempt = this.attempt\r\n if (!attempt) return null\r\n clearInterval(attempt.timer)\r\n clearTimeout(attempt.timeout)\r\n this.attempt = null\r\n return attempt\r\n }\r\n\r\n private onPopupMessage = (event: MessageEvent<PopupCallbackMessage>) => {\r\n const attempt = this.attempt\r\n const message = event.data\r\n if (\r\n !attempt ||\r\n event.origin !== window.location.origin ||\r\n event.source !== attempt.popup ||\r\n message?.type !== POPUP_MESSAGE_TYPE ||\r\n message.correlationId !== attempt.correlationId ||\r\n correlationFromState(message.state || null) !== attempt.correlationId ||\r\n message.state !== attempt.state\r\n )\r\n return\r\n\r\n const completed = this.finishAttempt()\r\n if (!completed) return\r\n if (message.error || !message.code) {\r\n completed.popup.close()\r\n completed.reject(new Error(message.error || 'POFSIS Auth callback was incomplete.'))\r\n return\r\n }\r\n void this.completeCode(message.code, message.state, completed.verifier)\r\n .then(() => {\r\n completed.popup.close()\r\n if (completed.returnUrl) window.history.replaceState(null, '', completed.returnUrl)\r\n completed.resolve({ status: 'authenticated', user: this.getUser()! })\r\n })\r\n .catch((error) => {\r\n completed.popup.close()\r\n completed.reject(error instanceof Error ? error : new Error(String(error)))\r\n })\r\n }\r\n\r\n private async completeCode(code: string, state: string, verifier: string) {\r\n if (!state || !verifier) throw new Error('Authentication state could not be verified.')\r\n const client = await this.loadClient()\r\n this.accept(await exchangeCode(this.config, code, verifier, client))\r\n }\r\n\r\n async completeRedirectCallback(code: string, state: string) {\r\n const expected = sessionStorage.getItem(this.storageKey('state'))\r\n const verifier = sessionStorage.getItem(this.storageKey('verifier'))\r\n sessionStorage.removeItem(this.storageKey('state'))\r\n sessionStorage.removeItem(this.storageKey('verifier'))\r\n if (!expected || !verifier || state !== expected) {\r\n throw new Error('Authentication state could not be verified.')\r\n }\r\n await this.completeCode(code, state, verifier)\r\n }\r\n}\r\n\r\nexport function createPofsisAuth(config: PofsisAuthClientConfig) {\r\n return new PofsisAuthClient(config)\r\n}\r\n","import { createPofsisAuth, type PofsisAuthClient } from '../core'\r\nimport type { AuthLaunchOptions } from '../types'\r\n\r\nconst observed = [\r\n 'application-id',\r\n 'api-base-url',\r\n 'auth-url',\r\n 'scope',\r\n 'return-url',\r\n 'screen',\r\n 'method',\r\n 'login-hint',\r\n]\r\n\r\nexport class PofsisSignInElement extends HTMLElement {\r\n static get observedAttributes() {\r\n return observed\r\n }\r\n private client: PofsisAuthClient | null = null\r\n private button: HTMLButtonElement | null = null\r\n\r\n connectedCallback() {\r\n this.render()\r\n }\r\n disconnectedCallback() {\r\n this.client?.destroy()\r\n }\r\n attributeChangedCallback() {\r\n if (this.isConnected) this.render()\r\n }\r\n\r\n private required(name: string) {\r\n const value = this.getAttribute(name)?.trim()\r\n if (!value) throw new Error(`<pofsis-sign-in> requires ${name}`)\r\n return value\r\n }\r\n\r\n private render() {\r\n this.client?.destroy()\r\n this.client = createPofsisAuth({\r\n applicationId: this.required('application-id'),\r\n apiBaseUrl: this.required('api-base-url'),\r\n authUrl: this.required('auth-url'),\r\n scope: this.getAttribute('scope') || undefined,\r\n })\r\n const label = this.textContent?.trim() || 'Sign in'\r\n this.replaceChildren()\r\n this.button = document.createElement('button')\r\n this.button.type = 'button'\r\n this.button.part.add('button')\r\n this.button.textContent = label\r\n this.button.addEventListener('click', () => void this.launch())\r\n this.append(this.button)\r\n }\r\n\r\n private async launch() {\r\n if (!this.client || !this.button) return\r\n this.button.disabled = true\r\n const options: AuthLaunchOptions = {\r\n presentation: 'popup',\r\n returnUrl: this.getAttribute('return-url') || undefined,\r\n screen: (this.getAttribute('screen') || 'login') as AuthLaunchOptions['screen'],\r\n method: (this.getAttribute('method') || undefined) as AuthLaunchOptions['method'],\r\n loginHint: this.getAttribute('login-hint') || undefined,\r\n }\r\n try {\r\n const result = await this.client.login(options)\r\n this.dispatchEvent(\r\n new CustomEvent(`pofsis-auth-${result.status}`, {\r\n bubbles: true,\r\n composed: true,\r\n detail: result,\r\n }),\r\n )\r\n } catch (error) {\r\n this.dispatchEvent(\r\n new CustomEvent('pofsis-auth-error', {\r\n bubbles: true,\r\n composed: true,\r\n detail: { error },\r\n }),\r\n )\r\n } finally {\r\n this.button.disabled = false\r\n }\r\n }\r\n}\r\n\r\nif (!customElements.get('pofsis-sign-in')) {\r\n customElements.define('pofsis-sign-in', PofsisSignInElement)\r\n}\r\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,eAAgB,kBAAmB,EACrC,CAAC,EACP,GAAG,GAAM,OACb,CACJ,CAAC,EACD,GAAI,CAAC,EAAS,GAAI,CACd,IAAM,EAAY,MAAM,YAAY,EAAK,WAAW,EAAS,OAAO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O,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"}
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { PofsisAuth } from '../PofsisAuth';
|
|
2
2
|
export { attachAuthInterceptor } from '../attachAuthInterceptor';
|
|
3
|
-
export { AuthErrorScreen, AuthLoadingScreen,
|
|
3
|
+
export { AuthErrorScreen, AuthLoadingScreen, RequireAuth } from '../components';
|
|
4
4
|
export type { RequireAuthProps } from '../components';
|
|
5
5
|
export { useAuth } from '../context/useAuth';
|
|
6
|
-
export type { AccountProfile, AuthComponentOverrides, AuthContextValue, AuthErrorScreenProps, AuthLaunchOptions, AuthLoadingScreenProps, AuthMethod, AuthPopupOptions, AuthResult, AuthScreen, OAuthClientConfig, PofsisAuthConfig, PofsisAuthProps,
|
|
6
|
+
export type { AccountProfile, AuthComponentOverrides, AuthContextValue, AuthErrorScreenProps, AuthLaunchOptions, AuthLoadingScreenProps, AuthMethod, AuthPopupOptions, AuthResult, AuthScreen, OAuthClientConfig, PofsisAuthConfig, PofsisAuthProps, PofsisUser, SessionPayload, TokenResponse, } from '../types';
|
|
7
7
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +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,
|
|
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
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./RequireAuth-CPhXupYh.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
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as e, i as t, n, o as r, r as i,
|
|
2
|
-
export {
|
|
1
|
+
import { a as e, i as t, n, o as r, r as i, t as a } from "./RequireAuth-DFa8_MR1.js";
|
|
2
|
+
export { r as AuthErrorScreen, e as AuthLoadingScreen, t as PofsisAuth, a as RequireAuth, i as attachAuthInterceptor, n as useAuth };
|
package/dist/types.d.ts
CHANGED
|
@@ -27,14 +27,14 @@ export interface TokenResponse extends SessionPayload {
|
|
|
27
27
|
access_token: string;
|
|
28
28
|
}
|
|
29
29
|
export interface OAuthClientConfig {
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
application_id: string;
|
|
31
|
+
application_name: string;
|
|
32
32
|
client_id: string;
|
|
33
33
|
redirect_uri: string;
|
|
34
34
|
logout_uri: string;
|
|
35
35
|
}
|
|
36
36
|
export interface PofsisAuthConfig {
|
|
37
|
-
|
|
37
|
+
applicationId: string;
|
|
38
38
|
apiBaseUrl: string;
|
|
39
39
|
authUrl: string;
|
|
40
40
|
scope: string;
|
|
@@ -70,9 +70,7 @@ export type AuthLaunchOptions = {
|
|
|
70
70
|
loginHint?: string;
|
|
71
71
|
method?: AuthMethod;
|
|
72
72
|
/** Popup for explicit user actions; redirect for route guards and fallback. */
|
|
73
|
-
presentation?: 'popup' | 'redirect'
|
|
74
|
-
/** Required only for `presentation: 'iframe'`. */
|
|
75
|
-
target?: HTMLIFrameElement;
|
|
73
|
+
presentation?: 'popup' | 'redirect';
|
|
76
74
|
};
|
|
77
75
|
export type AuthResult = {
|
|
78
76
|
status: 'authenticated';
|
|
@@ -83,7 +81,7 @@ export type AuthResult = {
|
|
|
83
81
|
status: 'redirecting';
|
|
84
82
|
};
|
|
85
83
|
export type PofsisAuthClientConfig = {
|
|
86
|
-
|
|
84
|
+
applicationId: string;
|
|
87
85
|
apiBaseUrl: string;
|
|
88
86
|
authUrl: string;
|
|
89
87
|
scope?: string;
|
|
@@ -98,7 +96,6 @@ export interface AuthContextValue {
|
|
|
98
96
|
login: (options?: AuthLaunchOptions) => Promise<AuthResult>;
|
|
99
97
|
signup: (options?: Omit<AuthLaunchOptions, 'screen'>) => Promise<AuthResult>;
|
|
100
98
|
resetPassword: (options?: Omit<AuthLaunchOptions, 'screen'>) => Promise<AuthResult>;
|
|
101
|
-
cancelIframeLogin: () => void;
|
|
102
99
|
logout: () => Promise<void>;
|
|
103
100
|
refreshSession: () => Promise<void>;
|
|
104
101
|
getAccessToken: () => string | null;
|
|
@@ -113,8 +110,8 @@ export interface AuthContextValue {
|
|
|
113
110
|
}
|
|
114
111
|
export type PofsisAuthProps = {
|
|
115
112
|
children: import('react').ReactNode;
|
|
116
|
-
/**
|
|
117
|
-
|
|
113
|
+
/** Immutable application UUID registered with POFSIS Auth. */
|
|
114
|
+
applicationId: string;
|
|
118
115
|
/** Auth API base URL. */
|
|
119
116
|
apiBaseUrl: string;
|
|
120
117
|
/** OAuth authorize URL. */
|
|
@@ -130,15 +127,4 @@ export type PofsisAuthProps = {
|
|
|
130
127
|
/** Override the package's default loading and error screens. */
|
|
131
128
|
components?: AuthComponentOverrides;
|
|
132
129
|
};
|
|
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
|
-
};
|
|
144
130
|
//# sourceMappingURL=types.d.ts.map
|
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,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAAW,cAAc;IAC3B,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;IAClB,IAAI,EAAE,UAAU,CAAA;CACnB;AAED,MAAM,WAAW,aAAc,SAAQ,cAAc;IACjD,YAAY,EAAE,MAAM,CAAA;CACvB;AAED,MAAM,WAAW,iBAAiB;IAC9B,
|
|
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;IACn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K,OAAO,CAAC,cAAc,CAAC,CAAA;IACjF,gBAAgB,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;CACnE;AAED,MAAM,MAAM,eAAe,GAAG;IAC1B,QAAQ,EAAE,OAAO,OAAO,EAAE,SAAS,CAAA;IACnC,8DAA8D;IAC9D,aAAa,EAAE,MAAM,CAAA;IACrB,yBAAyB;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"}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# Application-ID Integration Update
|
|
2
|
+
|
|
3
|
+
This guide covers only the frontend integration changes required to migrate an existing POFSIS tool
|
|
4
|
+
from the legacy `@pofsis/auth-react` package and application-name configuration to
|
|
5
|
+
`@pofsis-nbt/pofsis-auth` v2 and an immutable application UUID.
|
|
6
|
+
|
|
7
|
+
## Required values
|
|
8
|
+
|
|
9
|
+
Obtain the correct `applications.id` UUID for each environment from the Auth application registry.
|
|
10
|
+
Do not reuse a development UUID in staging or production unless that environment has been verified
|
|
11
|
+
to use the same registration.
|
|
12
|
+
|
|
13
|
+
For Vite applications, configure:
|
|
14
|
+
|
|
15
|
+
```env
|
|
16
|
+
VITE_POFSIS_APPLICATION_ID=<APPLICATION_UUID>
|
|
17
|
+
VITE_POFSIS_API_BASE_URL=https://dev-auth.pofsis.com/api
|
|
18
|
+
VITE_POFSIS_AUTH_URL=https://dev-auth.pofsis.com/authorize
|
|
19
|
+
VITE_POFSIS_SCOPE=openid profile email
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Remove:
|
|
23
|
+
|
|
24
|
+
```env
|
|
25
|
+
VITE_POFSIS_APP_NAME=<LEGACY_APPLICATION_NAME>
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The application UUID is a public identifier, not a secret. Do not add `client_id`, redirect URI, or
|
|
29
|
+
logout URI to the frontend environment. The library discovers those values through Auth BE using
|
|
30
|
+
the UUID and the browser's exact origin.
|
|
31
|
+
|
|
32
|
+
## Upgrade the package
|
|
33
|
+
|
|
34
|
+
Remove the old dependency:
|
|
35
|
+
|
|
36
|
+
```powershell
|
|
37
|
+
npm uninstall @pofsis/auth-react
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Install v2:
|
|
41
|
+
|
|
42
|
+
```powershell
|
|
43
|
+
npm install @pofsis-nbt/pofsis-auth@^2.0.0
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
If the old package was vendored under `packages/pofsis-auth-react`, delete that directory after all
|
|
47
|
+
imports have been replaced. Remove any Vite `optimizeDeps.exclude` entry that existed only for the
|
|
48
|
+
vendored package.
|
|
49
|
+
|
|
50
|
+
Replace imports throughout the tool:
|
|
51
|
+
|
|
52
|
+
```diff
|
|
53
|
+
- import { PofsisAuth, RequireAuth, useAuth } from '@pofsis/auth-react'
|
|
54
|
+
+ import { PofsisAuth, RequireAuth, useAuth } from '@pofsis-nbt/pofsis-auth'
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Import the v2 stylesheet exactly once in the application entry point:
|
|
58
|
+
|
|
59
|
+
```js
|
|
60
|
+
import '@pofsis-nbt/pofsis-auth/style.css'
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Check for remaining legacy references:
|
|
64
|
+
|
|
65
|
+
```powershell
|
|
66
|
+
rg "@pofsis/auth-react|VITE_POFSIS_APP_NAME|appName|\?app=" src .envs package.json vite.config.*
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Configure the React provider
|
|
70
|
+
|
|
71
|
+
The library does not read environment variables directly. The consuming application must pass its
|
|
72
|
+
configuration to `PofsisAuth`:
|
|
73
|
+
|
|
74
|
+
```jsx
|
|
75
|
+
import { PofsisAuth } from '@pofsis-nbt/pofsis-auth'
|
|
76
|
+
|
|
77
|
+
<PofsisAuth
|
|
78
|
+
applicationId={import.meta.env.VITE_POFSIS_APPLICATION_ID}
|
|
79
|
+
apiBaseUrl={import.meta.env.VITE_POFSIS_API_BASE_URL}
|
|
80
|
+
authUrl={import.meta.env.VITE_POFSIS_AUTH_URL}
|
|
81
|
+
scope={import.meta.env.VITE_POFSIS_SCOPE}
|
|
82
|
+
callbackPath="/auth/callback"
|
|
83
|
+
postLoginPath="/"
|
|
84
|
+
>
|
|
85
|
+
<App />
|
|
86
|
+
</PofsisAuth>
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`applicationId`, `apiBaseUrl`, and `authUrl` are required. Missing values fail during configuration
|
|
90
|
+
instead of silently selecting another application.
|
|
91
|
+
|
|
92
|
+
## Update protected routes
|
|
93
|
+
|
|
94
|
+
The v2 `RequireAuth` contract is:
|
|
95
|
+
|
|
96
|
+
```text
|
|
97
|
+
RequireAuth({ children, fallback?, onUnauthenticated? })
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Legacy `mode` and `returnTo` props are not supported. The basic integration is:
|
|
101
|
+
|
|
102
|
+
```jsx
|
|
103
|
+
import { RequireAuth } from '@pofsis-nbt/pofsis-auth'
|
|
104
|
+
|
|
105
|
+
function ProtectedRoute({ children }) {
|
|
106
|
+
return (
|
|
107
|
+
<RequireAuth fallback={<LoadingScreen />}>
|
|
108
|
+
{children}
|
|
109
|
+
</RequireAuth>
|
|
110
|
+
)
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Without `onUnauthenticated`, `RequireAuth` starts its default redirect login. A tool that requires
|
|
115
|
+
different unauthenticated behavior can provide its own `onUnauthenticated` callback based on that
|
|
116
|
+
tool's product flow; this guide does not prescribe login, signup, popup, or return-path behavior.
|
|
117
|
+
|
|
118
|
+
## Keep protected API calls connected
|
|
119
|
+
|
|
120
|
+
The Axios interceptor signature is unchanged:
|
|
121
|
+
|
|
122
|
+
```js
|
|
123
|
+
import { attachAuthInterceptor } from '@pofsis-nbt/pofsis-auth'
|
|
124
|
+
|
|
125
|
+
attachAuthInterceptor(apiClient, auth.getAccessToken, auth.refreshSession)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Attach it only once per Axios client. If it is attached from a component, retain and call the
|
|
129
|
+
returned cleanup function when that component unmounts.
|
|
130
|
+
|
|
131
|
+
## Framework-neutral integration
|
|
132
|
+
|
|
133
|
+
Non-React applications can use the core client:
|
|
134
|
+
|
|
135
|
+
```js
|
|
136
|
+
import { createPofsisAuth } from '@pofsis-nbt/pofsis-auth/core'
|
|
137
|
+
|
|
138
|
+
const auth = createPofsisAuth({
|
|
139
|
+
applicationId: runtimeConfig.applicationId,
|
|
140
|
+
apiBaseUrl: runtimeConfig.apiBaseUrl,
|
|
141
|
+
authUrl: runtimeConfig.authUrl,
|
|
142
|
+
scope: 'openid profile email',
|
|
143
|
+
callbackPath: '/auth/callback',
|
|
144
|
+
})
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Consumer validation
|
|
148
|
+
|
|
149
|
+
Run the tool's standard checks:
|
|
150
|
+
|
|
151
|
+
```powershell
|
|
152
|
+
npm install
|
|
153
|
+
npm run test
|
|
154
|
+
npm run lint
|
|
155
|
+
npm run format:check
|
|
156
|
+
npm run build
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Run browser or E2E tests when available. Confirm that:
|
|
160
|
+
|
|
161
|
+
- Client discovery uses the configured application UUID and current browser origin.
|
|
162
|
+
- The generated authorization URL contains `client_id`, `state`, and PKCE fields.
|
|
163
|
+
- The authorization URL does not contain `app`, an application name/code, or `application_id`.
|
|
164
|
+
- The tool's existing authentication entry behavior remains correct for its product flow.
|
|
165
|
+
- `/auth/callback` returns to the requested safe local route.
|
|
166
|
+
- Refresh, logout, profile editing, and protected API calls still work.
|
|
167
|
+
- Invalid UUIDs and origins show an application error and do not start authentication.
|
|
168
|
+
|
|
169
|
+
## Per-environment integration checklist
|
|
170
|
+
|
|
171
|
+
- [ ] Confirm the environment-specific application UUID with the Auth owner.
|
|
172
|
+
- [ ] Replace the old package and all imports.
|
|
173
|
+
- [ ] Remove the vendored package and Vite exclusion.
|
|
174
|
+
- [ ] Replace `VITE_POFSIS_APP_NAME` with `VITE_POFSIS_APPLICATION_ID`.
|
|
175
|
+
- [ ] Pass explicit provider configuration.
|
|
176
|
+
- [ ] Update protected routes that used legacy `mode` or `returnTo` props.
|
|
177
|
+
- [ ] Import the package stylesheet once.
|
|
178
|
+
- [ ] Run unit, lint, formatting, build, and E2E checks.
|
|
179
|
+
- [ ] Smoke-test login, signup, callback, refresh, logout, and protected API calls.
|
|
180
|
+
- [ ] Repeat separately for development, staging, and production.
|