@confighub/react-auth 0.4.1 → 0.4.3
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 +6 -2
- package/dist/index.cjs +59 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +30 -5
- package/dist/index.d.ts +30 -5
- package/dist/index.js +57 -14
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
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
|
|
56
|
-
|
|
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
|
@@ -7,7 +7,36 @@ var jsxRuntime = require('react/jsx-runtime');
|
|
|
7
7
|
// src/provider.tsx
|
|
8
8
|
|
|
9
9
|
// src/core.ts
|
|
10
|
+
var OrganizationMissing = class extends Error {
|
|
11
|
+
constructor(returnTo) {
|
|
12
|
+
super("the identity provider issued a token with no organization");
|
|
13
|
+
this.returnTo = returnTo;
|
|
14
|
+
this.name = "OrganizationMissing";
|
|
15
|
+
}
|
|
16
|
+
};
|
|
10
17
|
var PKCE_KEY = "confighub_pkce";
|
|
18
|
+
var LAST_ORG_KEY = "confighub_last_org";
|
|
19
|
+
var lastOrgKey = (clientId) => `${LAST_ORG_KEY}:${clientId}`;
|
|
20
|
+
function rememberedOrganization(clientId) {
|
|
21
|
+
try {
|
|
22
|
+
return localStorage.getItem(lastOrgKey(clientId)) ?? void 0;
|
|
23
|
+
} catch {
|
|
24
|
+
return void 0;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function rememberOrganization(clientId, alias) {
|
|
28
|
+
try {
|
|
29
|
+
if (alias) localStorage.setItem(lastOrgKey(clientId), alias);
|
|
30
|
+
else localStorage.removeItem(lastOrgKey(clientId));
|
|
31
|
+
} catch {
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function organizationAliasOf(idpClaims) {
|
|
35
|
+
const org = idpClaims.organization;
|
|
36
|
+
if (!org || typeof org !== "object") return void 0;
|
|
37
|
+
const aliases = Object.keys(org);
|
|
38
|
+
return aliases.length === 1 ? aliases[0] : void 0;
|
|
39
|
+
}
|
|
11
40
|
var trimSlash = (s) => s.replace(/\/+$/, "");
|
|
12
41
|
var callbackUri = (opts) => window.location.origin + (opts?.callbackPath ?? "/");
|
|
13
42
|
var currentPath = () => window.location.pathname + window.location.search + window.location.hash;
|
|
@@ -40,7 +69,7 @@ async function oidcMetadata(issuer) {
|
|
|
40
69
|
if (!r.ok) throw new Error("OIDC discovery failed: " + r.status);
|
|
41
70
|
return r.json();
|
|
42
71
|
}
|
|
43
|
-
async function startLogin(base, clientId, login = {}, flow = {}) {
|
|
72
|
+
async function startLogin(base, clientId, login = {}, flow = {}, retry = {}) {
|
|
44
73
|
const info = await discover(base);
|
|
45
74
|
if (!info.AuthIssuer || !info.TokenExchangeEndpoint) {
|
|
46
75
|
throw new Error(
|
|
@@ -52,6 +81,8 @@ async function startLogin(base, clientId, login = {}, flow = {}) {
|
|
|
52
81
|
const challenge = await sha256(verifier);
|
|
53
82
|
const state = randomString(16);
|
|
54
83
|
const redirectUri = callbackUri(flow);
|
|
84
|
+
const alias = login.organization === null ? void 0 : login.organization ?? rememberedOrganization(clientId);
|
|
85
|
+
const orgScope = alias ? `organization:${alias}` : "organization";
|
|
55
86
|
const pkce = {
|
|
56
87
|
verifier,
|
|
57
88
|
state,
|
|
@@ -60,10 +91,11 @@ async function startLogin(base, clientId, login = {}, flow = {}) {
|
|
|
60
91
|
exchangeEndpoint: info.TokenExchangeEndpoint,
|
|
61
92
|
redirectUri,
|
|
62
93
|
returnTo: login.returnTo ?? currentPath(),
|
|
63
|
-
silent: login.prompt === "none"
|
|
94
|
+
silent: login.prompt === "none",
|
|
95
|
+
hintedOrganization: alias,
|
|
96
|
+
retriedForOrganization: retry.retriedForOrganization
|
|
64
97
|
};
|
|
65
98
|
sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));
|
|
66
|
-
const orgScope = login.organization ? `organization:${login.organization}` : "organization";
|
|
67
99
|
const params = {
|
|
68
100
|
response_type: "code",
|
|
69
101
|
client_id: clientId,
|
|
@@ -114,10 +146,16 @@ async function doCompleteLogin() {
|
|
|
114
146
|
throw new Error(`IdP token endpoint ${tokenResp.status}: ${await tokenResp.text()}`);
|
|
115
147
|
}
|
|
116
148
|
const idpToken = await tokenResp.json();
|
|
149
|
+
const idpClaims = decodeJwtClaims(idpToken.access_token);
|
|
150
|
+
if (!organizationAliasOf(idpClaims) && !saved.retriedForOrganization) {
|
|
151
|
+
if (saved.hintedOrganization) rememberOrganization(saved.clientId, void 0);
|
|
152
|
+
throw new OrganizationMissing(saved.returnTo);
|
|
153
|
+
}
|
|
117
154
|
const minted = await exchange(saved.exchangeEndpoint, idpToken.access_token);
|
|
155
|
+
rememberOrganization(saved.clientId, organizationAliasOf(idpClaims));
|
|
118
156
|
return {
|
|
119
157
|
...minted,
|
|
120
|
-
idpClaims
|
|
158
|
+
idpClaims,
|
|
121
159
|
idToken: typeof idpToken.id_token === "string" ? idpToken.id_token : void 0
|
|
122
160
|
};
|
|
123
161
|
}
|
|
@@ -178,12 +216,6 @@ function getAccessToken() {
|
|
|
178
216
|
}
|
|
179
217
|
var ConfigHubAuthContext = react.createContext(null);
|
|
180
218
|
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
219
|
function readPersisted() {
|
|
188
220
|
try {
|
|
189
221
|
const raw = sessionStorage.getItem(SESSION_KEY);
|
|
@@ -251,13 +283,23 @@ function ConfigHubAuthProvider({
|
|
|
251
283
|
setStatus("unauthenticated");
|
|
252
284
|
}).catch((e) => {
|
|
253
285
|
if (cancelled) return;
|
|
286
|
+
if (e instanceof OrganizationMissing) {
|
|
287
|
+
void startLogin(
|
|
288
|
+
baseUrl,
|
|
289
|
+
clientId,
|
|
290
|
+
{ returnTo: e.returnTo, organization: null },
|
|
291
|
+
flow,
|
|
292
|
+
{ retriedForOrganization: true }
|
|
293
|
+
);
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
254
296
|
setError(e instanceof Error ? e : new Error(String(e)));
|
|
255
297
|
setStatus("error");
|
|
256
298
|
});
|
|
257
299
|
return () => {
|
|
258
300
|
cancelled = true;
|
|
259
301
|
};
|
|
260
|
-
}, [applySession, persist]);
|
|
302
|
+
}, [applySession, persist, baseUrl, clientId, flow]);
|
|
261
303
|
const login = react.useCallback(
|
|
262
304
|
async (options) => {
|
|
263
305
|
setError(null);
|
|
@@ -290,13 +332,14 @@ function ConfigHubAuthProvider({
|
|
|
290
332
|
const current = sessionRef.current;
|
|
291
333
|
if (!current) throw new Error("not authenticated");
|
|
292
334
|
const minted = await switchOrganization(baseUrl, current.accessToken, organizationId);
|
|
335
|
+
rememberOrganization(clientId, void 0);
|
|
293
336
|
applySession({ ...current, ...minted });
|
|
294
337
|
},
|
|
295
|
-
[applySession, baseUrl]
|
|
338
|
+
[applySession, baseUrl, clientId]
|
|
296
339
|
);
|
|
297
340
|
const getToken = react.useCallback(() => sessionRef.current?.accessToken, []);
|
|
298
341
|
const reauthenticate = react.useCallback(async () => {
|
|
299
|
-
const organization =
|
|
342
|
+
const organization = organizationAliasOf(sessionRef.current?.idpClaims ?? {});
|
|
300
343
|
sessionRef.current = void 0;
|
|
301
344
|
setAccessToken(void 0);
|
|
302
345
|
persistSession(void 0);
|
|
@@ -347,10 +390,13 @@ function useConfigHub() {
|
|
|
347
390
|
|
|
348
391
|
exports.ConfigHubAuthContext = ConfigHubAuthContext;
|
|
349
392
|
exports.ConfigHubAuthProvider = ConfigHubAuthProvider;
|
|
393
|
+
exports.OrganizationMissing = OrganizationMissing;
|
|
350
394
|
exports.callbackUri = callbackUri;
|
|
351
395
|
exports.decodeJwtClaims = decodeJwtClaims;
|
|
352
396
|
exports.getAccessToken = getAccessToken;
|
|
353
397
|
exports.isExpired = isExpired;
|
|
398
|
+
exports.organizationAliasOf = organizationAliasOf;
|
|
399
|
+
exports.rememberedOrganization = rememberedOrganization;
|
|
354
400
|
exports.useAuth = useAuth;
|
|
355
401
|
exports.useConfigHub = useConfigHub;
|
|
356
402
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -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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EAAG,CAAC,YAAA,EAAc,cAAA,EAAgB,cAAc,CAAC,CAAA;AAGjD,EAAA,MAAM,MAAA,GAASD,aAAA;AAAA,IACb,MAAMI,yBAAA,CAAsB,EAAE,SAAS,QAAA,EAAU,cAAA,EAAgB,oBAAoB,CAAA;AAAA,IACrF,CAAC,OAAA,EAAS,QAAA,EAAU,kBAAkB;AAAA,GACxC;AAEA,EAAA,MAAM,KAAA,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":";;;;;;;;;AAiGO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,YAA4B,QAAA,EAAkB;AAC5C,IAAA,KAAA,CAAM,2DAA2D,CAAA;AADvC,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAE1B,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAOA,IAAM,QAAA,GAAW,gBAAA;AAC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AAA,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 /** The organization alias the authorize request hinted, if any. */\n hintedOrganization?: string;\n /** This login is already the retry after a token without an organization. */\n retriedForOrganization?: boolean;\n}\n\n/**\n * Thrown by `completeLoginFromRedirect` when the IdP token names no organization,\n * which the exchange would refuse. Seen on a fresh brokered (Google) login, where\n * Keycloak's organization step does not run; on the next login the SSO session is\n * alive and it does, so the caller logs in again, once, with no hint. Any\n * remembered alias has already been forgotten.\n */\nexport class OrganizationMissing extends Error {\n constructor(public readonly returnTo: string) {\n super('the identity provider issued a token with no organization');\n this.name = 'OrganizationMissing';\n }\n}\n\nexport interface RetryOptions {\n /** @internal set by the provider on the one retry after OrganizationMissing. */\n retriedForOrganization?: 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 retry: RetryOptions = {},\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 // 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 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 hintedOrganization: alias,\n retriedForOrganization: retry.retriedForOrganization,\n };\n sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));\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 idpClaims = decodeJwtClaims(idpToken.access_token);\n if (!organizationAliasOf(idpClaims) && !saved.retriedForOrganization) {\n // The exchange would refuse this token. Rather than surface that, log in\n // once more: with the SSO session now alive the IdP runs its organization\n // step. A hint that was sent evidently did not help, so forget it.\n if (saved.hintedOrganization) rememberOrganization(saved.clientId, undefined);\n throw new OrganizationMissing(saved.returnTo);\n }\n const minted = await exchange(saved.exchangeEndpoint, 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 OrganizationMissing,\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 if (e instanceof OrganizationMissing) {\n // Once, with no hint, flagged so a second miss surfaces as an error.\n void startLogin(\n baseUrl,\n clientId,\n { returnTo: e.returnTo, organization: null },\n flow,\n { retriedForOrganization: true },\n );\n return;\n }\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n });\n return () => {\n cancelled = true;\n };\n }, [applySession, persist, baseUrl, clientId, flow]);\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
|
-
*
|
|
31
|
-
* scope.
|
|
32
|
-
*
|
|
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,24 @@ interface FlowOptions {
|
|
|
47
54
|
*/
|
|
48
55
|
callbackPath?: string;
|
|
49
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Thrown by `completeLoginFromRedirect` when the IdP token names no organization,
|
|
59
|
+
* which the exchange would refuse. Seen on a fresh brokered (Google) login, where
|
|
60
|
+
* Keycloak's organization step does not run; on the next login the SSO session is
|
|
61
|
+
* alive and it does, so the caller logs in again, once, with no hint. Any
|
|
62
|
+
* remembered alias has already been forgotten.
|
|
63
|
+
*/
|
|
64
|
+
declare class OrganizationMissing extends Error {
|
|
65
|
+
readonly returnTo: string;
|
|
66
|
+
constructor(returnTo: string);
|
|
67
|
+
}
|
|
68
|
+
/** The organization alias of the last successful login for this client, if any. */
|
|
69
|
+
declare function rememberedOrganization(clientId: string): string | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* The alias in an IdP token's `organization` claim (`{ "<alias>": { id } }`), or
|
|
72
|
+
* undefined when the claim is absent or names more than one organization.
|
|
73
|
+
*/
|
|
74
|
+
declare function organizationAliasOf(idpClaims: Record<string, unknown>): string | undefined;
|
|
50
75
|
/** The fixed callback URI: the page origin plus the configured callback path. */
|
|
51
76
|
declare const callbackUri: (opts?: FlowOptions) => string;
|
|
52
77
|
/** Decode a JWT's claims without verifying it. Returns {} for anything malformed. */
|
|
@@ -160,4 +185,4 @@ declare function useConfigHub(): ConfigHubClient;
|
|
|
160
185
|
*/
|
|
161
186
|
declare function getAccessToken(): string | undefined;
|
|
162
187
|
|
|
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 };
|
|
188
|
+
export { type AuthStatus, ConfigHubAuthContext, type ConfigHubAuthContextValue, ConfigHubAuthProvider, type ConfigHubAuthProviderProps, type ConfigHubUser, type Discovery, type FlowOptions, type LoginOptions, type LogoutOptions, type MintedSession, OrganizationMissing, 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
|
-
*
|
|
31
|
-
* scope.
|
|
32
|
-
*
|
|
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,24 @@ interface FlowOptions {
|
|
|
47
54
|
*/
|
|
48
55
|
callbackPath?: string;
|
|
49
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Thrown by `completeLoginFromRedirect` when the IdP token names no organization,
|
|
59
|
+
* which the exchange would refuse. Seen on a fresh brokered (Google) login, where
|
|
60
|
+
* Keycloak's organization step does not run; on the next login the SSO session is
|
|
61
|
+
* alive and it does, so the caller logs in again, once, with no hint. Any
|
|
62
|
+
* remembered alias has already been forgotten.
|
|
63
|
+
*/
|
|
64
|
+
declare class OrganizationMissing extends Error {
|
|
65
|
+
readonly returnTo: string;
|
|
66
|
+
constructor(returnTo: string);
|
|
67
|
+
}
|
|
68
|
+
/** The organization alias of the last successful login for this client, if any. */
|
|
69
|
+
declare function rememberedOrganization(clientId: string): string | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* The alias in an IdP token's `organization` claim (`{ "<alias>": { id } }`), or
|
|
72
|
+
* undefined when the claim is absent or names more than one organization.
|
|
73
|
+
*/
|
|
74
|
+
declare function organizationAliasOf(idpClaims: Record<string, unknown>): string | undefined;
|
|
50
75
|
/** The fixed callback URI: the page origin plus the configured callback path. */
|
|
51
76
|
declare const callbackUri: (opts?: FlowOptions) => string;
|
|
52
77
|
/** Decode a JWT's claims without verifying it. Returns {} for anything malformed. */
|
|
@@ -160,4 +185,4 @@ declare function useConfigHub(): ConfigHubClient;
|
|
|
160
185
|
*/
|
|
161
186
|
declare function getAccessToken(): string | undefined;
|
|
162
187
|
|
|
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 };
|
|
188
|
+
export { type AuthStatus, ConfigHubAuthContext, type ConfigHubAuthContextValue, ConfigHubAuthProvider, type ConfigHubAuthProviderProps, type ConfigHubUser, type Discovery, type FlowOptions, type LoginOptions, type LogoutOptions, type MintedSession, OrganizationMissing, callbackUri, decodeJwtClaims, getAccessToken, isExpired, organizationAliasOf, rememberedOrganization, useAuth, useConfigHub };
|
package/dist/index.js
CHANGED
|
@@ -5,7 +5,36 @@ import { jsx } from 'react/jsx-runtime';
|
|
|
5
5
|
// src/provider.tsx
|
|
6
6
|
|
|
7
7
|
// src/core.ts
|
|
8
|
+
var OrganizationMissing = class extends Error {
|
|
9
|
+
constructor(returnTo) {
|
|
10
|
+
super("the identity provider issued a token with no organization");
|
|
11
|
+
this.returnTo = returnTo;
|
|
12
|
+
this.name = "OrganizationMissing";
|
|
13
|
+
}
|
|
14
|
+
};
|
|
8
15
|
var PKCE_KEY = "confighub_pkce";
|
|
16
|
+
var LAST_ORG_KEY = "confighub_last_org";
|
|
17
|
+
var lastOrgKey = (clientId) => `${LAST_ORG_KEY}:${clientId}`;
|
|
18
|
+
function rememberedOrganization(clientId) {
|
|
19
|
+
try {
|
|
20
|
+
return localStorage.getItem(lastOrgKey(clientId)) ?? void 0;
|
|
21
|
+
} catch {
|
|
22
|
+
return void 0;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function rememberOrganization(clientId, alias) {
|
|
26
|
+
try {
|
|
27
|
+
if (alias) localStorage.setItem(lastOrgKey(clientId), alias);
|
|
28
|
+
else localStorage.removeItem(lastOrgKey(clientId));
|
|
29
|
+
} catch {
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function organizationAliasOf(idpClaims) {
|
|
33
|
+
const org = idpClaims.organization;
|
|
34
|
+
if (!org || typeof org !== "object") return void 0;
|
|
35
|
+
const aliases = Object.keys(org);
|
|
36
|
+
return aliases.length === 1 ? aliases[0] : void 0;
|
|
37
|
+
}
|
|
9
38
|
var trimSlash = (s) => s.replace(/\/+$/, "");
|
|
10
39
|
var callbackUri = (opts) => window.location.origin + (opts?.callbackPath ?? "/");
|
|
11
40
|
var currentPath = () => window.location.pathname + window.location.search + window.location.hash;
|
|
@@ -38,7 +67,7 @@ async function oidcMetadata(issuer) {
|
|
|
38
67
|
if (!r.ok) throw new Error("OIDC discovery failed: " + r.status);
|
|
39
68
|
return r.json();
|
|
40
69
|
}
|
|
41
|
-
async function startLogin(base, clientId, login = {}, flow = {}) {
|
|
70
|
+
async function startLogin(base, clientId, login = {}, flow = {}, retry = {}) {
|
|
42
71
|
const info = await discover(base);
|
|
43
72
|
if (!info.AuthIssuer || !info.TokenExchangeEndpoint) {
|
|
44
73
|
throw new Error(
|
|
@@ -50,6 +79,8 @@ async function startLogin(base, clientId, login = {}, flow = {}) {
|
|
|
50
79
|
const challenge = await sha256(verifier);
|
|
51
80
|
const state = randomString(16);
|
|
52
81
|
const redirectUri = callbackUri(flow);
|
|
82
|
+
const alias = login.organization === null ? void 0 : login.organization ?? rememberedOrganization(clientId);
|
|
83
|
+
const orgScope = alias ? `organization:${alias}` : "organization";
|
|
53
84
|
const pkce = {
|
|
54
85
|
verifier,
|
|
55
86
|
state,
|
|
@@ -58,10 +89,11 @@ async function startLogin(base, clientId, login = {}, flow = {}) {
|
|
|
58
89
|
exchangeEndpoint: info.TokenExchangeEndpoint,
|
|
59
90
|
redirectUri,
|
|
60
91
|
returnTo: login.returnTo ?? currentPath(),
|
|
61
|
-
silent: login.prompt === "none"
|
|
92
|
+
silent: login.prompt === "none",
|
|
93
|
+
hintedOrganization: alias,
|
|
94
|
+
retriedForOrganization: retry.retriedForOrganization
|
|
62
95
|
};
|
|
63
96
|
sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));
|
|
64
|
-
const orgScope = login.organization ? `organization:${login.organization}` : "organization";
|
|
65
97
|
const params = {
|
|
66
98
|
response_type: "code",
|
|
67
99
|
client_id: clientId,
|
|
@@ -112,10 +144,16 @@ async function doCompleteLogin() {
|
|
|
112
144
|
throw new Error(`IdP token endpoint ${tokenResp.status}: ${await tokenResp.text()}`);
|
|
113
145
|
}
|
|
114
146
|
const idpToken = await tokenResp.json();
|
|
147
|
+
const idpClaims = decodeJwtClaims(idpToken.access_token);
|
|
148
|
+
if (!organizationAliasOf(idpClaims) && !saved.retriedForOrganization) {
|
|
149
|
+
if (saved.hintedOrganization) rememberOrganization(saved.clientId, void 0);
|
|
150
|
+
throw new OrganizationMissing(saved.returnTo);
|
|
151
|
+
}
|
|
115
152
|
const minted = await exchange(saved.exchangeEndpoint, idpToken.access_token);
|
|
153
|
+
rememberOrganization(saved.clientId, organizationAliasOf(idpClaims));
|
|
116
154
|
return {
|
|
117
155
|
...minted,
|
|
118
|
-
idpClaims
|
|
156
|
+
idpClaims,
|
|
119
157
|
idToken: typeof idpToken.id_token === "string" ? idpToken.id_token : void 0
|
|
120
158
|
};
|
|
121
159
|
}
|
|
@@ -176,12 +214,6 @@ function getAccessToken() {
|
|
|
176
214
|
}
|
|
177
215
|
var ConfigHubAuthContext = createContext(null);
|
|
178
216
|
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
217
|
function readPersisted() {
|
|
186
218
|
try {
|
|
187
219
|
const raw = sessionStorage.getItem(SESSION_KEY);
|
|
@@ -249,13 +281,23 @@ function ConfigHubAuthProvider({
|
|
|
249
281
|
setStatus("unauthenticated");
|
|
250
282
|
}).catch((e) => {
|
|
251
283
|
if (cancelled) return;
|
|
284
|
+
if (e instanceof OrganizationMissing) {
|
|
285
|
+
void startLogin(
|
|
286
|
+
baseUrl,
|
|
287
|
+
clientId,
|
|
288
|
+
{ returnTo: e.returnTo, organization: null },
|
|
289
|
+
flow,
|
|
290
|
+
{ retriedForOrganization: true }
|
|
291
|
+
);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
252
294
|
setError(e instanceof Error ? e : new Error(String(e)));
|
|
253
295
|
setStatus("error");
|
|
254
296
|
});
|
|
255
297
|
return () => {
|
|
256
298
|
cancelled = true;
|
|
257
299
|
};
|
|
258
|
-
}, [applySession, persist]);
|
|
300
|
+
}, [applySession, persist, baseUrl, clientId, flow]);
|
|
259
301
|
const login = useCallback(
|
|
260
302
|
async (options) => {
|
|
261
303
|
setError(null);
|
|
@@ -288,13 +330,14 @@ function ConfigHubAuthProvider({
|
|
|
288
330
|
const current = sessionRef.current;
|
|
289
331
|
if (!current) throw new Error("not authenticated");
|
|
290
332
|
const minted = await switchOrganization(baseUrl, current.accessToken, organizationId);
|
|
333
|
+
rememberOrganization(clientId, void 0);
|
|
291
334
|
applySession({ ...current, ...minted });
|
|
292
335
|
},
|
|
293
|
-
[applySession, baseUrl]
|
|
336
|
+
[applySession, baseUrl, clientId]
|
|
294
337
|
);
|
|
295
338
|
const getToken = useCallback(() => sessionRef.current?.accessToken, []);
|
|
296
339
|
const reauthenticate = useCallback(async () => {
|
|
297
|
-
const organization =
|
|
340
|
+
const organization = organizationAliasOf(sessionRef.current?.idpClaims ?? {});
|
|
298
341
|
sessionRef.current = void 0;
|
|
299
342
|
setAccessToken(void 0);
|
|
300
343
|
persistSession(void 0);
|
|
@@ -343,6 +386,6 @@ function useConfigHub() {
|
|
|
343
386
|
return useAuth().client;
|
|
344
387
|
}
|
|
345
388
|
|
|
346
|
-
export { ConfigHubAuthContext, ConfigHubAuthProvider, callbackUri, decodeJwtClaims, getAccessToken, isExpired, useAuth, useConfigHub };
|
|
389
|
+
export { ConfigHubAuthContext, ConfigHubAuthProvider, OrganizationMissing, callbackUri, decodeJwtClaims, getAccessToken, isExpired, organizationAliasOf, rememberedOrganization, useAuth, useConfigHub };
|
|
347
390
|
//# sourceMappingURL=index.js.map
|
|
348
391
|
//# 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,C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,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;AC5RO,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 * 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":";;;;;;;AAiGO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,YAA4B,QAAA,EAAkB;AAC5C,IAAA,KAAA,CAAM,2DAA2D,CAAA;AADvC,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAE1B,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAOA,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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//\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 /** The organization alias the authorize request hinted, if any. */\n hintedOrganization?: string;\n /** This login is already the retry after a token without an organization. */\n retriedForOrganization?: boolean;\n}\n\n/**\n * Thrown by `completeLoginFromRedirect` when the IdP token names no organization,\n * which the exchange would refuse. Seen on a fresh brokered (Google) login, where\n * Keycloak's organization step does not run; on the next login the SSO session is\n * alive and it does, so the caller logs in again, once, with no hint. Any\n * remembered alias has already been forgotten.\n */\nexport class OrganizationMissing extends Error {\n constructor(public readonly returnTo: string) {\n super('the identity provider issued a token with no organization');\n this.name = 'OrganizationMissing';\n }\n}\n\nexport interface RetryOptions {\n /** @internal set by the provider on the one retry after OrganizationMissing. */\n retriedForOrganization?: 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 retry: RetryOptions = {},\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 // 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 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 hintedOrganization: alias,\n retriedForOrganization: retry.retriedForOrganization,\n };\n sessionStorage.setItem(PKCE_KEY, JSON.stringify(pkce));\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 idpClaims = decodeJwtClaims(idpToken.access_token);\n if (!organizationAliasOf(idpClaims) && !saved.retriedForOrganization) {\n // The exchange would refuse this token. Rather than surface that, log in\n // once more: with the SSO session now alive the IdP runs its organization\n // step. A hint that was sent evidently did not help, so forget it.\n if (saved.hintedOrganization) rememberOrganization(saved.clientId, undefined);\n throw new OrganizationMissing(saved.returnTo);\n }\n const minted = await exchange(saved.exchangeEndpoint, 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 OrganizationMissing,\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 if (e instanceof OrganizationMissing) {\n // Once, with no hint, flagged so a second miss surfaces as an error.\n void startLogin(\n baseUrl,\n clientId,\n { returnTo: e.returnTo, organization: null },\n flow,\n { retriedForOrganization: true },\n );\n return;\n }\n setError(e instanceof Error ? e : new Error(String(e)));\n setStatus('error');\n });\n return () => {\n cancelled = true;\n };\n }, [applySession, persist, baseUrl, clientId, flow]);\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.
|
|
3
|
+
"version": "0.4.3",
|
|
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.
|
|
42
|
+
"@confighub/api": "^0.4.3"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
45
|
"react": "^18.0.0 || ^19.0.0"
|