@blackbelt-technology/pi-dashboard-client-utils 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,75 +1,45 @@
1
1
  /**
2
- * StatusPill primitive — state-tinted pill (badge) with optional MDI icon.
2
+ * StatusPill primitive (`ui:status-pill`): state-tinted pill with a default icon.
3
3
  *
4
4
  * Registered as `ui:status-pill` in the primitive registry. Plugins emit
5
- * `{primitive: "ui:status-pill", props: {state, text, icon?}}`.
5
+ * `{primitive: "ui:status-pill", props: {state, text, icon?, tooltip?}}`.
6
6
  *
7
- * Provides a consistent badge style so plugins migrating to intent
8
- * rendering get visual parity. See change:
9
- * adopt-server-driven-intent-rendering.
7
+ * Renders the runtime kit's `SettingsStatusPill`, so colours come from the
8
+ * `--severity-*` tokens in every theme palette (no raw colours, no theme
9
+ * observer). The public props and `data-status-pill` are unchanged.
10
+ *
11
+ * See change: adopt-server-driven-intent-rendering,
12
+ * align-ui-contract-recipes (design D2).
10
13
  */
11
- import React, { useEffect, useState } from "react";
12
- import Icon from "@mdi/react";
13
- import * as mdi from "@mdi/js";
14
+
15
+ import { SettingsStatusPill, type SettingsStatusTone } from "@blackbelt-technology/dashboard-plugin-runtime";
14
16
  import type {
15
17
  UiStatusPillProps,
16
18
  UiStatusPillState,
17
19
  } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
20
+ import { mdiLoading, mdiMinusCircleOutline } from "@mdi/js";
21
+ import { useMdiIconByKey } from "./mdi-by-key.js";
18
22
 
