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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-client-utils",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Small reusable React components, hooks, and helpers shared between the pi-dashboard shell and dashboard plugins. Per-subpath exports; no markdown stack.",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -33,6 +33,26 @@
33
33
  "types": "./src/escape-stack.ts",
34
34
  "default": "./src/escape-stack.ts"
35
35
  },
36
+ "./identity/pkce": {
37
+ "types": "./src/identity/pkce.ts",
38
+ "default": "./src/identity/pkce.ts"
39
+ },
40
+ "./identity/token-store": {
41
+ "types": "./src/identity/token-store.ts",
42
+ "default": "./src/identity/token-store.ts"
43
+ },
44
+ "./identity/oidc-flow": {
45
+ "types": "./src/identity/oidc-flow.ts",
46
+ "default": "./src/identity/oidc-flow.ts"
47
+ },
48
+ "./identity/login-flow": {
49
+ "types": "./src/identity/login-flow.ts",
50
+ "default": "./src/identity/login-flow.ts"
51
+ },
52
+ "./identity/dpop": {
53
+ "types": "./src/identity/dpop.ts",
54
+ "default": "./src/identity/dpop.ts"
55
+ },
36
56
  "./Popover": {
37
57
  "types": "./src/Popover.tsx",
38
58
  "default": "./src/Popover.tsx"
@@ -89,6 +109,10 @@
89
109
  "types": "./src/ActionList.tsx",
90
110
  "default": "./src/ActionList.tsx"
91
111
  },
112
+ "./mdi-by-key": {
113
+ "types": "./src/mdi-by-key.ts",
114
+ "default": "./src/mdi-by-key.ts"
115
+ },
92
116
  "./StatusPill": {
93
117
  "types": "./src/StatusPill.tsx",
94
118
  "default": "./src/StatusPill.tsx"
@@ -127,8 +151,8 @@
127
151
  "react-dom": ">=18.0.0"
128
152
  },
129
153
  "dependencies": {
130
- "@blackbelt-technology/dashboard-plugin-runtime": "^0.8.0",
131
- "@blackbelt-technology/pi-dashboard-shared": "^0.8.0",
154
+ "@blackbelt-technology/dashboard-plugin-runtime": "^0.9.0",
155
+ "@blackbelt-technology/pi-dashboard-shared": "^0.9.0",
132
156
  "@mdi/js": "^7.4.47",
133
157
  "@mdi/react": "^1.6.1"
134
158
  },
@@ -7,11 +7,12 @@
7
7
  *
8
8
  * See change: adopt-server-driven-intent-rendering.
9
9
  */
10
- import Icon from "@mdi/react";
11
- import * as mdi from "@mdi/js";
12
- // We accept icon as a string key (MDI), look up via resolveMdiIcon at render time.
13
- import type { UiActionListProps } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
10
+
14
11
  import { sendPluginAction } from "@blackbelt-technology/dashboard-plugin-runtime";
12
+ // Icon is an MDI key string, resolved lazily via useMdiIconByKey.
13
+ import type { UiActionListProps } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
14
+ import Icon from "@mdi/react";
15
+ import { useMdiIconByKey } from "./mdi-by-key.js";
15
16
 
16
17
  /**
17
18
  * Extended item shape: in addition to `onClick`, items may carry a
@@ -70,16 +71,12 @@ export function ActionList({ actions }: UiActionListProps) {
70
71
  }
71
72
 
72
73
  /**
73
- * Render an MDI icon by its export-name key. Best-effort — unknown keys
74
- * render nothing. The shell ships @mdi/js so this is a flat property
75
- * lookup.
74
+ * Render an MDI icon by its export-name key. Renders nothing while the full
75
+ * icon set loads and for unknown keys. See change:
76
+ * harden-ios-safari-memory-and-ws-diagnostics.
76
77
  */
77
78
  function IconByKey({ iconKey }: { iconKey: string }) {
78
- // @mdi/js is already eager (statically imported across the shell), so this
79
- // is a synchronous flat property lookup — no dynamic import, no loading
80
- // state. See change: shrink-client-index-chunk.
81
- const candidate = (mdi as Record<string, unknown>)[iconKey];
82
- const path = typeof candidate === "string" ? candidate : null;
79
+ const path = useMdiIconByKey(iconKey);
83
80
  if (!path) return null;
84
81
  return <Icon path={path} size={0.6} />;
85
82
  }
package/src/Dialog.tsx CHANGED
@@ -1,12 +1,15 @@
1
+ import { mdiClose } from "@mdi/js";
2
+ import { Icon } from "@mdi/react";
1
3
  import React, {
4
+ type ReactNode,
5
+ useCallback,
2
6
  useId,
3
7
  useRef,
4
- type ReactNode,
8
+ useState,
5
9
  } from "react";
6
- import { mdiClose } from "@mdi/js";
7
- import { Icon } from "@mdi/react";
8
10
  import { DialogPortal } from "./DialogPortal.js";
9
11
  import { useEscapeDismiss } from "./escape-stack.js";
