@blackbelt-technology/pi-dashboard-client-utils 0.7.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.
@@ -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
+ }