@burdenoff/microfe-auth 2026.925.1 → 2026.1005.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/dist/auth/AuthRoot.d.ts +0 -1
- package/dist/auth/AuthRoot.js.map +1 -1
- package/dist/auth/AuthRoutes.d.ts +1 -1
- package/dist/auth/AuthRoutes.js.map +1 -1
- package/dist/auth/components/AuthIcons.d.ts +12 -13
- package/dist/auth/components/AuthIcons.js.map +1 -1
- package/dist/auth/components/AuthLayout.d.ts +1 -2
- package/dist/auth/components/AuthLayout.js.map +1 -1
- package/dist/auth/components/CaptchaV2.d.ts +1 -1
- package/dist/auth/components/CaptchaV2.js +2 -2
- package/dist/auth/components/CaptchaV2.js.map +1 -1
- package/dist/auth/components/ConfirmActionDialog.d.ts +1 -1
- package/dist/auth/components/ConfirmActionDialog.js.map +1 -1
- package/dist/auth/components/profile/UserProfileMenu.d.ts +1 -1
- package/dist/auth/components/profile/UserProfileMenu.js.map +1 -1
- package/dist/auth/components/workspace/WorkspaceSelector.d.ts +1 -2
- package/dist/auth/components/workspace/WorkspaceSelector.js.map +1 -1
- package/dist/auth/constants/permissions.js.map +1 -1
- package/dist/auth/hooks/useAccountOperations.d.ts +0 -1
- package/dist/auth/hooks/useAccountOperations.js.map +1 -1
- package/dist/auth/hooks/useActiveContextBootstrapMirror.js.map +1 -1
- package/dist/auth/hooks/useApiKeyOperations.d.ts +1 -2
- package/dist/auth/hooks/useAppOperations.d.ts +1 -2
- package/dist/auth/hooks/useAuthOperations.d.ts +0 -1
- package/dist/auth/hooks/useAuthOperations.js.map +1 -1
- package/dist/auth/hooks/useAuthPermissions.js.map +1 -1
- package/dist/auth/hooks/useCaptchaV3.js +1 -1
- package/dist/auth/hooks/useCaptchaV3.js.map +1 -1
- package/dist/auth/hooks/useContextSwitcherData.d.ts +1 -1
- package/dist/auth/hooks/useContextSwitcherData.js +356 -234
- package/dist/auth/hooks/useContextSwitcherData.js.map +1 -1
- package/dist/auth/hooks/useDelegationOperations.d.ts +0 -1
- package/dist/auth/hooks/useMfaOperations.d.ts +0 -1
- package/dist/auth/hooks/useMfaOperations.js.map +1 -1
- package/dist/auth/hooks/useMyWorkspaces.d.ts +0 -1
- package/dist/auth/hooks/useMyWorkspaces.js.map +1 -1
- package/dist/auth/hooks/useOAuthOperations.d.ts +0 -1
- package/dist/auth/hooks/useOAuthOperations.js +2 -2
- package/dist/auth/hooks/useOAuthOperations.js.map +1 -1
- package/dist/auth/hooks/usePasswordOperations.d.ts +0 -1
- package/dist/auth/hooks/usePasswordOperations.js.map +1 -1
- package/dist/auth/hooks/useSessionOperations.d.ts +0 -1
- package/dist/auth/hooks/useSessionOperations.js.map +1 -1
- package/dist/auth/hooks/useSignupCaptcha.js +1 -1
- package/dist/auth/hooks/useSignupCaptcha.js.map +1 -1
- package/dist/auth/hooks/useSsoOperations.d.ts +0 -1
- package/dist/auth/hooks/useSsoOperations.js.map +1 -1
- package/dist/auth/hooks/useTokenRefresh.js.map +1 -1
- package/dist/auth/hooks/useUserOperations.d.ts +0 -1
- package/dist/auth/hooks/useUserOperations.js.map +1 -1
- package/dist/auth/hooks/useWorkspaceOperations.d.ts +0 -1
- package/dist/auth/hooks/useWorkspaceOperations.js.map +1 -1
- package/dist/auth/hooks/useWorkspaceToken.js.map +1 -1
- package/dist/auth/pages/AuditLogPage.d.ts +1 -1
- package/dist/auth/pages/AuditLogPage.js.map +1 -1
- package/dist/auth/pages/EmailVerifyPage.d.ts +1 -1
- package/dist/auth/pages/EmailVerifyPage.js.map +1 -1
- package/dist/auth/pages/LoginPage.d.ts +1 -1
- package/dist/auth/pages/LoginPage.js.map +1 -1
- package/dist/auth/pages/MagicLinkPage.d.ts +1 -1
- package/dist/auth/pages/MagicLinkPage.js.map +1 -1
- package/dist/auth/pages/MfaSetupPage.d.ts +1 -1
- package/dist/auth/pages/MfaSetupPage.js +88 -88
- package/dist/auth/pages/MfaSetupPage.js.map +1 -1
- package/dist/auth/pages/MfaVerifyPage.d.ts +1 -1
- package/dist/auth/pages/MfaVerifyPage.js.map +1 -1
- package/dist/auth/pages/OAuthCallbackPage.d.ts +1 -1
- package/dist/auth/pages/OAuthCallbackPage.js.map +1 -1
- package/dist/auth/pages/PasswordResetPage.d.ts +1 -1
- package/dist/auth/pages/PasswordResetPage.js.map +1 -1
- package/dist/auth/pages/ReactivatePage.d.ts +1 -1
- package/dist/auth/pages/ReactivatePage.js.map +1 -1
- package/dist/auth/pages/RegisterPage.d.ts +1 -1
- package/dist/auth/pages/RegisterPage.js.map +1 -1
- package/dist/auth/pages/SSOClearPage.d.ts +1 -1
- package/dist/auth/pages/SSOClearPage.js.map +1 -1
- package/dist/auth/pages/SSODepositPage.d.ts +1 -1
- package/dist/auth/pages/SSODepositPage.js.map +1 -1
- package/dist/auth/pages/SSORelayCallbackPage.d.ts +1 -1
- package/dist/auth/pages/SSORelayCallbackPage.js.map +1 -1
- package/dist/auth/pages/SSORelayPage.d.ts +1 -1
- package/dist/auth/pages/SSORelayPage.js.map +1 -1
- package/dist/auth/pages/SecurityPage.d.ts +1 -1
- package/dist/auth/pages/SecurityPage.js.map +1 -1
- package/dist/auth/pages/SessionBridgePage.d.ts +1 -1
- package/dist/auth/pages/SessionBridgePage.js.map +1 -1
- package/dist/auth/pages/SessionsPage.d.ts +1 -1
- package/dist/auth/pages/SessionsPage.js.map +1 -1
- package/dist/auth/pages/SsoCallbackPage.d.ts +1 -1
- package/dist/auth/pages/SsoCallbackPage.js.map +1 -1
- package/dist/auth/pages/SsoConfigPage.d.ts +1 -1
- package/dist/auth/pages/SsoConfigPage.js.map +1 -1
- package/dist/auth/pages/SsoLoginPage.d.ts +1 -1
- package/dist/auth/pages/SsoLoginPage.js.map +1 -1
- package/dist/auth/pages/UserDetailsPage.d.ts +1 -1
- package/dist/auth/pages/UserDetailsPage.js.map +1 -1
- package/dist/auth/pages/UserProfilePage.d.ts +1 -1
- package/dist/auth/pages/UserProfilePage.js.map +1 -1
- package/dist/auth/pages/UsersPage.d.ts +1 -1
- package/dist/auth/pages/UsersPage.js.map +1 -1
- package/dist/auth/providers/AuthProvider.d.ts +0 -1
- package/dist/auth/providers/AuthProvider.js.map +1 -1
- package/dist/auth/providers/CaptchaProvider.d.ts +1 -2
- package/dist/auth/providers/CaptchaProvider.js +2 -2
- package/dist/auth/providers/CaptchaProvider.js.map +1 -1
- package/dist/auth/store/authStore.d.ts +0 -1
- package/dist/auth/store/authStore.js.map +1 -1
- package/dist/auth/types/index.d.ts +0 -1
- package/dist/auth/utils/captchaConfig.js.map +1 -1
- package/dist/auth/utils/formatters.js.map +1 -1
- package/dist/auth/utils/gatewayBaseUrls.js.map +1 -1
- package/dist/auth/utils/legalUrls.js.map +1 -1
- package/dist/auth/utils/redirect.js.map +1 -1
- package/dist/auth/utils/ssoOrigins.js.map +1 -1
- package/dist/auth/utils/validation.d.ts +0 -1
- package/dist/auth/utils/validation.js.map +1 -1
- package/dist/dev/main.d.ts +0 -1
- package/dist/generated/global-operations.js.map +1 -1
- package/dist/generated/wspace-operations.js.map +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/shared/hooks/useTr.js.map +1 -1
- package/dist/shared/types/index.d.ts +0 -1
- package/dist/translations/en.js.map +1 -1
- package/package.json +27 -20
- package/dist/_virtual/_rolldown/runtime.js +0 -13
- package/dist/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js +0 -70
- package/dist/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js.map +0 -1
- package/dist/node_modules/object-assign/index.js +0 -41
- package/dist/node_modules/object-assign/index.js.map +0 -1
- package/dist/node_modules/prop-types/checkPropTypes.js +0 -46
- package/dist/node_modules/prop-types/checkPropTypes.js.map +0 -1
- package/dist/node_modules/prop-types/factoryWithThrowingShims.js +0 -49
- package/dist/node_modules/prop-types/factoryWithThrowingShims.js.map +0 -1
- package/dist/node_modules/prop-types/factoryWithTypeCheckers.js +0 -272
- package/dist/node_modules/prop-types/factoryWithTypeCheckers.js.map +0 -1
- package/dist/node_modules/prop-types/index.js +0 -16
- package/dist/node_modules/prop-types/index.js.map +0 -1
- package/dist/node_modules/prop-types/lib/ReactPropTypesSecret.js +0 -10
- package/dist/node_modules/prop-types/lib/ReactPropTypesSecret.js.map +0 -1
- package/dist/node_modules/prop-types/lib/has.js +0 -10
- package/dist/node_modules/prop-types/lib/has.js.map +0 -1
- package/dist/node_modules/qrcode.react/lib/esm/index.js +0 -959
- package/dist/node_modules/qrcode.react/lib/esm/index.js.map +0 -1
- package/dist/node_modules/react-async-script/lib/esm/async-script-loader.js +0 -114
- package/dist/node_modules/react-async-script/lib/esm/async-script-loader.js.map +0 -1
- package/dist/node_modules/react-google-recaptcha/lib/esm/index.js +0 -8
- package/dist/node_modules/react-google-recaptcha/lib/esm/index.js.map +0 -1
- package/dist/node_modules/react-google-recaptcha/lib/esm/recaptcha-wrapper.js +0 -20
- package/dist/node_modules/react-google-recaptcha/lib/esm/recaptcha-wrapper.js.map +0 -1
- package/dist/node_modules/react-google-recaptcha/lib/esm/recaptcha.js +0 -148
- package/dist/node_modules/react-google-recaptcha/lib/esm/recaptcha.js.map +0 -1
- package/dist/node_modules/react-google-recaptcha-v3/dist/react-google-recaptcha-v3.esm.js +0 -445
- package/dist/node_modules/react-google-recaptcha-v3/dist/react-google-recaptcha-v3.esm.js.map +0 -1
- package/dist/node_modules/react-is/cjs/react-is.development.js +0 -84
- package/dist/node_modules/react-is/cjs/react-is.development.js.map +0 -1
- package/dist/node_modules/react-is/cjs/react-is.production.min.js +0 -64
- package/dist/node_modules/react-is/cjs/react-is.production.min.js.map +0 -1
- package/dist/node_modules/react-is/index.js +0 -12
- package/dist/node_modules/react-is/index.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authStore.js","names":[],"sources":["../../../src/auth/store/authStore.ts"],"sourcesContent":["import { create } from \"zustand\";\nimport { persist } from \"zustand/middleware\";\nimport { createProfileScopedStorage } from \"@burdenoff/fe-libs/shared/utils\";\nimport type {\n User,\n Session,\n MfaDevice,\n OAuthAccount,\n TrustedDevice,\n SecurityAudit,\n ApiKey,\n App,\n AppUserDelegation,\n Workspace,\n Organization,\n Project,\n} from \"../types\";\n\n/**\n * Sync auth state to profile-scoped storage (ProfileStorageManager keys).\n * The active profile ID comes from sessionStorage (\"bf-active-profile\").\n * Data is stored under localStorage keys: bf-p-{profileId}-user, bf-p-{profileId}-tokens, etc.\n */\nconst BF_PREFIX = \"bf-p\";\nconst BF_PROFILES = \"bf-profiles\";\nconst BF_ACTIVE = \"bf-active-profile\";\nconst AUTH_STORAGE_KEY = \"auth-storage\";\nconst AUTH_STATE_CLEARED_EVENT = \"bf-auth-state-cleared\";\n\nfunction getActiveProfileForSync(): string | null {\n return sessionStorage.getItem(BF_ACTIVE);\n}\n\nfunction pfKey(profileId: string, suffix: string): string {\n return `${BF_PREFIX}-${profileId}-${suffix}`;\n}\n\nfunction clearPersistedAuthStorage(profileId?: string | null): void {\n localStorage.removeItem(AUTH_STORAGE_KEY);\n if (profileId) {\n localStorage.removeItem(pfKey(profileId, AUTH_STORAGE_KEY));\n }\n for (const key of Object.keys(localStorage)) {\n if (\n key.startsWith(`${BF_PREFIX}-`) &&\n key.endsWith(`-${AUTH_STORAGE_KEY}`)\n ) {\n localStorage.removeItem(key);\n }\n }\n}\n\ninterface ProfileMeta {\n id: string;\n email: string;\n name: string;\n avatar?: string;\n lastLogin: string;\n}\n\n/** Dispatch custom event to notify fe-libs AuthProvider of storage changes (same-tab). */\nfunction notifyProfileStorageChange(): void {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"bf-profile-storage-change\"));\n }\n}\n\nfunction syncToProfileStorage(data: {\n user?: User | null;\n accessToken?: string | null;\n refreshToken?: string | null;\n workspaceToken?: string | null;\n clear?: boolean;\n}) {\n if (typeof window === \"undefined\") return;\n\n const profileId = getActiveProfileForSync();\n if (!profileId && !data.user && !data.clear) return;\n\n // For login/signup: prefer the user's own ID as the target profile.\n // This prevents overwriting an existing active profile when a NEW user\n // signs up or logs in (multi-account scenario).\n const targetId = data.user?.id ?? profileId;\n if (!targetId && !data.clear) return;\n\n if (data.clear) {\n clearPersistedAuthStorage(targetId);\n if (!targetId) {\n localStorage.removeItem(BF_PROFILES);\n sessionStorage.removeItem(BF_ACTIVE);\n return;\n }\n // Remove profile data keys\n localStorage.removeItem(pfKey(targetId, \"user\"));\n localStorage.removeItem(pfKey(targetId, \"tokens\"));\n localStorage.removeItem(pfKey(targetId, \"workspace-token\"));\n // Remove from profiles list\n try {\n const profilesRaw = localStorage.getItem(BF_PROFILES);\n const profiles: ProfileMeta[] = profilesRaw\n ? JSON.parse(profilesRaw)\n : [];\n const filtered = profiles.filter((p) => p.id !== targetId);\n localStorage.setItem(BF_PROFILES, JSON.stringify(filtered));\n } catch {\n /* ignore */\n }\n sessionStorage.removeItem(BF_ACTIVE);\n return;\n }\n\n if (!targetId) return;\n\n if (data.user) {\n localStorage.setItem(pfKey(targetId, \"user\"), JSON.stringify(data.user));\n // Update profiles list\n try {\n const profilesRaw = localStorage.getItem(BF_PROFILES);\n const profiles: ProfileMeta[] = profilesRaw\n ? JSON.parse(profilesRaw)\n : [];\n const existing = profiles.filter((p) => p.id !== targetId);\n existing.push({\n id: targetId,\n email: data.user.email ?? \"\",\n name:\n data.user.name ??\n `${data.user.firstName ?? \"\"} ${data.user.lastName ?? \"\"}`.trim(),\n avatar: data.user.avatar,\n lastLogin: new Date().toISOString(),\n });\n localStorage.setItem(BF_PROFILES, JSON.stringify(existing));\n } catch {\n /* ignore */\n }\n // Set as active profile in this tab\n sessionStorage.setItem(BF_ACTIVE, targetId);\n }\n\n if (data.accessToken !== undefined || data.refreshToken !== undefined) {\n const existingRaw = localStorage.getItem(pfKey(targetId, \"tokens\"));\n const existing = existingRaw ? JSON.parse(existingRaw) : {};\n // Compute expiresAt from the actual JWT exp claim if a new access token is provided\n let expiresAt = existing.expiresAt ?? Date.now() + 60 * 60 * 1000;\n const tokenToCheck = data.accessToken ?? existing.accessToken;\n if (tokenToCheck) {\n try {\n const raw = tokenToCheck\n .split(\".\")[1]\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\");\n const padded = raw.padEnd(Math.ceil(raw.length / 4) * 4, \"=\");\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp === \"number\") {\n expiresAt = payload.exp * 1000; // JWT exp is in seconds → ms\n }\n } catch {\n // Fallback: keep existing or default 1h\n }\n }\n const merged = {\n ...existing,\n ...(data.accessToken !== undefined\n ? { accessToken: data.accessToken }\n : {}),\n ...(data.refreshToken !== undefined\n ? { refreshToken: data.refreshToken }\n : {}),\n expiresAt,\n };\n if (merged.accessToken) {\n localStorage.setItem(pfKey(targetId, \"tokens\"), JSON.stringify(merged));\n } else {\n localStorage.removeItem(pfKey(targetId, \"tokens\"));\n }\n }\n\n if (data.workspaceToken !== undefined) {\n if (data.workspaceToken) {\n localStorage.setItem(\n pfKey(targetId, \"workspace-token\"),\n data.workspaceToken,\n );\n } else {\n localStorage.removeItem(pfKey(targetId, \"workspace-token\"));\n }\n }\n\n // Notify fe-libs AuthProvider of the change (same-tab custom event)\n notifyProfileStorageChange();\n\n // Set SSO cookie for cross-domain session sharing (works in all envs)\n // Stores profile ID + the origin where the user logged in.\n // Other shells use the origin to redirect to /auth/sso-relay for token relay.\n try {\n const hostname = window.location.hostname;\n // For local dev, set cookie on shared .local.burdenoff.com domain\n // For production, set cookie on current domain only (relay handles cross-domain)\n const isSharedDomain = hostname.endsWith(\".local.burdenoff.com\");\n const domain = isSharedDomain ? \".local.burdenoff.com\" : undefined;\n const domainPart = domain ? `; domain=${domain}` : \"\";\n const securePart = window.location.protocol === \"https:\" ? \"; secure\" : \"\";\n const cookieOpts = `${domainPart}; path=/; samesite=lax${securePart}`;\n\n if (data.accessToken && targetId) {\n // Store profile ID + login origin for SSO relay\n const ssoValue = JSON.stringify({\n id: targetId,\n origin: window.location.origin,\n });\n document.cookie = `bf-sso=${encodeURIComponent(ssoValue)}${cookieOpts}; max-age=86400`;\n document.cookie = `bf-sso-profile=${encodeURIComponent(ssoValue)}${cookieOpts}; max-age=86400`;\n }\n\n if (data.clear) {\n document.cookie = \"bf-sso=; path=/; max-age=0\";\n document.cookie = \"bf-sso-profile=; path=/; max-age=0\";\n if (domain) {\n document.cookie = `bf-sso=; path=/; domain=${domain}; max-age=0`;\n document.cookie = `bf-sso-profile=; path=/; domain=${domain}; max-age=0`;\n }\n if (hostname && ![\"localhost\", \"127.0.0.1\"].includes(hostname)) {\n document.cookie = `bf-sso=; path=/; domain=${hostname}; max-age=0`;\n document.cookie = `bf-sso-profile=; path=/; domain=${hostname}; max-age=0`;\n }\n }\n } catch {\n /* ignore */\n }\n}\n\ninterface AuthState {\n // Auth state\n user: User | null;\n accessToken: string | null;\n refreshToken: string | null;\n isAuthenticated: boolean;\n\n // Organization state\n organizations: Organization[];\n currentOrganizationId: string | null;\n isLoadingOrganizations: boolean;\n\n // Workspace state\n workspaces: Workspace[];\n currentWorkspaceId: string | null;\n workspaceToken: string | null;\n isLoadingWorkspaces: boolean;\n\n // Project state\n projects: Project[];\n currentProjectId: string | null;\n isLoadingProjects: boolean;\n\n // MFA state\n mfaRequired: boolean;\n mfaChallengeId: string | null;\n mfaDevices: MfaDevice[];\n\n // Session state\n activeSessions: Session[];\n currentSessionId: string | null;\n\n // OAuth state\n linkedAccounts: OAuthAccount[];\n\n // Security state\n trustedDevices: TrustedDevice[];\n securityEvents: SecurityAudit[];\n\n // API Keys state\n apiKeys: ApiKey[];\n\n // Apps state\n apps: App[];\n currentApp: App | null;\n\n // Delegations state\n delegations: AppUserDelegation[];\n grantedDelegations: AppUserDelegation[];\n\n // UI state\n isLoading: boolean;\n error: string | null;\n errorCode: string | null;\n\n // Actions - Auth\n setUser: (user: User | null) => void;\n setAccessToken: (token: string | null) => void;\n setAuthTokens: (accessToken: string, refreshToken: string) => void;\n setAuthenticated: (isAuthenticated: boolean) => void;\n clearAuth: () => void;\n\n // Actions - Organization\n setOrganizations: (organizations: Organization[]) => void;\n setCurrentOrganizationId: (orgId: string | null) => void;\n setLoadingOrganizations: (loading: boolean) => void;\n\n // Actions - Workspace\n setWorkspaces: (workspaces: Workspace[]) => void;\n setCurrentWorkspaceId: (workspaceId: string | null) => void;\n setWorkspaceToken: (token: string | null) => void;\n setLoadingWorkspaces: (loading: boolean) => void;\n clearWorkspace: () => void;\n\n // Actions - Project\n setProjects: (projects: Project[]) => void;\n setCurrentProjectId: (projectId: string | null) => void;\n setLoadingProjects: (loading: boolean) => void;\n clearProject: () => void;\n\n // Actions - Context (clears org, workspace, project)\n clearContext: () => void;\n\n // Actions - Profile Switch (load from profile storage without syncing back)\n loadFromProfile: (profileId: string) => void;\n\n // Actions - MFA\n setMfaRequired: (required: boolean, challengeId?: string) => void;\n setMfaDevices: (devices: MfaDevice[]) => void;\n removeMfaDevice: (deviceId: string) => void;\n\n // Actions - Sessions\n setActiveSessions: (sessions: Session[]) => void;\n removeSession: (sessionId: string) => void;\n\n // Actions - OAuth\n setLinkedAccounts: (accounts: OAuthAccount[]) => void;\n removeLinkedAccount: (accountId: string) => void;\n\n // Actions - Security\n setTrustedDevices: (devices: TrustedDevice[]) => void;\n removeTrustedDevice: (deviceId: string) => void;\n setSecurityEvents: (events: SecurityAudit[]) => void;\n\n // Actions - API Keys\n setApiKeys: (keys: ApiKey[]) => void;\n removeApiKey: (keyId: string) => void;\n\n // Actions - Apps\n setApps: (apps: App[]) => void;\n setCurrentApp: (app: App | null) => void;\n addApp: (app: App) => void;\n updateApp: (app: App) => void;\n removeApp: (appId: string) => void;\n\n // Actions - Delegations\n setDelegations: (delegations: AppUserDelegation[]) => void;\n setGrantedDelegations: (delegations: AppUserDelegation[]) => void;\n addDelegation: (delegation: AppUserDelegation) => void;\n removeDelegation: (delegationId: string) => void;\n\n // Actions - UI\n setLoading: (loading: boolean) => void;\n setError: (error: string | null, errorCode?: string | null) => void;\n}\n\n/**\n * Auth Zustand store — browser-tab-local state.\n *\n * SAFE for in-memory (no Redis needed):\n * - accessToken / refreshToken / user: per-tab, backed by profileScopedStorage\n * (localStorage key bf-p-{profileId}-*). Tabs sharing the same profile ID\n * stay in sync via the \"bf-profile-storage-change\" custom event + \"storage\"\n * cross-tab event.\n * - workspaceToken: same pattern as above.\n * - mfaRequired / mfaChallengeId: transient login-flow state; not needed\n * cross-tab (each login has its own challenge).\n * - organizations / workspaces / projects lists: cached context, re-fetched\n * after account switch; no cross-tab sharing needed.\n * - UI state (isLoading, error): purely ephemeral.\n *\n * NOT safe for in-memory (needs Redis in future if required server-side):\n * - Nothing currently — all server-side session tracking is done by the\n * backend (global-auth-svc) using its own DB. The frontend only holds\n * short-lived JWT access tokens that expire independently.\n */\nexport const useAuthStore = create<AuthState>()(\n persist(\n (set) => ({\n // Initial state\n user: null,\n accessToken: null,\n refreshToken: null,\n isAuthenticated: false,\n organizations: [],\n currentOrganizationId: null,\n isLoadingOrganizations: false,\n workspaces: [],\n currentWorkspaceId: null,\n workspaceToken: null,\n isLoadingWorkspaces: false,\n projects: [],\n currentProjectId: null,\n isLoadingProjects: false,\n mfaRequired: false,\n mfaChallengeId: null,\n mfaDevices: [],\n activeSessions: [],\n currentSessionId: null,\n linkedAccounts: [],\n trustedDevices: [],\n securityEvents: [],\n apiKeys: [],\n apps: [],\n currentApp: null,\n delegations: [],\n grantedDelegations: [],\n isLoading: false,\n error: null,\n errorCode: null,\n\n // Actions - Auth (with profile storage sync)\n setUser: (user) => {\n set({ user });\n syncToProfileStorage({ user });\n },\n\n setAccessToken: (token) => {\n set({ accessToken: token });\n syncToProfileStorage({ accessToken: token });\n },\n\n setAuthTokens: (accessToken, refreshToken) => {\n // Only set tokens here. Do NOT overwrite user — setUser() handles that\n // with the full user object from the GraphQL response (firstName, lastName, etc.).\n // Fall back to JWT-decoded user ONLY if no user is currently in the store.\n const currentState = useAuthStore.getState();\n if (currentState.user) {\n // User already set (from setUser call) — just update tokens\n set({ accessToken, refreshToken });\n syncToProfileStorage({ accessToken, refreshToken });\n } else {\n // No user yet — decode JWT as fallback\n try {\n const b64 = accessToken\n .split(\".\")[1]\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\");\n const padded = b64.padEnd(Math.ceil(b64.length / 4) * 4, \"=\");\n const payload = JSON.parse(atob(padded));\n const user: User = {\n id: payload.sub,\n email: payload.email,\n username: payload.username,\n role: payload.role,\n status: \"ACTIVE\",\n emailVerified: true,\n mfaEnabled: false,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n set({ accessToken, refreshToken, user });\n syncToProfileStorage({ accessToken, refreshToken, user });\n } catch (error) {\n console.error(\"[AuthStore] Failed to decode JWT:\", error);\n set({ accessToken, refreshToken });\n syncToProfileStorage({ accessToken, refreshToken });\n }\n }\n },\n\n setAuthenticated: (isAuthenticated) => set({ isAuthenticated }),\n\n clearAuth: () => {\n set({\n user: null,\n accessToken: null,\n refreshToken: null,\n isAuthenticated: false,\n mfaRequired: false,\n mfaChallengeId: null,\n activeSessions: [],\n currentSessionId: null,\n organizations: [],\n currentOrganizationId: null,\n isLoadingOrganizations: false,\n workspaces: [],\n workspaceToken: null,\n currentWorkspaceId: null,\n isLoadingWorkspaces: false,\n projects: [],\n currentProjectId: null,\n isLoadingProjects: false,\n });\n syncToProfileStorage({ clear: true });\n },\n\n // Actions - Organization\n setOrganizations: (organizations) => set({ organizations }),\n\n setCurrentOrganizationId: (orgId) =>\n set((state) =>\n state.currentOrganizationId === orgId\n ? state\n : { currentOrganizationId: orgId },\n ),\n\n setLoadingOrganizations: (loading) =>\n set({ isLoadingOrganizations: loading }),\n\n // Actions - Workspace\n setWorkspaces: (workspaces) => set({ workspaces }),\n\n setCurrentWorkspaceId: (workspaceId) =>\n set((state) =>\n state.currentWorkspaceId === workspaceId\n ? state\n : { currentWorkspaceId: workspaceId },\n ),\n\n setWorkspaceToken: (token) => {\n set({ workspaceToken: token });\n syncToProfileStorage({ workspaceToken: token });\n },\n\n setLoadingWorkspaces: (loading) => set({ isLoadingWorkspaces: loading }),\n\n clearWorkspace: () =>\n set({ currentWorkspaceId: null, workspaceToken: null, workspaces: [] }),\n\n // Actions - Project\n setProjects: (projects) => set({ projects }),\n\n setCurrentProjectId: (projectId) =>\n set((state) =>\n state.currentProjectId === projectId\n ? state\n : { currentProjectId: projectId },\n ),\n\n setLoadingProjects: (loading) => set({ isLoadingProjects: loading }),\n\n clearProject: () => set({ currentProjectId: null, projects: [] }),\n\n // Actions - Context (clears org, workspace, project)\n clearContext: () =>\n set({\n organizations: [],\n currentOrganizationId: null,\n isLoadingOrganizations: false,\n workspaces: [],\n currentWorkspaceId: null,\n workspaceToken: null,\n isLoadingWorkspaces: false,\n projects: [],\n currentProjectId: null,\n isLoadingProjects: false,\n }),\n\n // Actions - Profile Switch\n // Loads user/tokens from profile-scoped localStorage WITHOUT syncing back.\n // Used during account switching to align zustand with the new active profile.\n loadFromProfile: (profileId: string) => {\n let user: User | null = null;\n let accessToken: string | null = null;\n let refreshToken: string | null = null;\n let workspaceToken: string | null = null;\n\n try {\n const userRaw = localStorage.getItem(pfKey(profileId, \"user\"));\n if (userRaw) user = JSON.parse(userRaw);\n } catch {\n /* ignore */\n }\n\n try {\n const tokensRaw = localStorage.getItem(pfKey(profileId, \"tokens\"));\n if (tokensRaw) {\n const tokens = JSON.parse(tokensRaw);\n accessToken = tokens.accessToken ?? null;\n refreshToken = tokens.refreshToken ?? null;\n }\n } catch {\n /* ignore */\n }\n\n workspaceToken = localStorage.getItem(\n pfKey(profileId, \"workspace-token\"),\n );\n\n // Set everything in one batch — clears context data so it will be re-fetched\n set({\n user,\n accessToken,\n refreshToken,\n isAuthenticated: !!accessToken && !!user,\n workspaceToken,\n // Clear all context — will be re-fetched for the new user\n organizations: [],\n currentOrganizationId: null,\n isLoadingOrganizations: false,\n workspaces: [],\n currentWorkspaceId: null,\n isLoadingWorkspaces: false,\n projects: [],\n currentProjectId: null,\n isLoadingProjects: false,\n // Clear MFA state\n mfaRequired: false,\n mfaChallengeId: null,\n });\n\n // Notify listeners (e.g., AuthTokenProvider) without writing back to storage\n notifyProfileStorageChange();\n },\n\n // Actions - MFA\n setMfaRequired: (required, challengeId) =>\n set({ mfaRequired: required, mfaChallengeId: challengeId || null }),\n\n setMfaDevices: (devices) => set({ mfaDevices: devices }),\n\n removeMfaDevice: (deviceId) =>\n set((state) => ({\n mfaDevices: state.mfaDevices.filter((d) => d.id !== deviceId),\n })),\n\n // Actions - Sessions\n setActiveSessions: (sessions) => set({ activeSessions: sessions }),\n\n removeSession: (sessionId) =>\n set((state) => ({\n activeSessions: state.activeSessions.filter(\n (s) => s.id !== sessionId,\n ),\n })),\n\n // Actions - OAuth\n setLinkedAccounts: (accounts) => set({ linkedAccounts: accounts }),\n\n removeLinkedAccount: (accountId) =>\n set((state) => ({\n linkedAccounts: state.linkedAccounts.filter(\n (a) => a.id !== accountId,\n ),\n })),\n\n // Actions - Security\n setTrustedDevices: (devices) => set({ trustedDevices: devices }),\n\n removeTrustedDevice: (deviceId) =>\n set((state) => ({\n trustedDevices: state.trustedDevices.filter((d) => d.id !== deviceId),\n })),\n\n setSecurityEvents: (events) => set({ securityEvents: events }),\n\n // Actions - API Keys\n setApiKeys: (keys) => set({ apiKeys: keys }),\n\n removeApiKey: (keyId) =>\n set((state) => ({\n apiKeys: state.apiKeys.filter((k) => k.id !== keyId),\n })),\n\n // Actions - Apps\n setApps: (apps) => set({ apps }),\n\n setCurrentApp: (app) => set({ currentApp: app }),\n\n addApp: (app) =>\n set((state) => ({\n apps: [...state.apps, app],\n })),\n\n updateApp: (app) =>\n set((state) => ({\n apps: state.apps.map((a) => (a.id === app.id ? app : a)),\n currentApp: state.currentApp?.id === app.id ? app : state.currentApp,\n })),\n\n removeApp: (appId) =>\n set((state) => ({\n apps: state.apps.filter((a) => a.id !== appId),\n currentApp: state.currentApp?.id === appId ? null : state.currentApp,\n })),\n\n // Actions - Delegations\n setDelegations: (delegations) => set({ delegations }),\n\n setGrantedDelegations: (delegations) =>\n set({ grantedDelegations: delegations }),\n\n addDelegation: (delegation) =>\n set((state) => ({\n delegations: [...state.delegations, delegation],\n })),\n\n removeDelegation: (delegationId) =>\n set((state) => ({\n delegations: state.delegations.filter((d) => d.id !== delegationId),\n grantedDelegations: state.grantedDelegations.filter(\n (d) => d.id !== delegationId,\n ),\n })),\n\n // Actions - UI\n setLoading: (loading) => set({ isLoading: loading }),\n\n setError: (error, errorCode) =>\n set({ error, errorCode: errorCode ?? null }),\n }),\n {\n name: \"auth-storage\",\n storage: createProfileScopedStorage(),\n partialize: (state) => ({\n accessToken: state.accessToken,\n refreshToken: state.refreshToken,\n user: state.user,\n isAuthenticated: state.isAuthenticated,\n // Context state\n currentOrganizationId: state.currentOrganizationId,\n currentWorkspaceId: state.currentWorkspaceId,\n currentProjectId: state.currentProjectId,\n workspaceToken: state.workspaceToken,\n // MFA state must be persisted for login verification flow\n mfaRequired: state.mfaRequired,\n mfaChallengeId: state.mfaChallengeId,\n }),\n },\n ),\n);\n\ntype AuthClearWindow = Window & { __bfAuthClearListenerInstalled?: boolean };\n\nif (typeof window !== \"undefined\") {\n const authWindow = window as AuthClearWindow;\n if (!authWindow.__bfAuthClearListenerInstalled) {\n authWindow.__bfAuthClearListenerInstalled = true;\n window.addEventListener(AUTH_STATE_CLEARED_EVENT, () => {\n const state = useAuthStore.getState();\n if (\n state.isAuthenticated ||\n state.accessToken ||\n state.refreshToken ||\n state.user\n ) {\n state.clearAuth();\n return;\n }\n clearPersistedAuthStorage(sessionStorage.getItem(BF_ACTIVE));\n });\n }\n}\n"],"mappings":";;;;AAuBA,IAAM,IAAY,QACZ,IAAc,eACd,IAAY,qBACZ,IAAmB,gBACnB,IAA2B;AAEjC,SAAS,IAAyC;AAChD,QAAO,eAAe,QAAQ,EAAU;;AAG1C,SAAS,EAAM,GAAmB,GAAwB;AACxD,QAAO,GAAG,EAAU,GAAG,EAAU,GAAG;;AAGtC,SAAS,EAA0B,GAAiC;AAElE,CADA,aAAa,WAAW,EAAiB,EACrC,KACF,aAAa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ACN,SAAS,GAA4B;CACrC,aAAa,OAAW;EACtB,aAAa,EAAM;EACnB,cAAc,EAAM;EACpB,MAAM,EAAM;EACZ,iBAAiB,EAAM;EAEvB,uBAAuB,EAAM;EAC7B,oBAAoB,EAAM;EAC1B,kBAAkB,EAAM;EACxB,gBAAgB,EAAM;EAEtB,aAAa,EAAM;EACnB,gBAAgB,EAAM;EACvB;CACF,CACF,CACF;AAID,IAAI,OAAO,SAAW,KAAa;CACjC,IAAM,IAAa;AACnB,CAAK,EAAW,mCACd,EAAW,iCAAiC,IAC5C,OAAO,iBAAiB,SAAgC;EACtD,IAAM,IAAQ,EAAa,UAAU;AACrC,MACE,EAAM,mBACN,EAAM,eACN,EAAM,gBACN,EAAM,MACN;AACA,KAAM,WAAW;AACjB;;AAEF,IAA0B,eAAe,QAAQ,EAAU,CAAC;GAC5D"}
|
|
1
|
+
{"version":3,"file":"authStore.js","names":[],"sources":["../../../src/auth/store/authStore.ts"],"sourcesContent":["import { create } from \"zustand\";\nimport { persist } from \"zustand/middleware\";\nimport { createProfileScopedStorage } from \"@burdenoff/fe-libs/shared/utils\";\nimport type {\n User,\n Session,\n MfaDevice,\n OAuthAccount,\n TrustedDevice,\n SecurityAudit,\n ApiKey,\n App,\n AppUserDelegation,\n Workspace,\n Organization,\n Project,\n} from \"../types\";\n\n/**\n * Sync auth state to profile-scoped storage (ProfileStorageManager keys).\n * The active profile ID comes from sessionStorage (\"bf-active-profile\").\n * Data is stored under localStorage keys: bf-p-{profileId}-user, bf-p-{profileId}-tokens, etc.\n */\nconst BF_PREFIX = \"bf-p\";\nconst BF_PROFILES = \"bf-profiles\";\nconst BF_ACTIVE = \"bf-active-profile\";\nconst AUTH_STORAGE_KEY = \"auth-storage\";\nconst AUTH_STATE_CLEARED_EVENT = \"bf-auth-state-cleared\";\n\nfunction getActiveProfileForSync(): string | null {\n return sessionStorage.getItem(BF_ACTIVE);\n}\n\nfunction pfKey(profileId: string, suffix: string): string {\n return `${BF_PREFIX}-${profileId}-${suffix}`;\n}\n\nfunction clearPersistedAuthStorage(profileId?: string | null): void {\n localStorage.removeItem(AUTH_STORAGE_KEY);\n if (profileId) {\n localStorage.removeItem(pfKey(profileId, AUTH_STORAGE_KEY));\n }\n for (const key of Object.keys(localStorage)) {\n if (\n key.startsWith(`${BF_PREFIX}-`) &&\n key.endsWith(`-${AUTH_STORAGE_KEY}`)\n ) {\n localStorage.removeItem(key);\n }\n }\n}\n\ninterface ProfileMeta {\n id: string;\n email: string;\n name: string;\n avatar?: string;\n lastLogin: string;\n}\n\n/** Dispatch custom event to notify fe-libs AuthProvider of storage changes (same-tab). */\nfunction notifyProfileStorageChange(): void {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"bf-profile-storage-change\"));\n }\n}\n\nfunction syncToProfileStorage(data: {\n user?: User | null;\n accessToken?: string | null;\n refreshToken?: string | null;\n workspaceToken?: string | null;\n clear?: boolean;\n}) {\n if (typeof window === \"undefined\") return;\n\n const profileId = getActiveProfileForSync();\n if (!profileId && !data.user && !data.clear) return;\n\n // For login/signup: prefer the user's own ID as the target profile.\n // This prevents overwriting an existing active profile when a NEW user\n // signs up or logs in (multi-account scenario).\n const targetId = data.user?.id ?? profileId;\n if (!targetId && !data.clear) return;\n\n if (data.clear) {\n clearPersistedAuthStorage(targetId);\n if (!targetId) {\n localStorage.removeItem(BF_PROFILES);\n sessionStorage.removeItem(BF_ACTIVE);\n return;\n }\n // Remove profile data keys\n localStorage.removeItem(pfKey(targetId, \"user\"));\n localStorage.removeItem(pfKey(targetId, \"tokens\"));\n localStorage.removeItem(pfKey(targetId, \"workspace-token\"));\n // Remove from profiles list\n try {\n const profilesRaw = localStorage.getItem(BF_PROFILES);\n const profiles: ProfileMeta[] = profilesRaw\n ? JSON.parse(profilesRaw)\n : [];\n const filtered = profiles.filter((p) => p.id !== targetId);\n localStorage.setItem(BF_PROFILES, JSON.stringify(filtered));\n } catch {\n /* ignore */\n }\n sessionStorage.removeItem(BF_ACTIVE);\n return;\n }\n\n if (!targetId) return;\n\n if (data.user) {\n localStorage.setItem(pfKey(targetId, \"user\"), JSON.stringify(data.user));\n // Update profiles list\n try {\n const profilesRaw = localStorage.getItem(BF_PROFILES);\n const profiles: ProfileMeta[] = profilesRaw\n ? JSON.parse(profilesRaw)\n : [];\n const existing = profiles.filter((p) => p.id !== targetId);\n existing.push({\n id: targetId,\n email: data.user.email ?? \"\",\n name:\n data.user.name ??\n `${data.user.firstName ?? \"\"} ${data.user.lastName ?? \"\"}`.trim(),\n avatar: data.user.avatar,\n lastLogin: new Date().toISOString(),\n });\n localStorage.setItem(BF_PROFILES, JSON.stringify(existing));\n } catch {\n /* ignore */\n }\n // Set as active profile in this tab\n sessionStorage.setItem(BF_ACTIVE, targetId);\n }\n\n if (data.accessToken !== undefined || data.refreshToken !== undefined) {\n const existingRaw = localStorage.getItem(pfKey(targetId, \"tokens\"));\n const existing = existingRaw ? JSON.parse(existingRaw) : {};\n // Compute expiresAt from the actual JWT exp claim if a new access token is provided\n let expiresAt = existing.expiresAt ?? Date.now() + 60 * 60 * 1000;\n const tokenToCheck = data.accessToken ?? existing.accessToken;\n if (tokenToCheck) {\n try {\n const raw = tokenToCheck\n .split(\".\")[1]\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\");\n const padded = raw.padEnd(Math.ceil(raw.length / 4) * 4, \"=\");\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp === \"number\") {\n expiresAt = payload.exp * 1000; // JWT exp is in seconds → ms\n }\n } catch {\n // Fallback: keep existing or default 1h\n }\n }\n const merged = {\n ...existing,\n ...(data.accessToken !== undefined\n ? { accessToken: data.accessToken }\n : {}),\n ...(data.refreshToken !== undefined\n ? { refreshToken: data.refreshToken }\n : {}),\n expiresAt,\n };\n if (merged.accessToken) {\n localStorage.setItem(pfKey(targetId, \"tokens\"), JSON.stringify(merged));\n } else {\n localStorage.removeItem(pfKey(targetId, \"tokens\"));\n }\n }\n\n if (data.workspaceToken !== undefined) {\n if (data.workspaceToken) {\n localStorage.setItem(\n pfKey(targetId, \"workspace-token\"),\n data.workspaceToken,\n );\n } else {\n localStorage.removeItem(pfKey(targetId, \"workspace-token\"));\n }\n }\n\n // Notify fe-libs AuthProvider of the change (same-tab custom event)\n notifyProfileStorageChange();\n\n // Set SSO cookie for cross-domain session sharing (works in all envs)\n // Stores profile ID + the origin where the user logged in.\n // Other shells use the origin to redirect to /auth/sso-relay for token relay.\n try {\n const hostname = window.location.hostname;\n // For local dev, set cookie on shared .local.burdenoff.com domain\n // For production, set cookie on current domain only (relay handles cross-domain)\n const isSharedDomain = hostname.endsWith(\".local.burdenoff.com\");\n const domain = isSharedDomain ? \".local.burdenoff.com\" : undefined;\n const domainPart = domain ? `; domain=${domain}` : \"\";\n const securePart = window.location.protocol === \"https:\" ? \"; secure\" : \"\";\n const cookieOpts = `${domainPart}; path=/; samesite=lax${securePart}`;\n\n if (data.accessToken && targetId) {\n // Store profile ID + login origin for SSO relay\n const ssoValue = JSON.stringify({\n id: targetId,\n origin: window.location.origin,\n });\n document.cookie = `bf-sso=${encodeURIComponent(ssoValue)}${cookieOpts}; max-age=86400`;\n document.cookie = `bf-sso-profile=${encodeURIComponent(ssoValue)}${cookieOpts}; max-age=86400`;\n }\n\n if (data.clear) {\n document.cookie = \"bf-sso=; path=/; max-age=0\";\n document.cookie = \"bf-sso-profile=; path=/; max-age=0\";\n if (domain) {\n document.cookie = `bf-sso=; path=/; domain=${domain}; max-age=0`;\n document.cookie = `bf-sso-profile=; path=/; domain=${domain}; max-age=0`;\n }\n if (hostname && ![\"localhost\", \"127.0.0.1\"].includes(hostname)) {\n document.cookie = `bf-sso=; path=/; domain=${hostname}; max-age=0`;\n document.cookie = `bf-sso-profile=; path=/; domain=${hostname}; max-age=0`;\n }\n }\n } catch {\n /* ignore */\n }\n}\n\ninterface AuthState {\n // Auth state\n user: User | null;\n accessToken: string | null;\n refreshToken: string | null;\n isAuthenticated: boolean;\n\n // Organization state\n organizations: Organization[];\n currentOrganizationId: string | null;\n isLoadingOrganizations: boolean;\n\n // Workspace state\n workspaces: Workspace[];\n currentWorkspaceId: string | null;\n workspaceToken: string | null;\n isLoadingWorkspaces: boolean;\n\n // Project state\n projects: Project[];\n currentProjectId: string | null;\n isLoadingProjects: boolean;\n\n // MFA state\n mfaRequired: boolean;\n mfaChallengeId: string | null;\n mfaDevices: MfaDevice[];\n\n // Session state\n activeSessions: Session[];\n currentSessionId: string | null;\n\n // OAuth state\n linkedAccounts: OAuthAccount[];\n\n // Security state\n trustedDevices: TrustedDevice[];\n securityEvents: SecurityAudit[];\n\n // API Keys state\n apiKeys: ApiKey[];\n\n // Apps state\n apps: App[];\n currentApp: App | null;\n\n // Delegations state\n delegations: AppUserDelegation[];\n grantedDelegations: AppUserDelegation[];\n\n // UI state\n isLoading: boolean;\n error: string | null;\n errorCode: string | null;\n\n // Actions - Auth\n setUser: (user: User | null) => void;\n setAccessToken: (token: string | null) => void;\n setAuthTokens: (accessToken: string, refreshToken: string) => void;\n setAuthenticated: (isAuthenticated: boolean) => void;\n clearAuth: () => void;\n\n // Actions - Organization\n setOrganizations: (organizations: Organization[]) => void;\n setCurrentOrganizationId: (orgId: string | null) => void;\n setLoadingOrganizations: (loading: boolean) => void;\n\n // Actions - Workspace\n setWorkspaces: (workspaces: Workspace[]) => void;\n setCurrentWorkspaceId: (workspaceId: string | null) => void;\n setWorkspaceToken: (token: string | null) => void;\n setLoadingWorkspaces: (loading: boolean) => void;\n clearWorkspace: () => void;\n\n // Actions - Project\n setProjects: (projects: Project[]) => void;\n setCurrentProjectId: (projectId: string | null) => void;\n setLoadingProjects: (loading: boolean) => void;\n clearProject: () => void;\n\n // Actions - Context (clears org, workspace, project)\n clearContext: () => void;\n\n // Actions - Profile Switch (load from profile storage without syncing back)\n loadFromProfile: (profileId: string) => void;\n\n // Actions - MFA\n setMfaRequired: (required: boolean, challengeId?: string) => void;\n setMfaDevices: (devices: MfaDevice[]) => void;\n removeMfaDevice: (deviceId: string) => void;\n\n // Actions - Sessions\n setActiveSessions: (sessions: Session[]) => void;\n removeSession: (sessionId: string) => void;\n\n // Actions - OAuth\n setLinkedAccounts: (accounts: OAuthAccount[]) => void;\n removeLinkedAccount: (accountId: string) => void;\n\n // Actions - Security\n setTrustedDevices: (devices: TrustedDevice[]) => void;\n removeTrustedDevice: (deviceId: string) => void;\n setSecurityEvents: (events: SecurityAudit[]) => void;\n\n // Actions - API Keys\n setApiKeys: (keys: ApiKey[]) => void;\n removeApiKey: (keyId: string) => void;\n\n // Actions - Apps\n setApps: (apps: App[]) => void;\n setCurrentApp: (app: App | null) => void;\n addApp: (app: App) => void;\n updateApp: (app: App) => void;\n removeApp: (appId: string) => void;\n\n // Actions - Delegations\n setDelegations: (delegations: AppUserDelegation[]) => void;\n setGrantedDelegations: (delegations: AppUserDelegation[]) => void;\n addDelegation: (delegation: AppUserDelegation) => void;\n removeDelegation: (delegationId: string) => void;\n\n // Actions - UI\n setLoading: (loading: boolean) => void;\n setError: (error: string | null, errorCode?: string | null) => void;\n}\n\n/**\n * Auth Zustand store — browser-tab-local state.\n *\n * SAFE for in-memory (no Redis needed):\n * - accessToken / refreshToken / user: per-tab, backed by profileScopedStorage\n * (localStorage key bf-p-{profileId}-*). Tabs sharing the same profile ID\n * stay in sync via the \"bf-profile-storage-change\" custom event + \"storage\"\n * cross-tab event.\n * - workspaceToken: same pattern as above.\n * - mfaRequired / mfaChallengeId: transient login-flow state; not needed\n * cross-tab (each login has its own challenge).\n * - organizations / workspaces / projects lists: cached context, re-fetched\n * after account switch; no cross-tab sharing needed.\n * - UI state (isLoading, error): purely ephemeral.\n *\n * NOT safe for in-memory (needs Redis in future if required server-side):\n * - Nothing currently — all server-side session tracking is done by the\n * backend (global-auth-svc) using its own DB. The frontend only holds\n * short-lived JWT access tokens that expire independently.\n */\nexport const useAuthStore = create<AuthState>()(\n persist(\n (set) => ({\n // Initial state\n user: null,\n accessToken: null,\n refreshToken: null,\n isAuthenticated: false,\n organizations: [],\n currentOrganizationId: null,\n isLoadingOrganizations: false,\n workspaces: [],\n currentWorkspaceId: null,\n workspaceToken: null,\n isLoadingWorkspaces: false,\n projects: [],\n currentProjectId: null,\n isLoadingProjects: false,\n mfaRequired: false,\n mfaChallengeId: null,\n mfaDevices: [],\n activeSessions: [],\n currentSessionId: null,\n linkedAccounts: [],\n trustedDevices: [],\n securityEvents: [],\n apiKeys: [],\n apps: [],\n currentApp: null,\n delegations: [],\n grantedDelegations: [],\n isLoading: false,\n error: null,\n errorCode: null,\n\n // Actions - Auth (with profile storage sync)\n setUser: (user) => {\n set({ user });\n syncToProfileStorage({ user });\n },\n\n setAccessToken: (token) => {\n set({ accessToken: token });\n syncToProfileStorage({ accessToken: token });\n },\n\n setAuthTokens: (accessToken, refreshToken) => {\n // Only set tokens here. Do NOT overwrite user — setUser() handles that\n // with the full user object from the GraphQL response (firstName, lastName, etc.).\n // Fall back to JWT-decoded user ONLY if no user is currently in the store.\n const currentState = useAuthStore.getState();\n if (currentState.user) {\n // User already set (from setUser call) — just update tokens\n set({ accessToken, refreshToken });\n syncToProfileStorage({ accessToken, refreshToken });\n } else {\n // No user yet — decode JWT as fallback\n try {\n const b64 = accessToken\n .split(\".\")[1]\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\");\n const padded = b64.padEnd(Math.ceil(b64.length / 4) * 4, \"=\");\n const payload = JSON.parse(atob(padded));\n const user: User = {\n id: payload.sub,\n email: payload.email,\n username: payload.username,\n role: payload.role,\n status: \"ACTIVE\",\n emailVerified: true,\n mfaEnabled: false,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n set({ accessToken, refreshToken, user });\n syncToProfileStorage({ accessToken, refreshToken, user });\n } catch (error) {\n console.error(\"[AuthStore] Failed to decode JWT:\", error);\n set({ accessToken, refreshToken });\n syncToProfileStorage({ accessToken, refreshToken });\n }\n }\n },\n\n setAuthenticated: (isAuthenticated) => set({ isAuthenticated }),\n\n clearAuth: () => {\n set({\n user: null,\n accessToken: null,\n refreshToken: null,\n isAuthenticated: false,\n mfaRequired: false,\n mfaChallengeId: null,\n activeSessions: [],\n currentSessionId: null,\n organizations: [],\n currentOrganizationId: null,\n isLoadingOrganizations: false,\n workspaces: [],\n workspaceToken: null,\n currentWorkspaceId: null,\n isLoadingWorkspaces: false,\n projects: [],\n currentProjectId: null,\n isLoadingProjects: false,\n });\n syncToProfileStorage({ clear: true });\n },\n\n // Actions - Organization\n setOrganizations: (organizations) => set({ organizations }),\n\n setCurrentOrganizationId: (orgId) =>\n set((state) =>\n state.currentOrganizationId === orgId\n ? state\n : { currentOrganizationId: orgId },\n ),\n\n setLoadingOrganizations: (loading) =>\n set({ isLoadingOrganizations: loading }),\n\n // Actions - Workspace\n setWorkspaces: (workspaces) => set({ workspaces }),\n\n setCurrentWorkspaceId: (workspaceId) =>\n set((state) =>\n state.currentWorkspaceId === workspaceId\n ? state\n : { currentWorkspaceId: workspaceId },\n ),\n\n setWorkspaceToken: (token) => {\n set({ workspaceToken: token });\n syncToProfileStorage({ workspaceToken: token });\n },\n\n setLoadingWorkspaces: (loading) => set({ isLoadingWorkspaces: loading }),\n\n clearWorkspace: () =>\n set({ currentWorkspaceId: null, workspaceToken: null, workspaces: [] }),\n\n // Actions - Project\n setProjects: (projects) => set({ projects }),\n\n setCurrentProjectId: (projectId) =>\n set((state) =>\n state.currentProjectId === projectId\n ? state\n : { currentProjectId: projectId },\n ),\n\n setLoadingProjects: (loading) => set({ isLoadingProjects: loading }),\n\n clearProject: () => set({ currentProjectId: null, projects: [] }),\n\n // Actions - Context (clears org, workspace, project)\n clearContext: () =>\n set({\n organizations: [],\n currentOrganizationId: null,\n isLoadingOrganizations: false,\n workspaces: [],\n currentWorkspaceId: null,\n workspaceToken: null,\n isLoadingWorkspaces: false,\n projects: [],\n currentProjectId: null,\n isLoadingProjects: false,\n }),\n\n // Actions - Profile Switch\n // Loads user/tokens from profile-scoped localStorage WITHOUT syncing back.\n // Used during account switching to align zustand with the new active profile.\n loadFromProfile: (profileId: string) => {\n let user: User | null = null;\n let accessToken: string | null = null;\n let refreshToken: string | null = null;\n let workspaceToken: string | null = null;\n\n try {\n const userRaw = localStorage.getItem(pfKey(profileId, \"user\"));\n if (userRaw) user = JSON.parse(userRaw);\n } catch {\n /* ignore */\n }\n\n try {\n const tokensRaw = localStorage.getItem(pfKey(profileId, \"tokens\"));\n if (tokensRaw) {\n const tokens = JSON.parse(tokensRaw);\n accessToken = tokens.accessToken ?? null;\n refreshToken = tokens.refreshToken ?? null;\n }\n } catch {\n /* ignore */\n }\n\n workspaceToken = localStorage.getItem(\n pfKey(profileId, \"workspace-token\"),\n );\n\n // Set everything in one batch — clears context data so it will be re-fetched\n set({\n user,\n accessToken,\n refreshToken,\n isAuthenticated: !!accessToken && !!user,\n workspaceToken,\n // Clear all context — will be re-fetched for the new user\n organizations: [],\n currentOrganizationId: null,\n isLoadingOrganizations: false,\n workspaces: [],\n currentWorkspaceId: null,\n isLoadingWorkspaces: false,\n projects: [],\n currentProjectId: null,\n isLoadingProjects: false,\n // Clear MFA state\n mfaRequired: false,\n mfaChallengeId: null,\n });\n\n // Notify listeners (e.g., AuthTokenProvider) without writing back to storage\n notifyProfileStorageChange();\n },\n\n // Actions - MFA\n setMfaRequired: (required, challengeId) =>\n set({ mfaRequired: required, mfaChallengeId: challengeId || null }),\n\n setMfaDevices: (devices) => set({ mfaDevices: devices }),\n\n removeMfaDevice: (deviceId) =>\n set((state) => ({\n mfaDevices: state.mfaDevices.filter((d) => d.id !== deviceId),\n })),\n\n // Actions - Sessions\n setActiveSessions: (sessions) => set({ activeSessions: sessions }),\n\n removeSession: (sessionId) =>\n set((state) => ({\n activeSessions: state.activeSessions.filter(\n (s) => s.id !== sessionId,\n ),\n })),\n\n // Actions - OAuth\n setLinkedAccounts: (accounts) => set({ linkedAccounts: accounts }),\n\n removeLinkedAccount: (accountId) =>\n set((state) => ({\n linkedAccounts: state.linkedAccounts.filter(\n (a) => a.id !== accountId,\n ),\n })),\n\n // Actions - Security\n setTrustedDevices: (devices) => set({ trustedDevices: devices }),\n\n removeTrustedDevice: (deviceId) =>\n set((state) => ({\n trustedDevices: state.trustedDevices.filter((d) => d.id !== deviceId),\n })),\n\n setSecurityEvents: (events) => set({ securityEvents: events }),\n\n // Actions - API Keys\n setApiKeys: (keys) => set({ apiKeys: keys }),\n\n removeApiKey: (keyId) =>\n set((state) => ({\n apiKeys: state.apiKeys.filter((k) => k.id !== keyId),\n })),\n\n // Actions - Apps\n setApps: (apps) => set({ apps }),\n\n setCurrentApp: (app) => set({ currentApp: app }),\n\n addApp: (app) =>\n set((state) => ({\n apps: [...state.apps, app],\n })),\n\n updateApp: (app) =>\n set((state) => ({\n apps: state.apps.map((a) => (a.id === app.id ? app : a)),\n currentApp: state.currentApp?.id === app.id ? app : state.currentApp,\n })),\n\n removeApp: (appId) =>\n set((state) => ({\n apps: state.apps.filter((a) => a.id !== appId),\n currentApp: state.currentApp?.id === appId ? null : state.currentApp,\n })),\n\n // Actions - Delegations\n setDelegations: (delegations) => set({ delegations }),\n\n setGrantedDelegations: (delegations) =>\n set({ grantedDelegations: delegations }),\n\n addDelegation: (delegation) =>\n set((state) => ({\n delegations: [...state.delegations, delegation],\n })),\n\n removeDelegation: (delegationId) =>\n set((state) => ({\n delegations: state.delegations.filter((d) => d.id !== delegationId),\n grantedDelegations: state.grantedDelegations.filter(\n (d) => d.id !== delegationId,\n ),\n })),\n\n // Actions - UI\n setLoading: (loading) => set({ isLoading: loading }),\n\n setError: (error, errorCode) =>\n set({ error, errorCode: errorCode ?? null }),\n }),\n {\n name: \"auth-storage\",\n storage: createProfileScopedStorage(),\n partialize: (state) => ({\n accessToken: state.accessToken,\n refreshToken: state.refreshToken,\n user: state.user,\n isAuthenticated: state.isAuthenticated,\n // Context state\n currentOrganizationId: state.currentOrganizationId,\n currentWorkspaceId: state.currentWorkspaceId,\n currentProjectId: state.currentProjectId,\n workspaceToken: state.workspaceToken,\n // MFA state must be persisted for login verification flow\n mfaRequired: state.mfaRequired,\n mfaChallengeId: state.mfaChallengeId,\n }),\n },\n ),\n);\n\ntype AuthClearWindow = Window & { __bfAuthClearListenerInstalled?: boolean };\n\nif (typeof window !== \"undefined\") {\n const authWindow = window as AuthClearWindow;\n if (!authWindow.__bfAuthClearListenerInstalled) {\n authWindow.__bfAuthClearListenerInstalled = true;\n window.addEventListener(AUTH_STATE_CLEARED_EVENT, () => {\n const state = useAuthStore.getState();\n if (\n state.isAuthenticated ||\n state.accessToken ||\n state.refreshToken ||\n state.user\n ) {\n state.clearAuth();\n return;\n }\n clearPersistedAuthStorage(sessionStorage.getItem(BF_ACTIVE));\n });\n }\n}\n"],"mappings":";;;;AAuBA,IAAM,IAAY,QACZ,IAAc,eACd,IAAY,qBACZ,IAAmB,gBACnB,IAA2B;AAEjC,SAAS,IAAyC;CAChD,OAAO,eAAe,QAAQ,CAAS;AACzC;AAEA,SAAS,EAAM,GAAmB,GAAwB;CACxD,OAAO,GAAG,EAAU,GAAG,EAAU,GAAG;AACtC;AAEA,SAAS,EAA0B,GAAiC;CAElE,AADA,aAAa,WAAW,CAAgB,GACpC,KACF,aAAa,WAAW,EAAM,GAAW,CAAgB,CAAC;CAE5D,KAAK,IAAM,KAAO,OAAO,KAAK,YAAY,GACxC,AACE,EAAI,WAAW,GAAG,EAAU,EAAE,KAC9B,EAAI,SAAS,IAAI,GAAkB,KAEnC,aAAa,WAAW,CAAG;AAGjC;AAWA,SAAS,IAAmC;CAC1C,AAAI,OAAO,SAAW,OACpB,OAAO,cAAc,IAAI,MAAM,2BAA2B,CAAC;AAE/D;AAEA,SAAS,EAAqB,GAM3B;CACD,IAAI,OAAO,SAAW,KAAa;CAEnC,IAAM,IAAY,EAAwB;CAC1C,IAAI,CAAC,KAAa,CAAC,EAAK,QAAQ,CAAC,EAAK,OAAO;CAK7C,IAAM,IAAW,EAAK,MAAM,MAAM;CAC9B,OAAC,KAAY,CAAC,EAAK,QAEvB;MAAI,EAAK,OAAO;GAEd,IADA,EAA0B,CAAQ,GAC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AC5C,OAAO,iBAAiB,SAAgC;EACtD,IAAM,IAAQ,EAAa,SAAS;EACpC,IACE,EAAM,mBACN,EAAM,eACN,EAAM,gBACN,EAAM,MACN;GACA,EAAM,UAAU;GAChB;EACF;EACA,EAA0B,eAAe,QAAQ,CAAS,CAAC;CAC7D,CAAC;AAEL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"captchaConfig.js","names":[],"sources":["../../../src/auth/utils/captchaConfig.ts"],"sourcesContent":["const CAPTCHA_ENABLED = import.meta.env.VITE_CAPTCHA_ENABLED === \"true\";\n\nexport function isCaptchaEnabled(): boolean {\n return CAPTCHA_ENABLED;\n}\n\nexport function getRecaptchaSiteKey(): string | undefined {\n const siteKey = import.meta.env.VITE_RECAPTCHA_SITE_KEY;\n return typeof siteKey === \"string\" && siteKey.trim().length > 0\n ? siteKey.trim()\n : undefined;\n}\n\nexport function requireRecaptchaSiteKey(): string {\n const siteKey = getRecaptchaSiteKey();\n if (!siteKey) {\n throw new Error(\"reCAPTCHA site key is not configured\");\n }\n return siteKey;\n}\n"],"mappings":";AAAA,IAAM,IAAkB;AAExB,SAAgB,IAA4B;
|
|
1
|
+
{"version":3,"file":"captchaConfig.js","names":[],"sources":["../../../src/auth/utils/captchaConfig.ts"],"sourcesContent":["const CAPTCHA_ENABLED = import.meta.env.VITE_CAPTCHA_ENABLED === \"true\";\n\nexport function isCaptchaEnabled(): boolean {\n return CAPTCHA_ENABLED;\n}\n\nexport function getRecaptchaSiteKey(): string | undefined {\n const siteKey = import.meta.env.VITE_RECAPTCHA_SITE_KEY;\n return typeof siteKey === \"string\" && siteKey.trim().length > 0\n ? siteKey.trim()\n : undefined;\n}\n\nexport function requireRecaptchaSiteKey(): string {\n const siteKey = getRecaptchaSiteKey();\n if (!siteKey) {\n throw new Error(\"reCAPTCHA site key is not configured\");\n }\n return siteKey;\n}\n"],"mappings":";AAAA,IAAM,IAAkB;AAExB,SAAgB,IAA4B;CAC1C,OAAO;AACT;AAEA,SAAgB,IAA0C,CAK1D;AAEA,SAAgB,IAAkC;CAG9C,MAAU,MAAM,sCAAsC;AAG1D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatters.js","names":[],"sources":["../../../src/auth/utils/formatters.ts"],"sourcesContent":["/**\n * Format date relative to now (e.g., \"2 minutes ago\", \"3 days ago\")\n */\nexport function formatRelativeTime(dateString: string): string {\n const date = new Date(dateString);\n const now = new Date();\n const diffMs = now.getTime() - date.getTime();\n const diffSecs = Math.floor(diffMs / 1000);\n const diffMins = Math.floor(diffSecs / 60);\n const diffHours = Math.floor(diffMins / 60);\n const diffDays = Math.floor(diffHours / 24);\n\n if (diffSecs < 60) return \"just now\";\n if (diffMins < 60)\n return `${diffMins} minute${diffMins !== 1 ? \"s\" : \"\"} ago`;\n if (diffHours < 24)\n return `${diffHours} hour${diffHours !== 1 ? \"s\" : \"\"} ago`;\n if (diffDays < 7) return `${diffDays} day${diffDays !== 1 ? \"s\" : \"\"} ago`;\n if (diffDays < 30) {\n const weeks = Math.floor(diffDays / 7);\n return `${weeks} week${weeks !== 1 ? \"s\" : \"\"} ago`;\n }\n if (diffDays < 365) {\n const months = Math.floor(diffDays / 30);\n return `${months} month${months !== 1 ? \"s\" : \"\"} ago`;\n }\n const years = Math.floor(diffDays / 365);\n return `${years} year${years !== 1 ? \"s\" : \"\"} ago`;\n}\n\n/**\n * Format date to human-readable string\n */\nexport function formatDate(dateString: string): string {\n const date = new Date(dateString);\n return date.toLocaleDateString(\"en-US\", {\n year: \"numeric\",\n month: \"short\",\n day: \"numeric\",\n });\n}\n\n/**\n * Format date and time\n */\nexport function formatDateTime(dateString: string): string {\n const date = new Date(dateString);\n return date.toLocaleString(\"en-US\", {\n year: \"numeric\",\n month: \"short\",\n day: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n });\n}\n\n/**\n * Mask API key (show only prefix and last 4 characters)\n */\nexport function maskApiKey(key: string, prefix: string): string {\n if (key.length <= 12) return key;\n const last4 = key.slice(-4);\n return `${prefix}_${\"•\".repeat(20)}${last4}`;\n}\n\n/**\n * Format IP address with location\n */\nexport function formatLocationString(\n ipAddress: string,\n location: string | null,\n): string {\n if (!location) return ipAddress;\n return `${ipAddress} · ${location}`;\n}\n\n/**\n * Get device icon based on user agent\n */\nexport function getDeviceIcon(userAgent: string): string {\n const ua = userAgent.toLowerCase();\n\n if (\n ua.includes(\"mobile\") ||\n ua.includes(\"android\") ||\n ua.includes(\"iphone\")\n ) {\n return \"📱\";\n }\n\n if (ua.includes(\"ipad\") || ua.includes(\"tablet\")) {\n return \"📱\";\n }\n\n if (ua.includes(\"mac\")) {\n return \"💻\";\n }\n\n if (ua.includes(\"windows\")) {\n return \"💻\";\n }\n\n if (ua.includes(\"linux\")) {\n return \"💻\";\n }\n\n return \"🖥️\";\n}\n\n/**\n * Parse device name from user agent\n */\nexport function parseDeviceName(userAgent: string | null | undefined): string {\n if (!userAgent) return \"Unknown Device\";\n const ua = userAgent.toLowerCase();\n\n // Mobile devices\n if (ua.includes(\"iphone\")) return \"iPhone\";\n if (ua.includes(\"ipad\")) return \"iPad\";\n if (ua.includes(\"android\")) return \"Android Device\";\n\n // Desktop OS\n if (ua.includes(\"mac\")) return \"Mac\";\n if (ua.includes(\"windows\")) return \"Windows PC\";\n if (ua.includes(\"linux\")) return \"Linux\";\n\n return \"Unknown Device\";\n}\n\n/**\n * Parse browser name from user agent\n */\nexport function parseBrowserName(userAgent: string | null | undefined): string {\n if (!userAgent) return \"Unknown Browser\";\n const ua = userAgent.toLowerCase();\n\n if (ua.includes(\"edg\")) return \"Edge\";\n if (ua.includes(\"chrome\")) return \"Chrome\";\n if (ua.includes(\"firefox\")) return \"Firefox\";\n if (ua.includes(\"safari\") && !ua.includes(\"chrome\")) return \"Safari\";\n if (ua.includes(\"opera\")) return \"Opera\";\n\n return \"Unknown Browser\";\n}\n\n/**\n * Format OAuth provider name\n */\nexport function formatOAuthProvider(provider: string): string {\n const providers: Record<string, string> = {\n google: \"Google\",\n github: \"GitHub\",\n microsoft: \"Microsoft\",\n apple: \"Apple\",\n linkedin: \"LinkedIn\",\n facebook: \"Facebook\",\n };\n\n return providers[provider.toLowerCase()] || provider;\n}\n"],"mappings":";AAGA,SAAgB,EAAmB,GAA4B;CAC7D,IAAM,IAAO,IAAI,KAAK,
|
|
1
|
+
{"version":3,"file":"formatters.js","names":[],"sources":["../../../src/auth/utils/formatters.ts"],"sourcesContent":["/**\n * Format date relative to now (e.g., \"2 minutes ago\", \"3 days ago\")\n */\nexport function formatRelativeTime(dateString: string): string {\n const date = new Date(dateString);\n const now = new Date();\n const diffMs = now.getTime() - date.getTime();\n const diffSecs = Math.floor(diffMs / 1000);\n const diffMins = Math.floor(diffSecs / 60);\n const diffHours = Math.floor(diffMins / 60);\n const diffDays = Math.floor(diffHours / 24);\n\n if (diffSecs < 60) return \"just now\";\n if (diffMins < 60)\n return `${diffMins} minute${diffMins !== 1 ? \"s\" : \"\"} ago`;\n if (diffHours < 24)\n return `${diffHours} hour${diffHours !== 1 ? \"s\" : \"\"} ago`;\n if (diffDays < 7) return `${diffDays} day${diffDays !== 1 ? \"s\" : \"\"} ago`;\n if (diffDays < 30) {\n const weeks = Math.floor(diffDays / 7);\n return `${weeks} week${weeks !== 1 ? \"s\" : \"\"} ago`;\n }\n if (diffDays < 365) {\n const months = Math.floor(diffDays / 30);\n return `${months} month${months !== 1 ? \"s\" : \"\"} ago`;\n }\n const years = Math.floor(diffDays / 365);\n return `${years} year${years !== 1 ? \"s\" : \"\"} ago`;\n}\n\n/**\n * Format date to human-readable string\n */\nexport function formatDate(dateString: string): string {\n const date = new Date(dateString);\n return date.toLocaleDateString(\"en-US\", {\n year: \"numeric\",\n month: \"short\",\n day: \"numeric\",\n });\n}\n\n/**\n * Format date and time\n */\nexport function formatDateTime(dateString: string): string {\n const date = new Date(dateString);\n return date.toLocaleString(\"en-US\", {\n year: \"numeric\",\n month: \"short\",\n day: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n });\n}\n\n/**\n * Mask API key (show only prefix and last 4 characters)\n */\nexport function maskApiKey(key: string, prefix: string): string {\n if (key.length <= 12) return key;\n const last4 = key.slice(-4);\n return `${prefix}_${\"•\".repeat(20)}${last4}`;\n}\n\n/**\n * Format IP address with location\n */\nexport function formatLocationString(\n ipAddress: string,\n location: string | null,\n): string {\n if (!location) return ipAddress;\n return `${ipAddress} · ${location}`;\n}\n\n/**\n * Get device icon based on user agent\n */\nexport function getDeviceIcon(userAgent: string): string {\n const ua = userAgent.toLowerCase();\n\n if (\n ua.includes(\"mobile\") ||\n ua.includes(\"android\") ||\n ua.includes(\"iphone\")\n ) {\n return \"📱\";\n }\n\n if (ua.includes(\"ipad\") || ua.includes(\"tablet\")) {\n return \"📱\";\n }\n\n if (ua.includes(\"mac\")) {\n return \"💻\";\n }\n\n if (ua.includes(\"windows\")) {\n return \"💻\";\n }\n\n if (ua.includes(\"linux\")) {\n return \"💻\";\n }\n\n return \"🖥️\";\n}\n\n/**\n * Parse device name from user agent\n */\nexport function parseDeviceName(userAgent: string | null | undefined): string {\n if (!userAgent) return \"Unknown Device\";\n const ua = userAgent.toLowerCase();\n\n // Mobile devices\n if (ua.includes(\"iphone\")) return \"iPhone\";\n if (ua.includes(\"ipad\")) return \"iPad\";\n if (ua.includes(\"android\")) return \"Android Device\";\n\n // Desktop OS\n if (ua.includes(\"mac\")) return \"Mac\";\n if (ua.includes(\"windows\")) return \"Windows PC\";\n if (ua.includes(\"linux\")) return \"Linux\";\n\n return \"Unknown Device\";\n}\n\n/**\n * Parse browser name from user agent\n */\nexport function parseBrowserName(userAgent: string | null | undefined): string {\n if (!userAgent) return \"Unknown Browser\";\n const ua = userAgent.toLowerCase();\n\n if (ua.includes(\"edg\")) return \"Edge\";\n if (ua.includes(\"chrome\")) return \"Chrome\";\n if (ua.includes(\"firefox\")) return \"Firefox\";\n if (ua.includes(\"safari\") && !ua.includes(\"chrome\")) return \"Safari\";\n if (ua.includes(\"opera\")) return \"Opera\";\n\n return \"Unknown Browser\";\n}\n\n/**\n * Format OAuth provider name\n */\nexport function formatOAuthProvider(provider: string): string {\n const providers: Record<string, string> = {\n google: \"Google\",\n github: \"GitHub\",\n microsoft: \"Microsoft\",\n apple: \"Apple\",\n linkedin: \"LinkedIn\",\n facebook: \"Facebook\",\n };\n\n return providers[provider.toLowerCase()] || provider;\n}\n"],"mappings":";AAGA,SAAgB,EAAmB,GAA4B;CAC7D,IAAM,IAAO,IAAI,KAAK,CAAU,GAE1B,qBAAS,IADC,KACD,GAAI,QAAQ,IAAI,EAAK,QAAQ,GACtC,IAAW,KAAK,MAAM,IAAS,GAAI,GACnC,IAAW,KAAK,MAAM,IAAW,EAAE,GACnC,IAAY,KAAK,MAAM,IAAW,EAAE,GACpC,IAAW,KAAK,MAAM,IAAY,EAAE;CAE1C,IAAI,IAAW,IAAI,OAAO;CAC1B,IAAI,IAAW,IACb,OAAO,GAAG,EAAS,SAAS,MAAa,IAAU,KAAN,IAAS;CACxD,IAAI,IAAY,IACd,OAAO,GAAG,EAAU,OAAO,MAAc,IAAU,KAAN,IAAS;CACxD,IAAI,IAAW,GAAG,OAAO,GAAG,EAAS,MAAM,MAAa,IAAU,KAAN,IAAS;CACrE,IAAI,IAAW,IAAI;EACjB,IAAM,IAAQ,KAAK,MAAM,IAAW,CAAC;EACrC,OAAO,GAAG,EAAM,OAAO,MAAU,IAAU,KAAN,IAAS;CAChD;CACA,IAAI,IAAW,KAAK;EAClB,IAAM,IAAS,KAAK,MAAM,IAAW,EAAE;EACvC,OAAO,GAAG,EAAO,QAAQ,MAAW,IAAU,KAAN,IAAS;CACnD;CACA,IAAM,IAAQ,KAAK,MAAM,IAAW,GAAG;CACvC,OAAO,GAAG,EAAM,OAAO,MAAU,IAAU,KAAN,IAAS;AAChD;AAKA,SAAgB,EAAW,GAA4B;CAErD,OAAO,IADU,KAAK,CACf,EAAK,mBAAmB,SAAS;EACtC,MAAM;EACN,OAAO;EACP,KAAK;CACP,CAAC;AACH;AAKA,SAAgB,EAAe,GAA4B;CAEzD,OAAO,IADU,KAAK,CACf,EAAK,eAAe,SAAS;EAClC,MAAM;EACN,OAAO;EACP,KAAK;EACL,MAAM;EACN,QAAQ;CACV,CAAC;AACH;AA0DA,SAAgB,EAAgB,GAA8C;CAC5E,IAAI,CAAC,GAAW,OAAO;CACvB,IAAM,IAAK,EAAU,YAAY;CAYjC,OATI,EAAG,SAAS,QAAQ,IAAU,WAC9B,EAAG,SAAS,MAAM,IAAU,SAC5B,EAAG,SAAS,SAAS,IAAU,mBAG/B,EAAG,SAAS,KAAK,IAAU,QAC3B,EAAG,SAAS,SAAS,IAAU,eAC/B,EAAG,SAAS,OAAO,IAAU,UAE1B;AACT;AAKA,SAAgB,EAAiB,GAA8C;CAC7E,IAAI,CAAC,GAAW,OAAO;CACvB,IAAM,IAAK,EAAU,YAAY;CAQjC,OANI,EAAG,SAAS,KAAK,IAAU,SAC3B,EAAG,SAAS,QAAQ,IAAU,WAC9B,EAAG,SAAS,SAAS,IAAU,YAC/B,EAAG,SAAS,QAAQ,KAAK,CAAC,EAAG,SAAS,QAAQ,IAAU,WACxD,EAAG,SAAS,OAAO,IAAU,UAE1B;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gatewayBaseUrls.js","names":[],"sources":["../../../src/auth/utils/gatewayBaseUrls.ts"],"sourcesContent":["export interface GatewayBaseUrls {\n globalBaseUrl: string;\n workspaceBaseUrl: string;\n}\n\nexport function resolveGatewayBaseUrls(): GatewayBaseUrls {\n const hostname =\n typeof window !== \"undefined\" ? window.location.hostname.toLowerCase() : \"\";\n\n // Production\n if (hostname === \"app.burdenoff.com\") {\n return {\n globalBaseUrl: \"https://graphql.burdenoff.com\",\n workspaceBaseUrl: \"https://graphqlworkspaces.burdenoff.com\",\n };\n }\n\n // Alpha / staging\n if (hostname === \"alphaapp.burdenoff.com\") {\n return {\n globalBaseUrl: \"https://alphagraphql.burdenoff.com\",\n workspaceBaseUrl: \"https://alphagraphqlworkspaces.burdenoff.com\",\n };\n }\n\n // Everything else is local development (localhost, 127.0.0.1, app.local.burdenoff.com, etc.)\n return {\n globalBaseUrl: \"https://gw-global.local.burdenoff.com\",\n workspaceBaseUrl: \"https://gw-wspace.local.burdenoff.com\",\n };\n}\n"],"mappings":";AAKA,SAAgB,IAA0C;CACxD,IAAM,IACJ,OAAO,SAAW,MAAc,OAAO,SAAS,SAAS,
|
|
1
|
+
{"version":3,"file":"gatewayBaseUrls.js","names":[],"sources":["../../../src/auth/utils/gatewayBaseUrls.ts"],"sourcesContent":["export interface GatewayBaseUrls {\n globalBaseUrl: string;\n workspaceBaseUrl: string;\n}\n\nexport function resolveGatewayBaseUrls(): GatewayBaseUrls {\n const hostname =\n typeof window !== \"undefined\" ? window.location.hostname.toLowerCase() : \"\";\n\n // Production\n if (hostname === \"app.burdenoff.com\") {\n return {\n globalBaseUrl: \"https://graphql.burdenoff.com\",\n workspaceBaseUrl: \"https://graphqlworkspaces.burdenoff.com\",\n };\n }\n\n // Alpha / staging\n if (hostname === \"alphaapp.burdenoff.com\") {\n return {\n globalBaseUrl: \"https://alphagraphql.burdenoff.com\",\n workspaceBaseUrl: \"https://alphagraphqlworkspaces.burdenoff.com\",\n };\n }\n\n // Everything else is local development (localhost, 127.0.0.1, app.local.burdenoff.com, etc.)\n return {\n globalBaseUrl: \"https://gw-global.local.burdenoff.com\",\n workspaceBaseUrl: \"https://gw-wspace.local.burdenoff.com\",\n };\n}\n"],"mappings":";AAKA,SAAgB,IAA0C;CACxD,IAAM,IACJ,OAAO,SAAW,MAAc,OAAO,SAAS,SAAS,YAAY,IAAI;CAmB3E,OAhBI,MAAa,sBACR;EACL,eAAe;EACf,kBAAkB;CACpB,IAIE,MAAa,2BACR;EACL,eAAe;EACf,kBAAkB;CACpB,IAIK;EACL,eAAe;EACf,kBAAkB;CACpB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"legalUrls.js","names":[],"sources":["../../../src/auth/utils/legalUrls.ts"],"sourcesContent":["/**\n * Public legal-document URLs for the signup consent copy.\n *\n * The signup form is shown to SIGNED-OUT visitors, so its \"Terms of Service\" and\n * \"Privacy Policy\" links must resolve to the public marketing site. They used to\n * be written as the app-relative paths `/legal/terms` and `/legal/privacy`, which\n * resolved against the app origin (e.g. `https://app.fluidgrids.ai/legal/terms`).\n * That route lives *inside* the shell's authenticated block, so a visitor who\n * clicked it was bounced to `/auth/login?returnTo=%2Flegal%2Fterms` and the shell\n * footer fired two FORBIDDEN queries on the way out:\n *\n * [Burdenoff backend error] You do not have permission to do that.\n * {code: FORBIDDEN, operationName: GetFooterContentPages}\n * {code: FORBIDDEN, operationName: GetFooterProduct}\n *\n * i.e. the consent links were unreadable for exactly the people being asked to\n * consent. The marketing site is also the authoritative home of the policy text\n * (rendered from the dated drafts in `fluidgrids-website/src/content/legal/`),\n * so linking there avoids maintaining a second copy that can drift.\n *\n * microfe-auth is mounted by every Burdenoff product shell, so the origin is\n * DERIVED from the current host rather than hardcoded — hardcoding one product's\n * domain would send every other product's users to the wrong company's terms.\n * Every product serves its marketing site at `www.<product-domain>` using the\n * same `/terms` and `/privacy` route names (verified against fluidgrids.ai,\n * burdenoff.com, bigconsole.com, planmagnet.com, adaptercloud.com, botmanor.com and\n * timecampus.com).\n */\n\n/**\n * Shell subdomains that front a product's app surface. Stripping one of these\n * leaves the bare product domain whose `www.` host serves the marketing site.\n */\nconst APP_HOST_PREFIXES = [\n \"app.\",\n \"alphaapp.\",\n \"admin.\",\n \"alphaadmin.\",\n \"www.\",\n];\n\n/**\n * Resolve the public marketing origin for the product currently being served,\n * or `null` when it cannot be determined (local development, or a host with no\n * registrable domain). Exported for unit testing; prefer `resolveLegalUrl`.\n */\nexport function resolveMarketingOrigin(hostname?: string): string | null {\n const host = (\n hostname ?? (typeof window !== \"undefined\" ? window.location.hostname : \"\")\n )\n .toLowerCase()\n .trim();\n\n if (!host) return null;\n\n // Local development has no marketing site to link to. `0.0.0.0` and IPv6\n // literals (which `location.hostname` reports bracketed, e.g. \"[::1]\") are\n // included because a bare dotted-quad would otherwise survive the \"has a dot\"\n // check below and produce a nonsense origin like `https://www.0.0.0.0`.\n if (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"0.0.0.0\" ||\n host.startsWith(\"[\") ||\n host.endsWith(\".local.burdenoff.com\")\n ) {\n return null;\n }\n\n // Any other IPv4 literal is likewise not a registrable domain.\n if (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host)) return null;\n\n let domain = host;\n for (const prefix of APP_HOST_PREFIXES) {\n if (domain.startsWith(prefix)) {\n domain = domain.slice(prefix.length);\n break;\n }\n }\n\n // A bare hostname with no dot is not a registrable domain we can build on.\n if (!domain.includes(\".\")) return null;\n\n return `https://www.${domain}`;\n}\n\n/** Public legal pages, by the route name every product marketing site uses. */\nexport type LegalDocumentPath = \"/terms\" | \"/privacy\";\n\n/**\n * Absolute URL of a public legal document for the current product.\n *\n * Falls back to the bare path when the marketing origin cannot be resolved\n * (local development), which keeps the link valid-looking in dev without\n * inventing a production domain.\n */\nexport function resolveLegalUrl(path: LegalDocumentPath): string {\n const origin = resolveMarketingOrigin();\n return origin ? `${origin}${path}` : path;\n}\n"],"mappings":";AAiCA,IAAM,IAAoB;CACxB;CACA;CACA;CACA;CACA;
|
|
1
|
+
{"version":3,"file":"legalUrls.js","names":[],"sources":["../../../src/auth/utils/legalUrls.ts"],"sourcesContent":["/**\n * Public legal-document URLs for the signup consent copy.\n *\n * The signup form is shown to SIGNED-OUT visitors, so its \"Terms of Service\" and\n * \"Privacy Policy\" links must resolve to the public marketing site. They used to\n * be written as the app-relative paths `/legal/terms` and `/legal/privacy`, which\n * resolved against the app origin (e.g. `https://app.fluidgrids.ai/legal/terms`).\n * That route lives *inside* the shell's authenticated block, so a visitor who\n * clicked it was bounced to `/auth/login?returnTo=%2Flegal%2Fterms` and the shell\n * footer fired two FORBIDDEN queries on the way out:\n *\n * [Burdenoff backend error] You do not have permission to do that.\n * {code: FORBIDDEN, operationName: GetFooterContentPages}\n * {code: FORBIDDEN, operationName: GetFooterProduct}\n *\n * i.e. the consent links were unreadable for exactly the people being asked to\n * consent. The marketing site is also the authoritative home of the policy text\n * (rendered from the dated drafts in `fluidgrids-website/src/content/legal/`),\n * so linking there avoids maintaining a second copy that can drift.\n *\n * microfe-auth is mounted by every Burdenoff product shell, so the origin is\n * DERIVED from the current host rather than hardcoded — hardcoding one product's\n * domain would send every other product's users to the wrong company's terms.\n * Every product serves its marketing site at `www.<product-domain>` using the\n * same `/terms` and `/privacy` route names (verified against fluidgrids.ai,\n * burdenoff.com, bigconsole.com, planmagnet.com, adaptercloud.com, botmanor.com and\n * timecampus.com).\n */\n\n/**\n * Shell subdomains that front a product's app surface. Stripping one of these\n * leaves the bare product domain whose `www.` host serves the marketing site.\n */\nconst APP_HOST_PREFIXES = [\n \"app.\",\n \"alphaapp.\",\n \"admin.\",\n \"alphaadmin.\",\n \"www.\",\n];\n\n/**\n * Resolve the public marketing origin for the product currently being served,\n * or `null` when it cannot be determined (local development, or a host with no\n * registrable domain). Exported for unit testing; prefer `resolveLegalUrl`.\n */\nexport function resolveMarketingOrigin(hostname?: string): string | null {\n const host = (\n hostname ?? (typeof window !== \"undefined\" ? window.location.hostname : \"\")\n )\n .toLowerCase()\n .trim();\n\n if (!host) return null;\n\n // Local development has no marketing site to link to. `0.0.0.0` and IPv6\n // literals (which `location.hostname` reports bracketed, e.g. \"[::1]\") are\n // included because a bare dotted-quad would otherwise survive the \"has a dot\"\n // check below and produce a nonsense origin like `https://www.0.0.0.0`.\n if (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"0.0.0.0\" ||\n host.startsWith(\"[\") ||\n host.endsWith(\".local.burdenoff.com\")\n ) {\n return null;\n }\n\n // Any other IPv4 literal is likewise not a registrable domain.\n if (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host)) return null;\n\n let domain = host;\n for (const prefix of APP_HOST_PREFIXES) {\n if (domain.startsWith(prefix)) {\n domain = domain.slice(prefix.length);\n break;\n }\n }\n\n // A bare hostname with no dot is not a registrable domain we can build on.\n if (!domain.includes(\".\")) return null;\n\n return `https://www.${domain}`;\n}\n\n/** Public legal pages, by the route name every product marketing site uses. */\nexport type LegalDocumentPath = \"/terms\" | \"/privacy\";\n\n/**\n * Absolute URL of a public legal document for the current product.\n *\n * Falls back to the bare path when the marketing origin cannot be resolved\n * (local development), which keeps the link valid-looking in dev without\n * inventing a production domain.\n */\nexport function resolveLegalUrl(path: LegalDocumentPath): string {\n const origin = resolveMarketingOrigin();\n return origin ? `${origin}${path}` : path;\n}\n"],"mappings":";AAiCA,IAAM,IAAoB;CACxB;CACA;CACA;CACA;CACA;AACF;AAOA,SAAgB,EAAuB,GAAkC;CACvE,IAAM,KACJ,MAAa,OAAO,SAAW,MAAc,OAAO,SAAS,WAAW,KAEvE,YAAY,EACZ,KAAK;CAmBR,IAjBI,CAAC,KAOH,MAAS,eACT,MAAS,eACT,MAAS,aACT,EAAK,WAAW,GAAG,KACnB,EAAK,SAAS,sBAAsB,KAMlC,uBAAuB,KAAK,CAAI,GAAG,OAAO;CAE9C,IAAI,IAAS;CACb,KAAK,IAAM,KAAU,GACnB,IAAI,EAAO,WAAW,CAAM,GAAG;EAC7B,IAAS,EAAO,MAAM,EAAO,MAAM;EACnC;CACF;CAMF,OAFK,EAAO,SAAS,GAAG,IAEjB,eAAe,MAFY;AAGpC;AAYA,SAAgB,EAAgB,GAAiC;CAC/D,IAAM,IAAS,EAAuB;CACtC,OAAO,IAAS,GAAG,IAAS,MAAS;AACvC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redirect.js","names":[],"sources":["../../../src/auth/utils/redirect.ts"],"sourcesContent":["/**\n * Redirect helpers for the post-login flow.\n *\n * Keeps redirect-sanitization logic pure and unit-testable so the login page\n * cannot accidentally redirect back into an auth route (BOFF-6807).\n */\n\nfunction isAuthRoutePath(path: string): boolean {\n if (typeof window === \"undefined\") return false;\n try {\n const url = new URL(path, window.location.origin);\n return url.pathname.startsWith(\"/auth\");\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure the post-login destination never lands back on an auth route.\n * Falls back to `/dashboard` when the supplied path is empty, \"/\", or an\n * `/auth/*` path.\n */\nexport function sanitizePostLoginPath(path: string): string {\n if (typeof window === \"undefined\") return path;\n if (!path || path === \"/\" || isAuthRoutePath(path)) {\n return \"/dashboard\";\n }\n return path;\n}\n"],"mappings":";AAOA,SAAS,EAAgB,GAAuB;
|
|
1
|
+
{"version":3,"file":"redirect.js","names":[],"sources":["../../../src/auth/utils/redirect.ts"],"sourcesContent":["/**\n * Redirect helpers for the post-login flow.\n *\n * Keeps redirect-sanitization logic pure and unit-testable so the login page\n * cannot accidentally redirect back into an auth route (BOFF-6807).\n */\n\nfunction isAuthRoutePath(path: string): boolean {\n if (typeof window === \"undefined\") return false;\n try {\n const url = new URL(path, window.location.origin);\n return url.pathname.startsWith(\"/auth\");\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure the post-login destination never lands back on an auth route.\n * Falls back to `/dashboard` when the supplied path is empty, \"/\", or an\n * `/auth/*` path.\n */\nexport function sanitizePostLoginPath(path: string): string {\n if (typeof window === \"undefined\") return path;\n if (!path || path === \"/\" || isAuthRoutePath(path)) {\n return \"/dashboard\";\n }\n return path;\n}\n"],"mappings":";AAOA,SAAS,EAAgB,GAAuB;CAC9C,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAI;EAEF,OAAO,IADS,IAAI,GAAM,OAAO,SAAS,MACnC,EAAI,SAAS,WAAW,OAAO;CACxC,QAAQ;EACN,OAAO;CACT;AACF;AAOA,SAAgB,EAAsB,GAAsB;CAK1D,OAJI,OAAO,SAAW,MAAoB,IACtC,CAAC,KAAQ,MAAS,OAAO,EAAgB,CAAI,IACxC,eAEF;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssoOrigins.js","names":[],"sources":["../../../src/auth/utils/ssoOrigins.ts"],"sourcesContent":["/**\n * Shared first-party SSO origin allow-list for the cross-domain auth pages\n * (SSOClearPage, SSODepositPage, SSORelayPage, SessionBridgePage).\n *\n * These four pages each used to hand-roll an identical copy of this domain set\n * plus its matching function, and they drifted independently — BOFF-4120 was\n * exactly that drift (SSOClearPage's copy was missing admin./alphaadmin., so an\n * admin logout returnTo was rejected on the bridge host and stranded the\n * operator on app.burdenoff.com). Keep the list + matching logic HERE only so\n * a new product domain or subdomain is added in one place. BOFF-4124.\n */\n\nconst ALLOWED_SSO_DOMAINS = new Set<string>([\n \"burdenoff.com\",\n \"vibecontrols.com\",\n \"fluidgrids.com\",\n // BotManor (formerly Botlit): botmanor.com is the primary domain; botlit.ai\n // stays trusted while it redirects there, so in-flight relays still return.\n \"botlit.ai\",\n \"botmanor.com\",\n \"bigconsole.com\",\n \"gethealthybowl.com\",\n \"headshotmarketing.com\",\n \"timecampus.com\",\n \"ggnomad.com\",\n \"movethewheels.com\",\n \"crewfoundry.com\",\n \"planmagnet.com\",\n \"eventfullymanaged.com\",\n \"kadaikodi.com\",\n \"assethandler.com\",\n \"technospam.com\",\n \"semanticfed.com\",\n \"manufacturedops.com\",\n \"theglobalfuel.com\",\n \"housingvista.com\",\n \"proserviceworld.com\",\n \"mybodyshield.com\",\n \"artistrybase.com\",\n \"collabkin.com\",\n \"brainyrich.com\",\n \"theculturepost.com\",\n \"comradecircle.com\",\n \"cosmicintersection.com\",\n \"govcitizenhub.com\",\n \"intelwatchtower.com\",\n \"ecoimpacthub.com\",\n \"buildmyiq.com\",\n \"fluidgrids.ai\",\n \"atheletebridge.com\",\n \"adaptercloud.com\",\n \"coolandlovely.com\",\n \"subscriberbot.com\",\n \"labsofscience.com\",\n \"hookmovies.com\",\n]);\n\n/**\n * True when `url` is a first-party Burdenoff shell origin permitted to take\n * part in the cross-domain SSO relay / clear / deposit / session-bridge flow:\n * - localhost / 127.0.0.1 (any port, local dev)\n * - *.local.burdenoff.com (local dev behind nginx)\n * - https://{\"\" | app. | alphaapp. | admin. | alphaadmin. | www.}<product-domain>\n * — note admin./alphaadmin. are included: the admin app shells\n * (admin.burdenoff.com / alphaadmin.burdenoff.com) are first-party origins\n * that relay through and return from the central bridge host.\n */\nexport function isAllowedSsoOrigin(url: URL): boolean {\n if (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\") return true;\n if (url.hostname.endsWith(\".local.burdenoff.com\")) return true;\n if (url.protocol !== \"https:\") return false;\n for (const domain of ALLOWED_SSO_DOMAINS) {\n if (\n url.hostname === domain ||\n url.hostname === `app.${domain}` ||\n url.hostname === `alphaapp.${domain}` ||\n url.hostname === `admin.${domain}` ||\n url.hostname === `alphaadmin.${domain}` ||\n url.hostname === `www.${domain}`\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * String-origin variant for postMessage origin checks (SessionBridgePage),\n * which receives a raw origin string rather than a parsed URL. Returns false on\n * an unparseable origin.\n */\nexport function isAllowedSsoOriginString(origin: string): boolean {\n try {\n return isAllowedSsoOrigin(new URL(origin));\n } catch {\n return false;\n }\n}\n"],"mappings":";AAYA,IAAM,IAAsB,IAAI,IAAY,
|
|
1
|
+
{"version":3,"file":"ssoOrigins.js","names":[],"sources":["../../../src/auth/utils/ssoOrigins.ts"],"sourcesContent":["/**\n * Shared first-party SSO origin allow-list for the cross-domain auth pages\n * (SSOClearPage, SSODepositPage, SSORelayPage, SessionBridgePage).\n *\n * These four pages each used to hand-roll an identical copy of this domain set\n * plus its matching function, and they drifted independently — BOFF-4120 was\n * exactly that drift (SSOClearPage's copy was missing admin./alphaadmin., so an\n * admin logout returnTo was rejected on the bridge host and stranded the\n * operator on app.burdenoff.com). Keep the list + matching logic HERE only so\n * a new product domain or subdomain is added in one place. BOFF-4124.\n */\n\nconst ALLOWED_SSO_DOMAINS = new Set<string>([\n \"burdenoff.com\",\n \"vibecontrols.com\",\n \"fluidgrids.com\",\n // BotManor (formerly Botlit): botmanor.com is the primary domain; botlit.ai\n // stays trusted while it redirects there, so in-flight relays still return.\n \"botlit.ai\",\n \"botmanor.com\",\n \"bigconsole.com\",\n \"gethealthybowl.com\",\n \"headshotmarketing.com\",\n \"timecampus.com\",\n \"ggnomad.com\",\n \"movethewheels.com\",\n \"crewfoundry.com\",\n \"planmagnet.com\",\n \"eventfullymanaged.com\",\n \"kadaikodi.com\",\n \"assethandler.com\",\n \"technospam.com\",\n \"semanticfed.com\",\n \"manufacturedops.com\",\n \"theglobalfuel.com\",\n \"housingvista.com\",\n \"proserviceworld.com\",\n \"mybodyshield.com\",\n \"artistrybase.com\",\n \"collabkin.com\",\n \"brainyrich.com\",\n \"theculturepost.com\",\n \"comradecircle.com\",\n \"cosmicintersection.com\",\n \"govcitizenhub.com\",\n \"intelwatchtower.com\",\n \"ecoimpacthub.com\",\n \"buildmyiq.com\",\n \"fluidgrids.ai\",\n \"atheletebridge.com\",\n \"adaptercloud.com\",\n \"coolandlovely.com\",\n \"subscriberbot.com\",\n \"labsofscience.com\",\n \"hookmovies.com\",\n]);\n\n/**\n * True when `url` is a first-party Burdenoff shell origin permitted to take\n * part in the cross-domain SSO relay / clear / deposit / session-bridge flow:\n * - localhost / 127.0.0.1 (any port, local dev)\n * - *.local.burdenoff.com (local dev behind nginx)\n * - https://{\"\" | app. | alphaapp. | admin. | alphaadmin. | www.}<product-domain>\n * — note admin./alphaadmin. are included: the admin app shells\n * (admin.burdenoff.com / alphaadmin.burdenoff.com) are first-party origins\n * that relay through and return from the central bridge host.\n */\nexport function isAllowedSsoOrigin(url: URL): boolean {\n if (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\") return true;\n if (url.hostname.endsWith(\".local.burdenoff.com\")) return true;\n if (url.protocol !== \"https:\") return false;\n for (const domain of ALLOWED_SSO_DOMAINS) {\n if (\n url.hostname === domain ||\n url.hostname === `app.${domain}` ||\n url.hostname === `alphaapp.${domain}` ||\n url.hostname === `admin.${domain}` ||\n url.hostname === `alphaadmin.${domain}` ||\n url.hostname === `www.${domain}`\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * String-origin variant for postMessage origin checks (SessionBridgePage),\n * which receives a raw origin string rather than a parsed URL. Returns false on\n * an unparseable origin.\n */\nexport function isAllowedSsoOriginString(origin: string): boolean {\n try {\n return isAllowedSsoOrigin(new URL(origin));\n } catch {\n return false;\n }\n}\n"],"mappings":";AAYA,IAAM,IAAsB,IAAI,IAAY,0rBA2C5C,CAAC;AAYD,SAAgB,EAAmB,GAAmB;CAEpD,IADI,EAAI,aAAa,eAAe,EAAI,aAAa,eACjD,EAAI,SAAS,SAAS,sBAAsB,GAAG,OAAO;CAC1D,IAAI,EAAI,aAAa,UAAU,OAAO;CACtC,KAAK,IAAM,KAAU,GACnB,IACE,EAAI,aAAa,KACjB,EAAI,aAAa,OAAO,OACxB,EAAI,aAAa,YAAY,OAC7B,EAAI,aAAa,SAAS,OAC1B,EAAI,aAAa,cAAc,OAC/B,EAAI,aAAa,OAAO,KAExB,OAAO;CAGX,OAAO;AACT;AAOA,SAAgB,EAAyB,GAAyB;CAChE,IAAI;EACF,OAAO,EAAmB,IAAI,IAAI,CAAM,CAAC;CAC3C,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","names":[],"sources":["../../../src/auth/utils/validation.ts"],"sourcesContent":["import type { PasswordStrength } from \"../types\";\n\n/**\n * Validate email format\n */\nexport function validateEmail(email: string): boolean {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n\n/**\n * Validate password requirements\n */\nexport function validatePassword(password: string): {\n valid: boolean;\n errors: string[];\n} {\n const errors: string[] = [];\n\n if (password.length < 12) {\n errors.push(\"Password must be at least 12 characters long\");\n }\n\n if (!/[A-Z]/.test(password)) {\n errors.push(\"Password must contain at least one uppercase letter\");\n }\n\n if (!/[a-z]/.test(password)) {\n errors.push(\"Password must contain at least one lowercase letter\");\n }\n\n if (!/[0-9]/.test(password)) {\n errors.push(\"Password must contain at least one number\");\n }\n\n if (!/[!@#$%^&*(),.?\":{}|<>]/.test(password)) {\n errors.push(\"Password must contain at least one special character\");\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n}\n\n/**\n * Calculate password strength using Zxcvbn-like algorithm\n * Returns a score from 0-4 (0 = very weak, 4 = very strong)\n */\nexport function calculatePasswordStrength(password: string): PasswordStrength {\n let score: 0 | 1 | 2 | 3 | 4 = 0;\n const feedback: string[] = [];\n\n // Length check\n if (password.length >= 8) score++;\n if (password.length >= 12) score++;\n if (password.length >= 16) score++;\n\n // Complexity checks\n if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;\n if (/[0-9]/.test(password)) score++;\n if (/[!@#$%^&*(),.?\":{}|<>]/.test(password)) score++;\n\n // Common patterns\n if (/^[a-z]+$/.test(password.toLowerCase())) {\n feedback.push(\"Add uppercase letters, numbers, and symbols\");\n score = Math.max(0, score - 1) as 0 | 1 | 2 | 3 | 4;\n }\n\n if (/^[0-9]+$/.test(password)) {\n feedback.push(\"Avoid using only numbers\");\n score = 0;\n }\n\n if (/(.)\\1{2,}/.test(password)) {\n feedback.push(\"Avoid repeating characters\");\n score = Math.max(0, score - 1) as 0 | 1 | 2 | 3 | 4;\n }\n\n // Common passwords\n const commonPasswords = [\"password\", \"123456\", \"qwerty\", \"admin\", \"letmein\"];\n if (commonPasswords.some((p) => password.toLowerCase().includes(p))) {\n feedback.push(\"Avoid using common passwords\");\n score = 0;\n }\n\n // Ensure score is 0-4\n score = Math.min(4, Math.max(0, score)) as 0 | 1 | 2 | 3 | 4;\n\n // Crack time estimation\n const crackTime =\n score === 0\n ? \"less than 1 second\"\n : score === 1\n ? \"less than 1 minute\"\n : score === 2\n ? \"less than 1 hour\"\n : score === 3\n ? \"less than 1 day\"\n : \"centuries\";\n\n return { score, feedback, crackTime };\n}\n\n/**\n * Validate MFA code format (6 digits)\n */\nexport function validateMfaCode(code: string): boolean {\n return /^\\d{6}$/.test(code);\n}\n\n/**\n * Validate API key name\n */\nexport function validateApiKeyName(name: string): {\n valid: boolean;\n error?: string;\n} {\n if (!name || name.trim().length === 0) {\n return { valid: false, error: \"API key name is required\" };\n }\n\n if (name.length > 100) {\n return {\n valid: false,\n error: \"API key name must be less than 100 characters\",\n };\n }\n\n return { valid: true };\n}\n/**\n * Minimum/maximum lengths for a person's name (first or last), measured in\n * Unicode code points (NOT JavaScript `.length`, which counts UTF-16 code\n * units — see `lengthInCodePoints`).\n *\n * Picked to stay well under the 255-char Prisma `User.firstName/lastName`\n * columns with headroom.\n */\nconst NAME_MIN_LENGTH = 1;\nconst NAME_MAX_LENGTH = 100;\n\n/**\n * Count Unicode code points in `s` instead of UTF-16 code units. Names\n * written in scripts that live in the supplementary plane (Adlam 𞤁𞤔𞤣,\n * many CJK extensions, etc.) have each letter encoded as two UTF-16 units,\n * so a 51-letter Adlam name would otherwise be miscounted as 102 and\n * rejected as too long (Codex P2 review).\n *\n * Code-point counting is sufficient for the name validator — grapheme-\n * cluster counting would also handle emoji ZWJ sequences, but the name\n * regex already disallows emoji.\n */\nfunction lengthInCodePoints(s: string): number {\n return [...s].length;\n}\n\n/**\n * Regex for an acceptable name. Must contain at least one letter (so \"12345\",\n * \"12 34\", \"---\" all fail). Every character must be a letter, mark, literal\n * space, hyphen, apostrophe, period, middle-dot, or join control —\n * diacritics-friendly across scripts (Latin, Tamil, Chinese, etc.).\n *\n * Note: a literal space, not `\\s` — `\\s` matches tabs/newlines/other Unicode\n * whitespace which has no business being inside a person's name (review #2).\n *\n * Two middle-dot codepoints are allowed as-is, NOT folded to `.` — they're\n * orthographically distinct and silently rewriting the user's name would\n * corrupt their identity (Codex P2 reviews):\n * U+00B7 — middle dot, used in Catalan (`Joan·Maria`), Chinese\n * (`阿布杜拉·阿扎姆`), and Russian.\n * U+30FB — katakana middle dot, the standard Japanese separator for\n * foreign personal names (`ジョン・スミス`).\n *\n * Zero-width join controls are also allowed as-is:\n * U+200C ZERO WIDTH NON-JOINER — required for Persian compound names\n * like `محمدرضا` so the letters don't ligate.\n * U+200D ZERO WIDTH JOINER — used in some Indic scripts and emoji\n * sequences (we don't allow emoji ZWJ, but the codepoint is\n * accepted as a generic join marker).\n *\n * Typographic apostrophes (U+2018 / U+2019) and modifier letter apostrophe\n * (U+02BC), and typographic hyphens (U+2010 / U+2011), ARE folded to their\n * ASCII equivalents before validation — they're typographic variants of the\n * same character, not semantically distinct (Codex P2 review).\n *\n * BOFF-7214.\n */\nconst NAME_ALLOWED_CHARS =\n /^[\\p{L}\\p{M} '.\\-\\u00B7\\u30FB\\u200C\\u200D]*\\p{L}[\\p{L}\\p{M} '.\\-\\u00B7\\u30FB\\u200C\\u200D]*$/u;\nconst TYPOGRAPHIC_APOSTROPHES = /[\\u2018\\u2019\\u02BC]/g;\nconst TYPOGRAPHIC_HYPHENS = /[\\u2010\\u2011]/g;\n\n/**\n * Machine-readable name-validation error codes. The caller maps each code\n * to a distinct i18n key (review #1) so that one validator error doesn't\n * collapse N different messages into one translated string.\n */\nexport type NameErrorCode =\n | \"required\"\n | \"too_long\"\n | \"no_letter\"\n | \"invalid_chars\";\n\nexport type NameValidationResult =\n | { valid: true; value: string }\n | { valid: false; code: NameErrorCode; message: string };\n\n/**\n * Validate a person's name (first or last).\n * Accepts `string | undefined | null` because the signup form types name\n * fields as optional (matching the `SignUpInput` contract); an absent value\n * is treated as \"missing\" and fails the validation.\n * On success the result carries the canonicalised `value` (trimmed, with\n * typographic apostrophes folded to ASCII) so the caller can submit the\n * exact same string the validator approved — otherwise the validated\n * string and the value sent to `signUp()` would diverge (e.g. user types\n * `\" O'Connor \"`, validator normalises to `\"O'Connor\"`, but signUp\n * receives the original raw value).\n * Returns a structured result so the caller can decide how to render errors.\n */\nexport function validateName(\n name: string | undefined | null,\n): NameValidationResult {\n // Normalise typographic apostrophes and hyphens to their ASCII\n // equivalents before testing — these are typographic variants of the\n // same character, so the canonical ASCII form is what reaches the DB.\n // (Middle-dot U+00B7 is preserved as-is: see NAME_ALLOWED_CHARS comment.)\n // NFC normalisation happens before trim/length so combining-mark\n // sequences (e.g. `e\\u0301` for `é`) fold to their precomposed\n // form first — otherwise `(\"e\\u0301\").repeat(51)` would over-count\n // to 102 code points and reject a valid 51-character name (Codex P2).\n const trimmed = (name ?? \"\")\n .normalize(\"NFC\")\n .replace(TYPOGRAPHIC_APOSTROPHES, \"'\")\n .replace(TYPOGRAPHIC_HYPHENS, \"-\")\n .trim();\n\n if (lengthInCodePoints(trimmed) < NAME_MIN_LENGTH) {\n return { valid: false, code: \"required\", message: \"Name is required\" };\n }\n\n if (lengthInCodePoints(trimmed) > NAME_MAX_LENGTH) {\n return {\n valid: false,\n code: \"too_long\",\n message: `Name must be ${NAME_MAX_LENGTH} characters or fewer`,\n };\n }\n\n if (!NAME_ALLOWED_CHARS.test(trimmed)) {\n // The combined regex distinguishes the two failure modes that matter\n // to the user: a value with no letters vs. a value with disallowed\n // characters. Surface the right hint for each.\n if (!/\\p{L}/u.test(trimmed)) {\n return {\n valid: false,\n code: \"no_letter\",\n message: \"Name must contain at least one letter\",\n };\n }\n return {\n valid: false,\n code: \"invalid_chars\",\n message:\n \"Name can only contain letters, spaces, periods, hyphens, and apostrophes\",\n };\n }\n\n return { valid: true, value: trimmed };\n}\n\n/**\n * Regex for characters allowed in a username. Letters, digits, underscores,\n * hyphens — the existing rule. The new rule layered on top (BOFF-7214):\n * a username must contain at least one letter, so an attacker cannot create\n * an account like \"12345\" with a throwaway email.\n */\nconst USERNAME_ALLOWED_CHARS = /^[a-zA-Z0-9_-]+$/;\nconst USERNAME_MIN_LENGTH = 3;\nconst USERNAME_MAX_LENGTH = 30;\n/**\n * Machine-readable username-validation error codes — one per failing rule\n * (review #1) so each can map to its own i18n key.\n */\nexport type UsernameErrorCode =\n | \"required\"\n | \"too_short\"\n | \"too_long\"\n | \"invalid_chars\"\n | \"no_letter\";\n\nexport type UsernameValidationResult =\n | { valid: true; value: string }\n | {\n valid: false;\n errors: Array<{ code: UsernameErrorCode; message: string }>;\n };\n\n/**\n * Validate a username.\n * Accepts `string | undefined | null` for parity with `validateName` and the\n * optional `SignUpInput.username` contract.\n *\n * Surrounding whitespace is trimmed before the length / character checks —\n * a pasted `\" alice_01 \"` would otherwise fail with a misleading\n * \"can only contain letters, numbers, underscores, and hyphens\" error\n * when the actual problem is invisible whitespace. On success the result\n * carries the trimmed `value` so the caller submits the same string the\n * validator approved (Claude LOW review).\n * Returns a structured result with a list of errors so the caller can\n * render every failing rule at once (mirrors `validatePassword`).\n */\nexport function validateUsername(\n username: string | undefined | null,\n): UsernameValidationResult {\n const errors: Array<{ code: UsernameErrorCode; message: string }> = [];\n const value = (username ?? \"\").trim();\n\n if (lengthInCodePoints(value) === 0) {\n errors.push({\n code: \"required\",\n message: \"Username is required\",\n });\n } else {\n if (lengthInCodePoints(value) < USERNAME_MIN_LENGTH) {\n errors.push({\n code: \"too_short\",\n message: `Username must be at least ${USERNAME_MIN_LENGTH} characters`,\n });\n }\n\n if (lengthInCodePoints(value) > USERNAME_MAX_LENGTH) {\n errors.push({\n code: \"too_long\",\n message: `Username must be ${USERNAME_MAX_LENGTH} characters or fewer`,\n });\n }\n\n if (!USERNAME_ALLOWED_CHARS.test(value)) {\n errors.push({\n code: \"invalid_chars\",\n message:\n \"Username can only contain letters, numbers, underscores, and hyphens\",\n });\n }\n\n // Must contain at least one letter — guards against all-numeric or\n // all-symbol usernames slipping through. Pure numeric values like\n // \"12345\" previously passed the character allow-list alone.\n if (\n lengthInCodePoints(value) >= USERNAME_MIN_LENGTH &&\n !/[a-zA-Z]/.test(value)\n ) {\n errors.push({\n code: \"no_letter\",\n message: \"Username must contain at least one letter\",\n });\n }\n }\n\n return errors.length === 0\n ? { valid: true, value }\n : { valid: false, errors };\n}\n\n/**\n * Bundle validation across all three user-identity fields so callers\n * (RegisterPage, UserProfilePage, UsersPage) can fail fast on the whole\n * form instead of piecemeal — and so the BOFF-7214 invariant\n * (firstName / lastName contain a letter; username contains a letter)\n * is enforced at every mutation surface, not just signup.\n *\n * On success, the result carries the canonicalised values from each\n * individual validator so the caller submits the same strings the\n * validators approved (no validate/submit divergence).\n *\n * The caller is responsible for mapping each `{ field, code, message }`\n * error to its own i18n key — different surfaces have different key\n * namespaces (`auth.register.*`, `auth.profile.*`, `auth.users.*`).\n */\nexport type UserFieldKey = \"firstName\" | \"lastName\" | \"username\";\n\nexport interface UserFieldError {\n field: UserFieldKey;\n code: string;\n message: string;\n}\n\nexport interface ValidatedUserFields {\n firstName: string;\n lastName: string;\n username: string;\n}\n\nexport type UserFieldsValidationResult =\n | { valid: true; values: ValidatedUserFields }\n | { valid: false; errors: UserFieldError[] };\n\nexport function validateUserFields(\n input: {\n firstName?: string | null;\n lastName?: string | null;\n username?: string | null;\n },\n options: { requireAll?: boolean } = {},\n): UserFieldsValidationResult {\n // Default to requiring every field. Profile-edit surfaces pass\n // `requireAll: false` so an existing user whose optional firstName /\n // lastName is unset (e.g. provisioned via an identity provider) can\n // still update unrelated fields like phone or role (Codex P2 review).\n const requireAll = options.requireAll ?? true;\n const errors: UserFieldError[] = [];\n\n // Skip the validator entirely when a field is empty AND requireAll is\n // false — that means \"user is leaving this field blank\". The signup\n // form always requires every field; profile edit does not.\n const isBlank = (v: string | null | undefined): boolean =>\n !v || v.trim().length === 0;\n\n const firstName =\n !isBlank(input.firstName) || requireAll\n ? validateName(input.firstName)\n : null;\n if (firstName && !firstName.valid) {\n errors.push({\n field: \"firstName\",\n code: firstName.code,\n message: firstName.message,\n });\n }\n\n const lastName =\n !isBlank(input.lastName) || requireAll\n ? validateName(input.lastName)\n : null;\n if (lastName && !lastName.valid) {\n errors.push({\n field: \"lastName\",\n code: lastName.code,\n message: lastName.message,\n });\n }\n\n const username =\n !isBlank(input.username) || requireAll\n ? validateUsername(input.username)\n : null;\n if (username && !username.valid) {\n for (const e of username.errors) {\n errors.push({ field: \"username\", code: e.code, message: e.message });\n }\n }\n\n if (errors.length > 0) return { valid: false, errors };\n\n // Return canonical values: trimmed/NFC-normalised when validated, the\n // original trimmed value when the field was optional and left blank.\n // The cast is sound because the `errors.length > 0` early-return above\n // guarantees each result, when non-null, is the `{ valid: true }` arm.\n const valueOr = (\n result: { valid: true; value: string } | null,\n fallback: string | null | undefined,\n ): string => (result ? result.value : (fallback ?? \"\").trim());\n\n return {\n valid: true,\n values: {\n firstName: valueOr(\n firstName as { valid: true; value: string } | null,\n input.firstName,\n ),\n lastName: valueOr(\n lastName as { valid: true; value: string } | null,\n input.lastName,\n ),\n username: valueOr(\n username as { valid: true; value: string } | null,\n input.username,\n ),\n },\n };\n}\n\n/**\n * Validate a phone number (BOFF-7216).\n *\n * Phone numbers are optional on profile / admin edit forms — an empty input\n * is accepted. When a value is supplied it must:\n * - contain only digits, spaces, and the formatting characters + - ( )\n * - include 7–15 digits (E.164-style length bounds; we don't strip \"+\"\n * country prefix here, we just count digits)\n * - start with +, a digit, or (\n *\n * Returns `{ valid: true }` on an empty / whitespace-only input.\n * Returns `{ valid: false, error }` with a human-readable message on\n * rejection. The message is intentionally plain English so the caller can\n * either display it verbatim or pipe it through `tr()` with an i18n key.\n */\nexport function validatePhoneNumber(phone: string): {\n valid: boolean;\n error?: string;\n} {\n const trimmed = phone.trim();\n\n if (trimmed.length === 0) {\n return { valid: true };\n }\n\n if (!/^[0-9+\\-() ]+$/.test(trimmed)) {\n return {\n valid: false,\n error:\n \"Phone number can only contain digits, spaces, and the characters + - ( )\",\n };\n }\n\n const digits = trimmed.replace(/[^\\d]/g, \"\");\n if (digits.length < 7) {\n return { valid: false, error: \"Phone number is too short\" };\n }\n\n if (digits.length > 15) {\n return { valid: false, error: \"Phone number is too long\" };\n }\n\n if (!/^[+\\d(]/.test(trimmed)) {\n return {\n valid: false,\n error: \"Phone number must start with +, a digit, or (\",\n };\n }\n\n return { valid: true };\n}\n"],"mappings":";AAKA,SAAgB,EAAc,GAAwB;AAEpD,QADmB,6BACD,KAAK,EAAM;;AAM/B,SAAgB,EAAiB,GAG/B;CACA,IAAM,IAA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,SAAS,KAAY,IAAI,MAAM;AAE7D,QAAO;EACL,OAAO;EACP,QAAQ;GACN,WAAW,EACT,GACA,EAAM,UACP;GACD,UAAU,EACR,GACA,EAAM,SACP;GACD,UAAU,EACR,GACA,EAAM,SACP;GACF;EACF;;AAkBH,SAAgB,EAAoB,GAGlC;CACA,IAAM,IAAU,EAAM,MAAM;AAE5B,KAAI,EAAQ,WAAW,EACrB,QAAO,EAAE,OAAO,IAAM;AAGxB,KAAI,CAAC,iBAAiB,KAAK,EAAQ,CACjC,QAAO;EACL,OAAO;EACP,OACE;EACH;CAGH,IAAM,IAAS,EAAQ,QAAQ,UAAU,GAAG;AAgB5C,QAfI,EAAO,SAAS,IACX;EAAE,OAAO;EAAO,OAAO;EAA6B,GAGzD,EAAO,SAAS,KACX;EAAE,OAAO;EAAO,OAAO;EAA4B,GAGvD,UAAU,KAAK,EAAQ,GAOrB,EAAE,OAAO,IAAM,GANb;EACL,OAAO;EACP,OAAO;EACR"}
|
|
1
|
+
{"version":3,"file":"validation.js","names":[],"sources":["../../../src/auth/utils/validation.ts"],"sourcesContent":["import type { PasswordStrength } from \"../types\";\n\n/**\n * Validate email format\n */\nexport function validateEmail(email: string): boolean {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n\n/**\n * Validate password requirements\n */\nexport function validatePassword(password: string): {\n valid: boolean;\n errors: string[];\n} {\n const errors: string[] = [];\n\n if (password.length < 12) {\n errors.push(\"Password must be at least 12 characters long\");\n }\n\n if (!/[A-Z]/.test(password)) {\n errors.push(\"Password must contain at least one uppercase letter\");\n }\n\n if (!/[a-z]/.test(password)) {\n errors.push(\"Password must contain at least one lowercase letter\");\n }\n\n if (!/[0-9]/.test(password)) {\n errors.push(\"Password must contain at least one number\");\n }\n\n if (!/[!@#$%^&*(),.?\":{}|<>]/.test(password)) {\n errors.push(\"Password must contain at least one special character\");\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n}\n\n/**\n * Calculate password strength using Zxcvbn-like algorithm\n * Returns a score from 0-4 (0 = very weak, 4 = very strong)\n */\nexport function calculatePasswordStrength(password: string): PasswordStrength {\n let score: 0 | 1 | 2 | 3 | 4 = 0;\n const feedback: string[] = [];\n\n // Length check\n if (password.length >= 8) score++;\n if (password.length >= 12) score++;\n if (password.length >= 16) score++;\n\n // Complexity checks\n if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;\n if (/[0-9]/.test(password)) score++;\n if (/[!@#$%^&*(),.?\":{}|<>]/.test(password)) score++;\n\n // Common patterns\n if (/^[a-z]+$/.test(password.toLowerCase())) {\n feedback.push(\"Add uppercase letters, numbers, and symbols\");\n score = Math.max(0, score - 1) as 0 | 1 | 2 | 3 | 4;\n }\n\n if (/^[0-9]+$/.test(password)) {\n feedback.push(\"Avoid using only numbers\");\n score = 0;\n }\n\n if (/(.)\\1{2,}/.test(password)) {\n feedback.push(\"Avoid repeating characters\");\n score = Math.max(0, score - 1) as 0 | 1 | 2 | 3 | 4;\n }\n\n // Common passwords\n const commonPasswords = [\"password\", \"123456\", \"qwerty\", \"admin\", \"letmein\"];\n if (commonPasswords.some((p) => password.toLowerCase().includes(p))) {\n feedback.push(\"Avoid using common passwords\");\n score = 0;\n }\n\n // Ensure score is 0-4\n score = Math.min(4, Math.max(0, score)) as 0 | 1 | 2 | 3 | 4;\n\n // Crack time estimation\n const crackTime =\n score === 0\n ? \"less than 1 second\"\n : score === 1\n ? \"less than 1 minute\"\n : score === 2\n ? \"less than 1 hour\"\n : score === 3\n ? \"less than 1 day\"\n : \"centuries\";\n\n return { score, feedback, crackTime };\n}\n\n/**\n * Validate MFA code format (6 digits)\n */\nexport function validateMfaCode(code: string): boolean {\n return /^\\d{6}$/.test(code);\n}\n\n/**\n * Validate API key name\n */\nexport function validateApiKeyName(name: string): {\n valid: boolean;\n error?: string;\n} {\n if (!name || name.trim().length === 0) {\n return { valid: false, error: \"API key name is required\" };\n }\n\n if (name.length > 100) {\n return {\n valid: false,\n error: \"API key name must be less than 100 characters\",\n };\n }\n\n return { valid: true };\n}\n/**\n * Minimum/maximum lengths for a person's name (first or last), measured in\n * Unicode code points (NOT JavaScript `.length`, which counts UTF-16 code\n * units — see `lengthInCodePoints`).\n *\n * Picked to stay well under the 255-char Prisma `User.firstName/lastName`\n * columns with headroom.\n */\nconst NAME_MIN_LENGTH = 1;\nconst NAME_MAX_LENGTH = 100;\n\n/**\n * Count Unicode code points in `s` instead of UTF-16 code units. Names\n * written in scripts that live in the supplementary plane (Adlam 𞤁𞤔𞤣,\n * many CJK extensions, etc.) have each letter encoded as two UTF-16 units,\n * so a 51-letter Adlam name would otherwise be miscounted as 102 and\n * rejected as too long (Codex P2 review).\n *\n * Code-point counting is sufficient for the name validator — grapheme-\n * cluster counting would also handle emoji ZWJ sequences, but the name\n * regex already disallows emoji.\n */\nfunction lengthInCodePoints(s: string): number {\n return [...s].length;\n}\n\n/**\n * Regex for an acceptable name. Must contain at least one letter (so \"12345\",\n * \"12 34\", \"---\" all fail). Every character must be a letter, mark, literal\n * space, hyphen, apostrophe, period, middle-dot, or join control —\n * diacritics-friendly across scripts (Latin, Tamil, Chinese, etc.).\n *\n * Note: a literal space, not `\\s` — `\\s` matches tabs/newlines/other Unicode\n * whitespace which has no business being inside a person's name (review #2).\n *\n * Two middle-dot codepoints are allowed as-is, NOT folded to `.` — they're\n * orthographically distinct and silently rewriting the user's name would\n * corrupt their identity (Codex P2 reviews):\n * U+00B7 — middle dot, used in Catalan (`Joan·Maria`), Chinese\n * (`阿布杜拉·阿扎姆`), and Russian.\n * U+30FB — katakana middle dot, the standard Japanese separator for\n * foreign personal names (`ジョン・スミス`).\n *\n * Zero-width join controls are also allowed as-is:\n * U+200C ZERO WIDTH NON-JOINER — required for Persian compound names\n * like `محمدرضا` so the letters don't ligate.\n * U+200D ZERO WIDTH JOINER — used in some Indic scripts and emoji\n * sequences (we don't allow emoji ZWJ, but the codepoint is\n * accepted as a generic join marker).\n *\n * Typographic apostrophes (U+2018 / U+2019) and modifier letter apostrophe\n * (U+02BC), and typographic hyphens (U+2010 / U+2011), ARE folded to their\n * ASCII equivalents before validation — they're typographic variants of the\n * same character, not semantically distinct (Codex P2 review).\n *\n * BOFF-7214.\n */\nconst NAME_ALLOWED_CHARS =\n /^[\\p{L}\\p{M} '.\\-\\u00B7\\u30FB\\u200C\\u200D]*\\p{L}[\\p{L}\\p{M} '.\\-\\u00B7\\u30FB\\u200C\\u200D]*$/u;\nconst TYPOGRAPHIC_APOSTROPHES = /[\\u2018\\u2019\\u02BC]/g;\nconst TYPOGRAPHIC_HYPHENS = /[\\u2010\\u2011]/g;\n\n/**\n * Machine-readable name-validation error codes. The caller maps each code\n * to a distinct i18n key (review #1) so that one validator error doesn't\n * collapse N different messages into one translated string.\n */\nexport type NameErrorCode =\n | \"required\"\n | \"too_long\"\n | \"no_letter\"\n | \"invalid_chars\";\n\nexport type NameValidationResult =\n | { valid: true; value: string }\n | { valid: false; code: NameErrorCode; message: string };\n\n/**\n * Validate a person's name (first or last).\n * Accepts `string | undefined | null` because the signup form types name\n * fields as optional (matching the `SignUpInput` contract); an absent value\n * is treated as \"missing\" and fails the validation.\n * On success the result carries the canonicalised `value` (trimmed, with\n * typographic apostrophes folded to ASCII) so the caller can submit the\n * exact same string the validator approved — otherwise the validated\n * string and the value sent to `signUp()` would diverge (e.g. user types\n * `\" O'Connor \"`, validator normalises to `\"O'Connor\"`, but signUp\n * receives the original raw value).\n * Returns a structured result so the caller can decide how to render errors.\n */\nexport function validateName(\n name: string | undefined | null,\n): NameValidationResult {\n // Normalise typographic apostrophes and hyphens to their ASCII\n // equivalents before testing — these are typographic variants of the\n // same character, so the canonical ASCII form is what reaches the DB.\n // (Middle-dot U+00B7 is preserved as-is: see NAME_ALLOWED_CHARS comment.)\n // NFC normalisation happens before trim/length so combining-mark\n // sequences (e.g. `e\\u0301` for `é`) fold to their precomposed\n // form first — otherwise `(\"e\\u0301\").repeat(51)` would over-count\n // to 102 code points and reject a valid 51-character name (Codex P2).\n const trimmed = (name ?? \"\")\n .normalize(\"NFC\")\n .replace(TYPOGRAPHIC_APOSTROPHES, \"'\")\n .replace(TYPOGRAPHIC_HYPHENS, \"-\")\n .trim();\n\n if (lengthInCodePoints(trimmed) < NAME_MIN_LENGTH) {\n return { valid: false, code: \"required\", message: \"Name is required\" };\n }\n\n if (lengthInCodePoints(trimmed) > NAME_MAX_LENGTH) {\n return {\n valid: false,\n code: \"too_long\",\n message: `Name must be ${NAME_MAX_LENGTH} characters or fewer`,\n };\n }\n\n if (!NAME_ALLOWED_CHARS.test(trimmed)) {\n // The combined regex distinguishes the two failure modes that matter\n // to the user: a value with no letters vs. a value with disallowed\n // characters. Surface the right hint for each.\n if (!/\\p{L}/u.test(trimmed)) {\n return {\n valid: false,\n code: \"no_letter\",\n message: \"Name must contain at least one letter\",\n };\n }\n return {\n valid: false,\n code: \"invalid_chars\",\n message:\n \"Name can only contain letters, spaces, periods, hyphens, and apostrophes\",\n };\n }\n\n return { valid: true, value: trimmed };\n}\n\n/**\n * Regex for characters allowed in a username. Letters, digits, underscores,\n * hyphens — the existing rule. The new rule layered on top (BOFF-7214):\n * a username must contain at least one letter, so an attacker cannot create\n * an account like \"12345\" with a throwaway email.\n */\nconst USERNAME_ALLOWED_CHARS = /^[a-zA-Z0-9_-]+$/;\nconst USERNAME_MIN_LENGTH = 3;\nconst USERNAME_MAX_LENGTH = 30;\n/**\n * Machine-readable username-validation error codes — one per failing rule\n * (review #1) so each can map to its own i18n key.\n */\nexport type UsernameErrorCode =\n | \"required\"\n | \"too_short\"\n | \"too_long\"\n | \"invalid_chars\"\n | \"no_letter\";\n\nexport type UsernameValidationResult =\n | { valid: true; value: string }\n | {\n valid: false;\n errors: Array<{ code: UsernameErrorCode; message: string }>;\n };\n\n/**\n * Validate a username.\n * Accepts `string | undefined | null` for parity with `validateName` and the\n * optional `SignUpInput.username` contract.\n *\n * Surrounding whitespace is trimmed before the length / character checks —\n * a pasted `\" alice_01 \"` would otherwise fail with a misleading\n * \"can only contain letters, numbers, underscores, and hyphens\" error\n * when the actual problem is invisible whitespace. On success the result\n * carries the trimmed `value` so the caller submits the same string the\n * validator approved (Claude LOW review).\n * Returns a structured result with a list of errors so the caller can\n * render every failing rule at once (mirrors `validatePassword`).\n */\nexport function validateUsername(\n username: string | undefined | null,\n): UsernameValidationResult {\n const errors: Array<{ code: UsernameErrorCode; message: string }> = [];\n const value = (username ?? \"\").trim();\n\n if (lengthInCodePoints(value) === 0) {\n errors.push({\n code: \"required\",\n message: \"Username is required\",\n });\n } else {\n if (lengthInCodePoints(value) < USERNAME_MIN_LENGTH) {\n errors.push({\n code: \"too_short\",\n message: `Username must be at least ${USERNAME_MIN_LENGTH} characters`,\n });\n }\n\n if (lengthInCodePoints(value) > USERNAME_MAX_LENGTH) {\n errors.push({\n code: \"too_long\",\n message: `Username must be ${USERNAME_MAX_LENGTH} characters or fewer`,\n });\n }\n\n if (!USERNAME_ALLOWED_CHARS.test(value)) {\n errors.push({\n code: \"invalid_chars\",\n message:\n \"Username can only contain letters, numbers, underscores, and hyphens\",\n });\n }\n\n // Must contain at least one letter — guards against all-numeric or\n // all-symbol usernames slipping through. Pure numeric values like\n // \"12345\" previously passed the character allow-list alone.\n if (\n lengthInCodePoints(value) >= USERNAME_MIN_LENGTH &&\n !/[a-zA-Z]/.test(value)\n ) {\n errors.push({\n code: \"no_letter\",\n message: \"Username must contain at least one letter\",\n });\n }\n }\n\n return errors.length === 0\n ? { valid: true, value }\n : { valid: false, errors };\n}\n\n/**\n * Bundle validation across all three user-identity fields so callers\n * (RegisterPage, UserProfilePage, UsersPage) can fail fast on the whole\n * form instead of piecemeal — and so the BOFF-7214 invariant\n * (firstName / lastName contain a letter; username contains a letter)\n * is enforced at every mutation surface, not just signup.\n *\n * On success, the result carries the canonicalised values from each\n * individual validator so the caller submits the same strings the\n * validators approved (no validate/submit divergence).\n *\n * The caller is responsible for mapping each `{ field, code, message }`\n * error to its own i18n key — different surfaces have different key\n * namespaces (`auth.register.*`, `auth.profile.*`, `auth.users.*`).\n */\nexport type UserFieldKey = \"firstName\" | \"lastName\" | \"username\";\n\nexport interface UserFieldError {\n field: UserFieldKey;\n code: string;\n message: string;\n}\n\nexport interface ValidatedUserFields {\n firstName: string;\n lastName: string;\n username: string;\n}\n\nexport type UserFieldsValidationResult =\n | { valid: true; values: ValidatedUserFields }\n | { valid: false; errors: UserFieldError[] };\n\nexport function validateUserFields(\n input: {\n firstName?: string | null;\n lastName?: string | null;\n username?: string | null;\n },\n options: { requireAll?: boolean } = {},\n): UserFieldsValidationResult {\n // Default to requiring every field. Profile-edit surfaces pass\n // `requireAll: false` so an existing user whose optional firstName /\n // lastName is unset (e.g. provisioned via an identity provider) can\n // still update unrelated fields like phone or role (Codex P2 review).\n const requireAll = options.requireAll ?? true;\n const errors: UserFieldError[] = [];\n\n // Skip the validator entirely when a field is empty AND requireAll is\n // false — that means \"user is leaving this field blank\". The signup\n // form always requires every field; profile edit does not.\n const isBlank = (v: string | null | undefined): boolean =>\n !v || v.trim().length === 0;\n\n const firstName =\n !isBlank(input.firstName) || requireAll\n ? validateName(input.firstName)\n : null;\n if (firstName && !firstName.valid) {\n errors.push({\n field: \"firstName\",\n code: firstName.code,\n message: firstName.message,\n });\n }\n\n const lastName =\n !isBlank(input.lastName) || requireAll\n ? validateName(input.lastName)\n : null;\n if (lastName && !lastName.valid) {\n errors.push({\n field: \"lastName\",\n code: lastName.code,\n message: lastName.message,\n });\n }\n\n const username =\n !isBlank(input.username) || requireAll\n ? validateUsername(input.username)\n : null;\n if (username && !username.valid) {\n for (const e of username.errors) {\n errors.push({ field: \"username\", code: e.code, message: e.message });\n }\n }\n\n if (errors.length > 0) return { valid: false, errors };\n\n // Return canonical values: trimmed/NFC-normalised when validated, the\n // original trimmed value when the field was optional and left blank.\n // The cast is sound because the `errors.length > 0` early-return above\n // guarantees each result, when non-null, is the `{ valid: true }` arm.\n const valueOr = (\n result: { valid: true; value: string } | null,\n fallback: string | null | undefined,\n ): string => (result ? result.value : (fallback ?? \"\").trim());\n\n return {\n valid: true,\n values: {\n firstName: valueOr(\n firstName as { valid: true; value: string } | null,\n input.firstName,\n ),\n lastName: valueOr(\n lastName as { valid: true; value: string } | null,\n input.lastName,\n ),\n username: valueOr(\n username as { valid: true; value: string } | null,\n input.username,\n ),\n },\n };\n}\n\n/**\n * Validate a phone number (BOFF-7216).\n *\n * Phone numbers are optional on profile / admin edit forms — an empty input\n * is accepted. When a value is supplied it must:\n * - contain only digits, spaces, and the formatting characters + - ( )\n * - include 7–15 digits (E.164-style length bounds; we don't strip \"+\"\n * country prefix here, we just count digits)\n * - start with +, a digit, or (\n *\n * Returns `{ valid: true }` on an empty / whitespace-only input.\n * Returns `{ valid: false, error }` with a human-readable message on\n * rejection. The message is intentionally plain English so the caller can\n * either display it verbatim or pipe it through `tr()` with an i18n key.\n */\nexport function validatePhoneNumber(phone: string): {\n valid: boolean;\n error?: string;\n} {\n const trimmed = phone.trim();\n\n if (trimmed.length === 0) {\n return { valid: true };\n }\n\n if (!/^[0-9+\\-() ]+$/.test(trimmed)) {\n return {\n valid: false,\n error:\n \"Phone number can only contain digits, spaces, and the characters + - ( )\",\n };\n }\n\n const digits = trimmed.replace(/[^\\d]/g, \"\");\n if (digits.length < 7) {\n return { valid: false, error: \"Phone number is too short\" };\n }\n\n if (digits.length > 15) {\n return { valid: false, error: \"Phone number is too long\" };\n }\n\n if (!/^[+\\d(]/.test(trimmed)) {\n return {\n valid: false,\n error: \"Phone number must start with +, a digit, or (\",\n };\n }\n\n return { valid: true };\n}\n"],"mappings":";AAKA,SAAgB,EAAc,GAAwB;CAEpD,OAAO,6BAAW,KAAK,CAAK;AAC9B;AAKA,SAAgB,EAAiB,GAG/B;CACA,IAAM,IAAmB,CAAC;CAsB1B,OApBI,EAAS,SAAS,MACpB,EAAO,KAAK,8CAA8C,GAGvD,QAAQ,KAAK,CAAQ,KACxB,EAAO,KAAK,qDAAqD,GAG9D,QAAQ,KAAK,CAAQ,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