12
+ import { LayerHostProvider } from "./LayerPortal.js";
10
13
  import { useFocusTrap } from "./useFocusTrap.js";
11
14
 
12
15
  export type DialogSize = "sm" | "md" | "lg" | "full";
@@ -75,6 +78,16 @@ export function Dialog({
75
78
  }: DialogProps) {
76
79
  const containerRef = useRef<HTMLDivElement>(null);
77
80
  const titleId = useId();
81
+ // The panel doubles as the layer host for any `LayerPortal` overlay a child
82
+ // opens (e.g. the run-config ModelSelector): portaling to `document.body`
83
+ // would land it at `z-popover`, BELOW this dialog's `z-dialog` backdrop. State
84
+ // (not just the ref) so children re-render once the element exists.
85
+ // See change: fix-composer-popover-layering.
86
+ const [panelEl, setPanelEl] = useState<HTMLDivElement | null>(null);
87
+ const setPanel = useCallback((el: HTMLDivElement | null) => {
88
+ containerRef.current = el;
89
+ setPanelEl(el);
90
+ }, []);
78
91
 
79
92
  useFocusTrap(containerRef, open);
80
93
 
@@ -101,7 +114,7 @@ export function Dialog({
101
114
  data-testid={testId ? `${testId}-overlay` : undefined}
102
115
  />
103
116
  <div
104
- ref={containerRef}
117
+ ref={setPanel}
105
118
  role="dialog"
106
119
  aria-modal="true"
107
120
  aria-labelledby={title ? titleId : undefined}
@@ -142,7 +155,7 @@ export function Dialog({
142
155
  )}
143
156
  </div>
144
157
  )}
145
- {children}
158
+ <LayerHostProvider host={panelEl}>{children}</LayerHostProvider>
146
159
  </div>
147
160
  </div>
148
161
  </DialogPortal>
@@ -1,10 +1,42 @@
1
+ import { createContext, type ReactNode, useContext } from "react";
1
2
  import { createPortal } from "react-dom";
2
- import type { ReactNode } from "react";
3
3
 
4
4
  /**
5
- * LayerPortal — portals an overlay to the top-level layer root (`document.body`)
6
- * so it escapes ALL ancestor stacking contexts (`transform`, `will-change`,
7
- * `opacity < 1`, `isolation: isolate`, an ancestor's own `z-*`).
5
+ * The nearest layer host a `LayerPortal` should portal INTO, overriding the
6
+ * default `document.body`.
7
+ *
8
+ * `body` is the right host only while nothing higher on the layer scale wraps
9
+ * the overlay. Inside a `Dialog` it is wrong: the dialog paints at `z-dialog`
10
+ * with a full-viewport backdrop, so a popover portaled to `body` becomes its
11
+ * SIBLING at the lower `z-popover` — it sinks behind the backdrop and every
12
+ * click on it dismisses the dialog instead. Portaling into the dialog panel
13
+ * keeps the popover inside the dialog's stacking context (so it rides the
14
+ * dialog's rank against the rest of the scale) and inside its focus trap, while
15
+ * still escaping the ancestor stacking contexts INSIDE the dialog.
16
+ *
17
+ * `null` (the default, and the value while a host element is still mounting)
18
+ * means `document.body` — the composer/card case, which must keep escaping all
19
+ * the way out.
20
+ *
21
+ * See change: fix-composer-popover-layering.
22
+ */
23
+ export const LayerHostContext = createContext<HTMLElement | null>(null);
24
+
25
+ export function LayerHostProvider({
26
+ host,
27
+ children,
28
+ }: {
29
+ host: HTMLElement | null;
30
+ children: ReactNode;
31
+ }) {
32
+ return <LayerHostContext.Provider value={host}>{children}</LayerHostContext.Provider>;
33
+ }
34
+
35
+ /**
36
+ * LayerPortal — portals an overlay to the nearest layer host, defaulting to the
37
+ * top-level layer root (`document.body`), so it escapes ALL ancestor stacking
38
+ * contexts (`transform`, `will-change`, `opacity < 1`, `isolation: isolate`, an
39
+ * ancestor's own `z-*`).
8
40
  *
9
41
  * This is the mechanism the `overlay-layering` spec calls "portal-or-perish":
10
42
  * a numeric z-index only orders siblings WITHIN the nearest ancestor stacking
@@ -20,8 +52,10 @@ import type { ReactNode } from "react";
20
52
  * its box. The portaled surface positions itself (`position: fixed`) from its
21
53
  * trigger's viewport rect and carries a `z-*` layer utility.
22
54
  *
23
- * See openspec spec overlay-layering. See change: add-overlay-layering-system.
55
+ * See openspec spec overlay-layering. See change: add-overlay-layering-system,
56
+ * fix-composer-popover-layering.
24
57
  */
25
58
  export function LayerPortal({ children }: { children: ReactNode }) {
26
- return createPortal(children, document.body);
59
+ const host = useContext(LayerHostContext);
60
+ return createPortal(children, host ?? document.body);
27
61
  }
@@ -7,6 +7,26 @@ export interface SelectOption {
7
7
  description?: string;
8
8
  badge?: string;
9
9
  badgeColor?: string;
10
+ /**
11
+ * Group caption this option renders under. Options sharing a group render
12
+ * beneath one caption, in first-appearance order; ungrouped options keep
13
+ * the flat list. Inert unless set.
14
+ */
15
+ group?: string;
16
+ /**
17
+ * Rendered visible but non-selectable (e.g. a picker entry whose selection
18
+ * would overwrite a conflicting credential). Arrow navigation skips it and
19
+ * Enter is a no-op. Inert unless set.
20
+ */
21
+ disabled?: boolean;
22
+ /** Tooltip for a disabled option — names the way out (e.g. remove-first). */
23
+ disabledReason?: string;
24
+ /**
25
+ * Always rendered, even when the search filter does not match — for a
26
+ * pinned entry (e.g. "Custom endpoint…") that must stay reachable under any
27
+ * search term. Inert unless set.
28
+ */
29
+ pinned?: boolean;
10
30
  }
11
31
 
12
32
  interface Props {
@@ -38,37 +58,59 @@ export function SearchableSelectDialog({
38
58
  const filtered = useMemo(() => {
39
59
  if (!query.trim()) return options;
40
60
  const q = query.toLowerCase();
61
+ // `value` is the id — the picker contract matches on display name AND id.
62
+ // Pinned options stay reachable under any search term.
41
63
  return options.filter(
42
- (o) => o.label.toLowerCase().includes(q) || o.description?.toLowerCase().includes(q),
64
+ (o) =>
65
+ o.pinned ||
66
+ o.label.toLowerCase().includes(q) ||
67
+ o.description?.toLowerCase().includes(q) ||
68
+ o.value.toLowerCase().includes(q),
43
69
  );
44
70
  }, [options, query]);
45
71
 
46
72
  // Reset selection when filter changes
47
73
  useEffect(() => {
48
74
  setSelectedIndex(0);
49
- }, [filtered.length]);
75
+ }, [filtered.length, query]);
50
76
 
51
- // Scroll selected item into view
77
+ // Scroll selected item into view. A group caption renders as its own child
78
+ // before its options, so children indices no longer map to option indices —
79
+ // target the selected row by attribute instead.
52
80
  useEffect(() => {
53
- const el = listRef.current?.children[selectedIndex] as HTMLElement | undefined;
81
+ const el = listRef.current?.querySelector('[data-active="true"]') as HTMLElement | undefined;
54
82
  el?.scrollIntoView?.({ block: "nearest" });
55
83
  }, [selectedIndex]);
56
84
 
85
+ const moveSelection = (dir: 1 | -1) => {
86
+ setSelectedIndex((i) => {
87
+ let next = i;
88
+ // Arrow navigation skips disabled options so Enter never lands on one.
89
+ do {
90
+ next += dir;
91
+ } while (next > 0 && next < filtered.length - 1 && filtered[next]?.disabled);
92
+ return Math.max(0, Math.min(next, filtered.length - 1));
93
+ });
94
+ };
95
+
57
96
  const handleKeyDown = (e: React.KeyboardEvent) => {
58
97
  if (e.key === "ArrowDown") {
59
98
  e.preventDefault();
60
- setSelectedIndex((i) => Math.min(i + 1, filtered.length - 1));
99
+ moveSelection(1);
61
100
  } else if (e.key === "ArrowUp") {
62
101
  e.preventDefault();
63
- setSelectedIndex((i) => Math.max(i - 1, 0));
102
+ moveSelection(-1);
64
103
  } else if (e.key === "Enter") {
65
104
  e.preventDefault();
66
- if (filtered[selectedIndex]) {
67
- onSelect(filtered[selectedIndex].value);
105
+ const opt = filtered[selectedIndex];
106
+ if (opt && !opt.disabled) {
107
+ onSelect(opt.value);
68
108
  }
69
109
  }
70
110
  };
71
111
 
112
+ let lastGroup: string | undefined;
113
+
72
114
  return (
73
115
  <Dialog open onClose={onCancel} title={title} size="sm">
74
116
  {/* Search */}
@@ -89,30 +131,51 @@ export function SearchableSelectDialog({
89
131
  {filtered.length === 0 ? (
90
132
  <div className="px-3 py-4 text-xs text-[var(--text-muted)] text-center">{emptyMessage}</div>
91
133
  ) : (
92
- filtered.map((opt, i) => (
93
- <div
94
- key={opt.value}
95
- onClick={() => onSelect(opt.value)}
96
- onMouseEnter={() => setSelectedIndex(i)}
97
- className={`px-3 py-1.5 rounded-lg cursor-pointer flex items-center gap-2 ${
98
- i === selectedIndex
99
- ? "bg-blue-500/15 text-[var(--text-primary)]"
100
- : "text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)]"
101
- }`}
102
- >
103
- <div className="flex-1 min-w-0">
104
- <div className="text-xs truncate">{opt.label}</div>
105
- {opt.description && (
106
- <div className="text-[10px] text-[var(--text-muted)] truncate">{opt.description}</div>
134
+ filtered.map((opt, i) => {
135
+ const caption = opt.group !== undefined && opt.group !== lastGroup ? opt.group : null;
136
+ lastGroup = opt.group;
137
+ return (
138
+ <React.Fragment key={opt.value}>
139
+ {caption && (
140
+ <div className="px-2 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)]">
141
+ {caption}
142
+ </div>
107
143
  )}
108
- </div>
109
- {opt.badge && (
110
- <span className={`text-[9px] px-1 py-0.5 rounded flex-shrink-0 ${opt.badgeColor || "text-[var(--text-tertiary)]"}`}>
111
- {opt.badge}
112
- </span>
113
- )}
114
- </div>
115
- ))
144
+ <div
145
+ role="option"
146
+ aria-selected={i === selectedIndex && !opt.disabled}
147
+ aria-disabled={opt.disabled || undefined}
148
+ title={opt.disabled ? opt.disabledReason : undefined}
149
+ data-active={i === selectedIndex}
150
+ onClick={() => { if (!opt.disabled) onSelect(opt.value); }}
151
+ onMouseEnter={() => setSelectedIndex(i)}
152
+ className={`px-3 py-1.5 rounded-lg flex items-center gap-2 ${
153
+ opt.disabled
154
+ ? "cursor-not-allowed opacity-55"
155
+ : "cursor-pointer"
156
+ } ${
157
+ i === selectedIndex
158
+ ? "bg-blue-500/15 text-[var(--text-primary)]"
159
+ : "text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)]"
160
+ }`}
161
+ >
162
+ <div className="flex-1 min-w-0">
163
+ <div className="text-xs truncate">{opt.label}</div>
164
+ {opt.description && (
165
+ <div className="text-[10px] text-[var(--text-muted)] truncate">
166
+ {opt.description}
167
+ </div>
168
+ )}
169
+ </div>
170
+ {opt.badge && (
171
+ <span className={`text-[9px] px-1 py-0.5 rounded flex-shrink-0 ${opt.badgeColor || "text-[var(--text-tertiary)]"}`}>
172
+ {opt.badge}
173
+ </span>
174
+ )}
175
+ </div>
176
+ </React.Fragment>
177
+ );
178
+ })
116
179
  )}
117
180
  </div>
118
181
 
@@ -8,13 +8,14 @@
8
8
  * rendering get visual parity. See change:
9
9
  * adopt-server-driven-intent-rendering.
10
10
  */
11
- import React, { useEffect, useState } from "react";
12
- import Icon from "@mdi/react";
13
- import * as mdi from "@mdi/js";
11
+
14
12
  import type {
15
13
  UiStatusPillProps,
16
14
  UiStatusPillState,
17
15
  } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
16
+ import Icon from "@mdi/react";
17
+ import React, { useEffect, useState } from "react";
18
+ import { useMdiIconByKey } from "./mdi-by-key.js";
18
19
 
19
20
  const STATE_STYLE_DARK: Record<UiStatusPillState, { bg: string; fg: string }> = {
20
21
  running: { bg: "rgba(34, 197, 94, 0.15)", fg: "rgb(134, 239, 172)" },
@@ -64,12 +65,13 @@ export function StatusPill({ state, text, icon, tooltip }: UiStatusPillProps) {
64
65
  );
65
66
  }
66
67
 
68
+ /**
69
+ * Render an MDI icon by its export-name key. Renders nothing while the full
70
+ * icon set loads and for unknown keys. See change:
71
+ * harden-ios-safari-memory-and-ws-diagnostics.
72
+ */
67
73
  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;
74
+ const path = useMdiIconByKey(iconKey);
73
75
  if (!path) return null;
74
76
  return <Icon path={path} size={0.55} />;
75
77
  }
@@ -1,6 +1,6 @@
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";
3
+ import React from "react";
4
4
  // Shared zoom controls — used by MermaidBlock and FlowGraph
5
5
 
6
6
  export function ZoomControls({
@@ -8,11 +8,14 @@ export function ZoomControls({
8
8
  onZoomOut,
9
9
  onReset,
10
10
  scale,
11
+ initialScale = 1,
11
12
  }: {
12
13
  onZoomIn: () => void;
13
14
  onZoomOut: () => void;
14
15
  onReset: () => void;
15
16
  scale: number;
17
+ /** Scale the surface starts/resets at; the % readout shows only when scale differs. */
18
+ initialScale?: number;
16
19
  }) {
17
20
  const btnClass =
18
21
  "w-7 h-7 flex items-center justify-center rounded " +
@@ -35,7 +38,7 @@ export function ZoomControls({
35
38
  <button className={btnClass} onClick={onReset} title="Reset zoom">
36
39
  <Icon path={mdiArrowExpandAll} size={0.6} />
37
40
  </button>
38
- {scale !== 1 && (
41
+ {scale !== initialScale && (
39
42
  <div className="text-[10px] text-[var(--text-muted)] text-center tabular-nums">
40
43
  {Math.round(scale * 100)}%
41
44
  </div>
@@ -0,0 +1,75 @@
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
+ /** Generate a non-extractable ES256 keypair + export its public JWK. */
30
+ export async function generateDpopKey(): Promise<DpopKey> {
31
+ const keyPair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, [
32
+ "sign",
33
+ "verify",
34
+ ]);
35
+ const full = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
36
+ // Only the public coordinates go on the wire (RFC 9449 §4.2 `jwk` header).
37
+ const publicJwk: JsonWebKey = { kty: full.kty, crv: full.crv, x: full.x, y: full.y };
38
+ return { keyPair, publicJwk };
39
+ }
40
+
41
+ /**
42
+ * Create a fresh DPoP proof JWT binding an HTTP method (`htm`) + URL (`htu`).
43
+ * `nonce` is included when the server supplied one via `DPoP-Nonce`. Each call
44
+ * mints a unique `jti` + `iat`, so proofs are never reused.
45
+ */
46
+ export async function createDpopProof(
47
+ key: DpopKey,
48
+ htm: string,
49
+ htu: string,
50
+ nonce?: string,
51
+ ): Promise<string> {
52
+ const header = { typ: "dpop+jwt", alg: "ES256", jwk: key.publicJwk };
53
+ const payload: Record<string, unknown> = {
54
+ jti: base64Url(crypto.getRandomValues(new Uint8Array(16))),
55
+ htm: htm.toUpperCase(),
56
+ htu,
57
+ iat: Math.floor(Date.now() / 1000),
58
+ ...(nonce ? { nonce } : {}),
59
+ };
60
+ const signingInput = `${base64Url(new TextEncoder().encode(JSON.stringify(header)))}.${base64Url(
61
+ new TextEncoder().encode(JSON.stringify(payload)),
62
+ )}`;
63
+ const sig = await crypto.subtle.sign(
64
+ { name: "ECDSA", hash: "SHA-256" },
65
+ key.keyPair.privateKey,
66
+ new TextEncoder().encode(signingInput),
67
+ );
68
+ return `${signingInput}.${base64Url(sig)}`;
69
+ }
70
+
71
+ /** True when a token-endpoint response carries a `cnf.jkt` (DPoP-bound). */
72
+ export function isDpopBound(tokenResponse: { cnf?: { jkt?: string } } | Record<string, unknown>): boolean {
73
+ const cnf = (tokenResponse as { cnf?: { jkt?: unknown } }).cnf;
74
+ return typeof cnf?.jkt === "string" && cnf.jkt.length > 0;
75
+ }
@@ -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
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * OIDC public-client PKCE (RFC 7636) primitives for the browser identity plane
3
+ * (openspec §12.1 / design D-topology-B). Pure functions over WebCrypto —
4
+ * `globalThis.crypto` works in the browser and in the jsdom/Node test env.
5
+ *
6
+ * The verifier is a high-entropy random string; the challenge is
7
+ * `BASE64URL(SHA-256(verifier))` with method `S256` (the only method we send —
8
+ * `plain` is disallowed by RFC 9700 for public clients).
9
+ */
10
+
11
+ /** A PKCE verifier/challenge pair. `method` is always `S256`. */
12
+ export interface PkcePair {
13
+ verifier: string;
14
+ challenge: string;
15
+ method: "S256";
16
+ }
17
+
18
+ /** Base64url (no padding) encode raw bytes — the RFC 7636 A-Z a-z 0-9 -_ set. */
19
+ function base64UrlEncode(bytes: Uint8Array): string {
20
+ let bin = "";
21
+ for (const b of bytes) bin += String.fromCharCode(b);
22
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
23
+ }
24
+
25
+ /**
26
+ * Generate a code verifier: 32 random bytes → base64url (43 chars), inside the
27
+ * RFC 7636 43–128 length window.
28
+ */
29
+ export function createCodeVerifier(): string {
30
+ const bytes = new Uint8Array(32);
31
+ crypto.getRandomValues(bytes);
32
+ return base64UrlEncode(bytes);
33
+ }
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // Pure-JS SHA-256 fallback (D17/R1). `crypto.subtle` exists only in secure
37
+ // contexts (HTTPS or localhost); on a plain-HTTP non-loopback origin — the
38
+ // legitimate remote topology-B case, e.g. `http://<tailnet-ip>:<port>` — it is
39
+ // undefined and S256 derivation would throw. FIPS 180-4, test-vectored against
40
+ // WebCrypto (`pkce-sha256-fallback.test.ts`). Used ONLY when `subtle` is
41
+ // absent; `crypto.getRandomValues` is never emulated (it exists everywhere).
42
+ // ---------------------------------------------------------------------------
43
+
44
+ // prettier-ignore
45
+ const K = new Uint32Array([
46
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
47
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
48
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
49
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
50
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
51
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
52
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
53
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
54
+ ]);
55
+
56
+ const rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));
57
+
58
+ /**
59
+ * FIPS 180-4 SHA-256 of raw bytes — the insecure-context fallback digest.
60
+ * Exported for known-answer/parity tests only; production callers go through
61
+ * `deriveCodeChallenge`, which prefers WebCrypto when available.
62
+ */
63
+ export function sha256Bytes(data: Uint8Array): Uint8Array {
64
+ const H = new Uint32Array([
65
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
66
+ ]);
67
+ const l = data.length;
68
+ // Smallest multiple of 64 that fits message + 0x80 marker + 64-bit length.
69
+ const padded = new Uint8Array((((l + 8) >> 6) + 1) << 6);
70
+ padded.set(data);
71
+ padded[l] = 0x80;
72
+ const dv = new DataView(padded.buffer);
73
+ dv.setUint32(padded.length - 8, Math.floor(l / 0x20000000));
74
+ dv.setUint32(padded.length - 4, (l << 3) >>> 0);
75
+ const w = new Uint32Array(64);
76
+ for (let off = 0; off < padded.length; off += 64) {
77
+ for (let i = 0; i < 16; i++) w[i] = dv.getUint32(off + i * 4);
78
+ for (let i = 16; i < 64; i++) {
79
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
80
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
81
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
82
+ }
83
+ let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];
84
+ for (let i = 0; i < 64; i++) {
85
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
86
+ const ch = (e & f) ^ (~e & g);
87
+ const t1 = (h + S1 + ch + K[i] + w[i]) >>> 0;
88
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
89
+ const maj = (a & b) ^ (a & c) ^ (b & c);
90
+ const t2 = (S0 + maj) >>> 0;
91
+ h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
92
+ }
93
+ H[0] = (H[0] + a) >>> 0; H[1] = (H[1] + b) >>> 0; H[2] = (H[2] + c) >>> 0; H[3] = (H[3] + d) >>> 0;
94
+ H[4] = (H[4] + e) >>> 0; H[5] = (H[5] + f) >>> 0; H[6] = (H[6] + g) >>> 0; H[7] = (H[7] + h) >>> 0;
95
+ }
96
+ const out = new Uint8Array(32);
97
+ const ov = new DataView(out.buffer);
98
+ for (let i = 0; i < 8; i++) ov.setUint32(i * 4, H[i]);
99
+ return out;
100
+ }
101
+
102
+ /**
103
+ * Derive the S256 challenge for a verifier: base64url(SHA-256(verifier)).
104
+ * Prefers WebCrypto; falls back to the pure-JS digest when `crypto.subtle`
105
+ * is unavailable (insecure context — plain-HTTP non-loopback origin, D17/R1).
106
+ * Method stays `S256` either way; RFC 9700 forbids `plain`.
107
+ */
108
+ export async function deriveCodeChallenge(verifier: string): Promise<string> {
109
+ const bytes = new TextEncoder().encode(verifier);
110
+ if (crypto.subtle) {
111
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
112
+ return base64UrlEncode(new Uint8Array(digest));
113
+ }
114
+ return base64UrlEncode(sha256Bytes(bytes));
115
+ }
116
+
117
+ /** Create a fresh verifier + its S256 challenge. */
118
+ export async function createPkcePair(): Promise<PkcePair> {
119
+ const verifier = createCodeVerifier();
120
+ const challenge = await deriveCodeChallenge(verifier);
121
+ return { verifier, challenge, method: "S256" };
122
+ }
123
+
124
+ /** A random URL-safe `state`/`nonce` value (32 bytes base64url). */
125
+ export function createRandomState(): string {
126
+ const bytes = new Uint8Array(32);
127
+ crypto.getRandomValues(bytes);
128
+ return base64UrlEncode(bytes);
129
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * In-memory access-token store for the browser identity plane (openspec §12.1).
3
+ *
4
+ * The access token is held in a module-scoped variable — NEVER localStorage /
5
+ * sessionStorage / cookie (RFC 9700 public-client guidance: an access token in
6
+ * web storage is XSS-exfiltratable). It lives only for the tab's lifetime; a
7
+ * reload re-runs the PKCE flow (silent via the IdP session when present).
8
+ *
9
+ * Distinct from the paired-device bearer (`lib/pairing/device-auth.ts`), which
10
+ * is a durable localStorage credential for a phone paired via `/pair`. The two
11
+ * never mix: the identity-plane bearer is this in-memory token.
12
+ */
13
+
14
+ interface TokenState {
15
+ accessToken: string;
16
+ /** Epoch ms after which the token is treated as expired (from `expires_in`). */
17
+ expiresAt: number;
18
+ }
19
+
20
+ let state: TokenState | null = null;
21
+
22
+ /** ID token retained solely as a future `id_token_hint` for RP-initiated logout (D18). */
23
+ let idToken: string | null = null;
24
+
25
+ /**
26
+ * Store an access token with its `expires_in` (seconds). A non-positive or
27
+ * missing lifetime stores the token with an already-past expiry, so a caller
28
+ * that ignores `expiresAt` still gets a token while a caller that honors it
29
+ * treats it as needing refresh.
30
+ */
31
+ export function setAccessToken(accessToken: string, expiresInSeconds: number): void {
32
+ state = { accessToken, expiresAt: Date.now() + Math.max(0, expiresInSeconds) * 1000 };
33
+ }
34
+
35
+ /** The current access token, or null when absent or expired. */
36
+ export function getAccessToken(now: number = Date.now()): string | null {
37
+ if (!state) return null;
38
+ if (now >= state.expiresAt) return null;
39
+ return state.accessToken;
40
+ }
41
+
42
+ /** Epoch ms the current token expires at, or null when no token is held. */
43
+ export function getExpiresAt(): number | null {
44
+ return state?.expiresAt ?? null;
45
+ }
46
+
47
+ /** True when a live (non-expired) token is held. */
48
+ export function hasLiveToken(now: number = Date.now()): boolean {
49
+ return getAccessToken(now) !== null;
50
+ }
51
+
52
+ /** Retain the id_token (in-memory only) for logout's `id_token_hint` (D18). */
53
+ export function setIdToken(token: string): void {
54
+ idToken = token;
55
+ }
56
+
57
+ /** The retained id_token, or null. Not lifetime-checked — hint use only. */
58
+ export function getIdToken(): string | null {
59
+ return idToken;
60
+ }
61
+
62
+ /** Forget the in-memory tokens (logout / expiry / reconnect-on-401). */
63
+ export function clearAccessToken(): void {
64
+ state = null;
65
+ idToken = null;
66
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Lazy MDI icon-by-key resolver.
3
+ *
4
+ * Resolving an icon from a runtime key string (`"mdiRefresh"`) needs the FULL
5
+ * `@mdi/js` namespace (~2.78 MB raw), which must stay off the cold landing
6
+ * load (iOS Safari WebContent memory kills, #712). The set is fetched on
7
+ * demand, the first time a key is resolved, and shared by every resolver.
8
+ *
9
+ * The dynamic import targets `@mdi/js/commonjs/mdi.js` — a DISTINCT module
10
+ * identity from the `@mdi/js` ESM entry that named imports use. Rollup cannot
11
+ * split one module across chunks, so importing `@mdi/js` itself would keep the
12
+ * whole namespace in the eager graph.
13
+ *
14
+ * While loading, and for unknown keys, resolvers return `null` (render
15
+ * nothing). A failed import resolves to `null` and clears the memo, so a
16
+ * later call retries.
17
+ *
18
+ * See change: harden-ios-safari-memory-and-ws-diagnostics (design D1).
19
+ */
20
+ import { useEffect, useState } from "react";
21
+
22
+ type IconSet = Record<string, unknown>;
23
+ type Importer = () => Promise<unknown>;
24
+
25
+ const defaultImporter: Importer = () => import("@mdi/js/commonjs/mdi.js");
26
+
27
+ let importer: Importer = defaultImporter;
28
+ let loaded: IconSet | null = null;
29
+ let pending: Promise<IconSet | null> | null = null;
30
+ /** Bumped by the test reset so an in-flight import cannot repopulate the set. */
31
+ let generation = 0;
32
+
33
+ /** Load (once) and return the full icon set, or `null` if the import failed. */
34
+ export function loadMdiIconSet(): Promise<IconSet | null> {
35
+ if (loaded) return Promise.resolve(loaded);
36
+ if (pending) return pending;
37
+ const gen = generation;
38
+ pending = importer().then(
39
+ (mod) => {
40
+ const m = mod as { default?: unknown };
41
+ const set = (m && typeof m.default === "object" && m.default !== null ? m.default : mod) as IconSet;
42
+ if (gen === generation) loaded = set;
43
+ return set;
44
+ },
45
+ () => {
46
+ if (gen === generation) pending = null; // retry on the next call
47
+ return null;
48
+ },
49
+ );
50
+ return pending;
51
+ }
52
+
53
+ /** Synchronous lookup: the SVG path if the set is loaded and the key is known, else `null`. */
54
+ export function resolveMdiIconSync(key: string | undefined | null): string | null {
55
+ if (!loaded || !key || typeof key !== "string" || !key.startsWith("mdi")) return null;
56
+ const path = loaded[key];
57
+ return typeof path === "string" && path.length > 0 ? path : null;
58
+ }
59
+
60
+ /** Hook: resolves `key`, triggering the lazy load and re-rendering once it lands. */
61
+ export function useMdiIconByKey(key: string | undefined | null): string | null {
62
+ const [, setTick] = useState(0);
63
+ const path = resolveMdiIconSync(key);
64
+ // Only keys that could resolve justify fetching the ~2.8 MB set.
65
+ const needsLoad = !loaded && typeof key === "string" && key.startsWith("mdi");
66
+ useEffect(() => {
67
+ if (!needsLoad) return;
68
+ let alive = true;
69
+ void loadMdiIconSet().then((set) => {
70
+ if (alive && set) setTick((t) => t + 1);
71
+ });
72
+ return () => {
73
+ alive = false;
74
+ };
75
+ }, [needsLoad]);
76
+ return path;
77
+ }
78
+
79
+ /** Test seam: replace the dynamic importer. */
80
+ export function __setMdiIconSetImporterForTests(fn: Importer): void {
81
+ importer = fn;
82
+ }
83
+
84
+ /** Test seam: forget the loaded set and restore the real importer. */
85
+ export function __resetMdiIconSetForTests(): void {
86
+ importer = defaultImporter;
87
+ loaded = null;
88
+ pending = null;
89
+ generation++;
90
+ }
package/src/useZoomPan.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { useCallback, useRef, useState } from "react";
1
+ import type React from "react";
2
+ import { useCallback, useLayoutEffect, useRef, useState } from "react";
2
3
 
3
4
  export interface ZoomPanState {
4
5
  scale: number;
@@ -10,6 +11,13 @@ export interface UseZoomPanOptions {
10
11
  minScale?: number;
11
12
  maxScale?: number;
12
13
  zoomStep?: number;
14
+ /**
15
+ * Scale the surface starts at and that reset / double-click return to.
16
+ * Clamped into [minScale, maxScale]; defaults to 1. While the user has not
17
+ * interacted, a changed value re-seeds the view (fit may resolve async).
18
+ * See change: fix-markdown-remount-storm (D4).
19
+ */
20
+ initialScale?: number;
13
21
  }
14
22
 
15
23
  const DEFAULT_MIN = 0.5;
@@ -26,7 +34,23 @@ export function useZoomPan(options?: UseZoomPanOptions) {
26
34
  const maxScale = options?.maxScale ?? DEFAULT_MAX;
27
35
  const zoomStep = options?.zoomStep ?? DEFAULT_STEP;
28
36
 
29
- const [state, setState] = useState<ZoomPanState>({ scale: 1, translateX: 0, translateY: 0 });
37
+ const initialScale = Math.min(maxScale, Math.max(minScale, options?.initialScale ?? 1));
38
+
39
+ const [state, rawSetState] = useState<ZoomPanState>({ scale: initialScale, translateX: 0, translateY: 0 });
40
+ // True once the user zoomed/panned; a late initialScale change must not override that.
41
+ const touched = useRef(false);
42
+ const setState = useCallback((u: React.SetStateAction<ZoomPanState>) => {
43
+ touched.current = true;
44
+ rawSetState(u);
45
+ }, []);
46
+ const resetToInitial = useCallback(() => {
47
+ touched.current = false;
48
+ rawSetState({ scale: initialScale, translateX: 0, translateY: 0 });
49
+ }, [initialScale]);
50
+
51
+ useLayoutEffect(() => {
52
+ if (!touched.current) rawSetState({ scale: initialScale, translateX: 0, translateY: 0 });
53
+ }, [initialScale]);
30
54
 
31
55
  // Refs for drag tracking (avoid re-renders during drag)
32
56
  const dragging = useRef(false);
@@ -59,7 +83,7 @@ export function useZoomPan(options?: UseZoomPanOptions) {
59
83
  };
60
84
  });
61
85
  },
62
- [clampScale],
86
+ [clampScale, setState],
63
87
  );
64
88
 
65
89
  // ── Wheel handler ──────────────────────────────────────────────────
@@ -108,7 +132,7 @@ export function useZoomPan(options?: UseZoomPanOptions) {
108
132
  translateX: prev.translateX + dx,
109
133
  translateY: prev.translateY + dy,
110
134
  }));
111
- }, []);
135
+ }, [setState]);
112
136
 
113
137
  const onPointerUp = useCallback(() => {
114
138
  dragging.current = false;
@@ -142,9 +166,7 @@ export function useZoomPan(options?: UseZoomPanOptions) {
142
166
  }, []);
143
167
 
144
168
  // ── Double-click reset ─────────────────────────────────────────────
145
- const onDoubleClick = useCallback(() => {
146
- setState({ scale: 1, translateX: 0, translateY: 0 });
147
- }, []);
169
+ const onDoubleClick = resetToInitial;
148
170
 
149
171
  // ── Button controls ────────────────────────────────────────────────
150
172
  const zoomIn = useCallback(() => {
@@ -152,18 +174,16 @@ export function useZoomPan(options?: UseZoomPanOptions) {
152
174
  const newScale = clampScale(prev.scale * zoomStep);
153
175
  return { ...prev, scale: newScale };
154
176
  });
155
- }, [clampScale, zoomStep]);
177
+ }, [clampScale, zoomStep, setState]);
156
178
 
157
179
  const zoomOut = useCallback(() => {
158
180
  setState((prev) => {
159
181
  const newScale = clampScale(prev.scale / zoomStep);
160
182
  return { ...prev, scale: newScale };
161
183
  });
162
- }, [clampScale, zoomStep]);
184
+ }, [clampScale, zoomStep, setState]);
163
185
 
164
- const reset = useCallback(() => {
165
- setState({ scale: 1, translateX: 0, translateY: 0 });
166
- }, []);
186
+ const reset = resetToInitial;
167
187
 
168
188
  const handlers = {
169
189
  onWheel,
@@ -175,5 +195,5 @@ export function useZoomPan(options?: UseZoomPanOptions) {
175
195
  onDoubleClick,
176
196
  };
177
197
 
178
- return { state, handlers, zoomIn, zoomOut, reset };
198
+ return { state, handlers, zoomIn, zoomOut, reset, initialScale };
179
199
  }