@confighub/react-auth 0.4.0 → 0.4.2

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/README.md CHANGED
@@ -52,8 +52,12 @@ const { status, user, error, login, logout, switchOrganization, reauthenticate,
52
52
 
53
53
  - `login(options?)` — redirects to the IdP. `returnTo` picks the landing path
54
54
  (default: the current one). `organization` is a Keycloak organization alias, sent
55
- as the `organization:<alias>` scope so a multi-org user is not prompted; without
56
- it Keycloak prompts. `prompt: 'none' | 'login'` is passed through.
55
+ as the `organization:<alias>` scope so a multi-org user is not prompted. Left
56
+ out, the alias of the last successful login in this browser is used (remembered
57
+ per client in `localStorage`; a short public name, not a credential), so a new
58
+ tab or a login after logout lands in the same organization silently. `null`
59
+ sends no hint on purpose, so Keycloak prompts: that is "switch organization".
60
+ `prompt: 'none' | 'login'` is passed through.
57
61
  - `logout(options?)` — forgets the session in this tab. `endSession: true` also ends
58
62
  the IdP session (RP-initiated logout with `id_token_hint`), landing on
59
63
  `postLogoutRedirectUri` (default: the callback URI), which must be registered
package/dist/index.cjs CHANGED
@@ -8,6 +8,28 @@ var jsxRuntime = require('react/jsx-runtime');
8
8
 
9
9
  // src/core.ts
10
10
  var PKCE_KEY = "confighub_pkce";
11
+ var LAST_ORG_KEY = "confighub_last_org";
12
+ var lastOrgKey = (clientId) => `${LAST_ORG_KEY}:${clientId}`;
13
+ function rememberedOrganization(clientId) {
14
+ try {
15
+ return localStorage.getItem(lastOrgKey(clientId)) ?? void 0;
16
+ } catch {
17
+ return void 0;
18
+ }
19
+ }
20
+ function rememberOrganization(clientId, alias) {
21
+ try {
22
+ if (alias) localStorage.setItem(lastOrgKey(clientId), alias);
23
+ else localStorage.removeItem(lastOrgKey(clientId));
24
+ } catch {
25
+ }
26
+ }
27
+ function organizationAliasOf(idpClaims) {
28
+ const org = idpClaims.organization;
29
+ if (!org || typeof org !== "object") return void 0;
30
+ const aliases = Object.keys(org);
31
+ return aliases.length === 1 ? aliases[0] : void 0;
32
+ }
11
33
  var trimSlash = (s) => s.replace(/\/+$/, "");
12
34
  var callbackUri = (opts) => window.location.origin + (opts?.callbackPath ?? "/");
13
35
  var currentPath = () => window.location.pathname + window.location.search + window.location.hash;
@@ -63,7 +85,8 @@ async function startLogin(base, clientId, login = {}, flow = {}) {
63
85
  silent: login.prompt === "none"
64
86
  };
65
87
  sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));
66
- const orgScope = login.organization ? `organization:${login.organization}` : "organization";
88
+ const alias = login.organization === null ? void 0 : login.organization ?? rememberedOrganization(clientId);
89
+ const orgScope = alias ? `organization:${alias}` : "organization";
67
90
  const params = {
68
91
  response_type: "code",
69
92
  client_id: clientId,
@@ -115,9 +138,11 @@ async function doCompleteLogin() {
115
138
  }
116
139
  const idpToken = await tokenResp.json();
117
140
  const minted = await exchange(saved.exchangeEndpoint, idpToken.access_token);
141
+ const idpClaims = decodeJwtClaims(idpToken.access_token);
142
+ rememberOrganization(saved.clientId, organizationAliasOf(idpClaims));
118
143
  return {
119
144
  ...minted,
120
- idpClaims: decodeJwtClaims(idpToken.access_token),
145
+ idpClaims,
121
146
  idToken: typeof idpToken.id_token === "string" ? idpToken.id_token : void 0
122
147
  };
123
148
  }
@@ -178,12 +203,6 @@ function getAccessToken() {
178
203
  }
179
204
  var ConfigHubAuthContext = react.createContext(null);
180
205
  var SESSION_KEY = "confighub_session";