19
- const STATE_STYLE_DARK: Record<UiStatusPillState, { bg: string; fg: string }> = {
20
- running: { bg: "rgba(34, 197, 94, 0.15)", fg: "rgb(134, 239, 172)" },
21
- success: { bg: "rgba(34, 197, 94, 0.15)", fg: "rgb(134, 239, 172)" },
22
- info: { bg: "rgba(59, 130, 246, 0.15)", fg: "rgb(147, 197, 253)" },
23
- warn: { bg: "rgba(234, 179, 8, 0.15)", fg: "rgb(253, 224, 71)" },
24
- error: { bg: "rgba(239, 68, 68, 0.15)", fg: "rgb(252, 165, 165)" },
25
- muted: { bg: "rgba(107, 114, 128, 0.2)", fg: "rgb(209, 213, 219)" },
26
- };
27
-
28
- const STATE_STYLE_LIGHT: Record<UiStatusPillState, { bg: string; fg: string }> = {
29
- running: { bg: "rgba(34, 197, 94, 0.18)", fg: "rgb(21, 128, 61)" },
30
- success: { bg: "rgba(34, 197, 94, 0.18)", fg: "rgb(21, 128, 61)" },
31
- info: { bg: "rgba(59, 130, 246, 0.15)", fg: "rgb(29, 78, 216)" },
32
- warn: { bg: "rgba(234, 179, 8, 0.20)", fg: "rgb(161, 98, 7)" },
33
- error: { bg: "rgba(239, 68, 68, 0.15)", fg: "rgb(185, 28, 28)" },
34
- muted: { bg: "rgba(107, 114, 128, 0.20)", fg: "rgb(55, 65, 81)" },
23
+ const STATE_TONE: Record<UiStatusPillState, SettingsStatusTone> = {
24
+ running: "info",
25
+ success: "success",
26
+ info: "info",
27
+ warn: "warning",
28
+ error: "error",
29
+ muted: "neutral",
35
30
  };
36
31
 
37
- function useIsLightTheme(): boolean {
38
- const read = () =>
39
- typeof document !== "undefined" &&
40
- document.documentElement.getAttribute("data-theme") === "light";
41
- const [light, setLight] = useState(read);
42
- useEffect(() => {
43
- if (typeof document === "undefined") return;
44
- const obs = new MutationObserver(() => setLight(read()));
45
- obs.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
46
- return () => obs.disconnect();
47
- }, []);
48
- return light;
49
- }
50
-
51
32
  export function StatusPill({ state, text, icon, tooltip }: UiStatusPillProps) {
52
- const light = useIsLightTheme();
53
- const palette = light ? STATE_STYLE_LIGHT[state] : STATE_STYLE_DARK[state];
33
+ const running = state === "running";
34
+ // A progress state always shows the progress glyph, so it never needs the lazy set.
35
+ const resolved = useMdiIconByKey(running ? undefined : icon);
36
+ // The kit's neutral tone has no default glyph; `muted` still reads without colour.
37
+ const glyph = running ? mdiLoading : (resolved ?? (state === "muted" ? mdiMinusCircleOutline : undefined));
54
38
  return (
55
- <span
56
- title={tooltip}
57
- className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium"
58
- style={{ backgroundColor: palette.bg, color: palette.fg }}
59
- data-status-pill={state}
60
- >
61
- {icon ? <IconByKey iconKey={icon} /> : null}
62
- <span>{text}</span>
39
+ <span title={tooltip} data-status-pill={state} className="inline-flex">
40
+ <SettingsStatusPill tone={STATE_TONE[state]} icon={glyph} spinning={running}>
41
+ {text}
42
+ </SettingsStatusPill>
63
43
  </span>
64
44
  );
65
45
  }
66
-
67
- function IconByKey({ iconKey }: { iconKey: string }) {
68
- // @mdi/js is already eager (statically imported across the shell), so this
69
- // is a synchronous flat property lookup — no dynamic import, no loading
70
- // state. See change: shrink-client-index-chunk.
71
- const candidate = (mdi as Record<string, unknown>)[iconKey];
72
- const path = typeof candidate === "string" ? candidate : null;
73
- if (!path) return null;
74
- return <Icon path={path} size={0.55} />;
75
- }
@@ -1,21 +1,36 @@
1
- import React from "react";
1
+ import { mdiArrowExpandAll, mdiMagnifyMinusOutline, mdiMagnifyPlusOutline } from "@mdi/js";
2
2
  import { Icon } from "@mdi/react";
3
- import { mdiMagnifyPlusOutline, mdiMagnifyMinusOutline, mdiArrowExpandAll } from "@mdi/js";
4
- // Shared zoom controls — used by MermaidBlock and FlowGraph
3
+ import React from "react";
4
+ // Shared zoom controls — used by MermaidBlock, DiagramPreview, FlowGraph and team-app
5
+
6
+ export interface ZoomControlLabels {
7
+ zoomIn: string;
8
+ zoomOut: string;
9
+ reset: string;
10
+ }
11
+
12
+ const DEFAULT_LABELS: ZoomControlLabels = { zoomIn: "Zoom in", zoomOut: "Zoom out", reset: "Reset zoom" };
5
13
 
6
14
  export function ZoomControls({
7
15
  onZoomIn,
8
16
  onZoomOut,
9
17
  onReset,
10
18
  scale,
19
+ initialScale = 1,
20
+ labels = DEFAULT_LABELS,
11
21
  }: {
12
22
  onZoomIn: () => void;
13
23
  onZoomOut: () => void;
14
24
  onReset: () => void;
15
25
  scale: number;
26
+ /** Scale the surface starts/resets at; the % readout shows only when scale differs. */
27
+ initialScale?: number;
28
+ /** Accessible names + titles. client-utils has no i18n, so hosts pass translated strings. */
29
+ labels?: ZoomControlLabels;
16
30
  }) {
31
+ // Icon-only buttons: 44 px below `sm`, 32 px from `sm` (ui-contract tap-target).
17
32
  const btnClass =
18
- "w-7 h-7 flex items-center justify-center rounded " +
33
+ "focus-ring min-w-[44px] min-h-[44px] sm:min-w-[32px] sm:min-h-[32px] flex items-center justify-center rounded " +
19
34
  "bg-[var(--bg-surface)]/80 hover:bg-[var(--bg-surface)] " +
20
35
  "border border-[var(--border-subtle)] " +
21
36
  "text-[var(--text-secondary)] hover:text-[var(--text-primary)] " +
@@ -26,20 +41,18 @@ export function ZoomControls({
26
41
  className="absolute top-2 right-2 z-10 flex flex-col gap-1"
27
42
  onPointerDown={(e) => e.stopPropagation()}
28
43
  >
29
- <button className={btnClass} onClick={onZoomIn} title="Zoom in">
30
- <Icon path={mdiMagnifyPlusOutline} size={0.6} />
44
+ <button type="button" className={btnClass} onClick={onZoomIn} title={labels.zoomIn} aria-label={labels.zoomIn}>
45
+ <Icon path={mdiMagnifyPlusOutline} size={0.6} aria-hidden="true" />
31
46
  </button>
32
- <button className={btnClass} onClick={onZoomOut} title="Zoom out">
33
- <Icon path={mdiMagnifyMinusOutline} size={0.6} />
47
+ <button type="button" className={btnClass} onClick={onZoomOut} title={labels.zoomOut} aria-label={labels.zoomOut}>
48
+ <Icon path={mdiMagnifyMinusOutline} size={0.6} aria-hidden="true" />
34
49
  </button>
35
- <button className={btnClass} onClick={onReset} title="Reset zoom">
36
- <Icon path={mdiArrowExpandAll} size={0.6} />
50
+ <button type="button" className={btnClass} onClick={onReset} title={labels.reset} aria-label={labels.reset}>
51
+ <Icon path={mdiArrowExpandAll} size={0.6} aria-hidden="true" />
37
52
  </button>
38
- {scale !== 1 && (
39
- <div className="text-[10px] text-[var(--text-muted)] text-center tabular-nums">
40
- {Math.round(scale * 100)}%
41
- </div>
42
- )}
53
+ <div aria-live="polite" className="text-[11px] text-[var(--text-secondary)] text-center tabular-nums">
54
+ {scale !== initialScale ? `${Math.round(scale * 100)}%` : null}
55
+ </div>
43
56
  </div>
44
57
  );
45
58
  }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Conditional DPoP (RFC 9449) for the browser identity plane (openspec §12.5).
3
+ *
4
+ * DPoP is OPT-IN and driven entirely by the IdP: the client generates a proof
5
+ * only once the token endpoint has issued a `cnf.jkt`-bound token. When the
6
+ * token is unbound (no `cnf.jkt`), no keypair is created and no proof is ever
7
+ * attached — the plane behaves as a plain bearer client.
8
+ *
9
+ * The signing keypair is a NON-EXTRACTABLE WebCrypto ES256 key: the private key
10
+ * never leaves the browser's key store (cannot be serialized, cannot be
11
+ * exfiltrated by XSS), so a stolen access token is useless without this origin's
12
+ * live key. A fresh proof is minted per REST call and per ticket mint — never
13
+ * reused — each carrying a unique `jti` and the request's `htm`/`htu`.
14
+ */
15
+
16
+ /** A bound DPoP session: the live keypair + its public JWK (for the proof header). */
17
+ export interface DpopKey {
18
+ keyPair: CryptoKeyPair;
19
+ publicJwk: JsonWebKey;
20
+ }
21
+
22
+ function base64Url(bytes: ArrayBuffer | Uint8Array): string {
23
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
24
+ let bin = "";
25
+ for (const x of b) bin += String.fromCharCode(x);
26
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
27
+ }
28
+
29
+ /**
30
+ * True when WebCrypto's `crypto.subtle` exists. It is secure-context-only
31
+ * (HTTPS / localhost), so a dashboard served on a plain-http LAN origin — e.g.
32
+ * after a knock pairing — has no DPoP: callers must treat that as "unbound
33
+ * bearer client" rather than an error. See change: add-lan-knock-pairing (D17).
34
+ */
35
+ export function isDpopAvailable(): boolean {
36
+ return typeof crypto !== "undefined" && !!crypto.subtle;
37
+ }
38
+
39
+ /**
40
+ * Generate a non-extractable ES256 keypair + export its public JWK.
41
+ * Resolves `null` (never throws a TypeError) when DPoP is unavailable in this
42
+ * context — check `isDpopAvailable()` or the result. A `DpopKey` can only exist
43
+ * where `crypto.subtle` does, so `createDpopProof` needs no separate guard.
44
+ */
45
+ export async function generateDpopKey(): Promise<DpopKey | null> {
46
+ if (!isDpopAvailable()) return null;
47
+ const keyPair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, [
48
+ "sign",
49
+ "verify",
50
+ ]);
51
+ const full = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
52
+ // Only the public coordinates go on the wire (RFC 9449 §4.2 `jwk` header).
53
+ const publicJwk: JsonWebKey = { kty: full.kty, crv: full.crv, x: full.x, y: full.y };
54
+ return { keyPair, publicJwk };
55
+ }
56
+
57
+ /**
58
+ * Create a fresh DPoP proof JWT binding an HTTP method (`htm`) + URL (`htu`).
59
+ * `nonce` is included when the server supplied one via `DPoP-Nonce`. Each call
60
+ * mints a unique `jti` + `iat`, so proofs are never reused.
61
+ */
62
+ export async function createDpopProof(
63
+ key: DpopKey,
64
+ htm: string,
65
+ htu: string,
66
+ nonce?: string,
67
+ ): Promise<string> {
68
+ const header = { typ: "dpop+jwt", alg: "ES256", jwk: key.publicJwk };
69
+ const payload: Record<string, unknown> = {
70
+ jti: base64Url(crypto.getRandomValues(new Uint8Array(16))),
71
+ htm: htm.toUpperCase(),
72
+ htu,
73
+ iat: Math.floor(Date.now() / 1000),
74
+ ...(nonce ? { nonce } : {}),
75
+ };
76
+ const signingInput = `${base64Url(new TextEncoder().encode(JSON.stringify(header)))}.${base64Url(
77
+ new TextEncoder().encode(JSON.stringify(payload)),
78
+ )}`;
79
+ const sig = await crypto.subtle.sign(
80
+ { name: "ECDSA", hash: "SHA-256" },
81
+ key.keyPair.privateKey,
82
+ new TextEncoder().encode(signingInput),
83
+ );
84
+ return `${signingInput}.${base64Url(sig)}`;
85
+ }
86
+
87
+ /** True when a token-endpoint response carries a `cnf.jkt` (DPoP-bound). */
88
+ export function isDpopBound(tokenResponse: { cnf?: { jkt?: string } } | Record<string, unknown>): boolean {
89
+ const cnf = (tokenResponse as { cnf?: { jkt?: unknown } }).cnf;
90
+ return typeof cnf?.jkt === "string" && cnf.jkt.length > 0;
91
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Reusable browser OIDC login/logout mechanics (D16/D17/D18).
3
+ *
4
+ * Provider-agnostic engine for the identity seam: any dashboard plugin that
5
+ * claims the core `login-provider` slot drives these functions to run the
6
+ * browser half of an authorization-code + PKCE flow. Core ships NO login UI
7
+ * and the token-resolver plugin ships none either — the login/logout UI is a
8
+ * separate authorization plugin that imports this module (seam-only delivery).
9
+ *
10
+ * Pure of React so it unit-tests without jsdom. Reads/writes the shared
11
+ * `token-store` singleton — the SAME module core's fetch wrapper reads, so a
12
+ * token written here is visible to every subsequent `/api` request without any
13
+ * handoff.
14
+ *
15
+ * `start` half: fetch the generic login descriptor (`/api/identity/login-config`)
16
+ * → OIDC-discover the browser issuer → build a PKCE-S256 authorize request →
17
+ * persist {verifier,state,returnTo,+endpoints} → redirect. `callback` half:
18
+ * verify `state`, exchange the code, store the (plain bearer) token, report the
19
+ * recovered return-to. `logout` half: clear tokens FIRST, then RP-initiated
20
+ * logout redirect.
21
+ *
22
+ * Core owns return-to VALIDATION (open-redirect defence) and the post-callback
23
+ * navigation; this module only persists the value core handed it and relays it
24
+ * back via the callback result. DPoP-bound login is a documented non-goal
25
+ * (B4/LG-19): a plain bearer is stored, no key is persisted across the redirect.
26
+ */
27
+
28
+ import { buildAuthorizeRequest, exchangeCode, type OidcClientConfig } from "./oidc-flow.js";
29
+ import { clearAccessToken, getIdToken, setAccessToken, setIdToken } from "./token-store.js";
30
+
31
+ /** sessionStorage key holding the transient PKCE state across the redirect. */
32
+ export const STASH_KEY = "pi-identity:login";
33
+ /** Core-owned pre-token route the authorize request redirects back to. */
34
+ export const CALLBACK_PATH = "/callback";
35
+
36
+ interface LoginConfig {
37
+ active: boolean;
38
+ issuer?: string;
39
+ clientId?: string;
40
+ }
41
+
42
+ interface Stash {
43
+ verifier: string;
44
+ state: string;
45
+ returnTo: string;
46
+ tokenEndpoint: string;
47
+ clientId: string;
48
+ redirectUri: string;
49
+ }
50
+
51
+ /** OIDC discovery document fields this flow consumes. */
52
+ interface Discovery {
53
+ authorization_endpoint: string;
54
+ token_endpoint: string;
55
+ /** RP-initiated logout endpoint (D18). */
56
+ end_session_endpoint?: string;
57
+ }
58
+
59
+ /** Why a login attempt failed (D17/R3) — rendered by the provider for diagnosis. */
60
+ export type LoginFailureReason =
61
+ | "insecure-context"
62
+ | "discovery-failed"
63
+ | "exchange-failed"
64
+ | "state-mismatch"
65
+ | "idp-error";
66
+
67
+ /** Typed rejection from `beginLogin`/`beginLogout` so the provider can render a cause. */
68
+ export class LoginFlowError extends Error {
69
+ readonly reason: LoginFailureReason;
70
+ constructor(reason: LoginFailureReason, cause?: unknown) {
71
+ super(reason, { cause });
72
+ this.name = "LoginFlowError";
73
+ this.reason = reason;
74
+ }
75
+ }
76
+
77
+ async function fetchJson<T>(url: string): Promise<T> {
78
+ const res = await fetch(url);
79
+ if (!res.ok) throw new Error(`fetch failed: ${res.status}`);
80
+ return (await res.json()) as T;
81
+ }
82
+
83
+ /**
84
+ * Start phase: discover, build the PKCE authorize request, persist the
85
+ * transient state, and redirect the browser. Throws when login is not
86
+ * configured (the caller renders the failure state).
87
+ */
88
+ export async function beginLogin(returnTo: string): Promise<void> {
89
+ let cfg: LoginConfig;
90
+ let disc: Discovery;
91
+ try {
92
+ cfg = await fetchJson<LoginConfig>("/api/identity/login-config");
93
+ if (!cfg.active || !cfg.issuer || !cfg.clientId) throw new Error("login not configured");
94
+ disc = await fetchJson<Discovery>(
95
+ `${cfg.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`,
96
+ );
97
+ } catch (err) {
98
+ throw new LoginFlowError("discovery-failed", err);
99
+ }
100
+ const redirectUri = `${window.location.origin}${CALLBACK_PATH}`;
101
+ const config: OidcClientConfig = {
102
+ authorizationEndpoint: disc.authorization_endpoint,
103
+ tokenEndpoint: disc.token_endpoint,
104
+ clientId: cfg.clientId,
105
+ redirectUri,
106
+ scope: "openid",
107
+ };
108
+ let req: Awaited<ReturnType<typeof buildAuthorizeRequest>>;
109
+ try {
110
+ req = await buildAuthorizeRequest(config);
111
+ } catch (err) {
112
+ // Belt-and-braces (D17): with the pure-JS S256 fallback this arm is
113
+ // normally unreachable, but a missing WebCrypto is still worth naming.
114
+ throw new LoginFlowError(globalThis.crypto?.subtle ? "discovery-failed" : "insecure-context", err);
115
+ }
116
+ const stash: Stash = {
117
+ verifier: req.verifier,
118
+ state: req.state,
119
+ returnTo,
120
+ tokenEndpoint: config.tokenEndpoint,
121
+ clientId: cfg.clientId,
122
+ redirectUri,
123
+ };
124
+ sessionStorage.setItem(STASH_KEY, JSON.stringify(stash));
125
+ window.location.assign(req.url);
126
+ }
127
+
128
+ /**
129
+ * Logout phase (D18): the local tokens are cleared FIRST — a broken IdP can
130
+ * never keep this browser signed in locally — then the browser is redirected
131
+ * to the IdP's `end_session_endpoint` (OIDC RP-Initiated Logout 1.0) with
132
+ * `client_id`, a same-origin `post_logout_redirect_uri`, and `id_token_hint`
133
+ * when one was retained. Throws a typed `LoginFlowError` when the IdP side
134
+ * cannot be reached (the local sign-out has already happened).
135
+ */
136
+ export async function beginLogout(): Promise<void> {
137
+ const idToken = getIdToken();
138
+ clearAccessToken();
139
+ let cfg: LoginConfig;
140
+ let disc: Discovery;
141
+ try {
142
+ cfg = await fetchJson<LoginConfig>("/api/identity/login-config");
143
+ if (!cfg.active || !cfg.issuer || !cfg.clientId) throw new Error("login not configured");
144
+ disc = await fetchJson<Discovery>(
145
+ `${cfg.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`,
146
+ );
147
+ if (!disc.end_session_endpoint) throw new Error("no end_session_endpoint");
148
+ } catch (err) {
149
+ throw new LoginFlowError("discovery-failed", err);
150
+ }
151
+ const url = new URL(disc.end_session_endpoint);
152
+ url.searchParams.set("client_id", cfg.clientId);
153
+ url.searchParams.set("post_logout_redirect_uri", `${window.location.origin}/`);
154
+ if (idToken) url.searchParams.set("id_token_hint", idToken);
155
+ window.location.assign(url.toString());
156
+ }
157
+
158
+ export type CallbackResult =
159
+ /** Token stored; core validates `returnTo` again and navigates. */
160
+ | { kind: "done"; returnTo: string }
161
+ /** No code / missing stash — abandon quietly, show the manual affordance. */
162
+ | { kind: "idle" }
163
+ /** IdP error, state mismatch, or exchange failure — show the failure state. */
164
+ | { kind: "error"; reason: LoginFailureReason };
165
+
166
+ /**
167
+ * Callback phase: verify `state`, exchange the code, store the bearer, and
168
+ * return the recovered return-to. Never throws on an expected non-happy path
169
+ * (IdP error, mismatch, missing stash) — those map to a `CallbackResult`.
170
+ */
171
+ export async function completeLogin(search: string): Promise<CallbackResult> {
172
+ const params = new URLSearchParams(search);
173
+ if (params.get("error")) return { kind: "error", reason: "idp-error" }; // LG-14 — no exchange
174
+ const code = params.get("code");
175
+ const state = params.get("state");
176
+ const raw = sessionStorage.getItem(STASH_KEY);
177
+ if (!raw || !code || !state) return { kind: "idle" }; // LG-13 — safe landing
178
+ const stash = JSON.parse(raw) as Stash;
179
+ if (stash.state !== state) return { kind: "error", reason: "state-mismatch" }; // LG-10 — no exchange
180
+ const config: OidcClientConfig = {
181
+ authorizationEndpoint: "",
182
+ tokenEndpoint: stash.tokenEndpoint,
183
+ clientId: stash.clientId,
184
+ redirectUri: stash.redirectUri,
185
+ };
186
+ try {
187
+ const tok = await exchangeCode(config, { code, verifier: stash.verifier });
188
+ setAccessToken(tok.accessToken, tok.expiresIn);
189
+ if (tok.idToken) setIdToken(tok.idToken); // retained for logout's id_token_hint (D18)
190
+ } catch {
191
+ // Token endpoint unreachable or refused the exchange (D17/R3) — an
192
+ // expected non-happy path, never an unhandled rejection.
193
+ return { kind: "error", reason: "exchange-failed" };
194
+ }
195
+ sessionStorage.removeItem(STASH_KEY);
196
+ return { kind: "done", returnTo: stash.returnTo };
197
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * OIDC public-client authorization-code + PKCE flow helpers (openspec §12.1,
3
+ * RFC 6749 §4.1 + RFC 7636). Pure functions over a resolved client config so
4
+ * they unit-test without a live IdP; the UI glue (redirect + callback capture)
5
+ * and the server-provided config live at the call site.
6
+ */
7
+
8
+ import { createPkcePair, createRandomState, type PkcePair } from "./pkce.js";
9
+
10
+ /** Public-client OIDC config, sourced from the server/discovery at runtime. */
11
+ export interface OidcClientConfig {
12
+ authorizationEndpoint: string;
13
+ tokenEndpoint: string;
14
+ clientId: string;
15
+ redirectUri: string;
16
+ /** Space-delimited scopes; defaults to `openid` when omitted. */
17
+ scope?: string;
18
+ }
19
+
20
+ /** The transient state a caller stashes between authorize and callback. */
21
+ export interface AuthorizeRequest {
22
+ url: string;
23
+ verifier: string;
24
+ state: string;
25
+ }
26
+
27
+ /** Normalized token-endpoint response. */
28
+ export interface TokenResponse {
29
+ accessToken: string;
30
+ expiresIn: number;
31
+ /** Present when the IdP issued a `cnf.jkt`-bound (DPoP) token (§12.5). */
32
+ tokenType: string;
33
+ /** ID token, when issued — retained only as logout's `id_token_hint` (D18). */
34
+ idToken?: string;
35
+ }
36
+
37
+ /**
38
+ * Build the authorization-request URL (S256 PKCE) plus the `verifier`/`state`
39
+ * the caller must retain to complete the exchange. Redirect the browser to
40
+ * `url`; on return, match `state` and call `exchangeCode` with `verifier`.
41
+ */
42
+ export async function buildAuthorizeRequest(
43
+ config: OidcClientConfig,
44
+ pkce?: PkcePair,
45
+ ): Promise<AuthorizeRequest> {
46
+ const pair = pkce ?? (await createPkcePair());
47
+ const state = createRandomState();
48
+ const q = new URLSearchParams({
49
+ response_type: "code",
50
+ client_id: config.clientId,
51
+ redirect_uri: config.redirectUri,
52
+ scope: config.scope ?? "openid",
53
+ code_challenge: pair.challenge,
54
+ code_challenge_method: pair.method,
55
+ state,
56
+ });
57
+ return { url: `${config.authorizationEndpoint}?${q.toString()}`, verifier: pair.verifier, state };
58
+ }
59
+
60
+ /**
61
+ * Exchange an authorization `code` + PKCE `verifier` for tokens at the token
62
+ * endpoint. `extraHeaders` carries a DPoP proof when the flow is bound (§12.5).
63
+ * Throws on a non-2xx response so the caller surfaces the auth failure.
64
+ */
65
+ export async function exchangeCode(
66
+ config: OidcClientConfig,
67
+ input: { code: string; verifier: string },
68
+ extraHeaders?: Record<string, string>,
69
+ ): Promise<TokenResponse> {
70
+ const body = new URLSearchParams({
71
+ grant_type: "authorization_code",
72
+ code: input.code,
73
+ client_id: config.clientId,
74
+ redirect_uri: config.redirectUri,
75
+ code_verifier: input.verifier,
76
+ });
77
+ const res = await fetch(config.tokenEndpoint, {
78
+ method: "POST",
79
+ headers: { "Content-Type": "application/x-www-form-urlencoded", ...extraHeaders },
80
+ body: body.toString(),
81
+ });
82
+ if (!res.ok) throw new Error(`token exchange failed: ${res.status}`);
83
+ const json = (await res.json()) as {
84
+ access_token?: string;
85
+ expires_in?: number;
86
+ token_type?: string;
87
+ id_token?: string;
88
+ };
89
+ if (!json.access_token) throw new Error("token exchange returned no access_token");
90
+ return {
91
+ accessToken: json.access_token,
92
+ expiresIn: json.expires_in ?? 0,
93
+ tokenType: json.token_type ?? "Bearer",
94
+ idToken: json.id_token,
95
+ };
96
+ }