@korajs/auth 0.5.0 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react/AuthProvider.tsx","../src/react/auth-context.ts","../src/react/hooks.ts","../src/react/org-hooks.ts"],"sourcesContent":["import { createElement, useEffect, useState } from 'react'\nimport type { ReactElement, ReactNode } from 'react'\nimport type { AuthClient, AuthState } from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\n/**\n * Props for the AuthProvider component.\n */\ninterface AuthProviderProps {\n\t/** The AuthClient instance to provide to child components */\n\tclient: AuthClient\n\n\t/** Child components that will have access to auth context */\n\tchildren: ReactNode\n\n\t/**\n\t * Optional fallback content to render while the auth client is initializing.\n\t * If not provided, children are rendered with `isLoading: true` in the context.\n\t */\n\tfallback?: ReactNode\n}\n\n/**\n * React context provider that wraps the AuthClient for use with auth hooks.\n *\n * Calls `client.initialize()` on mount to restore any existing session from\n * stored tokens. Subscribes to auth state changes and re-renders children\n * when the state transitions.\n *\n * Must be placed above any component that uses {@link useAuth},\n * {@link useCurrentUser}, or {@link useAuthStatus}.\n *\n * @param props - Provider props including the AuthClient instance and children\n * @returns A React element wrapping children in the AuthContext\n *\n * @example\n * ```typescript\n * import { AuthClient } from '@korajs/auth'\n * import { AuthProvider } from '@korajs/auth/react'\n *\n * const authClient = new AuthClient({ serverUrl: 'http://localhost:3001' })\n *\n * function App() {\n * return (\n * <AuthProvider client={authClient} fallback={<div>Loading...</div>}>\n * <MyApp />\n * </AuthProvider>\n * )\n * }\n * ```\n */\nfunction AuthProvider({ client, children, fallback }: AuthProviderProps): ReactElement {\n\tconst [state, setState] = useState<AuthState>(client.state)\n\tconst [isLoading, setIsLoading] = useState(true)\n\tconst [initError, setInitError] = useState<Error | null>(null)\n\n\t// Initialize the auth client on mount\n\tuseEffect(() => {\n\t\tlet cancelled = false\n\n\t\t// Subscribe to auth state changes\n\t\tconst unsubscribe = client.onAuthChange((newState) => {\n\t\t\tif (!cancelled) {\n\t\t\t\tsetState(newState)\n\t\t\t}\n\t\t})\n\n\t\tclient\n\t\t\t.initialize()\n\t\t\t.then(() => {\n\t\t\t\tif (!cancelled) {\n\t\t\t\t\tsetState(client.state)\n\t\t\t\t\tsetIsLoading(false)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tif (!cancelled) {\n\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error))\n\t\t\t\t\tconsole.error('[Kora Auth] Initialization failed:', err)\n\t\t\t\t\tsetInitError(err)\n\t\t\t\t\tsetIsLoading(false)\n\t\t\t\t}\n\t\t\t})\n\n\t\treturn () => {\n\t\t\tcancelled = true\n\t\t\tunsubscribe()\n\t\t}\n\t}, [client])\n\n\t// Show error if initialization failed\n\tif (initError) {\n\t\treturn createElement(\n\t\t\t'div',\n\t\t\t{\n\t\t\t\tstyle: { color: 'red', padding: '1rem', fontFamily: 'monospace' },\n\t\t\t\trole: 'alert',\n\t\t\t},\n\t\t\tcreateElement('strong', null, 'Kora Auth initialization error: '),\n\t\t\tinitError.message,\n\t\t)\n\t}\n\n\t// Show fallback while loading\n\tif (isLoading && fallback !== undefined) {\n\t\treturn fallback as ReactElement\n\t}\n\n\tconst contextValue = {\n\t\tclient,\n\t\tstate,\n\t\tisLoading,\n\t}\n\n\treturn createElement(AuthContext.Provider, { value: contextValue }, children)\n}\n\nexport { AuthProvider }\nexport type { AuthProviderProps }\n","import { createContext } from 'react'\nimport type { AuthClient } from '../client/auth-client'\n\n/**\n * Possible authentication states for the client.\n * - 'loading': Initial state while restoring tokens from storage\n * - 'authenticated': User is signed in with a valid session\n * - 'unauthenticated': No valid session exists\n */\ntype AuthState = 'loading' | 'authenticated' | 'unauthenticated'\n\n/**\n * Shape of the value provided by the AuthContext.\n * Includes the AuthClient instance, reactive state, and a loading flag.\n */\ninterface AuthContextValue {\n\t/** The underlying AuthClient instance for direct access */\n\tclient: AuthClient\n\n\t/** Current authentication state */\n\tstate: AuthState\n\n\t/** Whether the client is still initializing (restoring session from storage) */\n\tisLoading: boolean\n}\n\n/**\n * React context for Kora authentication.\n *\n * Provides the AuthClient and reactive auth state to child components.\n * Must be provided by an AuthProvider higher in the component tree.\n * Defaults to null — hooks that consume this context throw if it is missing.\n */\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\nexport { AuthContext }\nexport type { AuthContextValue, AuthState }\n","import { useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react'\nimport type {\n\tAuthState,\n\tAuthUser,\n\tLinkedOAuthAccount,\n\tOAuthAuthorizationOptions,\n\tOAuthAuthorizationResult,\n\tOAuthCallbackParams,\n} from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\n// ---------------------------------------------------------------------------\n// Internal context accessor\n// ---------------------------------------------------------------------------\n\n/**\n * Internal hook that reads and validates the AuthContext.\n * Throws a descriptive error if used outside an AuthProvider.\n */\nfunction useAuthContext(): {\n\tclient: import('../client/auth-client').AuthClient\n\tstate: AuthState\n\tisLoading: boolean\n} {\n\tconst ctx = useContext(AuthContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useAuth / useCurrentUser / useAuthStatus must be used within an <AuthProvider>. ' +\n\t\t\t\t'Wrap your component tree with <AuthProvider client={authClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Return value of the {@link useAuth} hook.\n */\ninterface UseAuthResult {\n\t/** Current authenticated user, or null if not signed in */\n\tuser: AuthUser | null\n\n\t/** Whether the user is currently authenticated */\n\tisAuthenticated: boolean\n\n\t/** Whether the auth client is still initializing (restoring session) */\n\tisLoading: boolean\n\n\t/** Sign up a new user account */\n\tsignUp: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tname?: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\n\t/** Sign in with email and password */\n\tsignIn: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\n\t/** Start OAuth sign-in. Web apps can redirect; desktop/mobile can open the returned URL. */\n\tsignInWithOAuth: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\n\t/** Complete an OAuth sign-in callback with code and state. */\n\tcompleteOAuthSignIn: (provider: string, params: OAuthCallbackParams) => Promise<void>\n\n\t/** Create an OAuth authorization URL without redirecting. */\n\tgetOAuthAuthorizationUrl: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\n\t/** Link an OAuth provider to the current user. */\n\tlinkOAuth: (provider: string, params: OAuthCallbackParams) => Promise<LinkedOAuthAccount | null>\n\n\t/** List OAuth accounts linked to the current user. */\n\tlistLinkedAccounts: () => Promise<LinkedOAuthAccount[]>\n\n\t/** Unlink an OAuth provider from the current user. */\n\tunlinkOAuth: (provider: string) => Promise<void>\n\n\t/** Sign out the current user */\n\tsignOut: () => Promise<void>\n\n\t/** Last error message from a sign-up, sign-in, or sign-out attempt, or null */\n\terror: string | null\n}\n\n/**\n * Auth status information returned by {@link useAuthStatus}.\n */\ninterface AuthStatus {\n\t/** Current authentication state */\n\tstate: AuthState\n\n\t/** Whether the user is currently authenticated */\n\tisAuthenticated: boolean\n\n\t/** Whether the auth client is still initializing */\n\tisLoading: boolean\n}\n\n// ---------------------------------------------------------------------------\n// useAuth\n// ---------------------------------------------------------------------------\n\n/**\n * React hook providing full authentication functionality.\n *\n * Returns the current user, loading state, error state, and methods for\n * sign-up, sign-in, and sign-out. Re-renders when auth state changes.\n *\n * Must be used within an {@link AuthProvider}.\n *\n * @returns An object with user info, auth methods, and status flags\n *\n * @example\n * ```typescript\n * function LoginPage() {\n * const { user, isAuthenticated, isLoading, signIn, error } = useAuth()\n *\n * if (isLoading) return <div>Loading...</div>\n * if (isAuthenticated) return <div>Welcome, {user?.name}</div>\n *\n * return (\n * <form onSubmit={async (e) => {\n * e.preventDefault()\n * await signIn({ email: 'user@example.com', password: 'secret' })\n * }}>\n * {error && <p>{error}</p>}\n * <button type=\"submit\">Sign In</button>\n * </form>\n * )\n * }\n * ```\n */\nfunction useAuth(): UseAuthResult {\n\tconst { client, state, isLoading } = useAuthContext()\n\tconst [error, setError] = useState<string | null>(null)\n\n\t// Use useSyncExternalStore to track the user reactively via auth state changes\n\tconst userSnapshotRef = useRef<AuthUser | null>(client.currentUser)\n\tconst stateSerializedRef = useRef<string>(JSON.stringify(client.currentUser))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onAuthChange(() => {\n\t\t\t\tconst newUser = client.currentUser\n\t\t\t\tconst newSerialized = JSON.stringify(newUser)\n\t\t\t\tif (newSerialized !== stateSerializedRef.current) {\n\t\t\t\t\tuserSnapshotRef.current = newUser\n\t\t\t\t\tstateSerializedRef.current = newSerialized\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getSnapshot = useCallback((): AuthUser | null => {\n\t\treturn userSnapshotRef.current\n\t}, [])\n\n\tconst user = useSyncExternalStore(subscribe, getSnapshot)\n\n\tconst signUp = useCallback(\n\t\tasync (params: {\n\t\t\temail: string\n\t\t\tpassword: string\n\t\t\tname?: string\n\t\t\tdeviceId?: string\n\t\t\tdevicePublicKey?: string\n\t\t}): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.signUp(params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst signIn = useCallback(\n\t\tasync (params: {\n\t\t\temail: string\n\t\t\tpassword: string\n\t\t\tdeviceId?: string\n\t\t\tdevicePublicKey?: string\n\t\t}): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.signIn(params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst signInWithOAuth = useCallback(\n\t\tasync (\n\t\t\tprovider: string,\n\t\t\toptions?: OAuthAuthorizationOptions,\n\t\t): Promise<OAuthAuthorizationResult> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.signInWithOAuth(provider, options)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst completeOAuthSignIn = useCallback(\n\t\tasync (provider: string, params: OAuthCallbackParams): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.completeOAuthSignIn(provider, params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getOAuthAuthorizationUrl = useCallback(\n\t\tasync (\n\t\t\tprovider: string,\n\t\t\toptions?: OAuthAuthorizationOptions,\n\t\t): Promise<OAuthAuthorizationResult> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.getOAuthAuthorizationUrl(provider, options)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst linkOAuth = useCallback(\n\t\tasync (provider: string, params: OAuthCallbackParams): Promise<LinkedOAuthAccount | null> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.linkOAuth(provider, params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst listLinkedAccounts = useCallback(async (): Promise<LinkedOAuthAccount[]> => {\n\t\tsetError(null)\n\t\ttry {\n\t\t\treturn await client.listLinkedAccounts()\n\t\t} catch (err: unknown) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\tsetError(message)\n\t\t\treturn []\n\t\t}\n\t}, [client])\n\n\tconst unlinkOAuth = useCallback(\n\t\tasync (provider: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.unlinkOAuth(provider)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst signOut = useCallback(async (): Promise<void> => {\n\t\tsetError(null)\n\t\ttry {\n\t\t\tawait client.signOut()\n\t\t} catch (err: unknown) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\tsetError(message)\n\t\t}\n\t}, [client])\n\n\treturn {\n\t\tuser,\n\t\tisAuthenticated: state === 'authenticated',\n\t\tisLoading,\n\t\tsignUp,\n\t\tsignIn,\n\t\tsignInWithOAuth,\n\t\tcompleteOAuthSignIn,\n\t\tgetOAuthAuthorizationUrl,\n\t\tlinkOAuth,\n\t\tlistLinkedAccounts,\n\t\tunlinkOAuth,\n\t\tsignOut,\n\t\terror,\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// useCurrentUser\n// ---------------------------------------------------------------------------\n\n/**\n * React hook that returns the currently authenticated user, or null.\n *\n * A lightweight alternative to {@link useAuth} when you only need the user\n * object and do not need auth methods or error state.\n *\n * Must be used within an {@link AuthProvider}.\n *\n * @returns The current AuthUser or null if not authenticated\n *\n * @example\n * ```typescript\n * function UserAvatar() {\n * const user = useCurrentUser()\n * if (!user) return null\n * return <span>{user.name ?? user.email}</span>\n * }\n * ```\n */\nfunction useCurrentUser(): AuthUser | null {\n\tconst { client } = useAuthContext()\n\n\tconst userSnapshotRef = useRef<AuthUser | null>(client.currentUser)\n\tconst stateSerializedRef = useRef<string>(JSON.stringify(client.currentUser))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onAuthChange(() => {\n\t\t\t\tconst newUser = client.currentUser\n\t\t\t\tconst newSerialized = JSON.stringify(newUser)\n\t\t\t\tif (newSerialized !== stateSerializedRef.current) {\n\t\t\t\t\tuserSnapshotRef.current = newUser\n\t\t\t\t\tstateSerializedRef.current = newSerialized\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getSnapshot = useCallback((): AuthUser | null => {\n\t\treturn userSnapshotRef.current\n\t}, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\n// ---------------------------------------------------------------------------\n// useAuthStatus\n// ---------------------------------------------------------------------------\n\n/**\n * React hook that returns the current authentication status.\n *\n * Re-renders only when the auth state changes, not on every auth event.\n * Use this for status indicators, route guards, and conditional rendering.\n *\n * Must be used within an {@link AuthProvider}.\n *\n * @returns An AuthStatus object with state, isAuthenticated, and isLoading flags\n *\n * @example\n * ```typescript\n * function AuthGuard({ children }: { children: React.ReactNode }) {\n * const { isAuthenticated, isLoading } = useAuthStatus()\n * if (isLoading) return <Spinner />\n * if (!isAuthenticated) return <Navigate to=\"/login\" />\n * return <>{children}</>\n * }\n * ```\n */\nfunction useAuthStatus(): AuthStatus {\n\tconst { state, isLoading } = useAuthContext()\n\n\treturn {\n\t\tstate,\n\t\tisAuthenticated: state === 'authenticated',\n\t\tisLoading,\n\t}\n}\n\nexport { useAuth, useCurrentUser, useAuthStatus }\nexport type { UseAuthResult, AuthStatus }\n","import {\n\tcreateContext,\n\tuseCallback,\n\tuseContext,\n\tuseEffect,\n\tuseRef,\n\tuseState,\n\tuseSyncExternalStore,\n} from 'react'\nimport type {\n\tClientInvitation,\n\tClientMembership,\n\tClientOrganization,\n\tOrgClient,\n} from '../client/org-client'\n\n// ============================================================================\n// OrgContext\n// ============================================================================\n\n/**\n * Shape of the OrgContext value.\n */\nexport interface OrgContextValue {\n\t/** The OrgClient instance */\n\tclient: OrgClient\n}\n\n/**\n * React context for organization state.\n */\nexport const OrgContext = createContext<OrgContextValue | null>(null)\n\nfunction useOrgContext(): OrgContextValue {\n\tconst ctx = useContext(OrgContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useOrg / useOrgMembers / usePermission must be used within an <OrgProvider>. ' +\n\t\t\t\t'Wrap your component tree with <OrgProvider client={orgClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\n// ============================================================================\n// useOrg\n// ============================================================================\n\n/**\n * Return value of the {@link useOrg} hook.\n */\nexport interface UseOrgResult {\n\t/** Currently active organization, or null */\n\torg: ClientOrganization | null\n\t/** Current user's role in the active organization, or null */\n\trole: string | null\n\t/** Active organization ID, or null */\n\torgId: string | null\n\t/** Switch to a different organization */\n\tswitchOrg: (orgId: string) => Promise<void>\n\t/** Create a new organization */\n\tcreateOrg: (params: { name: string; slug?: string }) => Promise<ClientOrganization>\n\t/** Leave the active organization */\n\tleaveOrg: () => Promise<void>\n\t/** Clear the active organization */\n\tclearOrg: () => void\n\t/** List all organizations the user belongs to */\n\tlistOrgs: () => Promise<ClientOrganization[]>\n\t/** Last error, or null */\n\terror: string | null\n}\n\n/**\n * React hook for organization management and context switching.\n *\n * Re-renders when the active organization changes.\n *\n * @example\n * ```typescript\n * function OrgSwitcher() {\n * const { org, switchOrg, listOrgs, error } = useOrg()\n * const [orgs, setOrgs] = useState<ClientOrganization[]>([])\n *\n * useEffect(() => { listOrgs().then(setOrgs) }, [listOrgs])\n *\n * return (\n * <select value={org?.id ?? ''} onChange={(e) => switchOrg(e.target.value)}>\n * <option value=\"\">Select org...</option>\n * {orgs.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}\n * </select>\n * )\n * }\n * ```\n */\nexport function useOrg(): UseOrgResult {\n\tconst { client } = useOrgContext()\n\tconst [error, setError] = useState<string | null>(null)\n\n\t// Track active org reactively\n\tconst orgSnapshotRef = useRef({\n\t\torgId: client.activeOrgId,\n\t\torg: client.activeOrg,\n\t\trole: client.activeRole,\n\t})\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onOrgChange(() => {\n\t\t\t\torgSnapshotRef.current = {\n\t\t\t\t\torgId: client.activeOrgId,\n\t\t\t\t\torg: client.activeOrg,\n\t\t\t\t\trole: client.activeRole,\n\t\t\t\t}\n\t\t\t\tonStoreChange()\n\t\t\t})\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getSnapshot = useCallback(() => orgSnapshotRef.current, [])\n\n\tconst { orgId, org, role } = useSyncExternalStore(subscribe, getSnapshot)\n\n\tconst switchOrg = useCallback(\n\t\tasync (newOrgId: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.switchOrg(newOrgId)\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst createOrg = useCallback(\n\t\tasync (params: { name: string; slug?: string }): Promise<ClientOrganization> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.createOrg(params)\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(msg)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst leaveOrg = useCallback(async (): Promise<void> => {\n\t\tif (!orgId) return\n\t\tsetError(null)\n\t\ttry {\n\t\t\tawait client.leaveOrg(orgId)\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t}\n\t}, [client, orgId])\n\n\tconst clearOrg = useCallback((): void => {\n\t\tclient.clearActiveOrg()\n\t}, [client])\n\n\tconst listOrgs = useCallback(async (): Promise<ClientOrganization[]> => {\n\t\ttry {\n\t\t\treturn await client.listOrgs()\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\treturn []\n\t\t}\n\t}, [client])\n\n\treturn { org, role, orgId, switchOrg, createOrg, leaveOrg, clearOrg, listOrgs, error }\n}\n\n// ============================================================================\n// useOrgMembers\n// ============================================================================\n\n/**\n * Return value of the {@link useOrgMembers} hook.\n */\nexport interface UseOrgMembersResult {\n\t/** Members of the organization (empty until loaded) */\n\tmembers: ClientMembership[]\n\t/** Whether members are being loaded */\n\tisLoading: boolean\n\t/** Reload the members list */\n\trefresh: () => Promise<void>\n\t/** Invite a user by email */\n\tinvite: (email: string, role: string) => Promise<ClientInvitation>\n\t/** Remove a member */\n\tremoveMember: (userId: string) => Promise<void>\n\t/** Update a member's role */\n\tupdateRole: (userId: string, role: string) => Promise<void>\n\t/** Last error, or null */\n\terror: string | null\n}\n\n/**\n * React hook for managing organization members.\n *\n * Automatically loads members when the orgId changes.\n *\n * @param orgId - Organization ID to manage members for\n */\nexport function useOrgMembers(orgId: string): UseOrgMembersResult {\n\tconst { client } = useOrgContext()\n\tconst [members, setMembers] = useState<ClientMembership[]>([])\n\tconst [isLoading, setIsLoading] = useState(true)\n\tconst [error, setError] = useState<string | null>(null)\n\n\tconst refresh = useCallback(async () => {\n\t\tsetIsLoading(true)\n\t\tsetError(null)\n\t\ttry {\n\t\t\tconst result = await client.listMembers(orgId)\n\t\t\tsetMembers(result)\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t} finally {\n\t\t\tsetIsLoading(false)\n\t\t}\n\t}, [client, orgId])\n\n\tuseEffect(() => {\n\t\trefresh()\n\t}, [refresh])\n\n\tconst invite = useCallback(\n\t\tasync (email: string, role: string): Promise<ClientInvitation> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tconst result = await client.inviteMember(orgId, { email, role })\n\t\t\t\treturn result\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(msg)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client, orgId],\n\t)\n\n\tconst removeMember = useCallback(\n\t\tasync (userId: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.removeMember(orgId, userId)\n\t\t\t\tawait refresh()\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client, orgId, refresh],\n\t)\n\n\tconst updateRole = useCallback(\n\t\tasync (userId: string, role: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.updateMemberRole(orgId, userId, role)\n\t\t\t\tawait refresh()\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client, orgId, refresh],\n\t)\n\n\treturn { members, isLoading, refresh, invite, removeMember, updateRole, error }\n}\n\n// ============================================================================\n// usePermission\n// ============================================================================\n\n/**\n * React hook that checks if the current user has a specific role level\n * in the active organization.\n *\n * @param requiredRole - Minimum role required (uses ROLE_HIERARCHY from org-types)\n * @returns true if the user's role is at least requiredRole\n *\n * @example\n * ```typescript\n * function AdminPanel() {\n * const canManage = usePermission('admin')\n * if (!canManage) return <p>Access denied</p>\n * return <AdminSettings />\n * }\n * ```\n */\nexport function usePermission(requiredRole: string): boolean {\n\tconst { client } = useOrgContext()\n\n\tconst snapshotRef = useRef(checkPermission(client.activeRole, requiredRole))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onOrgChange(() => {\n\t\t\t\tconst newValue = checkPermission(client.activeRole, requiredRole)\n\t\t\t\tif (newValue !== snapshotRef.current) {\n\t\t\t\t\tsnapshotRef.current = newValue\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[client, requiredRole],\n\t)\n\n\tconst getSnapshot = useCallback(() => snapshotRef.current, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\n// Simple role hierarchy check (mirrors ROLE_HIERARCHY from org-types)\nconst ROLE_LEVELS: Record<string, number> = {\n\tviewer: 10,\n\tbilling: 15,\n\tmember: 20,\n\tadmin: 30,\n\towner: 40,\n}\n\nfunction checkPermission(currentRole: string | null, requiredRole: string): boolean {\n\tif (!currentRole) return false\n\tconst currentLevel = ROLE_LEVELS[currentRole] ?? 0\n\tconst requiredLevel = ROLE_LEVELS[requiredRole] ?? 0\n\treturn currentLevel >= requiredLevel\n}\n"],"mappings":";AAAA,SAAS,eAAe,WAAW,gBAAgB;;;ACAnD,SAAS,qBAAqB;AAiC9B,IAAM,cAAc,cAAuC,IAAI;;;ADkB/D,SAAS,aAAa,EAAE,QAAQ,UAAU,SAAS,GAAoC;AACtF,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAoB,OAAO,KAAK;AAC1D,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,IAAI;AAC/C,QAAM,CAAC,WAAW,YAAY,IAAI,SAAuB,IAAI;AAG7D,YAAU,MAAM;AACf,QAAI,YAAY;AAGhB,UAAM,cAAc,OAAO,aAAa,CAAC,aAAa;AACrD,UAAI,CAAC,WAAW;AACf,iBAAS,QAAQ;AAAA,MAClB;AAAA,IACD,CAAC;AAED,WACE,WAAW,EACX,KAAK,MAAM;AACX,UAAI,CAAC,WAAW;AACf,iBAAS,OAAO,KAAK;AACrB,qBAAa,KAAK;AAAA,MACnB;AAAA,IACD,CAAC,EACA,MAAM,CAAC,UAAmB;AAC1B,UAAI,CAAC,WAAW;AACf,cAAM,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACpE,gBAAQ,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AAChE,YAAI,aAAa,YAAY,SAAS;AACrC,sBAAY,UAAU;AACtB,wBAAc;AAAA,QACf;AAAA,MACD,CAAC;AAAA,IACF;AAAA,IACA,CAAC,QAAQ,YAAY;AAAA,EACtB;AAEA,QAAM,cAAcA,aAAY,MAAM,YAAY,SAAS,CAAC,CAAC;AAE7D,SAAOK,sBAAqB,WAAW,WAAW;AACnD;AAGA,IAAM,cAAsC;AAAA,EAC3C,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,OAAO;AACR;AAEA,SAAS,gBAAgB,aAA4B,cAA+B;AACnF,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,eAAe,YAAY,WAAW,KAAK;AACjD,QAAM,gBAAgB,YAAY,YAAY,KAAK;AACnD,SAAO,gBAAgB;AACxB;","names":["useState","useState","createContext","useCallback","useContext","useEffect","useRef","useState","useSyncExternalStore"]}
1
+ {"version":3,"sources":["../src/react/AuthProvider.tsx","../src/react/auth-context.ts","../src/react/hooks.ts","../src/react/OrgProvider.tsx","../src/react/org-hooks.ts"],"sourcesContent":["import { createElement, useEffect, useMemo, useSyncExternalStore } from 'react'\nimport type { ReactElement, ReactNode } from 'react'\nimport { createAuthSession } from '../bindings/create-auth-session'\nimport type { AuthClient } from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\ninterface AuthProviderProps {\n\tclient: AuthClient\n\tchildren: ReactNode\n\tfallback?: ReactNode\n}\n\nfunction AuthProvider({ client, children, fallback }: AuthProviderProps): ReactElement {\n\tconst session = useMemo(() => createAuthSession(client), [client])\n\n\tuseEffect(() => () => session.destroy(), [session])\n\n\tconst snapshot = useSyncExternalStore(\n\t\t(onStoreChange) => session.subscribe(onStoreChange),\n\t\t() => session.getSnapshot(),\n\t\t() => session.getSnapshot(),\n\t)\n\n\tif (snapshot.initError) {\n\t\treturn createElement(\n\t\t\t'div',\n\t\t\t{\n\t\t\t\tstyle: { color: 'red', padding: '1rem', fontFamily: 'monospace' },\n\t\t\t\trole: 'alert',\n\t\t\t},\n\t\t\tcreateElement('strong', null, 'Kora Auth initialization error: '),\n\t\t\tsnapshot.initError.message,\n\t\t)\n\t}\n\n\tif (snapshot.isLoading && fallback !== undefined) {\n\t\treturn fallback as ReactElement\n\t}\n\n\tconst contextValue = {\n\t\tclient,\n\t\tsession,\n\t\tstate: snapshot.state,\n\t\tisLoading: snapshot.isLoading,\n\t}\n\n\treturn createElement(AuthContext.Provider, { value: contextValue }, children)\n}\n\nexport { AuthProvider }\nexport type { AuthProviderProps }\n","import { createContext } from 'react'\nimport type { AuthSession } from '../bindings/create-auth-session'\nimport type { AuthClient } from '../client/auth-client'\n\n/**\n * Possible authentication states for the client.\n */\ntype AuthState = 'loading' | 'authenticated' | 'unauthenticated'\n\n/**\n * Shape of the value provided by the AuthContext.\n */\ninterface AuthContextValue {\n\tclient: AuthClient\n\tsession: AuthSession\n\tstate: AuthState\n\tisLoading: boolean\n}\n\n/**\n * React context for Kora authentication.\n */\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\nexport { AuthContext }\nexport type { AuthContextValue, AuthState }\n","import { useContext, useSyncExternalStore } from 'react'\nimport type {\n\tAuthState,\n\tAuthUser,\n\tLinkedOAuthAccount,\n\tOAuthAuthorizationOptions,\n\tOAuthAuthorizationResult,\n\tOAuthCallbackParams,\n} from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\nfunction useAuthContext() {\n\tconst ctx = useContext(AuthContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useAuth / useCurrentUser / useAuthStatus must be used within an <AuthProvider>. ' +\n\t\t\t\t'Wrap your component tree with <AuthProvider client={authClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\ninterface UseAuthResult {\n\tuser: AuthUser | null\n\tisAuthenticated: boolean\n\tisLoading: boolean\n\tsignUp: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tname?: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\tsignIn: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\tsignInWithOAuth: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\tcompleteOAuthSignIn: (provider: string, params: OAuthCallbackParams) => Promise<void>\n\tgetOAuthAuthorizationUrl: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\tlinkOAuth: (provider: string, params: OAuthCallbackParams) => Promise<LinkedOAuthAccount | null>\n\tlistLinkedAccounts: () => Promise<LinkedOAuthAccount[]>\n\tunlinkOAuth: (provider: string) => Promise<void>\n\tsignOut: () => Promise<void>\n\terror: string | null\n\tinitError: Error | null\n}\n\ninterface AuthStatus {\n\tstate: AuthState\n\tisAuthenticated: boolean\n\tisLoading: boolean\n}\n\nfunction useAuthSessionSnapshot() {\n\tconst { session } = useAuthContext()\n\n\treturn useSyncExternalStore(\n\t\t(onStoreChange) => session.subscribe(onStoreChange),\n\t\t() => session.getSnapshot(),\n\t\t() => session.getSnapshot(),\n\t)\n}\n\nfunction useAuth(): UseAuthResult {\n\tconst { session } = useAuthContext()\n\tconst snapshot = useAuthSessionSnapshot()\n\n\treturn {\n\t\tuser: snapshot.user,\n\t\tisAuthenticated: snapshot.isAuthenticated,\n\t\tisLoading: snapshot.isLoading,\n\t\terror: snapshot.error,\n\t\tinitError: snapshot.initError,\n\t\tsignUp: (params) => session.signUp(params),\n\t\tsignIn: (params) => session.signIn(params),\n\t\tsignInWithOAuth: (provider, options) => session.signInWithOAuth(provider, options),\n\t\tcompleteOAuthSignIn: (provider, params) => session.completeOAuthSignIn(provider, params),\n\t\tgetOAuthAuthorizationUrl: (provider, options) =>\n\t\t\tsession.getOAuthAuthorizationUrl(provider, options),\n\t\tlinkOAuth: (provider, params) => session.linkOAuth(provider, params),\n\t\tlistLinkedAccounts: () => session.listLinkedAccounts(),\n\t\tunlinkOAuth: (provider) => session.unlinkOAuth(provider),\n\t\tsignOut: () => session.signOut(),\n\t}\n}\n\nfunction useCurrentUser(): AuthUser | null {\n\treturn useAuthSessionSnapshot().user\n}\n\nfunction useAuthStatus(): AuthStatus {\n\tconst snapshot = useAuthSessionSnapshot()\n\treturn {\n\t\tstate: snapshot.state,\n\t\tisAuthenticated: snapshot.isAuthenticated,\n\t\tisLoading: snapshot.isLoading,\n\t}\n}\n\nexport { useAuth, useCurrentUser, useAuthStatus }\nexport type { UseAuthResult, AuthStatus }\n","import { type ReactNode, useEffect, useMemo, useRef } from 'react'\nimport { type OrgSession, createOrgSession } from '../bindings/create-org-session'\nimport type { OrgClient } from '../client/org-client'\nimport { OrgContext, type OrgContextValue } from './org-hooks'\n\nexport interface OrgProviderProps {\n\tclient: OrgClient\n\tchildren?: ReactNode\n}\n\n/**\n * Provides organization context for {@link useOrg}, {@link useOrgMembers}, and {@link usePermission}.\n */\nexport function OrgProvider({ client, children }: OrgProviderProps) {\n\tconst sessionRef = useRef<OrgSession | null>(null)\n\n\tif (sessionRef.current === null || sessionRef.current.client !== client) {\n\t\tsessionRef.current?.destroy()\n\t\tsessionRef.current = createOrgSession(client)\n\t}\n\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tsessionRef.current?.destroy()\n\t\t\tsessionRef.current = null\n\t\t}\n\t}, [])\n\n\tconst session = sessionRef.current\n\tconst value = useMemo<OrgContextValue>(\n\t\t() => ({\n\t\t\tclient,\n\t\t\tsession,\n\t\t}),\n\t\t[client, session],\n\t)\n\n\treturn <OrgContext.Provider value={value}>{children}</OrgContext.Provider>\n}\n\nexport type { OrgContextValue }\n","import {\n\tcreateContext,\n\tuseCallback,\n\tuseContext,\n\tuseEffect,\n\tuseRef,\n\tuseState,\n\tuseSyncExternalStore,\n} from 'react'\nimport {\n\ttype OrgSession,\n\ttype OrgSnapshot,\n\tcheckOrgPermission,\n\tcreateOrgMembersActions,\n\tcreateOrgSession,\n\tloadOrgMembers,\n} from '../bindings/create-org-session'\nimport type {\n\tClientInvitation,\n\tClientMembership,\n\tClientOrganization,\n\tOrgClient,\n} from '../client/org-client'\n\nexport interface OrgContextValue {\n\tclient: OrgClient\n\tsession: OrgSession\n}\n\nexport const OrgContext = createContext<OrgContextValue | null>(null)\n\nfunction useOrgContext(): OrgContextValue {\n\tconst ctx = useContext(OrgContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useOrg / useOrgMembers / usePermission must be used within an <OrgProvider>. ' +\n\t\t\t\t'Wrap your component tree with <OrgProvider client={orgClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\nfunction useOrgSnapshot(session: OrgSession): OrgSnapshot {\n\tconst snapshotRef = useRef(session.getSnapshot())\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn session.subscribe(() => {\n\t\t\t\tsnapshotRef.current = session.getSnapshot()\n\t\t\t\tonStoreChange()\n\t\t\t})\n\t\t},\n\t\t[session],\n\t)\n\n\tconst getSnapshot = useCallback(() => snapshotRef.current, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\nexport interface UseOrgResult {\n\torg: ClientOrganization | null\n\trole: string | null\n\torgId: string | null\n\tswitchOrg: (orgId: string) => Promise<void>\n\tcreateOrg: (params: { name: string; slug?: string }) => Promise<ClientOrganization>\n\tleaveOrg: () => Promise<void>\n\tclearOrg: () => void\n\tlistOrgs: () => Promise<ClientOrganization[]>\n\terror: string | null\n}\n\nexport function useOrg(): UseOrgResult {\n\tconst { client, session } = useOrgContext()\n\tconst { orgId, org, role } = useOrgSnapshot(session)\n\tconst [error, setError] = useState<string | null>(null)\n\n\tconst switchOrg = useCallback(\n\t\tasync (newOrgId: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.switchOrg(newOrgId)\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst createOrg = useCallback(\n\t\tasync (params: { name: string; slug?: string }): Promise<ClientOrganization> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.createOrg(params)\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(msg)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst leaveOrg = useCallback(async (): Promise<void> => {\n\t\tif (!orgId) return\n\t\tsetError(null)\n\t\ttry {\n\t\t\tawait client.leaveOrg(orgId)\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t}\n\t}, [client, orgId])\n\n\tconst clearOrg = useCallback((): void => {\n\t\tclient.clearActiveOrg()\n\t}, [client])\n\n\tconst listOrgs = useCallback(async (): Promise<ClientOrganization[]> => {\n\t\ttry {\n\t\t\treturn await client.listOrgs()\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\treturn []\n\t\t}\n\t}, [client])\n\n\treturn { org, role, orgId, switchOrg, createOrg, leaveOrg, clearOrg, listOrgs, error }\n}\n\nexport interface UseOrgMembersResult {\n\tmembers: ClientMembership[]\n\tisLoading: boolean\n\trefresh: () => Promise<void>\n\tinvite: (email: string, role: string) => Promise<ClientInvitation>\n\tremoveMember: (userId: string) => Promise<void>\n\tupdateRole: (userId: string, role: string) => Promise<void>\n\terror: string | null\n}\n\nexport function useOrgMembers(orgId: string): UseOrgMembersResult {\n\tconst { client } = useOrgContext()\n\tconst [members, setMembers] = useState<ClientMembership[]>([])\n\tconst [isLoading, setIsLoading] = useState(true)\n\tconst [error, setError] = useState<string | null>(null)\n\n\tconst refresh = useCallback(async () => {\n\t\tsetIsLoading(true)\n\t\tsetError(null)\n\t\ttry {\n\t\t\tsetMembers(await loadOrgMembers(client, orgId))\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t} finally {\n\t\t\tsetIsLoading(false)\n\t\t}\n\t}, [client, orgId])\n\n\tuseEffect(() => {\n\t\tvoid refresh()\n\t}, [refresh])\n\n\tconst actions = createOrgMembersActions(client, orgId, setError)\n\n\tconst invite = useCallback(\n\t\tasync (email: string, role: string): Promise<ClientInvitation> => {\n\t\t\tconst result = await actions.invite(email, role)\n\t\t\tawait refresh()\n\t\t\treturn result\n\t\t},\n\t\t[actions, refresh],\n\t)\n\n\tconst removeMember = useCallback(\n\t\tasync (userId: string): Promise<void> => {\n\t\t\tawait actions.removeMember(userId)\n\t\t\tawait refresh()\n\t\t},\n\t\t[actions, refresh],\n\t)\n\n\tconst updateRole = useCallback(\n\t\tasync (userId: string, role: string): Promise<void> => {\n\t\t\tawait actions.updateRole(userId, role)\n\t\t\tawait refresh()\n\t\t},\n\t\t[actions, refresh],\n\t)\n\n\treturn { members, isLoading, refresh, invite, removeMember, updateRole, error }\n}\n\nexport function usePermission(requiredRole: string): boolean {\n\tconst { session } = useOrgContext()\n\tconst snapshotRef = useRef(session.checkPermission(requiredRole))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn session.subscribe(() => {\n\t\t\t\tconst next = session.checkPermission(requiredRole)\n\t\t\t\tif (next !== snapshotRef.current) {\n\t\t\t\t\tsnapshotRef.current = next\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[session, requiredRole],\n\t)\n\n\tconst getSnapshot = useCallback(() => snapshotRef.current, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\nexport { checkOrgPermission }\n"],"mappings":";;;;;;;;;AAAA,SAAS,eAAe,WAAW,SAAS,4BAA4B;;;ACAxE,SAAS,qBAAqB;AAsB9B,IAAM,cAAc,cAAuC,IAAI;;;ADV/D,SAAS,aAAa,EAAE,QAAQ,UAAU,SAAS,GAAoC;AACtF,QAAM,UAAU,QAAQ,M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A,CAAC,QAAQ,OAAO;AAAA,EACjB;AAEA,SAAO,oBAAC,WAAW,UAAX,EAAoB,OAAe,UAAS;AACrD;","names":["useSyncExternalStore","useSyncExternalStore","useEffect","useMemo","useRef","createContext","useContext","useEffect","useSyncExternalStore","createContext","useContext","useSyncExternalStore","useEffect","useRef","useEffect","useMemo"]}
package/dist/server.cjs CHANGED
@@ -4490,6 +4490,13 @@ var OrgRoutes = class {
4490
4490
  body: { error: "Cannot assign owner role directly. Use ownership transfer." }
4491
4491
  };
4492
4492
  }