181
- function organizationAlias(session) {
182
- const org = session?.idpClaims.organization;
183
- if (!org || typeof org !== "object") return void 0;
184
- const aliases = Object.keys(org);
185
- return aliases.length === 1 ? aliases[0] : void 0;
186
- }
187
206
  function readPersisted() {
188
207
  try {
189
208
  const raw = sessionStorage.getItem(SESSION_KEY);
@@ -290,13 +309,14 @@ function ConfigHubAuthProvider({
290
309
  const current = sessionRef.current;
291
310
  if (!current) throw new Error("not authenticated");
292
311
  const minted = await switchOrganization(baseUrl, current.accessToken, organizationId);
312
+ rememberOrganization(clientId, void 0);
293
313
  applySession({ ...current, ...minted });
294
314
  },
295
- [applySession, baseUrl]
315
+ [applySession, baseUrl, clientId]
296
316
  );
297
317
  const getToken = react.useCallback(() => sessionRef.current?.accessToken, []);
298
318
  const reauthenticate = react.useCallback(async () => {
299
- const organization = organizationAlias(sessionRef.current);
319
+ const organization = organizationAliasOf(sessionRef.current?.idpClaims ?? {});
300
320
  sessionRef.current = void 0;
301
321
  setAccessToken(void 0);
302
322
  persistSession(void 0);
@@ -351,6 +371,8 @@ exports.callbackUri = callbackUri;
351
371
  exports.decodeJwtClaims = decodeJwtClaims;
352
372
  exports.getAccessToken = getAccessToken;
353
373
  exports.isExpired = isExpired;
374
+ exports.organizationAliasOf = organizationAliasOf;
375
+ exports.rememberedOrganization = rememberedOrganization;
354
376
  exports.useAuth = useAuth;
355
377
  exports.useConfigHub = useConfigHub;
356
378
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core.ts","../src/tokenStore.ts","../src/provider.tsx","../src/hooks.ts"],"names":["createContext","useState","useRef","useMemo","useCallback","useEffect","switchOrganization","createConfigHubClient","jsx","useContext"],"mappings":";;;;;;;;;AA+EA,IAAM,QAAA,GAAW,gBAAA;AAEjB,IAAM,YAAY,CAAC,CAAA,KAAsB,CAAA,CAAE,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAGtD,IAAM,cAAc,CAAC,IAAA,KAC1B,OAAO,QAAA,CAAS,MAAA,IAAU,MAAM,YAAA,IAAgB,GAAA;AAElD,IAAM,WAAA,GAAc,MAClB,MAAA,CAAO,QAAA,CAAS,WAAW,MAAA,CAAO,QAAA,CAAS,MAAA,GAAS,MAAA,CAAO,QAAA,CAAS,IAAA;AAEtE,IAAM,MAAA,GAAS,CAAC,GAAA,KACd,IAAA,CAAK,OAAO,YAAA,CAAa,GAAG,IAAI,UAAA,CAAW,GAAG,CAAC,CAAC,CAAA,CAC7C,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAClB,OAAA,CAAQ,OAAO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,GAAQJ,aAAA;AAAA,IACZ,OAAO;AAAA,MACL,MAAA;AAAA,MACA,IAAA;AAAA,MACA,KAAA;AAAA,MACA,KAAA;AAAA,MACA,MAAA;AAAA,MACA,kBAAA,EAAAG,mBAAAA;AAAA,MACA,cAAA;AAAA,MACA,QAAA;AAAA,MACA;AAAA,KACF,CAAA;AAAA,IACA,CAAC,QAAQ,IAAA,EAAM,KAAA,EAAO,OAAO,MAAA,EAAQA,mBAAAA,EAAoB,cAAA,EAAgB,QAAA,EAAU,MAAM;AAAA,GAC3F;AAEA,EAAA,uBACEE,cAAA,CAAC,oBAAA,CAAqB,QAAA,EAArB,EAA8B,OAAe,QAAA,EAAS,CAAA;AAE3D;AC5RO,SAAS,OAAA,GAAqC;AACnD,EAAA,MAAM,GAAA,GAAMC,iBAAW,oBAAoB,CAAA;AAC3C,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,MAAM,uDAAuD,CAAA;AAAA,EACzE;AACA,EAAA,OAAO,GAAA;AACT;AAYO,SAAS,YAAA,GAAgC;AAC9C,EAAA,OAAO,SAAQ,CAAE,MAAA;AACnB","file":"index.cjs","sourcesContent":["// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n//\n// Framework-neutral browser-auth engine for ConfigHub. Productionized from the\n// reference harness `test/browser-auth/src/confighubAuth.ts` in the ConfigHub\n// monorepo, which is validated end to end against staging and prod.\n//\n// Flow (design: third-party-browser-app-auth.md §6):\n// GET {base}/api/info -> discovery { AuthIssuer, TokenExchangeEndpoint }\n// OIDC discovery on AuthIssuer -> authorize/token/end_session endpoints\n// PKCE authorize + code->token -> IdP token\n// POST {TokenExchangeEndpoint} (8693) -> minted ConfigHub token\n//\n// The minted token then rides `Authorization: Bearer` against `/api`. The flow is\n// edition-agnostic: `AuthIssuer` is whatever discovery names (ConfigHub's bundled\n// Keycloak for Cloud, the org's own IdP for Enterprise), so the same code runs\n// against both. Tokens are held by the caller; only the transient PKCE state is\n// parked in sessionStorage across the authorize redirect.\n\nexport interface Discovery {\n AuthIssuer?: string;\n TokenExchangeEndpoint?: string;\n TokenExchangeAudience?: string;\n}\n\nexport interface MintedSession {\n accessToken: string;\n organizationId: string;\n /** Claims of the validated IdP token (owning-org, audience, organization shape). */\n idpClaims: Record<string, unknown>;\n /**\n * The IdP's ID token, kept only so logout can pass it as `id_token_hint` to the\n * end-session endpoint. Absent for sessions that did not come from an OIDC login.\n */\n idToken?: string;\n}\n\nexport interface LoginOptions {\n /**\n * Where to land after login, as a same-origin path (`/space/x?tab=units`). Carried\n * through the authorize round trip in the PKCE state, never in the redirect URI:\n * OAuth clients register exact redirect URIs, so the URI itself must not vary with\n * the page the user started from. Defaults to the current path and query.\n */\n returnTo?: string;\n /**\n * Keycloak organization alias to sign in to, sent as the `organization:<alias>`\n * scope. Without it Keycloak prompts a multi-org user to pick one (or uses the\n * organization already selected in the SSO session).\n */\n organization?: string;\n /**\n * `'none'` asks the IdP to re-authenticate without any UI, failing with\n * `login_required` if the SSO session is gone -- the way to refresh an expired\n * ConfigHub token when the user is still signed in at the IdP. `'login'` forces the\n * login form even with a live SSO session.\n */\n prompt?: 'none' | 'login';\n}\n\nexport interface FlowOptions {\n /**\n * Same-origin path the IdP redirects back to, and therefore the redirect URI to\n * register for the client: `{origin}{callbackPath}`. Defaults to `/`.\n */\n callbackPath?: string;\n}\n\ninterface PkceState {\n verifier: string;\n state: string;\n clientId: string;\n tokenEndpoint: string;\n exchangeEndpoint: string;\n redirectUri: string;\n returnTo: string;\n silent: boolean;\n}\n\nconst PKCE_KEY = 'confighub_pkce';\n\nconst trimSlash = (s: string): string => s.replace(/\\/+$/, '');\n\n/** The fixed callback URI: the page origin plus the configured callback path. */\nexport const callbackUri = (opts?: FlowOptions): string =>\n window.location.origin + (opts?.callbackPath ?? '/');\n\nconst currentPath = (): string =>\n window.location.pathname + window.location.search + window.location.hash;\n\nconst b64url = (buf: ArrayBuffer): string =>\n btoa(String.fromCharCode(...new Uint8Array(buf)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n\nconst randomString = (n = 64): string =>\n b64url(crypto.getRandomValues(new Uint8Array(n)).buffer);\n\nasync function sha256(s: string): Promise<string> {\n return b64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)));\n}\n\n/** Decode a JWT's claims without verifying it. Returns {} for anything malformed. */\nexport function decodeJwtClaims(token: string): Record<string, unknown> {\n const part = token.split('.')[1];\n if (!part) return {};\n try {\n return JSON.parse(atob(part.replace(/-/g, '+').replace(/_/g, '/')));\n } catch {\n return {};\n }\n}\n\n/** Whether a JWT's `exp` is in the past (with a small skew allowance). */\nexport function isExpired(token: string, skewSeconds = 30): boolean {\n const exp = decodeJwtClaims(token).exp;\n if (typeof exp !== 'number') return false;\n return exp * 1000 <= Date.now() + skewSeconds * 1000;\n}\n\nexport async function discover(base: string): Promise<Discovery> {\n const r = await fetch(trimSlash(base) + '/api/info');\n if (!r.ok) throw new Error('/api/info failed: ' + r.status);\n return r.json();\n}\n\ninterface OidcMetadata {\n authorization_endpoint: string;\n token_endpoint: string;\n end_session_endpoint?: string;\n}\n\nasync function oidcMetadata(issuer: string): Promise<OidcMetadata> {\n const r = await fetch(trimSlash(issuer) + '/.well-known/openid-configuration');\n if (!r.ok) throw new Error('OIDC discovery failed: ' + r.status);\n return r.json();\n}\n\n/**\n * Discover, build a PKCE request, and navigate to the IdP authorize endpoint.\n * Returns only by redirecting the page; `completeLoginFromRedirect()` finishes on\n * the way back.\n */\nexport async function startLogin(\n base: string,\n clientId: string,\n login: LoginOptions = {},\n flow: FlowOptions = {},\n): Promise<void> {\n const info = await discover(base);\n if (!info.AuthIssuer || !info.TokenExchangeEndpoint) {\n throw new Error(\n 'this instance is not configured for token-exchange auth (server needs CONFIGHUB_IDP_ISSUER)',\n );\n }\n const meta = await oidcMetadata(info.AuthIssuer);\n const verifier = randomString();\n const challenge = await sha256(verifier);\n const state = randomString(16);\n const redirectUri = callbackUri(flow);\n const pkce: PkceState = {\n verifier,\n state,\n clientId,\n tokenEndpoint: meta.token_endpoint,\n exchangeEndpoint: info.TokenExchangeEndpoint,\n redirectUri,\n returnTo: login.returnTo ?? currentPath(),\n silent: login.prompt === 'none',\n };\n sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));\n\n // The \"organization\" scope makes Keycloak emit the org claim the exchange resolves;\n // \"organization:<alias>\" selects one without prompting.\n const orgScope = login.organization ? `organization:${login.organization}` : 'organization';\n const params: Record<string, string> = {\n response_type: 'code',\n client_id: clientId,\n redirect_uri: redirectUri,\n scope: `openid email profile ${orgScope}`,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n state,\n };\n if (login.prompt) params.prompt = login.prompt;\n\n const authURL = new URL(meta.authorization_endpoint);\n authURL.search = new URLSearchParams(params).toString();\n window.location.assign(authURL.toString());\n}\n\n// Memoize so React StrictMode's double-mount can't redeem the one-time code twice.\nlet pending: Promise<MintedSession | null> | null = null;\n\n/**\n * If the page is the IdP redirect (`?code=...`), exchange the code for an IdP token\n * and then exchange that for a minted ConfigHub token, and restore the URL the\n * login started from. Returns null on a normal load, and also when a `prompt=none`\n * attempt came back with `login_required` (the SSO session is gone; the caller\n * should offer an interactive login).\n */\nexport function completeLoginFromRedirect(): Promise<MintedSession | null> {\n if (!pending) pending = doCompleteLogin();\n return pending;\n}\n\nconst SILENT_FAILURES = new Set(['login_required', 'interaction_required', 'consent_required']);\n\nasync function doCompleteLogin(): Promise<MintedSession | null> {\n const params = new URLSearchParams(window.location.search);\n const code = params.get('code');\n const error = params.get('error');\n if (!code && !error) return null;\n\n const savedRaw = sessionStorage.getItem(PKCE_KEY);\n sessionStorage.removeItem(PKCE_KEY);\n const saved: PkceState | null = savedRaw ? JSON.parse(savedRaw) : null;\n\n // Put the URL back to where the user started before anything else can fail, so\n // neither the code nor an error string lingers in the address bar or history.\n history.replaceState({}, '', saved?.returnTo ?? callbackUri());\n\n if (error) {\n if (saved?.silent && SILENT_FAILURES.has(error)) return null;\n throw new Error(`IdP returned error: ${error} ${params.get('error_description') ?? ''}`);\n }\n if (!saved) throw new Error('no PKCE state; restart login');\n if (params.get('state') !== saved.state) throw new Error('state mismatch; aborting');\n\n // Exchange the authorization code for an IdP token (PKCE, public client).\n const tokenResp = await fetch(saved.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code: code!,\n redirect_uri: saved.redirectUri,\n client_id: saved.clientId,\n code_verifier: saved.verifier,\n }),\n });\n if (!tokenResp.ok) {\n throw new Error(`IdP token endpoint ${tokenResp.status}: ${await tokenResp.text()}`);\n }\n const idpToken = await tokenResp.json();\n\n // RFC 8693 token exchange against ConfigHub -> minted ConfigHub token.\n const minted = await exchange(saved.exchangeEndpoint, idpToken.access_token);\n return {\n ...minted,\n idpClaims: decodeJwtClaims(idpToken.access_token),\n idToken: typeof idpToken.id_token === 'string' ? idpToken.id_token : undefined,\n };\n}\n\nasync function exchange(\n exchangeEndpoint: string,\n subjectToken: string,\n): Promise<Pick<MintedSession, 'accessToken' | 'organizationId'>> {\n const exResp = await fetch(exchangeEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: subjectToken,\n subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',\n }),\n });\n if (!exResp.ok) throw new Error(`/auth/exchange ${exResp.status}: ${await exResp.text()}`);\n const minted = await exResp.json();\n return { accessToken: minted.access_token, organizationId: minted.organization_id };\n}\n\n/**\n * Trade the current minted token for one scoped to another organization the user\n * belongs to (`POST {base}/auth/switch-organization`, bearer-authenticated). The\n * IdP session is untouched; only the ConfigHub token changes.\n */\nexport async function switchOrganization(\n base: string,\n accessToken: string,\n organizationId: string,\n): Promise<Pick<MintedSession, 'accessToken' | 'organizationId'>> {\n const r = await fetch(trimSlash(base) + '/auth/switch-organization', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({ organization_id: organizationId }),\n });\n if (!r.ok) throw new Error(`/auth/switch-organization ${r.status}: ${await r.text()}`);\n const minted = await r.json();\n return { accessToken: minted.access_token, organizationId: minted.organization_id };\n}\n\n/**\n * End the IdP session (RP-initiated logout) and land on `postLogoutRedirectUri`,\n * which must be registered for the client. Returns only by redirecting. If the\n * issuer publishes no end-session endpoint, navigates to the redirect URI directly.\n */\nexport async function endSession(\n base: string,\n clientId: string,\n idToken: string | undefined,\n postLogoutRedirectUri: string,\n): Promise<void> {\n const info = await discover(base);\n const meta = info.AuthIssuer ? await oidcMetadata(info.AuthIssuer) : undefined;\n if (!meta?.end_session_endpoint) {\n window.location.assign(postLogoutRedirectUri);\n return;\n }\n const params: Record<string, string> = {\n client_id: clientId,\n post_logout_redirect_uri: postLogoutRedirectUri,\n };\n if (idToken) params.id_token_hint = idToken;\n const url = new URL(meta.end_session_endpoint);\n url.search = new URLSearchParams(params).toString();\n window.location.assign(url.toString());\n}\n\n/** Discard the in-progress login memo (used on logout so a later login re-runs). */\nexport function resetPending(): void {\n pending = null;\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\n// A module-level holder for the current minted token, so non-React consumers can read\n// it. RTK Query's `prepareHeaders` (in @confighub/rtk-query) is not a hook and cannot\n// read React context, so it calls getAccessToken() instead. The provider keeps this in\n// sync with its React state.\nlet currentToken: string | undefined;\n\n/** @internal — called by the provider; not part of the public surface. */\nexport function setAccessToken(token: string | undefined): void {\n currentToken = token;\n}\n\n/**\n * The current minted ConfigHub token, or undefined when unauthenticated. Pass this as\n * the `getToken` for `@confighub/rtk-query`'s `configureConfigHub`, or read it anywhere\n * you need the token outside React.\n */\nexport function getAccessToken(): string | undefined {\n return currentToken;\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\nimport { createConfigHubClient, type ConfigHubClient } from '@confighub/api';\nimport {\n createContext,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport {\n callbackUri,\n completeLoginFromRedirect,\n endSession,\n isExpired,\n resetPending,\n startLogin,\n switchOrganization as switchOrganizationCore,\n type LoginOptions,\n type MintedSession,\n} from './core';\nimport { setAccessToken } from './tokenStore';\n\nexport type AuthStatus = 'loading' | 'authenticated' | 'unauthenticated' | 'error';\n\nexport interface ConfigHubUser {\n organizationId: string;\n idpClaims: Record<string, unknown>;\n}\n\nexport interface LogoutOptions {\n /**\n * Also end the IdP session (RP-initiated logout), so the next login asks for\n * credentials instead of riding the SSO cookie. Redirects the page; the landing\n * URI must be registered for the client. Default: false, which only forgets the\n * token in this tab.\n */\n endSession?: boolean;\n /** Where to land after IdP logout. Defaults to the callback URI. */\n postLogoutRedirectUri?: string;\n}\n\nexport interface ConfigHubAuthContextValue {\n status: AuthStatus;\n user: ConfigHubUser | null;\n error: Error | null;\n /** Begin login: redirects the page to the IdP. */\n login: (options?: LoginOptions) => Promise<void>;\n /** Forget the session in this tab and, optionally, end the IdP session too. */\n logout: (options?: LogoutOptions) => Promise<void>;\n /**\n * Re-mint the ConfigHub token for another organization the user belongs to. The\n * IdP session is untouched. Rejects with the server's error if the user is not a\n * member; the current session stays as it was.\n */\n switchOrganization: (organizationId: string) => Promise<void>;\n /**\n * The ConfigHub token stopped working (a 401). Try to get a new one without any\n * UI: a `prompt=none` round trip through the IdP, for the organization the session\n * already had. Status goes to `loading` meanwhile, not `unauthenticated`, so an\n * app that auto-logs-in on `unauthenticated` does not race this with an\n * interactive login. If the IdP session is gone too, the page comes back\n * `unauthenticated`. Redirects the page.\n */\n reauthenticate: () => Promise<void>;\n /** Current bearer token, or undefined when unauthenticated. */\n getToken: () => string | undefined;\n /** A typed API client pre-wired with the current token. Stable across renders. */\n client: ConfigHubClient;\n}\n\nexport const ConfigHubAuthContext = createContext<ConfigHubAuthContextValue | null>(null);\n\nexport interface ConfigHubAuthProviderProps {\n /** Absolute base URL of the ConfigHub instance, e.g. `https://hub.confighub.com`. */\n baseUrl: string;\n /** This app's registered OAuth `client_id` (from `cub oauthclient create`). */\n clientId: string;\n /**\n * Same-origin path the IdP redirects back to; `{origin}{callbackPath}` is the\n * redirect URI to register. Defaults to `/`. Fixed on purpose: the page a user\n * starts login from travels in the PKCE state, not in the redirect URI.\n */\n callbackPath?: string;\n /**\n * `'session'` keeps the minted token in `sessionStorage` so a reload or an in-tab\n * navigation does not round-trip through the IdP. Tab-scoped and gone when the tab\n * closes. Default `'none'`: memory only, a reload starts unauthenticated.\n */\n persist?: 'none' | 'session';\n /**\n * What a 401 from the API means. `'login'` (default): the token is stale, try a\n * silent re-authentication (`prompt=none`) and fall back to unauthenticated if the\n * IdP session is gone too. `'logout'`: just drop the session.\n */\n onUnauthorized?: 'login' | 'logout';\n children: ReactNode;\n}\n\nconst SESSION_KEY = 'confighub_session';\n\n/**\n * The Keycloak organization alias of the session, from the IdP token's\n * `organization` claim (`{ \"<alias>\": { id } }`), for re-selecting the same org\n * without a prompt. Undefined when the claim is absent or not in that shape.\n */\nfunction organizationAlias(session: MintedSession | undefined): string | undefined {\n const org = session?.idpClaims.organization;\n if (!org || typeof org !== 'object') return undefined;\n const aliases = Object.keys(org as Record<string, unknown>);\n return aliases.length === 1 ? aliases[0] : undefined;\n}\n\nfunction readPersisted(): MintedSession | null {\n try {\n const raw = sessionStorage.getItem(SESSION_KEY);\n if (!raw) return null;\n const session: MintedSession = JSON.parse(raw);\n if (!session.accessToken || isExpired(session.accessToken)) {\n sessionStorage.removeItem(SESSION_KEY);\n return null;\n }\n return session;\n } catch {\n return null;\n }\n}\n\n/**\n * Runs the browser-direct auth flow and manages the token lifecycle. On mount it\n * completes a redirect if the page is the IdP callback, restores a persisted\n * session if there is one, and otherwise starts unauthenticated until `login()`\n * is called.\n */\nexport function ConfigHubAuthProvider({\n baseUrl,\n clientId,\n callbackPath,\n persist = 'none',\n onUnauthorized = 'login',\n children,\n}: ConfigHubAuthProviderProps): JSX.Element {\n const [status, setStatus] = useState<AuthStatus>('loading');\n const [user, setUser] = useState<ConfigHubUser | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // The session lives in a ref so getToken() reads the latest value synchronously\n // without re-creating the API client on every render.\n const sessionRef = useRef<MintedSession | undefined>(undefined);\n const flow = useMemo(() => ({ callbackPath }), [callbackPath]);\n\n const persistSession = useCallback(\n (session: MintedSession | undefined) => {\n if (persist !== 'session') return;\n try {\n if (session) sessionStorage.setItem(SESSION_KEY, JSON.stringify(session));\n else sessionStorage.removeItem(SESSION_KEY);\n } catch {\n // Storage unavailable (private mode, quota): memory-only for this tab.\n }\n },\n [persist],\n );\n\n const applySession = useCallback(\n (session: MintedSession) => {\n sessionRef.current = session;\n setAccessToken(session.accessToken); // keep the non-React accessor in sync (rtk-query)\n persistSession(session);\n setUser({ organizationId: session.organizationId, idpClaims: session.idpClaims });\n setError(null);\n setStatus('authenticated');\n },\n [persistSession],\n );\n\n const clearSession = useCallback(() => {\n sessionRef.current = undefined;\n setAccessToken(undefined);\n persistSession(undefined);\n resetPending();\n setUser(null);\n setStatus('unauthenticated');\n }, [persistSession]);\n\n useEffect(() => {\n let cancelled = false;\n completeLoginFromRedirect()\n .then((session) => {\n if (cancelled) return;\n if (session) return applySession(session);\n const persisted = persist === 'session' ? readPersisted() : null;\n if (persisted) return applySession(persisted);\n setStatus('unauthenticated');\n })\n .catch((e: unknown) => {\n if (cancelled) return;\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n });\n return () => {\n cancelled = true;\n };\n }, [applySession, persist]);\n\n const login = useCallback(\n async (options?: LoginOptions) => {\n setError(null);\n try {\n await startLogin(baseUrl, clientId, options, flow);\n } catch (e: unknown) {\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n }\n },\n [baseUrl, clientId, flow],\n );\n\n const logout = useCallback(\n async (options?: LogoutOptions) => {\n const idToken = sessionRef.current?.idToken;\n clearSession();\n if (options?.endSession) {\n await endSession(\n baseUrl,\n clientId,\n idToken,\n options.postLogoutRedirectUri ?? callbackUri(flow),\n );\n }\n },\n [baseUrl, clientId, clearSession, flow],\n );\n\n const switchOrganization = useCallback(\n async (organizationId: string) => {\n const current = sessionRef.current;\n if (!current) throw new Error('not authenticated');\n const minted = await switchOrganizationCore(baseUrl, current.accessToken, organizationId);\n applySession({ ...current, ...minted });\n },\n [applySession, baseUrl],\n );\n\n const getToken = useCallback(() => sessionRef.current?.accessToken, []);\n\n const reauthenticate = useCallback(async () => {\n const organization = organizationAlias(sessionRef.current);\n // Forget the token but stay 'loading': the page is about to navigate away,\n // and 'unauthenticated' would invite an interactive login in the meantime.\n sessionRef.current = undefined;\n setAccessToken(undefined);\n persistSession(undefined);\n resetPending();\n setStatus('loading');\n try {\n await startLogin(baseUrl, clientId, { prompt: 'none', organization }, flow);\n } catch (e: unknown) {\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n }\n }, [baseUrl, clientId, flow, persistSession]);\n\n // A 401 means the minted token no longer works. Silent re-auth keeps the user's\n // place if the IdP session is still alive; otherwise the page comes back\n // unauthenticated and the app offers a real login.\n const handleUnauthorized = useCallback(() => {\n if (!sessionRef.current) return;\n if (onUnauthorized === 'login') void reauthenticate();\n else clearSession();\n }, [clearSession, reauthenticate, onUnauthorized]);\n\n // One client for the provider's lifetime. getToken reads the session ref.\n const client = useMemo(\n () => createConfigHubClient({ baseUrl, getToken, onUnauthorized: handleUnauthorized }),\n [baseUrl, getToken, handleUnauthorized],\n );\n\n const value = useMemo<ConfigHubAuthContextValue>(\n () => ({\n status,\n user,\n error,\n login,\n logout,\n switchOrganization,\n reauthenticate,\n getToken,\n client,\n }),\n [status, user, error, login, logout, switchOrganization, reauthenticate, getToken, client],\n );\n\n return (\n <ConfigHubAuthContext.Provider value={value}>{children}</ConfigHubAuthContext.Provider>\n );\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\nimport type { ConfigHubClient } from '@confighub/api';\nimport { useContext } from 'react';\nimport { ConfigHubAuthContext, type ConfigHubAuthContextValue } from './provider';\n\n/**\n * Access the ConfigHub auth state and actions. Must be called under a\n * `<ConfigHubAuthProvider>`.\n *\n * ```ts\n * const { status, user, login, logout } = useAuth();\n * ```\n */\nexport function useAuth(): ConfigHubAuthContextValue {\n const ctx = useContext(ConfigHubAuthContext);\n if (!ctx) {\n throw new Error('useAuth must be used within a <ConfigHubAuthProvider>');\n }\n return ctx;\n}\n\n/**\n * The typed ConfigHub API client, pre-wired with the current token. This is the\n * seam between `@confighub/react-auth` and `@confighub/api`: you never pass a\n * token by hand.\n *\n * ```ts\n * const api = useConfigHub();\n * const { data } = await api.GET('/space/{space_id}/unit', { params: { path: { space_id } } });\n * ```\n */\nexport function useConfigHub(): ConfigHubClient {\n return useAuth().client;\n}\n"]}
1
+ {"version":3,"sources":["../src/core.ts","../src/tokenStore.ts","../src/provider.tsx","../src/hooks.ts"],"names":["createContext","useState","useRef","useMemo","useCallback","useEffect","switchOrganization","createConfigHubClient","jsx","useContext"],"mappings":";;;;;;;;;AAsFA,IAAM,QAAA,GAAW,gBAAA;AACjB,IAAM,YAAA,GAAe,oBAAA;AAIrB,IAAM,aAAa,CAAC,QAAA,KAA6B,CAAA,EAAG,YAAY,IAAI,QAAQ,CAAA,CAAA;AAGrE,SAAS,uBAAuB,QAAA,EAAsC;AAC3E,EAAA,IAAI;AACF,IAAA,OAAO,YAAA,CAAa,OAAA,CAAQ,UAAA,CAAW,QAAQ,CAAC,CAAA,IAAK,KAAA,CAAA;AAAA,EACvD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAGO,SAAS,oBAAA,CAAqB,UAAkB,KAAA,EAAiC;AACtF,EAAA,IAAI;AACF,IAAA,IAAI,OAAO,YAAA,CAAa,OAAA,CAAQ,UAAA,CAAW,QAAQ,GAAG,KAAK,CAAA;AAAA,SACtD,Y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AAC,oBAAA,CAAqB,QAAA,EAArB,EAA8B,OAAe,QAAA,EAAS,CAAA;AAE3D;ACrRO,SAAS,OAAA,GAAqC;AACnD,EAAA,MAAM,GAAA,GAAMC,iBAAW,oBAAoB,CAAA;AAC3C,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,MAAM,uDAAuD,CAAA;AAAA,EACzE;AACA,EAAA,OAAO,GAAA;AACT;AAYO,SAAS,YAAA,GAAgC;AAC9C,EAAA,OAAO,SAAQ,CAAE,MAAA;AACnB","file":"index.cjs","sourcesContent":["// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n//\n// Framework-neutral browser-auth engine for ConfigHub. Productionized from the\n// reference harness `test/browser-auth/src/confighubAuth.ts` in the ConfigHub\n// monorepo, which is validated end to end against staging and prod.\n//\n// Flow (design: third-party-browser-app-auth.md §6):\n// GET {base}/api/info -> discovery { AuthIssuer, TokenExchangeEndpoint }\n// OIDC discovery on AuthIssuer -> authorize/token/end_session endpoints\n// PKCE authorize + code->token -> IdP token\n// POST {TokenExchangeEndpoint} (8693) -> minted ConfigHub token\n//\n// The minted token then rides `Authorization: Bearer` against `/api`. The flow is\n// edition-agnostic: `AuthIssuer` is whatever discovery names (ConfigHub's bundled\n// Keycloak for Cloud, the org's own IdP for Enterprise), so the same code runs\n// against both. Tokens are held by the caller; only the transient PKCE state is\n// parked in sessionStorage across the authorize redirect.\n\nexport interface Discovery {\n AuthIssuer?: string;\n TokenExchangeEndpoint?: string;\n TokenExchangeAudience?: string;\n}\n\nexport interface MintedSession {\n accessToken: string;\n organizationId: string;\n /** Claims of the validated IdP token (owning-org, audience, organization shape). */\n idpClaims: Record<string, unknown>;\n /**\n * The IdP's ID token, kept only so logout can pass it as `id_token_hint` to the\n * end-session endpoint. Absent for sessions that did not come from an OIDC login.\n */\n idToken?: string;\n}\n\nexport interface LoginOptions {\n /**\n * Where to land after login, as a same-origin path (`/space/x?tab=units`). Carried\n * through the authorize round trip in the PKCE state, never in the redirect URI:\n * OAuth clients register exact redirect URIs, so the URI itself must not vary with\n * the page the user started from. Defaults to the current path and query.\n */\n returnTo?: string;\n /**\n * Which organization to sign in to, as the Keycloak organization alias sent in\n * the `organization:<alias>` scope.\n *\n * - a string: that organization, no prompt;\n * - `undefined` (default): the organization of the last successful login in this\n * browser, remembered per client in `localStorage`, so a new tab or a login after\n * logout lands in the same organization without a prompt; with nothing\n * remembered, Keycloak decides (prompt for a multi-org user, or the org matching\n * the email domain on a fresh authentication);\n * - `null`: no hint on purpose, so Keycloak prompts. This is \"switch organization\".\n */\n organization?: string | null;\n /**\n * `'none'` asks the IdP to re-authenticate without any UI, failing with\n * `login_required` if the SSO session is gone -- the way to refresh an expired\n * ConfigHub token when the user is still signed in at the IdP. `'login'` forces the\n * login form even with a live SSO session.\n */\n prompt?: 'none' | 'login';\n}\n\nexport interface FlowOptions {\n /**\n * Same-origin path the IdP redirects back to, and therefore the redirect URI to\n * register for the client: `{origin}{callbackPath}`. Defaults to `/`.\n */\n callbackPath?: string;\n}\n\ninterface PkceState {\n verifier: string;\n state: string;\n clientId: string;\n tokenEndpoint: string;\n exchangeEndpoint: string;\n redirectUri: string;\n returnTo: string;\n silent: boolean;\n}\n\nconst PKCE_KEY = 'confighub_pkce';\nconst LAST_ORG_KEY = 'confighub_last_org';\n\n// The alias is a short public identifier, not a credential, so localStorage is the\n// right place: it must outlive the tab, which is exactly what the token must not.\nconst lastOrgKey = (clientId: string): string => `${LAST_ORG_KEY}:${clientId}`;\n\n/** The organization alias of the last successful login for this client, if any. */\nexport function rememberedOrganization(clientId: string): string | undefined {\n try {\n return localStorage.getItem(lastOrgKey(clientId)) ?? undefined;\n } catch {\n return undefined;\n }\n}\n\n/** @internal */\nexport function rememberOrganization(clientId: string, alias: string | undefined): void {\n try {\n if (alias) localStorage.setItem(lastOrgKey(clientId), alias);\n else localStorage.removeItem(lastOrgKey(clientId));\n } catch {\n // Storage unavailable: the next login gets no hint.\n }\n}\n\n/**\n * The alias in an IdP token's `organization` claim (`{ \"<alias>\": { id } }`), or\n * undefined when the claim is absent or names more than one organization.\n */\nexport function organizationAliasOf(idpClaims: Record<string, unknown>): string | undefined {\n const org = idpClaims.organization;\n if (!org || typeof org !== 'object') return undefined;\n const aliases = Object.keys(org as Record<string, unknown>);\n return aliases.length === 1 ? aliases[0] : undefined;\n}\n\nconst trimSlash = (s: string): string => s.replace(/\\/+$/, '');\n\n/** The fixed callback URI: the page origin plus the configured callback path. */\nexport const callbackUri = (opts?: FlowOptions): string =>\n window.location.origin + (opts?.callbackPath ?? '/');\n\nconst currentPath = (): string =>\n window.location.pathname + window.location.search + window.location.hash;\n\nconst b64url = (buf: ArrayBuffer): string =>\n btoa(String.fromCharCode(...new Uint8Array(buf)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n\nconst randomString = (n = 64): string =>\n b64url(crypto.getRandomValues(new Uint8Array(n)).buffer);\n\nasync function sha256(s: string): Promise<string> {\n return b64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)));\n}\n\n/** Decode a JWT's claims without verifying it. Returns {} for anything malformed. */\nexport function decodeJwtClaims(token: string): Record<string, unknown> {\n const part = token.split('.')[1];\n if (!part) return {};\n try {\n return JSON.parse(atob(part.replace(/-/g, '+').replace(/_/g, '/')));\n } catch {\n return {};\n }\n}\n\n/** Whether a JWT's `exp` is in the past (with a small skew allowance). */\nexport function isExpired(token: string, skewSeconds = 30): boolean {\n const exp = decodeJwtClaims(token).exp;\n if (typeof exp !== 'number') return false;\n return exp * 1000 <= Date.now() + skewSeconds * 1000;\n}\n\nexport async function discover(base: string): Promise<Discovery> {\n const r = await fetch(trimSlash(base) + '/api/info');\n if (!r.ok) throw new Error('/api/info failed: ' + r.status);\n return r.json();\n}\n\ninterface OidcMetadata {\n authorization_endpoint: string;\n token_endpoint: string;\n end_session_endpoint?: string;\n}\n\nasync function oidcMetadata(issuer: string): Promise<OidcMetadata> {\n const r = await fetch(trimSlash(issuer) + '/.well-known/openid-configuration');\n if (!r.ok) throw new Error('OIDC discovery failed: ' + r.status);\n return r.json();\n}\n\n/**\n * Discover, build a PKCE request, and navigate to the IdP authorize endpoint.\n * Returns only by redirecting the page; `completeLoginFromRedirect()` finishes on\n * the way back.\n */\nexport async function startLogin(\n base: string,\n clientId: string,\n login: LoginOptions = {},\n flow: FlowOptions = {},\n): Promise<void> {\n const info = await discover(base);\n if (!info.AuthIssuer || !info.TokenExchangeEndpoint) {\n throw new Error(\n 'this instance is not configured for token-exchange auth (server needs CONFIGHUB_IDP_ISSUER)',\n );\n }\n const meta = await oidcMetadata(info.AuthIssuer);\n const verifier = randomString();\n const challenge = await sha256(verifier);\n const state = randomString(16);\n const redirectUri = callbackUri(flow);\n const pkce: PkceState = {\n verifier,\n state,\n clientId,\n tokenEndpoint: meta.token_endpoint,\n exchangeEndpoint: info.TokenExchangeEndpoint,\n redirectUri,\n returnTo: login.returnTo ?? currentPath(),\n silent: login.prompt === 'none',\n };\n sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));\n\n // The \"organization\" scope makes Keycloak emit the org claim the exchange resolves;\n // \"organization:<alias>\" selects one without prompting.\n const alias =\n login.organization === null\n ? undefined\n : (login.organization ?? rememberedOrganization(clientId));\n const orgScope = alias ? `organization:${alias}` : 'organization';\n const params: Record<string, string> = {\n response_type: 'code',\n client_id: clientId,\n redirect_uri: redirectUri,\n scope: `openid email profile ${orgScope}`,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n state,\n };\n if (login.prompt) params.prompt = login.prompt;\n\n const authURL = new URL(meta.authorization_endpoint);\n authURL.search = new URLSearchParams(params).toString();\n window.location.assign(authURL.toString());\n}\n\n// Memoize so React StrictMode's double-mount can't redeem the one-time code twice.\nlet pending: Promise<MintedSession | null> | null = null;\n\n/**\n * If the page is the IdP redirect (`?code=...`), exchange the code for an IdP token\n * and then exchange that for a minted ConfigHub token, and restore the URL the\n * login started from. Returns null on a normal load, and also when a `prompt=none`\n * attempt came back with `login_required` (the SSO session is gone; the caller\n * should offer an interactive login).\n */\nexport function completeLoginFromRedirect(): Promise<MintedSession | null> {\n if (!pending) pending = doCompleteLogin();\n return pending;\n}\n\nconst SILENT_FAILURES = new Set(['login_required', 'interaction_required', 'consent_required']);\n\nasync function doCompleteLogin(): Promise<MintedSession | null> {\n const params = new URLSearchParams(window.location.search);\n const code = params.get('code');\n const error = params.get('error');\n if (!code && !error) return null;\n\n const savedRaw = sessionStorage.getItem(PKCE_KEY);\n sessionStorage.removeItem(PKCE_KEY);\n const saved: PkceState | null = savedRaw ? JSON.parse(savedRaw) : null;\n\n // Put the URL back to where the user started before anything else can fail, so\n // neither the code nor an error string lingers in the address bar or history.\n history.replaceState({}, '', saved?.returnTo ?? callbackUri());\n\n if (error) {\n if (saved?.silent && SILENT_FAILURES.has(error)) return null;\n throw new Error(`IdP returned error: ${error} ${params.get('error_description') ?? ''}`);\n }\n if (!saved) throw new Error('no PKCE state; restart login');\n if (params.get('state') !== saved.state) throw new Error('state mismatch; aborting');\n\n // Exchange the authorization code for an IdP token (PKCE, public client).\n const tokenResp = await fetch(saved.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code: code!,\n redirect_uri: saved.redirectUri,\n client_id: saved.clientId,\n code_verifier: saved.verifier,\n }),\n });\n if (!tokenResp.ok) {\n throw new Error(`IdP token endpoint ${tokenResp.status}: ${await tokenResp.text()}`);\n }\n const idpToken = await tokenResp.json();\n\n // RFC 8693 token exchange against ConfigHub -> minted ConfigHub token.\n const minted = await exchange(saved.exchangeEndpoint, idpToken.access_token);\n const idpClaims = decodeJwtClaims(idpToken.access_token);\n rememberOrganization(saved.clientId, organizationAliasOf(idpClaims));\n return {\n ...minted,\n idpClaims,\n idToken: typeof idpToken.id_token === 'string' ? idpToken.id_token : undefined,\n };\n}\n\nasync function exchange(\n exchangeEndpoint: string,\n subjectToken: string,\n): Promise<Pick<MintedSession, 'accessToken' | 'organizationId'>> {\n const exResp = await fetch(exchangeEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: subjectToken,\n subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',\n }),\n });\n if (!exResp.ok) throw new Error(`/auth/exchange ${exResp.status}: ${await exResp.text()}`);\n const minted = await exResp.json();\n return { accessToken: minted.access_token, organizationId: minted.organization_id };\n}\n\n/**\n * Trade the current minted token for one scoped to another organization the user\n * belongs to (`POST {base}/auth/switch-organization`, bearer-authenticated). The\n * IdP session is untouched; only the ConfigHub token changes.\n */\nexport async function switchOrganization(\n base: string,\n accessToken: string,\n organizationId: string,\n): Promise<Pick<MintedSession, 'accessToken' | 'organizationId'>> {\n const r = await fetch(trimSlash(base) + '/auth/switch-organization', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({ organization_id: organizationId }),\n });\n if (!r.ok) throw new Error(`/auth/switch-organization ${r.status}: ${await r.text()}`);\n const minted = await r.json();\n return { accessToken: minted.access_token, organizationId: minted.organization_id };\n}\n\n/**\n * End the IdP session (RP-initiated logout) and land on `postLogoutRedirectUri`,\n * which must be registered for the client. Returns only by redirecting. If the\n * issuer publishes no end-session endpoint, navigates to the redirect URI directly.\n */\nexport async function endSession(\n base: string,\n clientId: string,\n idToken: string | undefined,\n postLogoutRedirectUri: string,\n): Promise<void> {\n const info = await discover(base);\n const meta = info.AuthIssuer ? await oidcMetadata(info.AuthIssuer) : undefined;\n if (!meta?.end_session_endpoint) {\n window.location.assign(postLogoutRedirectUri);\n return;\n }\n const params: Record<string, string> = {\n client_id: clientId,\n post_logout_redirect_uri: postLogoutRedirectUri,\n };\n if (idToken) params.id_token_hint = idToken;\n const url = new URL(meta.end_session_endpoint);\n url.search = new URLSearchParams(params).toString();\n window.location.assign(url.toString());\n}\n\n/** Discard the in-progress login memo (used on logout so a later login re-runs). */\nexport function resetPending(): void {\n pending = null;\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\n// A module-level holder for the current minted token, so non-React consumers can read\n// it. RTK Query's `prepareHeaders` (in @confighub/rtk-query) is not a hook and cannot\n// read React context, so it calls getAccessToken() instead. The provider keeps this in\n// sync with its React state.\nlet currentToken: string | undefined;\n\n/** @internal — called by the provider; not part of the public surface. */\nexport function setAccessToken(token: string | undefined): void {\n currentToken = token;\n}\n\n/**\n * The current minted ConfigHub token, or undefined when unauthenticated. Pass this as\n * the `getToken` for `@confighub/rtk-query`'s `configureConfigHub`, or read it anywhere\n * you need the token outside React.\n */\nexport function getAccessToken(): string | undefined {\n return currentToken;\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\nimport { createConfigHubClient, type ConfigHubClient } from '@confighub/api';\nimport {\n createContext,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport {\n callbackUri,\n completeLoginFromRedirect,\n endSession,\n isExpired,\n organizationAliasOf,\n rememberOrganization,\n resetPending,\n startLogin,\n switchOrganization as switchOrganizationCore,\n type LoginOptions,\n type MintedSession,\n} from './core';\nimport { setAccessToken } from './tokenStore';\n\nexport type AuthStatus = 'loading' | 'authenticated' | 'unauthenticated' | 'error';\n\nexport interface ConfigHubUser {\n organizationId: string;\n idpClaims: Record<string, unknown>;\n}\n\nexport interface LogoutOptions {\n /**\n * Also end the IdP session (RP-initiated logout), so the next login asks for\n * credentials instead of riding the SSO cookie. Redirects the page; the landing\n * URI must be registered for the client. Default: false, which only forgets the\n * token in this tab.\n */\n endSession?: boolean;\n /** Where to land after IdP logout. Defaults to the callback URI. */\n postLogoutRedirectUri?: string;\n}\n\nexport interface ConfigHubAuthContextValue {\n status: AuthStatus;\n user: ConfigHubUser | null;\n error: Error | null;\n /** Begin login: redirects the page to the IdP. */\n login: (options?: LoginOptions) => Promise<void>;\n /** Forget the session in this tab and, optionally, end the IdP session too. */\n logout: (options?: LogoutOptions) => Promise<void>;\n /**\n * Re-mint the ConfigHub token for another organization the user belongs to. The\n * IdP session is untouched. Rejects with the server's error if the user is not a\n * member; the current session stays as it was.\n */\n switchOrganization: (organizationId: string) => Promise<void>;\n /**\n * The ConfigHub token stopped working (a 401). Try to get a new one without any\n * UI: a `prompt=none` round trip through the IdP, for the organization the session\n * already had. Status goes to `loading` meanwhile, not `unauthenticated`, so an\n * app that auto-logs-in on `unauthenticated` does not race this with an\n * interactive login. If the IdP session is gone too, the page comes back\n * `unauthenticated`. Redirects the page.\n */\n reauthenticate: () => Promise<void>;\n /** Current bearer token, or undefined when unauthenticated. */\n getToken: () => string | undefined;\n /** A typed API client pre-wired with the current token. Stable across renders. */\n client: ConfigHubClient;\n}\n\nexport const ConfigHubAuthContext = createContext<ConfigHubAuthContextValue | null>(null);\n\nexport interface ConfigHubAuthProviderProps {\n /** Absolute base URL of the ConfigHub instance, e.g. `https://hub.confighub.com`. */\n baseUrl: string;\n /** This app's registered OAuth `client_id` (from `cub oauthclient create`). */\n clientId: string;\n /**\n * Same-origin path the IdP redirects back to; `{origin}{callbackPath}` is the\n * redirect URI to register. Defaults to `/`. Fixed on purpose: the page a user\n * starts login from travels in the PKCE state, not in the redirect URI.\n */\n callbackPath?: string;\n /**\n * `'session'` keeps the minted token in `sessionStorage` so a reload or an in-tab\n * navigation does not round-trip through the IdP. Tab-scoped and gone when the tab\n * closes. Default `'none'`: memory only, a reload starts unauthenticated.\n */\n persist?: 'none' | 'session';\n /**\n * What a 401 from the API means. `'login'` (default): the token is stale, try a\n * silent re-authentication (`prompt=none`) and fall back to unauthenticated if the\n * IdP session is gone too. `'logout'`: just drop the session.\n */\n onUnauthorized?: 'login' | 'logout';\n children: ReactNode;\n}\n\nconst SESSION_KEY = 'confighub_session';\n\nfunction readPersisted(): MintedSession | null {\n try {\n const raw = sessionStorage.getItem(SESSION_KEY);\n if (!raw) return null;\n const session: MintedSession = JSON.parse(raw);\n if (!session.accessToken || isExpired(session.accessToken)) {\n sessionStorage.removeItem(SESSION_KEY);\n return null;\n }\n return session;\n } catch {\n return null;\n }\n}\n\n/**\n * Runs the browser-direct auth flow and manages the token lifecycle. On mount it\n * completes a redirect if the page is the IdP callback, restores a persisted\n * session if there is one, and otherwise starts unauthenticated until `login()`\n * is called.\n */\nexport function ConfigHubAuthProvider({\n baseUrl,\n clientId,\n callbackPath,\n persist = 'none',\n onUnauthorized = 'login',\n children,\n}: ConfigHubAuthProviderProps): JSX.Element {\n const [status, setStatus] = useState<AuthStatus>('loading');\n const [user, setUser] = useState<ConfigHubUser | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // The session lives in a ref so getToken() reads the latest value synchronously\n // without re-creating the API client on every render.\n const sessionRef = useRef<MintedSession | undefined>(undefined);\n const flow = useMemo(() => ({ callbackPath }), [callbackPath]);\n\n const persistSession = useCallback(\n (session: MintedSession | undefined) => {\n if (persist !== 'session') return;\n try {\n if (session) sessionStorage.setItem(SESSION_KEY, JSON.stringify(session));\n else sessionStorage.removeItem(SESSION_KEY);\n } catch {\n // Storage unavailable (private mode, quota): memory-only for this tab.\n }\n },\n [persist],\n );\n\n const applySession = useCallback(\n (session: MintedSession) => {\n sessionRef.current = session;\n setAccessToken(session.accessToken); // keep the non-React accessor in sync (rtk-query)\n persistSession(session);\n setUser({ organizationId: session.organizationId, idpClaims: session.idpClaims });\n setError(null);\n setStatus('authenticated');\n },\n [persistSession],\n );\n\n const clearSession = useCallback(() => {\n sessionRef.current = undefined;\n setAccessToken(undefined);\n persistSession(undefined);\n resetPending();\n setUser(null);\n setStatus('unauthenticated');\n }, [persistSession]);\n\n useEffect(() => {\n let cancelled = false;\n completeLoginFromRedirect()\n .then((session) => {\n if (cancelled) return;\n if (session) return applySession(session);\n const persisted = persist === 'session' ? readPersisted() : null;\n if (persisted) return applySession(persisted);\n setStatus('unauthenticated');\n })\n .catch((e: unknown) => {\n if (cancelled) return;\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n });\n return () => {\n cancelled = true;\n };\n }, [applySession, persist]);\n\n const login = useCallback(\n async (options?: LoginOptions) => {\n setError(null);\n try {\n await startLogin(baseUrl, clientId, options, flow);\n } catch (e: unknown) {\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n }\n },\n [baseUrl, clientId, flow],\n );\n\n const logout = useCallback(\n async (options?: LogoutOptions) => {\n const idToken = sessionRef.current?.idToken;\n clearSession();\n if (options?.endSession) {\n await endSession(\n baseUrl,\n clientId,\n idToken,\n options.postLogoutRedirectUri ?? callbackUri(flow),\n );\n }\n },\n [baseUrl, clientId, clearSession, flow],\n );\n\n const switchOrganization = useCallback(\n async (organizationId: string) => {\n const current = sessionRef.current;\n if (!current) throw new Error('not authenticated');\n const minted = await switchOrganizationCore(baseUrl, current.accessToken, organizationId);\n // The session's IdP claims still name the previous org, so its alias must not\n // be remembered as the default for the next login.\n rememberOrganization(clientId, undefined);\n applySession({ ...current, ...minted });\n },\n [applySession, baseUrl, clientId],\n );\n\n const getToken = useCallback(() => sessionRef.current?.accessToken, []);\n\n const reauthenticate = useCallback(async () => {\n const organization = organizationAliasOf(sessionRef.current?.idpClaims ?? {});\n // Forget the token but stay 'loading': the page is about to navigate away,\n // and 'unauthenticated' would invite an interactive login in the meantime.\n sessionRef.current = undefined;\n setAccessToken(undefined);\n persistSession(undefined);\n resetPending();\n setStatus('loading');\n try {\n await startLogin(baseUrl, clientId, { prompt: 'none', organization }, flow);\n } catch (e: unknown) {\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n }\n }, [baseUrl, clientId, flow, persistSession]);\n\n // A 401 means the minted token no longer works. Silent re-auth keeps the user's\n // place if the IdP session is still alive; otherwise the page comes back\n // unauthenticated and the app offers a real login.\n const handleUnauthorized = useCallback(() => {\n if (!sessionRef.current) return;\n if (onUnauthorized === 'login') void reauthenticate();\n else clearSession();\n }, [clearSession, reauthenticate, onUnauthorized]);\n\n // One client for the provider's lifetime. getToken reads the session ref.\n const client = useMemo(\n () => createConfigHubClient({ baseUrl, getToken, onUnauthorized: handleUnauthorized }),\n [baseUrl, getToken, handleUnauthorized],\n );\n\n const value = useMemo<ConfigHubAuthContextValue>(\n () => ({\n status,\n user,\n error,\n login,\n logout,\n switchOrganization,\n reauthenticate,\n getToken,\n client,\n }),\n [status, user, error, login, logout, switchOrganization, reauthenticate, getToken, client],\n );\n\n return (\n <ConfigHubAuthContext.Provider value={value}>{children}</ConfigHubAuthContext.Provider>\n );\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\nimport type { ConfigHubClient } from '@confighub/api';\nimport { useContext } from 'react';\nimport { ConfigHubAuthContext, type ConfigHubAuthContextValue } from './provider';\n\n/**\n * Access the ConfigHub auth state and actions. Must be called under a\n * `<ConfigHubAuthProvider>`.\n *\n * ```ts\n * const { status, user, login, logout } = useAuth();\n * ```\n */\nexport function useAuth(): ConfigHubAuthContextValue {\n const ctx = useContext(ConfigHubAuthContext);\n if (!ctx) {\n throw new Error('useAuth must be used within a <ConfigHubAuthProvider>');\n }\n return ctx;\n}\n\n/**\n * The typed ConfigHub API client, pre-wired with the current token. This is the\n * seam between `@confighub/react-auth` and `@confighub/api`: you never pass a\n * token by hand.\n *\n * ```ts\n * const api = useConfigHub();\n * const { data } = await api.GET('/space/{space_id}/unit', { params: { path: { space_id } } });\n * ```\n */\nexport function useConfigHub(): ConfigHubClient {\n return useAuth().client;\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -27,11 +27,18 @@ interface LoginOptions {
27
27
  */
28
28
  returnTo?: string;
29
29
  /**
30
- * Keycloak organization alias to sign in to, sent as the `organization:<alias>`
31
- * scope. Without it Keycloak prompts a multi-org user to pick one (or uses the
32
- * organization already selected in the SSO session).
30
+ * Which organization to sign in to, as the Keycloak organization alias sent in
31
+ * the `organization:<alias>` scope.
32
+ *
33
+ * - a string: that organization, no prompt;
34
+ * - `undefined` (default): the organization of the last successful login in this
35
+ * browser, remembered per client in `localStorage`, so a new tab or a login after
36
+ * logout lands in the same organization without a prompt; with nothing
37
+ * remembered, Keycloak decides (prompt for a multi-org user, or the org matching
38
+ * the email domain on a fresh authentication);
39
+ * - `null`: no hint on purpose, so Keycloak prompts. This is "switch organization".
33
40
  */
34
- organization?: string;
41
+ organization?: string | null;
35
42
  /**
36
43
  * `'none'` asks the IdP to re-authenticate without any UI, failing with
37
44
  * `login_required` if the SSO session is gone -- the way to refresh an expired
@@ -47,6 +54,13 @@ interface FlowOptions {
47
54
  */
48
55
  callbackPath?: string;
49
56
  }
57
+ /** The organization alias of the last successful login for this client, if any. */
58
+ declare function rememberedOrganization(clientId: string): string | undefined;
59
+ /**
60
+ * The alias in an IdP token's `organization` claim (`{ "<alias>": { id } }`), or
61
+ * undefined when the claim is absent or names more than one organization.
62
+ */
63
+ declare function organizationAliasOf(idpClaims: Record<string, unknown>): string | undefined;
50
64
  /** The fixed callback URI: the page origin plus the configured callback path. */
51
65
  declare const callbackUri: (opts?: FlowOptions) => string;
52
66
  /** Decode a JWT's claims without verifying it. Returns {} for anything malformed. */
@@ -160,4 +174,4 @@ declare function useConfigHub(): ConfigHubClient;
160
174
  */
161
175
  declare function getAccessToken(): string | undefined;
162
176
 
163
- export { type AuthStatus, ConfigHubAuthContext, type ConfigHubAuthContextValue, ConfigHubAuthProvider, type ConfigHubAuthProviderProps, type ConfigHubUser, type Discovery, type FlowOptions, type LoginOptions, type LogoutOptions, type MintedSession, callbackUri, decodeJwtClaims, getAccessToken, isExpired, useAuth, useConfigHub };
177
+ export { type AuthStatus, ConfigHubAuthContext, type ConfigHubAuthContextValue, ConfigHubAuthProvider, type ConfigHubAuthProviderProps, type ConfigHubUser, type Discovery, type FlowOptions, type LoginOptions, type LogoutOptions, type MintedSession, callbackUri, decodeJwtClaims, getAccessToken, isExpired, organizationAliasOf, rememberedOrganization, useAuth, useConfigHub };
package/dist/index.d.ts CHANGED
@@ -27,11 +27,18 @@ interface LoginOptions {
27
27
  */
28
28
  returnTo?: string;
29
29
  /**
30
- * Keycloak organization alias to sign in to, sent as the `organization:<alias>`
31
- * scope. Without it Keycloak prompts a multi-org user to pick one (or uses the
32
- * organization already selected in the SSO session).
30
+ * Which organization to sign in to, as the Keycloak organization alias sent in
31
+ * the `organization:<alias>` scope.
32
+ *
33
+ * - a string: that organization, no prompt;
34
+ * - `undefined` (default): the organization of the last successful login in this
35
+ * browser, remembered per client in `localStorage`, so a new tab or a login after
36
+ * logout lands in the same organization without a prompt; with nothing
37
+ * remembered, Keycloak decides (prompt for a multi-org user, or the org matching
38
+ * the email domain on a fresh authentication);
39
+ * - `null`: no hint on purpose, so Keycloak prompts. This is "switch organization".
33
40
  */
34
- organization?: string;
41
+ organization?: string | null;
35
42
  /**
36
43
  * `'none'` asks the IdP to re-authenticate without any UI, failing with
37
44
  * `login_required` if the SSO session is gone -- the way to refresh an expired
@@ -47,6 +54,13 @@ interface FlowOptions {
47
54
  */
48
55
  callbackPath?: string;
49
56
  }
57
+ /** The organization alias of the last successful login for this client, if any. */
58
+ declare function rememberedOrganization(clientId: string): string | undefined;
59
+ /**
60
+ * The alias in an IdP token's `organization` claim (`{ "<alias>": { id } }`), or
61
+ * undefined when the claim is absent or names more than one organization.
62
+ */
63
+ declare function organizationAliasOf(idpClaims: Record<string, unknown>): string | undefined;
50
64
  /** The fixed callback URI: the page origin plus the configured callback path. */
51
65
  declare const callbackUri: (opts?: FlowOptions) => string;
52
66
  /** Decode a JWT's claims without verifying it. Returns {} for anything malformed. */
@@ -160,4 +174,4 @@ declare function useConfigHub(): ConfigHubClient;
160
174
  */
161
175
  declare function getAccessToken(): string | undefined;
162
176
 
163
- export { type AuthStatus, ConfigHubAuthContext, type ConfigHubAuthContextValue, ConfigHubAuthProvider, type ConfigHubAuthProviderProps, type ConfigHubUser, type Discovery, type FlowOptions, type LoginOptions, type LogoutOptions, type MintedSession, callbackUri, decodeJwtClaims, getAccessToken, isExpired, useAuth, useConfigHub };
177
+ export { type AuthStatus, ConfigHubAuthContext, type ConfigHubAuthContextValue, ConfigHubAuthProvider, type ConfigHubAuthProviderProps, type ConfigHubUser, type Discovery, type FlowOptions, type LoginOptions, type LogoutOptions, type MintedSession, callbackUri, decodeJwtClaims, getAccessToken, isExpired, organizationAliasOf, rememberedOrganization, useAuth, useConfigHub };
package/dist/index.js CHANGED
@@ -6,6 +6,28 @@ import { jsx } from 'react/jsx-runtime';
6
6
 
7
7
  // src/core.ts
8
8
  var PKCE_KEY = "confighub_pkce";
9
+ var LAST_ORG_KEY = "confighub_last_org";
10
+ var lastOrgKey = (clientId) => `${LAST_ORG_KEY}:${clientId}`;
11
+ function rememberedOrganization(clientId) {
12
+ try {
13
+ return localStorage.getItem(lastOrgKey(clientId)) ?? void 0;
14
+ } catch {
15
+ return void 0;
16
+ }
17
+ }
18
+ function rememberOrganization(clientId, alias) {
19
+ try {
20
+ if (alias) localStorage.setItem(lastOrgKey(clientId), alias);
21
+ else localStorage.removeItem(lastOrgKey(clientId));
22
+ } catch {
23
+ }
24
+ }
25
+ function organizationAliasOf(idpClaims) {
26
+ const org = idpClaims.organization;
27
+ if (!org || typeof org !== "object") return void 0;
28
+ const aliases = Object.keys(org);
29
+ return aliases.length === 1 ? aliases[0] : void 0;
30
+ }
9
31
  var trimSlash = (s) => s.replace(/\/+$/, "");
10
32
  var callbackUri = (opts) => window.location.origin + (opts?.callbackPath ?? "/");
11
33
  var currentPath = () => window.location.pathname + window.location.search + window.location.hash;
@@ -61,7 +83,8 @@ async function startLogin(base, clientId, login = {}, flow = {}) {
61
83
  silent: login.prompt === "none"
62
84
  };
63
85
  sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));
64
- const orgScope = login.organization ? `organization:${login.organization}` : "organization";
86
+ const alias = login.organization === null ? void 0 : login.organization ?? rememberedOrganization(clientId);
87
+ const orgScope = alias ? `organization:${alias}` : "organization";
65
88
  const params = {
66
89
  response_type: "code",
67
90
  client_id: clientId,
@@ -113,9 +136,11 @@ async function doCompleteLogin() {
113
136
  }
114
137
  const idpToken = await tokenResp.json();
115
138
  const minted = await exchange(saved.exchangeEndpoint, idpToken.access_token);
139
+ const idpClaims = decodeJwtClaims(idpToken.access_token);
140
+ rememberOrganization(saved.clientId, organizationAliasOf(idpClaims));
116
141
  return {
117
142
  ...minted,
118
- idpClaims: decodeJwtClaims(idpToken.access_token),
143
+ idpClaims,
119
144
  idToken: typeof idpToken.id_token === "string" ? idpToken.id_token : void 0
120
145
  };
121
146
  }
@@ -176,12 +201,6 @@ function getAccessToken() {
176
201
  }
177
202
  var ConfigHubAuthContext = createContext(null);
178
203
  var SESSION_KEY = "confighub_session";
179
- function organizationAlias(session) {
180
- const org = session?.idpClaims.organization;
181
- if (!org || typeof org !== "object") return void 0;
182
- const aliases = Object.keys(org);
183
- return aliases.length === 1 ? aliases[0] : void 0;
184
- }
185
204
  function readPersisted() {
186
205
  try {
187
206
  const raw = sessionStorage.getItem(SESSION_KEY);
@@ -288,13 +307,14 @@ function ConfigHubAuthProvider({
288
307
  const current = sessionRef.current;
289
308
  if (!current) throw new Error("not authenticated");
290
309
  const minted = await switchOrganization(baseUrl, current.accessToken, organizationId);
310
+ rememberOrganization(clientId, void 0);
291
311
  applySession({ ...current, ...minted });
292
312
  },
293
- [applySession, baseUrl]
313
+ [applySession, baseUrl, clientId]
294
314
  );
295
315
  const getToken = useCallback(() => sessionRef.current?.accessToken, []);
296
316
  const reauthenticate = useCallback(async () => {
297
- const organization = organizationAlias(sessionRef.current);
317
+ const organization = organizationAliasOf(sessionRef.current?.idpClaims ?? {});
298
318
  sessionRef.current = void 0;
299
319
  setAccessToken(void 0);
300
320
  persistSession(void 0);
@@ -343,6 +363,6 @@ function useConfigHub() {
343
363
  return useAuth().client;
344
364
  }
345
365
 
346
- export { ConfigHubAuthContext, ConfigHubAuthProvider, callbackUri, decodeJwtClaims, getAccessToken, isExpired, useAuth, useConfigHub };
366
+ export { ConfigHubAuthContext, ConfigHubAuthProvider, callbackUri, decodeJwtClaims, getAccessToken, isExpired, organizationAliasOf, rememberedOrganization, useAuth, useConfigHub };
347
367
  //# sourceMappingURL=index.js.map
348
368
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core.ts","../src/tokenStore.ts","../src/provider.tsx","../src/hooks.ts"],"names":["switchOrganization"],"mappings":";;;;;;;AA+EA,IAAM,QAAA,GAAW,gBAAA;AAEjB,IAAM,YAAY,CAAC,CAAA,KAAsB,CAAA,CAAE,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAGtD,IAAM,cAAc,CAAC,IAAA,KAC1B,OAAO,QAAA,CAAS,MAAA,IAAU,MAAM,YAAA,IAAgB,GAAA;AAElD,IAAM,WAAA,GAAc,MAClB,MAAA,CAAO,QAAA,CAAS,WAAW,MAAA,CAAO,QAAA,CAAS,MAAA,GAAS,MAAA,CAAO,QAAA,CAAS,IAAA;AAEtE,IAAM,MAAA,GAAS,CAAC,GAAA,KACd,IAAA,CAAK,OAAO,YAAA,CAAa,GAAG,IAAI,UAAA,CAAW,GAAG,CAAC,CAAC,CAAA,CAC7C,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAClB,OAAA,CAAQ,OAAO,GAAG,CAAA,CAClB,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AAEtB,IAAM,YAAA,GAAe,CAAC,CAAA,GAAI,EAAA,KACxB,MAAA,CAAO,MAAA,CAAO,eAAA,CAAgB,IAAI,UAAA,CAAW,CAAC,CAAC,CAAA,CAAE,MAAM,CAAA;AAEzD,eAAe,OAAO,CAAA,EAA4B;AAChD,EAAA,OAAO,MAAA,CAAO,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,CAAC,CAAC,CAAC,CAAA;AAClF;AAGO,SAAS,gBAAgB,KAAA,EAAwC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OAAA,GAAqC;AACnD,EAAA,MAAM,GAAA,GAAM,WAAW,oBAAoB,CAAA;AAC3C,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,MAAM,uDAAuD,CAAA;AAAA,EACzE;AACA,EAAA,OAAO,GAAA;AACT;AAYO,SAAS,YAAA,GAAgC;AAC9C,EAAA,OAAO,SAAQ,CAAE,MAAA;AACnB","file":"index.js","sourcesContent":["// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n//\n// Framework-neutral browser-auth engine for ConfigHub. Productionized from the\n// reference harness `test/browser-auth/src/confighubAuth.ts` in the ConfigHub\n// monorepo, which is validated end to end against staging and prod.\n//\n// Flow (design: third-party-browser-app-auth.md §6):\n// GET {base}/api/info -> discovery { AuthIssuer, TokenExchangeEndpoint }\n// OIDC discovery on AuthIssuer -> authorize/token/end_session endpoints\n// PKCE authorize + code->token -> IdP token\n// POST {TokenExchangeEndpoint} (8693) -> minted ConfigHub token\n//\n// The minted token then rides `Authorization: Bearer` against `/api`. The flow is\n// edition-agnostic: `AuthIssuer` is whatever discovery names (ConfigHub's bundled\n// Keycloak for Cloud, the org's own IdP for Enterprise), so the same code runs\n// against both. Tokens are held by the caller; only the transient PKCE state is\n// parked in sessionStorage across the authorize redirect.\n\nexport interface Discovery {\n AuthIssuer?: string;\n TokenExchangeEndpoint?: string;\n TokenExchangeAudience?: string;\n}\n\nexport interface MintedSession {\n accessToken: string;\n organizationId: string;\n /** Claims of the validated IdP token (owning-org, audience, organization shape). */\n idpClaims: Record<string, unknown>;\n /**\n * The IdP's ID token, kept only so logout can pass it as `id_token_hint` to the\n * end-session endpoint. Absent for sessions that did not come from an OIDC login.\n */\n idToken?: string;\n}\n\nexport interface LoginOptions {\n /**\n * Where to land after login, as a same-origin path (`/space/x?tab=units`). Carried\n * through the authorize round trip in the PKCE state, never in the redirect URI:\n * OAuth clients register exact redirect URIs, so the URI itself must not vary with\n * the page the user started from. Defaults to the current path and query.\n */\n returnTo?: string;\n /**\n * Keycloak organization alias to sign in to, sent as the `organization:<alias>`\n * scope. Without it Keycloak prompts a multi-org user to pick one (or uses the\n * organization already selected in the SSO session).\n */\n organization?: string;\n /**\n * `'none'` asks the IdP to re-authenticate without any UI, failing with\n * `login_required` if the SSO session is gone -- the way to refresh an expired\n * ConfigHub token when the user is still signed in at the IdP. `'login'` forces the\n * login form even with a live SSO session.\n */\n prompt?: 'none' | 'login';\n}\n\nexport interface FlowOptions {\n /**\n * Same-origin path the IdP redirects back to, and therefore the redirect URI to\n * register for the client: `{origin}{callbackPath}`. Defaults to `/`.\n */\n callbackPath?: string;\n}\n\ninterface PkceState {\n verifier: string;\n state: string;\n clientId: string;\n tokenEndpoint: string;\n exchangeEndpoint: string;\n redirectUri: string;\n returnTo: string;\n silent: boolean;\n}\n\nconst PKCE_KEY = 'confighub_pkce';\n\nconst trimSlash = (s: string): string => s.replace(/\\/+$/, '');\n\n/** The fixed callback URI: the page origin plus the configured callback path. */\nexport const callbackUri = (opts?: FlowOptions): string =>\n window.location.origin + (opts?.callbackPath ?? '/');\n\nconst currentPath = (): string =>\n window.location.pathname + window.location.search + window.location.hash;\n\nconst b64url = (buf: ArrayBuffer): string =>\n btoa(String.fromCharCode(...new Uint8Array(buf)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n\nconst randomString = (n = 64): string =>\n b64url(crypto.getRandomValues(new Uint8Array(n)).buffer);\n\nasync function sha256(s: string): Promise<string> {\n return b64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)));\n}\n\n/** Decode a JWT's claims without verifying it. Returns {} for anything malformed. */\nexport function decodeJwtClaims(token: string): Record<string, unknown> {\n const part = token.split('.')[1];\n if (!part) return {};\n try {\n return JSON.parse(atob(part.replace(/-/g, '+').replace(/_/g, '/')));\n } catch {\n return {};\n }\n}\n\n/** Whether a JWT's `exp` is in the past (with a small skew allowance). */\nexport function isExpired(token: string, skewSeconds = 30): boolean {\n const exp = decodeJwtClaims(token).exp;\n if (typeof exp !== 'number') return false;\n return exp * 1000 <= Date.now() + skewSeconds * 1000;\n}\n\nexport async function discover(base: string): Promise<Discovery> {\n const r = await fetch(trimSlash(base) + '/api/info');\n if (!r.ok) throw new Error('/api/info failed: ' + r.status);\n return r.json();\n}\n\ninterface OidcMetadata {\n authorization_endpoint: string;\n token_endpoint: string;\n end_session_endpoint?: string;\n}\n\nasync function oidcMetadata(issuer: string): Promise<OidcMetadata> {\n const r = await fetch(trimSlash(issuer) + '/.well-known/openid-configuration');\n if (!r.ok) throw new Error('OIDC discovery failed: ' + r.status);\n return r.json();\n}\n\n/**\n * Discover, build a PKCE request, and navigate to the IdP authorize endpoint.\n * Returns only by redirecting the page; `completeLoginFromRedirect()` finishes on\n * the way back.\n */\nexport async function startLogin(\n base: string,\n clientId: string,\n login: LoginOptions = {},\n flow: FlowOptions = {},\n): Promise<void> {\n const info = await discover(base);\n if (!info.AuthIssuer || !info.TokenExchangeEndpoint) {\n throw new Error(\n 'this instance is not configured for token-exchange auth (server needs CONFIGHUB_IDP_ISSUER)',\n );\n }\n const meta = await oidcMetadata(info.AuthIssuer);\n const verifier = randomString();\n const challenge = await sha256(verifier);\n const state = randomString(16);\n const redirectUri = callbackUri(flow);\n const pkce: PkceState = {\n verifier,\n state,\n clientId,\n tokenEndpoint: meta.token_endpoint,\n exchangeEndpoint: info.TokenExchangeEndpoint,\n redirectUri,\n returnTo: login.returnTo ?? currentPath(),\n silent: login.prompt === 'none',\n };\n sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));\n\n // The \"organization\" scope makes Keycloak emit the org claim the exchange resolves;\n // \"organization:<alias>\" selects one without prompting.\n const orgScope = login.organization ? `organization:${login.organization}` : 'organization';\n const params: Record<string, string> = {\n response_type: 'code',\n client_id: clientId,\n redirect_uri: redirectUri,\n scope: `openid email profile ${orgScope}`,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n state,\n };\n if (login.prompt) params.prompt = login.prompt;\n\n const authURL = new URL(meta.authorization_endpoint);\n authURL.search = new URLSearchParams(params).toString();\n window.location.assign(authURL.toString());\n}\n\n// Memoize so React StrictMode's double-mount can't redeem the one-time code twice.\nlet pending: Promise<MintedSession | null> | null = null;\n\n/**\n * If the page is the IdP redirect (`?code=...`), exchange the code for an IdP token\n * and then exchange that for a minted ConfigHub token, and restore the URL the\n * login started from. Returns null on a normal load, and also when a `prompt=none`\n * attempt came back with `login_required` (the SSO session is gone; the caller\n * should offer an interactive login).\n */\nexport function completeLoginFromRedirect(): Promise<MintedSession | null> {\n if (!pending) pending = doCompleteLogin();\n return pending;\n}\n\nconst SILENT_FAILURES = new Set(['login_required', 'interaction_required', 'consent_required']);\n\nasync function doCompleteLogin(): Promise<MintedSession | null> {\n const params = new URLSearchParams(window.location.search);\n const code = params.get('code');\n const error = params.get('error');\n if (!code && !error) return null;\n\n const savedRaw = sessionStorage.getItem(PKCE_KEY);\n sessionStorage.removeItem(PKCE_KEY);\n const saved: PkceState | null = savedRaw ? JSON.parse(savedRaw) : null;\n\n // Put the URL back to where the user started before anything else can fail, so\n // neither the code nor an error string lingers in the address bar or history.\n history.replaceState({}, '', saved?.returnTo ?? callbackUri());\n\n if (error) {\n if (saved?.silent && SILENT_FAILURES.has(error)) return null;\n throw new Error(`IdP returned error: ${error} ${params.get('error_description') ?? ''}`);\n }\n if (!saved) throw new Error('no PKCE state; restart login');\n if (params.get('state') !== saved.state) throw new Error('state mismatch; aborting');\n\n // Exchange the authorization code for an IdP token (PKCE, public client).\n const tokenResp = await fetch(saved.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code: code!,\n redirect_uri: saved.redirectUri,\n client_id: saved.clientId,\n code_verifier: saved.verifier,\n }),\n });\n if (!tokenResp.ok) {\n throw new Error(`IdP token endpoint ${tokenResp.status}: ${await tokenResp.text()}`);\n }\n const idpToken = await tokenResp.json();\n\n // RFC 8693 token exchange against ConfigHub -> minted ConfigHub token.\n const minted = await exchange(saved.exchangeEndpoint, idpToken.access_token);\n return {\n ...minted,\n idpClaims: decodeJwtClaims(idpToken.access_token),\n idToken: typeof idpToken.id_token === 'string' ? idpToken.id_token : undefined,\n };\n}\n\nasync function exchange(\n exchangeEndpoint: string,\n subjectToken: string,\n): Promise<Pick<MintedSession, 'accessToken' | 'organizationId'>> {\n const exResp = await fetch(exchangeEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: subjectToken,\n subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',\n }),\n });\n if (!exResp.ok) throw new Error(`/auth/exchange ${exResp.status}: ${await exResp.text()}`);\n const minted = await exResp.json();\n return { accessToken: minted.access_token, organizationId: minted.organization_id };\n}\n\n/**\n * Trade the current minted token for one scoped to another organization the user\n * belongs to (`POST {base}/auth/switch-organization`, bearer-authenticated). The\n * IdP session is untouched; only the ConfigHub token changes.\n */\nexport async function switchOrganization(\n base: string,\n accessToken: string,\n organizationId: string,\n): Promise<Pick<MintedSession, 'accessToken' | 'organizationId'>> {\n const r = await fetch(trimSlash(base) + '/auth/switch-organization', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({ organization_id: organizationId }),\n });\n if (!r.ok) throw new Error(`/auth/switch-organization ${r.status}: ${await r.text()}`);\n const minted = await r.json();\n return { accessToken: minted.access_token, organizationId: minted.organization_id };\n}\n\n/**\n * End the IdP session (RP-initiated logout) and land on `postLogoutRedirectUri`,\n * which must be registered for the client. Returns only by redirecting. If the\n * issuer publishes no end-session endpoint, navigates to the redirect URI directly.\n */\nexport async function endSession(\n base: string,\n clientId: string,\n idToken: string | undefined,\n postLogoutRedirectUri: string,\n): Promise<void> {\n const info = await discover(base);\n const meta = info.AuthIssuer ? await oidcMetadata(info.AuthIssuer) : undefined;\n if (!meta?.end_session_endpoint) {\n window.location.assign(postLogoutRedirectUri);\n return;\n }\n const params: Record<string, string> = {\n client_id: clientId,\n post_logout_redirect_uri: postLogoutRedirectUri,\n };\n if (idToken) params.id_token_hint = idToken;\n const url = new URL(meta.end_session_endpoint);\n url.search = new URLSearchParams(params).toString();\n window.location.assign(url.toString());\n}\n\n/** Discard the in-progress login memo (used on logout so a later login re-runs). */\nexport function resetPending(): void {\n pending = null;\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\n// A module-level holder for the current minted token, so non-React consumers can read\n// it. RTK Query's `prepareHeaders` (in @confighub/rtk-query) is not a hook and cannot\n// read React context, so it calls getAccessToken() instead. The provider keeps this in\n// sync with its React state.\nlet currentToken: string | undefined;\n\n/** @internal — called by the provider; not part of the public surface. */\nexport function setAccessToken(token: string | undefined): void {\n currentToken = token;\n}\n\n/**\n * The current minted ConfigHub token, or undefined when unauthenticated. Pass this as\n * the `getToken` for `@confighub/rtk-query`'s `configureConfigHub`, or read it anywhere\n * you need the token outside React.\n */\nexport function getAccessToken(): string | undefined {\n return currentToken;\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\nimport { createConfigHubClient, type ConfigHubClient } from '@confighub/api';\nimport {\n createContext,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport {\n callbackUri,\n completeLoginFromRedirect,\n endSession,\n isExpired,\n resetPending,\n startLogin,\n switchOrganization as switchOrganizationCore,\n type LoginOptions,\n type MintedSession,\n} from './core';\nimport { setAccessToken } from './tokenStore';\n\nexport type AuthStatus = 'loading' | 'authenticated' | 'unauthenticated' | 'error';\n\nexport interface ConfigHubUser {\n organizationId: string;\n idpClaims: Record<string, unknown>;\n}\n\nexport interface LogoutOptions {\n /**\n * Also end the IdP session (RP-initiated logout), so the next login asks for\n * credentials instead of riding the SSO cookie. Redirects the page; the landing\n * URI must be registered for the client. Default: false, which only forgets the\n * token in this tab.\n */\n endSession?: boolean;\n /** Where to land after IdP logout. Defaults to the callback URI. */\n postLogoutRedirectUri?: string;\n}\n\nexport interface ConfigHubAuthContextValue {\n status: AuthStatus;\n user: ConfigHubUser | null;\n error: Error | null;\n /** Begin login: redirects the page to the IdP. */\n login: (options?: LoginOptions) => Promise<void>;\n /** Forget the session in this tab and, optionally, end the IdP session too. */\n logout: (options?: LogoutOptions) => Promise<void>;\n /**\n * Re-mint the ConfigHub token for another organization the user belongs to. The\n * IdP session is untouched. Rejects with the server's error if the user is not a\n * member; the current session stays as it was.\n */\n switchOrganization: (organizationId: string) => Promise<void>;\n /**\n * The ConfigHub token stopped working (a 401). Try to get a new one without any\n * UI: a `prompt=none` round trip through the IdP, for the organization the session\n * already had. Status goes to `loading` meanwhile, not `unauthenticated`, so an\n * app that auto-logs-in on `unauthenticated` does not race this with an\n * interactive login. If the IdP session is gone too, the page comes back\n * `unauthenticated`. Redirects the page.\n */\n reauthenticate: () => Promise<void>;\n /** Current bearer token, or undefined when unauthenticated. */\n getToken: () => string | undefined;\n /** A typed API client pre-wired with the current token. Stable across renders. */\n client: ConfigHubClient;\n}\n\nexport const ConfigHubAuthContext = createContext<ConfigHubAuthContextValue | null>(null);\n\nexport interface ConfigHubAuthProviderProps {\n /** Absolute base URL of the ConfigHub instance, e.g. `https://hub.confighub.com`. */\n baseUrl: string;\n /** This app's registered OAuth `client_id` (from `cub oauthclient create`). */\n clientId: string;\n /**\n * Same-origin path the IdP redirects back to; `{origin}{callbackPath}` is the\n * redirect URI to register. Defaults to `/`. Fixed on purpose: the page a user\n * starts login from travels in the PKCE state, not in the redirect URI.\n */\n callbackPath?: string;\n /**\n * `'session'` keeps the minted token in `sessionStorage` so a reload or an in-tab\n * navigation does not round-trip through the IdP. Tab-scoped and gone when the tab\n * closes. Default `'none'`: memory only, a reload starts unauthenticated.\n */\n persist?: 'none' | 'session';\n /**\n * What a 401 from the API means. `'login'` (default): the token is stale, try a\n * silent re-authentication (`prompt=none`) and fall back to unauthenticated if the\n * IdP session is gone too. `'logout'`: just drop the session.\n */\n onUnauthorized?: 'login' | 'logout';\n children: ReactNode;\n}\n\nconst SESSION_KEY = 'confighub_session';\n\n/**\n * The Keycloak organization alias of the session, from the IdP token's\n * `organization` claim (`{ \"<alias>\": { id } }`), for re-selecting the same org\n * without a prompt. Undefined when the claim is absent or not in that shape.\n */\nfunction organizationAlias(session: MintedSession | undefined): string | undefined {\n const org = session?.idpClaims.organization;\n if (!org || typeof org !== 'object') return undefined;\n const aliases = Object.keys(org as Record<string, unknown>);\n return aliases.length === 1 ? aliases[0] : undefined;\n}\n\nfunction readPersisted(): MintedSession | null {\n try {\n const raw = sessionStorage.getItem(SESSION_KEY);\n if (!raw) return null;\n const session: MintedSession = JSON.parse(raw);\n if (!session.accessToken || isExpired(session.accessToken)) {\n sessionStorage.removeItem(SESSION_KEY);\n return null;\n }\n return session;\n } catch {\n return null;\n }\n}\n\n/**\n * Runs the browser-direct auth flow and manages the token lifecycle. On mount it\n * completes a redirect if the page is the IdP callback, restores a persisted\n * session if there is one, and otherwise starts unauthenticated until `login()`\n * is called.\n */\nexport function ConfigHubAuthProvider({\n baseUrl,\n clientId,\n callbackPath,\n persist = 'none',\n onUnauthorized = 'login',\n children,\n}: ConfigHubAuthProviderProps): JSX.Element {\n const [status, setStatus] = useState<AuthStatus>('loading');\n const [user, setUser] = useState<ConfigHubUser | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // The session lives in a ref so getToken() reads the latest value synchronously\n // without re-creating the API client on every render.\n const sessionRef = useRef<MintedSession | undefined>(undefined);\n const flow = useMemo(() => ({ callbackPath }), [callbackPath]);\n\n const persistSession = useCallback(\n (session: MintedSession | undefined) => {\n if (persist !== 'session') return;\n try {\n if (session) sessionStorage.setItem(SESSION_KEY, JSON.stringify(session));\n else sessionStorage.removeItem(SESSION_KEY);\n } catch {\n // Storage unavailable (private mode, quota): memory-only for this tab.\n }\n },\n [persist],\n );\n\n const applySession = useCallback(\n (session: MintedSession) => {\n sessionRef.current = session;\n setAccessToken(session.accessToken); // keep the non-React accessor in sync (rtk-query)\n persistSession(session);\n setUser({ organizationId: session.organizationId, idpClaims: session.idpClaims });\n setError(null);\n setStatus('authenticated');\n },\n [persistSession],\n );\n\n const clearSession = useCallback(() => {\n sessionRef.current = undefined;\n setAccessToken(undefined);\n persistSession(undefined);\n resetPending();\n setUser(null);\n setStatus('unauthenticated');\n }, [persistSession]);\n\n useEffect(() => {\n let cancelled = false;\n completeLoginFromRedirect()\n .then((session) => {\n if (cancelled) return;\n if (session) return applySession(session);\n const persisted = persist === 'session' ? readPersisted() : null;\n if (persisted) return applySession(persisted);\n setStatus('unauthenticated');\n })\n .catch((e: unknown) => {\n if (cancelled) return;\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n });\n return () => {\n cancelled = true;\n };\n }, [applySession, persist]);\n\n const login = useCallback(\n async (options?: LoginOptions) => {\n setError(null);\n try {\n await startLogin(baseUrl, clientId, options, flow);\n } catch (e: unknown) {\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n }\n },\n [baseUrl, clientId, flow],\n );\n\n const logout = useCallback(\n async (options?: LogoutOptions) => {\n const idToken = sessionRef.current?.idToken;\n clearSession();\n if (options?.endSession) {\n await endSession(\n baseUrl,\n clientId,\n idToken,\n options.postLogoutRedirectUri ?? callbackUri(flow),\n );\n }\n },\n [baseUrl, clientId, clearSession, flow],\n );\n\n const switchOrganization = useCallback(\n async (organizationId: string) => {\n const current = sessionRef.current;\n if (!current) throw new Error('not authenticated');\n const minted = await switchOrganizationCore(baseUrl, current.accessToken, organizationId);\n applySession({ ...current, ...minted });\n },\n [applySession, baseUrl],\n );\n\n const getToken = useCallback(() => sessionRef.current?.accessToken, []);\n\n const reauthenticate = useCallback(async () => {\n const organization = organizationAlias(sessionRef.current);\n // Forget the token but stay 'loading': the page is about to navigate away,\n // and 'unauthenticated' would invite an interactive login in the meantime.\n sessionRef.current = undefined;\n setAccessToken(undefined);\n persistSession(undefined);\n resetPending();\n setStatus('loading');\n try {\n await startLogin(baseUrl, clientId, { prompt: 'none', organization }, flow);\n } catch (e: unknown) {\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n }\n }, [baseUrl, clientId, flow, persistSession]);\n\n // A 401 means the minted token no longer works. Silent re-auth keeps the user's\n // place if the IdP session is still alive; otherwise the page comes back\n // unauthenticated and the app offers a real login.\n const handleUnauthorized = useCallback(() => {\n if (!sessionRef.current) return;\n if (onUnauthorized === 'login') void reauthenticate();\n else clearSession();\n }, [clearSession, reauthenticate, onUnauthorized]);\n\n // One client for the provider's lifetime. getToken reads the session ref.\n const client = useMemo(\n () => createConfigHubClient({ baseUrl, getToken, onUnauthorized: handleUnauthorized }),\n [baseUrl, getToken, handleUnauthorized],\n );\n\n const value = useMemo<ConfigHubAuthContextValue>(\n () => ({\n status,\n user,\n error,\n login,\n logout,\n switchOrganization,\n reauthenticate,\n getToken,\n client,\n }),\n [status, user, error, login, logout, switchOrganization, reauthenticate, getToken, client],\n );\n\n return (\n <ConfigHubAuthContext.Provider value={value}>{children}</ConfigHubAuthContext.Provider>\n );\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\nimport type { ConfigHubClient } from '@confighub/api';\nimport { useContext } from 'react';\nimport { ConfigHubAuthContext, type ConfigHubAuthContextValue } from './provider';\n\n/**\n * Access the ConfigHub auth state and actions. Must be called under a\n * `<ConfigHubAuthProvider>`.\n *\n * ```ts\n * const { status, user, login, logout } = useAuth();\n * ```\n */\nexport function useAuth(): ConfigHubAuthContextValue {\n const ctx = useContext(ConfigHubAuthContext);\n if (!ctx) {\n throw new Error('useAuth must be used within a <ConfigHubAuthProvider>');\n }\n return ctx;\n}\n\n/**\n * The typed ConfigHub API client, pre-wired with the current token. This is the\n * seam between `@confighub/react-auth` and `@confighub/api`: you never pass a\n * token by hand.\n *\n * ```ts\n * const api = useConfigHub();\n * const { data } = await api.GET('/space/{space_id}/unit', { params: { path: { space_id } } });\n * ```\n */\nexport function useConfigHub(): ConfigHubClient {\n return useAuth().client;\n}\n"]}
1
+ {"version":3,"sources":["../src/core.ts","../src/tokenStore.ts","../src/provider.tsx","../src/hooks.ts"],"names":["switchOrganization"],"mappings":";;;;;;;AAsFA,IAAM,QAAA,GAAW,gBAAA;AACjB,IAAM,YAAA,GAAe,oBAAA;AAIrB,IAAM,aAAa,CAAC,QAAA,KAA6B,CAAA,EAAG,YAAY,IAAI,QAAQ,CAAA,CAAA;AAGrE,SAAS,uBAAuB,QAAA,EAAsC;AAC3E,EAAA,IAAI;AACF,IAAA,OAAO,YAAA,CAAa,OAAA,CAAQ,UAAA,CAAW,QAAQ,CAAC,CAAA,IAAK,KAAA,CAAA;AAAA,EACvD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAGO,SAAS,oBAAA,CAAqB,UAAkB,KAAA,EAAiC;AACtF,EAAA,IAAI;AACF,IAAA,IAAI,OAAO,YAAA,CAAa,OAAA,CAAQ,UAAA,CAAW,QAAQ,GAAG,KAAK,CAAA;AAAA,SACtD,YAAA,CAAa,UAAA,CAAW,UAAA,CAAW,QAAQ,CAAC,CAAA;AAAA,EACnD,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AAMO,SAAS,oBAAoB,SAAA,EAAwD;AAC1F,EAAA,MAAM,MAAM,SAAA,CAAU,YAAA;AACtB,EAAA,IAAI,CAAC,GAAA,IAAO,OAAO,GAAA,KAAQ,UAAU,OAAO,MAAA;AAC5C,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,IAAA,CAAK,GAA8B,CAAA;AAC1D,EAAA,OAAO,OAAA,CAAQ,MAAA,KAAW,CAAA,GAAI,OAAA,CAAQ,CAAC,CAAA,GAAI,MAAA;AAC7C;AAEA,IAAM,YAAY,CAAC,CAAA,KAAsB,CAAA,CAAE,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAGtD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AAS,KAAK,cAAA,EAAe;AAAA,SAC/C,YAAA,EAAa;AAAA,EACpB,CAAA,EAAG,CAAC,YAAA,EAAc,cAAA,EAAgB,cAAc,CAAC,CAAA;AAGjD,EAAA,MAAM,MAAA,GAAS,OAAA;AAAA,IACb,MAAM,qBAAA,CAAsB,EAAE,SAAS,QAAA,EAAU,cAAA,EAAgB,oBAAoB,CAAA;AAAA,IACrF,CAAC,OAAA,EAAS,QAAA,EAAU,kBAAkB;AAAA,GACxC;AAEA,EAAA,MAAM,KAAA,GAAQ,OAAA;AAAA,IACZ,OAAO;AAAA,MACL,MAAA;AAAA,MACA,IAAA;AAAA,MACA,KAAA;AAAA,MACA,KAAA;AAAA,MACA,MAAA;AAAA,MACA,kBAAA,EAAAA,mBAAAA;AAAA,MACA,cAAA;AAAA,MACA,QAAA;AAAA,MACA;AAAA,KACF,CAAA;AAAA,IACA,CAAC,QAAQ,IAAA,EAAM,KAAA,EAAO,OAAO,MAAA,EAAQA,mBAAAA,EAAoB,cAAA,EAAgB,QAAA,EAAU,MAAM;AAAA,GAC3F;AAEA,EAAA,uBACE,GAAA,CAAC,oBAAA,CAAqB,QAAA,EAArB,EAA8B,OAAe,QAAA,EAAS,CAAA;AAE3D;ACrRO,SAAS,OAAA,GAAqC;AACnD,EAAA,MAAM,GAAA,GAAM,WAAW,oBAAoB,CAAA;AAC3C,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,MAAM,uDAAuD,CAAA;AAAA,EACzE;AACA,EAAA,OAAO,GAAA;AACT;AAYO,SAAS,YAAA,GAAgC;AAC9C,EAAA,OAAO,SAAQ,CAAE,MAAA;AACnB","file":"index.js","sourcesContent":["// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n//\n// Framework-neutral browser-auth engine for ConfigHub. Productionized from the\n// reference harness `test/browser-auth/src/confighubAuth.ts` in the ConfigHub\n// monorepo, which is validated end to end against staging and prod.\n//\n// Flow (design: third-party-browser-app-auth.md §6):\n// GET {base}/api/info -> discovery { AuthIssuer, TokenExchangeEndpoint }\n// OIDC discovery on AuthIssuer -> authorize/token/end_session endpoints\n// PKCE authorize + code->token -> IdP token\n// POST {TokenExchangeEndpoint} (8693) -> minted ConfigHub token\n//\n// The minted token then rides `Authorization: Bearer` against `/api`. The flow is\n// edition-agnostic: `AuthIssuer` is whatever discovery names (ConfigHub's bundled\n// Keycloak for Cloud, the org's own IdP for Enterprise), so the same code runs\n// against both. Tokens are held by the caller; only the transient PKCE state is\n// parked in sessionStorage across the authorize redirect.\n\nexport interface Discovery {\n AuthIssuer?: string;\n TokenExchangeEndpoint?: string;\n TokenExchangeAudience?: string;\n}\n\nexport interface MintedSession {\n accessToken: string;\n organizationId: string;\n /** Claims of the validated IdP token (owning-org, audience, organization shape). */\n idpClaims: Record<string, unknown>;\n /**\n * The IdP's ID token, kept only so logout can pass it as `id_token_hint` to the\n * end-session endpoint. Absent for sessions that did not come from an OIDC login.\n */\n idToken?: string;\n}\n\nexport interface LoginOptions {\n /**\n * Where to land after login, as a same-origin path (`/space/x?tab=units`). Carried\n * through the authorize round trip in the PKCE state, never in the redirect URI:\n * OAuth clients register exact redirect URIs, so the URI itself must not vary with\n * the page the user started from. Defaults to the current path and query.\n */\n returnTo?: string;\n /**\n * Which organization to sign in to, as the Keycloak organization alias sent in\n * the `organization:<alias>` scope.\n *\n * - a string: that organization, no prompt;\n * - `undefined` (default): the organization of the last successful login in this\n * browser, remembered per client in `localStorage`, so a new tab or a login after\n * logout lands in the same organization without a prompt; with nothing\n * remembered, Keycloak decides (prompt for a multi-org user, or the org matching\n * the email domain on a fresh authentication);\n * - `null`: no hint on purpose, so Keycloak prompts. This is \"switch organization\".\n */\n organization?: string | null;\n /**\n * `'none'` asks the IdP to re-authenticate without any UI, failing with\n * `login_required` if the SSO session is gone -- the way to refresh an expired\n * ConfigHub token when the user is still signed in at the IdP. `'login'` forces the\n * login form even with a live SSO session.\n */\n prompt?: 'none' | 'login';\n}\n\nexport interface FlowOptions {\n /**\n * Same-origin path the IdP redirects back to, and therefore the redirect URI to\n * register for the client: `{origin}{callbackPath}`. Defaults to `/`.\n */\n callbackPath?: string;\n}\n\ninterface PkceState {\n verifier: string;\n state: string;\n clientId: string;\n tokenEndpoint: string;\n exchangeEndpoint: string;\n redirectUri: string;\n returnTo: string;\n silent: boolean;\n}\n\nconst PKCE_KEY = 'confighub_pkce';\nconst LAST_ORG_KEY = 'confighub_last_org';\n\n// The alias is a short public identifier, not a credential, so localStorage is the\n// right place: it must outlive the tab, which is exactly what the token must not.\nconst lastOrgKey = (clientId: string): string => `${LAST_ORG_KEY}:${clientId}`;\n\n/** The organization alias of the last successful login for this client, if any. */\nexport function rememberedOrganization(clientId: string): string | undefined {\n try {\n return localStorage.getItem(lastOrgKey(clientId)) ?? undefined;\n } catch {\n return undefined;\n }\n}\n\n/** @internal */\nexport function rememberOrganization(clientId: string, alias: string | undefined): void {\n try {\n if (alias) localStorage.setItem(lastOrgKey(clientId), alias);\n else localStorage.removeItem(lastOrgKey(clientId));\n } catch {\n // Storage unavailable: the next login gets no hint.\n }\n}\n\n/**\n * The alias in an IdP token's `organization` claim (`{ \"<alias>\": { id } }`), or\n * undefined when the claim is absent or names more than one organization.\n */\nexport function organizationAliasOf(idpClaims: Record<string, unknown>): string | undefined {\n const org = idpClaims.organization;\n if (!org || typeof org !== 'object') return undefined;\n const aliases = Object.keys(org as Record<string, unknown>);\n return aliases.length === 1 ? aliases[0] : undefined;\n}\n\nconst trimSlash = (s: string): string => s.replace(/\\/+$/, '');\n\n/** The fixed callback URI: the page origin plus the configured callback path. */\nexport const callbackUri = (opts?: FlowOptions): string =>\n window.location.origin + (opts?.callbackPath ?? '/');\n\nconst currentPath = (): string =>\n window.location.pathname + window.location.search + window.location.hash;\n\nconst b64url = (buf: ArrayBuffer): string =>\n btoa(String.fromCharCode(...new Uint8Array(buf)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n\nconst randomString = (n = 64): string =>\n b64url(crypto.getRandomValues(new Uint8Array(n)).buffer);\n\nasync function sha256(s: string): Promise<string> {\n return b64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)));\n}\n\n/** Decode a JWT's claims without verifying it. Returns {} for anything malformed. */\nexport function decodeJwtClaims(token: string): Record<string, unknown> {\n const part = token.split('.')[1];\n if (!part) return {};\n try {\n return JSON.parse(atob(part.replace(/-/g, '+').replace(/_/g, '/')));\n } catch {\n return {};\n }\n}\n\n/** Whether a JWT's `exp` is in the past (with a small skew allowance). */\nexport function isExpired(token: string, skewSeconds = 30): boolean {\n const exp = decodeJwtClaims(token).exp;\n if (typeof exp !== 'number') return false;\n return exp * 1000 <= Date.now() + skewSeconds * 1000;\n}\n\nexport async function discover(base: string): Promise<Discovery> {\n const r = await fetch(trimSlash(base) + '/api/info');\n if (!r.ok) throw new Error('/api/info failed: ' + r.status);\n return r.json();\n}\n\ninterface OidcMetadata {\n authorization_endpoint: string;\n token_endpoint: string;\n end_session_endpoint?: string;\n}\n\nasync function oidcMetadata(issuer: string): Promise<OidcMetadata> {\n const r = await fetch(trimSlash(issuer) + '/.well-known/openid-configuration');\n if (!r.ok) throw new Error('OIDC discovery failed: ' + r.status);\n return r.json();\n}\n\n/**\n * Discover, build a PKCE request, and navigate to the IdP authorize endpoint.\n * Returns only by redirecting the page; `completeLoginFromRedirect()` finishes on\n * the way back.\n */\nexport async function startLogin(\n base: string,\n clientId: string,\n login: LoginOptions = {},\n flow: FlowOptions = {},\n): Promise<void> {\n const info = await discover(base);\n if (!info.AuthIssuer || !info.TokenExchangeEndpoint) {\n throw new Error(\n 'this instance is not configured for token-exchange auth (server needs CONFIGHUB_IDP_ISSUER)',\n );\n }\n const meta = await oidcMetadata(info.AuthIssuer);\n const verifier = randomString();\n const challenge = await sha256(verifier);\n const state = randomString(16);\n const redirectUri = callbackUri(flow);\n const pkce: PkceState = {\n verifier,\n state,\n clientId,\n tokenEndpoint: meta.token_endpoint,\n exchangeEndpoint: info.TokenExchangeEndpoint,\n redirectUri,\n returnTo: login.returnTo ?? currentPath(),\n silent: login.prompt === 'none',\n };\n sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));\n\n // The \"organization\" scope makes Keycloak emit the org claim the exchange resolves;\n // \"organization:<alias>\" selects one without prompting.\n const alias =\n login.organization === null\n ? undefined\n : (login.organization ?? rememberedOrganization(clientId));\n const orgScope = alias ? `organization:${alias}` : 'organization';\n const params: Record<string, string> = {\n response_type: 'code',\n client_id: clientId,\n redirect_uri: redirectUri,\n scope: `openid email profile ${orgScope}`,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n state,\n };\n if (login.prompt) params.prompt = login.prompt;\n\n const authURL = new URL(meta.authorization_endpoint);\n authURL.search = new URLSearchParams(params).toString();\n window.location.assign(authURL.toString());\n}\n\n// Memoize so React StrictMode's double-mount can't redeem the one-time code twice.\nlet pending: Promise<MintedSession | null> | null = null;\n\n/**\n * If the page is the IdP redirect (`?code=...`), exchange the code for an IdP token\n * and then exchange that for a minted ConfigHub token, and restore the URL the\n * login started from. Returns null on a normal load, and also when a `prompt=none`\n * attempt came back with `login_required` (the SSO session is gone; the caller\n * should offer an interactive login).\n */\nexport function completeLoginFromRedirect(): Promise<MintedSession | null> {\n if (!pending) pending = doCompleteLogin();\n return pending;\n}\n\nconst SILENT_FAILURES = new Set(['login_required', 'interaction_required', 'consent_required']);\n\nasync function doCompleteLogin(): Promise<MintedSession | null> {\n const params = new URLSearchParams(window.location.search);\n const code = params.get('code');\n const error = params.get('error');\n if (!code && !error) return null;\n\n const savedRaw = sessionStorage.getItem(PKCE_KEY);\n sessionStorage.removeItem(PKCE_KEY);\n const saved: PkceState | null = savedRaw ? JSON.parse(savedRaw) : null;\n\n // Put the URL back to where the user started before anything else can fail, so\n // neither the code nor an error string lingers in the address bar or history.\n history.replaceState({}, '', saved?.returnTo ?? callbackUri());\n\n if (error) {\n if (saved?.silent && SILENT_FAILURES.has(error)) return null;\n throw new Error(`IdP returned error: ${error} ${params.get('error_description') ?? ''}`);\n }\n if (!saved) throw new Error('no PKCE state; restart login');\n if (params.get('state') !== saved.state) throw new Error('state mismatch; aborting');\n\n // Exchange the authorization code for an IdP token (PKCE, public client).\n const tokenResp = await fetch(saved.tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n code: code!,\n redirect_uri: saved.redirectUri,\n client_id: saved.clientId,\n code_verifier: saved.verifier,\n }),\n });\n if (!tokenResp.ok) {\n throw new Error(`IdP token endpoint ${tokenResp.status}: ${await tokenResp.text()}`);\n }\n const idpToken = await tokenResp.json();\n\n // RFC 8693 token exchange against ConfigHub -> minted ConfigHub token.\n const minted = await exchange(saved.exchangeEndpoint, idpToken.access_token);\n const idpClaims = decodeJwtClaims(idpToken.access_token);\n rememberOrganization(saved.clientId, organizationAliasOf(idpClaims));\n return {\n ...minted,\n idpClaims,\n idToken: typeof idpToken.id_token === 'string' ? idpToken.id_token : undefined,\n };\n}\n\nasync function exchange(\n exchangeEndpoint: string,\n subjectToken: string,\n): Promise<Pick<MintedSession, 'accessToken' | 'organizationId'>> {\n const exResp = await fetch(exchangeEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: subjectToken,\n subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',\n }),\n });\n if (!exResp.ok) throw new Error(`/auth/exchange ${exResp.status}: ${await exResp.text()}`);\n const minted = await exResp.json();\n return { accessToken: minted.access_token, organizationId: minted.organization_id };\n}\n\n/**\n * Trade the current minted token for one scoped to another organization the user\n * belongs to (`POST {base}/auth/switch-organization`, bearer-authenticated). The\n * IdP session is untouched; only the ConfigHub token changes.\n */\nexport async function switchOrganization(\n base: string,\n accessToken: string,\n organizationId: string,\n): Promise<Pick<MintedSession, 'accessToken' | 'organizationId'>> {\n const r = await fetch(trimSlash(base) + '/auth/switch-organization', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({ organization_id: organizationId }),\n });\n if (!r.ok) throw new Error(`/auth/switch-organization ${r.status}: ${await r.text()}`);\n const minted = await r.json();\n return { accessToken: minted.access_token, organizationId: minted.organization_id };\n}\n\n/**\n * End the IdP session (RP-initiated logout) and land on `postLogoutRedirectUri`,\n * which must be registered for the client. Returns only by redirecting. If the\n * issuer publishes no end-session endpoint, navigates to the redirect URI directly.\n */\nexport async function endSession(\n base: string,\n clientId: string,\n idToken: string | undefined,\n postLogoutRedirectUri: string,\n): Promise<void> {\n const info = await discover(base);\n const meta = info.AuthIssuer ? await oidcMetadata(info.AuthIssuer) : undefined;\n if (!meta?.end_session_endpoint) {\n window.location.assign(postLogoutRedirectUri);\n return;\n }\n const params: Record<string, string> = {\n client_id: clientId,\n post_logout_redirect_uri: postLogoutRedirectUri,\n };\n if (idToken) params.id_token_hint = idToken;\n const url = new URL(meta.end_session_endpoint);\n url.search = new URLSearchParams(params).toString();\n window.location.assign(url.toString());\n}\n\n/** Discard the in-progress login memo (used on logout so a later login re-runs). */\nexport function resetPending(): void {\n pending = null;\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\n// A module-level holder for the current minted token, so non-React consumers can read\n// it. RTK Query's `prepareHeaders` (in @confighub/rtk-query) is not a hook and cannot\n// read React context, so it calls getAccessToken() instead. The provider keeps this in\n// sync with its React state.\nlet currentToken: string | undefined;\n\n/** @internal — called by the provider; not part of the public surface. */\nexport function setAccessToken(token: string | undefined): void {\n currentToken = token;\n}\n\n/**\n * The current minted ConfigHub token, or undefined when unauthenticated. Pass this as\n * the `getToken` for `@confighub/rtk-query`'s `configureConfigHub`, or read it anywhere\n * you need the token outside React.\n */\nexport function getAccessToken(): string | undefined {\n return currentToken;\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\nimport { createConfigHubClient, type ConfigHubClient } from '@confighub/api';\nimport {\n createContext,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport {\n callbackUri,\n completeLoginFromRedirect,\n endSession,\n isExpired,\n organizationAliasOf,\n rememberOrganization,\n resetPending,\n startLogin,\n switchOrganization as switchOrganizationCore,\n type LoginOptions,\n type MintedSession,\n} from './core';\nimport { setAccessToken } from './tokenStore';\n\nexport type AuthStatus = 'loading' | 'authenticated' | 'unauthenticated' | 'error';\n\nexport interface ConfigHubUser {\n organizationId: string;\n idpClaims: Record<string, unknown>;\n}\n\nexport interface LogoutOptions {\n /**\n * Also end the IdP session (RP-initiated logout), so the next login asks for\n * credentials instead of riding the SSO cookie. Redirects the page; the landing\n * URI must be registered for the client. Default: false, which only forgets the\n * token in this tab.\n */\n endSession?: boolean;\n /** Where to land after IdP logout. Defaults to the callback URI. */\n postLogoutRedirectUri?: string;\n}\n\nexport interface ConfigHubAuthContextValue {\n status: AuthStatus;\n user: ConfigHubUser | null;\n error: Error | null;\n /** Begin login: redirects the page to the IdP. */\n login: (options?: LoginOptions) => Promise<void>;\n /** Forget the session in this tab and, optionally, end the IdP session too. */\n logout: (options?: LogoutOptions) => Promise<void>;\n /**\n * Re-mint the ConfigHub token for another organization the user belongs to. The\n * IdP session is untouched. Rejects with the server's error if the user is not a\n * member; the current session stays as it was.\n */\n switchOrganization: (organizationId: string) => Promise<void>;\n /**\n * The ConfigHub token stopped working (a 401). Try to get a new one without any\n * UI: a `prompt=none` round trip through the IdP, for the organization the session\n * already had. Status goes to `loading` meanwhile, not `unauthenticated`, so an\n * app that auto-logs-in on `unauthenticated` does not race this with an\n * interactive login. If the IdP session is gone too, the page comes back\n * `unauthenticated`. Redirects the page.\n */\n reauthenticate: () => Promise<void>;\n /** Current bearer token, or undefined when unauthenticated. */\n getToken: () => string | undefined;\n /** A typed API client pre-wired with the current token. Stable across renders. */\n client: ConfigHubClient;\n}\n\nexport const ConfigHubAuthContext = createContext<ConfigHubAuthContextValue | null>(null);\n\nexport interface ConfigHubAuthProviderProps {\n /** Absolute base URL of the ConfigHub instance, e.g. `https://hub.confighub.com`. */\n baseUrl: string;\n /** This app's registered OAuth `client_id` (from `cub oauthclient create`). */\n clientId: string;\n /**\n * Same-origin path the IdP redirects back to; `{origin}{callbackPath}` is the\n * redirect URI to register. Defaults to `/`. Fixed on purpose: the page a user\n * starts login from travels in the PKCE state, not in the redirect URI.\n */\n callbackPath?: string;\n /**\n * `'session'` keeps the minted token in `sessionStorage` so a reload or an in-tab\n * navigation does not round-trip through the IdP. Tab-scoped and gone when the tab\n * closes. Default `'none'`: memory only, a reload starts unauthenticated.\n */\n persist?: 'none' | 'session';\n /**\n * What a 401 from the API means. `'login'` (default): the token is stale, try a\n * silent re-authentication (`prompt=none`) and fall back to unauthenticated if the\n * IdP session is gone too. `'logout'`: just drop the session.\n */\n onUnauthorized?: 'login' | 'logout';\n children: ReactNode;\n}\n\nconst SESSION_KEY = 'confighub_session';\n\nfunction readPersisted(): MintedSession | null {\n try {\n const raw = sessionStorage.getItem(SESSION_KEY);\n if (!raw) return null;\n const session: MintedSession = JSON.parse(raw);\n if (!session.accessToken || isExpired(session.accessToken)) {\n sessionStorage.removeItem(SESSION_KEY);\n return null;\n }\n return session;\n } catch {\n return null;\n }\n}\n\n/**\n * Runs the browser-direct auth flow and manages the token lifecycle. On mount it\n * completes a redirect if the page is the IdP callback, restores a persisted\n * session if there is one, and otherwise starts unauthenticated until `login()`\n * is called.\n */\nexport function ConfigHubAuthProvider({\n baseUrl,\n clientId,\n callbackPath,\n persist = 'none',\n onUnauthorized = 'login',\n children,\n}: ConfigHubAuthProviderProps): JSX.Element {\n const [status, setStatus] = useState<AuthStatus>('loading');\n const [user, setUser] = useState<ConfigHubUser | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // The session lives in a ref so getToken() reads the latest value synchronously\n // without re-creating the API client on every render.\n const sessionRef = useRef<MintedSession | undefined>(undefined);\n const flow = useMemo(() => ({ callbackPath }), [callbackPath]);\n\n const persistSession = useCallback(\n (session: MintedSession | undefined) => {\n if (persist !== 'session') return;\n try {\n if (session) sessionStorage.setItem(SESSION_KEY, JSON.stringify(session));\n else sessionStorage.removeItem(SESSION_KEY);\n } catch {\n // Storage unavailable (private mode, quota): memory-only for this tab.\n }\n },\n [persist],\n );\n\n const applySession = useCallback(\n (session: MintedSession) => {\n sessionRef.current = session;\n setAccessToken(session.accessToken); // keep the non-React accessor in sync (rtk-query)\n persistSession(session);\n setUser({ organizationId: session.organizationId, idpClaims: session.idpClaims });\n setError(null);\n setStatus('authenticated');\n },\n [persistSession],\n );\n\n const clearSession = useCallback(() => {\n sessionRef.current = undefined;\n setAccessToken(undefined);\n persistSession(undefined);\n resetPending();\n setUser(null);\n setStatus('unauthenticated');\n }, [persistSession]);\n\n useEffect(() => {\n let cancelled = false;\n completeLoginFromRedirect()\n .then((session) => {\n if (cancelled) return;\n if (session) return applySession(session);\n const persisted = persist === 'session' ? readPersisted() : null;\n if (persisted) return applySession(persisted);\n setStatus('unauthenticated');\n })\n .catch((e: unknown) => {\n if (cancelled) return;\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n });\n return () => {\n cancelled = true;\n };\n }, [applySession, persist]);\n\n const login = useCallback(\n async (options?: LoginOptions) => {\n setError(null);\n try {\n await startLogin(baseUrl, clientId, options, flow);\n } catch (e: unknown) {\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n }\n },\n [baseUrl, clientId, flow],\n );\n\n const logout = useCallback(\n async (options?: LogoutOptions) => {\n const idToken = sessionRef.current?.idToken;\n clearSession();\n if (options?.endSession) {\n await endSession(\n baseUrl,\n clientId,\n idToken,\n options.postLogoutRedirectUri ?? callbackUri(flow),\n );\n }\n },\n [baseUrl, clientId, clearSession, flow],\n );\n\n const switchOrganization = useCallback(\n async (organizationId: string) => {\n const current = sessionRef.current;\n if (!current) throw new Error('not authenticated');\n const minted = await switchOrganizationCore(baseUrl, current.accessToken, organizationId);\n // The session's IdP claims still name the previous org, so its alias must not\n // be remembered as the default for the next login.\n rememberOrganization(clientId, undefined);\n applySession({ ...current, ...minted });\n },\n [applySession, baseUrl, clientId],\n );\n\n const getToken = useCallback(() => sessionRef.current?.accessToken, []);\n\n const reauthenticate = useCallback(async () => {\n const organization = organizationAliasOf(sessionRef.current?.idpClaims ?? {});\n // Forget the token but stay 'loading': the page is about to navigate away,\n // and 'unauthenticated' would invite an interactive login in the meantime.\n sessionRef.current = undefined;\n setAccessToken(undefined);\n persistSession(undefined);\n resetPending();\n setStatus('loading');\n try {\n await startLogin(baseUrl, clientId, { prompt: 'none', organization }, flow);\n } catch (e: unknown) {\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n }\n }, [baseUrl, clientId, flow, persistSession]);\n\n // A 401 means the minted token no longer works. Silent re-auth keeps the user's\n // place if the IdP session is still alive; otherwise the page comes back\n // unauthenticated and the app offers a real login.\n const handleUnauthorized = useCallback(() => {\n if (!sessionRef.current) return;\n if (onUnauthorized === 'login') void reauthenticate();\n else clearSession();\n }, [clearSession, reauthenticate, onUnauthorized]);\n\n // One client for the provider's lifetime. getToken reads the session ref.\n const client = useMemo(\n () => createConfigHubClient({ baseUrl, getToken, onUnauthorized: handleUnauthorized }),\n [baseUrl, getToken, handleUnauthorized],\n );\n\n const value = useMemo<ConfigHubAuthContextValue>(\n () => ({\n status,\n user,\n error,\n login,\n logout,\n switchOrganization,\n reauthenticate,\n getToken,\n client,\n }),\n [status, user, error, login, logout, switchOrganization, reauthenticate, getToken, client],\n );\n\n return (\n <ConfigHubAuthContext.Provider value={value}>{children}</ConfigHubAuthContext.Provider>\n );\n}\n","// Copyright (C) ConfigHub, Inc.\n// SPDX-License-Identifier: MIT\n\nimport type { ConfigHubClient } from '@confighub/api';\nimport { useContext } from 'react';\nimport { ConfigHubAuthContext, type ConfigHubAuthContextValue } from './provider';\n\n/**\n * Access the ConfigHub auth state and actions. Must be called under a\n * `<ConfigHubAuthProvider>`.\n *\n * ```ts\n * const { status, user, login, logout } = useAuth();\n * ```\n */\nexport function useAuth(): ConfigHubAuthContextValue {\n const ctx = useContext(ConfigHubAuthContext);\n if (!ctx) {\n throw new Error('useAuth must be used within a <ConfigHubAuthProvider>');\n }\n return ctx;\n}\n\n/**\n * The typed ConfigHub API client, pre-wired with the current token. This is the\n * seam between `@confighub/react-auth` and `@confighub/api`: you never pass a\n * token by hand.\n *\n * ```ts\n * const api = useConfigHub();\n * const { data } = await api.GET('/space/{space_id}/unit', { params: { path: { space_id } } });\n * ```\n */\nexport function useConfigHub(): ConfigHubClient {\n return useAuth().client;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@confighub/react-auth",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "React auth provider and hooks for ConfigHub browser apps (OIDC PKCE + RFC 8693 token exchange)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -39,7 +39,7 @@
39
39
  "prepublishOnly": "npm run build"
40
40
  },
41
41
  "dependencies": {
42
- "@confighub/api": "^0.4.0"
42
+ "@confighub/api": "^0.4.2"
43
43
  },
44
44
  "peerDependencies": {
45
45
  "react": "^18.0.0 || ^19.0.0"