4493
+ const org = await this.store.getOrg(orgId);
4494
+ if (org && org.ownerId === params.targetUserId) {
4495
+ return {
4496
+ status: 403,
4497
+ body: { error: "The organization owner's role cannot be changed. Use ownership transfer." }
4498
+ };
4499
+ }
4493
4500
  const callerMembership = await this.store.getMembership(orgId, userId);
4494
4501
  if (callerMembership && callerMembership.role !== "owner" && params.role === "admin") {
4495
4502
  return { status: 403, body: { error: "Only the owner can assign admin role." } };
@@ -6075,9 +6082,9 @@ var TotpManager = class {
6075
6082
  throw new TotpNotEnabledError(userId);
6076
6083
  }
6077
6084
  if (stored.verified) {
6078
- return this.validateCode(stored.secret, code);
6085
+ return this.consumeCode(stored, code);
6079
6086
  }
6080
- const valid = this.validateCode(stored.secret, code);
6087
+ const valid = await this.consumeCode(stored, code);
6081
6088
  if (!valid) {
6082
6089
  throw new TotpInvalidCodeError();
6083
6090
  }
@@ -6089,6 +6096,11 @@ var TotpManager = class {
6089
6096
  /**
6090
6097
  * Verify a TOTP code during login.
6091
6098
  * Returns true if the code is valid, false otherwise.
6099
+ *
6100
+ * Enforces single-use: a code is rejected if its time-step has already
6101
+ * been consumed (or predates a previously consumed time-step). This
6102
+ * prevents an attacker who observes one valid code from replaying it
6103
+ * within the acceptance window (RFC 6238 §5.2).
6092
6104
  */
6093
6105
  async verify(userId, code) {
6094
6106
  const stored = await this.store.getByUserId(userId);
@@ -6098,7 +6110,7 @@ var TotpManager = class {
6098
6110
  if (!stored.verified) {
6099
6111
  throw new TotpNotVerifiedError(userId);
6100
6112
  }
6101
- return this.validateCode(stored.secret, code);
6113
+ return this.consumeCode(stored, code);
6102
6114
  }
6103
6115
  /**
6104
6116
  * Verify a recovery code as an alternative to TOTP.
@@ -6182,16 +6194,41 @@ var TotpManager = class {
6182
6194
  }
6183
6195
  // --- Private ---
6184
6196
  validateCode(base32Secret, code) {
6197
+ return this.matchTimeStep(base32Secret, code) !== null;
6198
+ }
6199
+ /**
6200
+ * Find the TOTP time-step counter (within the acceptance window) whose
6201
+ * generated code matches `code`, or null if none matches. Comparison is
6202
+ * timing-safe.
6203
+ */
6204
+ matchTimeStep(base32Secret, code) {
6185
6205
  const secretBytes = base32Decode(base32Secret);
6186
6206
  const now = Math.floor(Date.now() / 1e3);
6187
6207
  for (let offset = -this.window; offset <= this.window; offset++) {
6188
6208
  const timeCounter = Math.floor((now + offset * this.period) / this.period);
6189
6209
  const expected = generateTotpCode(secretBytes, timeCounter, this.digits, this.algorithm);
6190
6210
  if (timingSafeEqual2(code, expected)) {
6191
- return true;
6211
+ return timeCounter;
6192
6212
  }
6193
6213
  }
6194
- return false;
6214
+ return null;
6215
+ }
6216
+ /**
6217
+ * Validate a code AND consume its time-step so it (and any earlier code in
6218
+ * the window) cannot be reused. Returns false for an invalid code or a
6219
+ * replay of an already-consumed time-step. Persists the consumed time-step.
6220
+ */
6221
+ async consumeCode(stored, code) {
6222
+ const matched = this.matchTimeStep(stored.secret, code);
6223
+ if (matched === null) {
6224
+ return false;
6225
+ }
6226
+ if (stored.lastUsedTimeStep !== void 0 && matched <= stored.lastUsedTimeStep) {
6227
+ return false;
6228
+ }
6229
+ stored.lastUsedTimeStep = matched;
6230
+ await this.store.save(stored);
6231
+ return true;
6195
6232
  }
6196
6233
  };
6197
6234
  function generateTotpCode(secret, counter, digits, algorithm) {