@hadoku/task-ui-components 4.22.7 → 4.23.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.
@@ -117,6 +117,18 @@ export interface SignInClient {
117
117
  saved: boolean;
118
118
  passkeys: number;
119
119
  }>;
120
+ /** A fresh passkey tap from the signed-in person; the assertion to post. Throws Error(message). */
121
+ stepUpPasskey?: (opts?: {
122
+ signal?: AbortSignal;
123
+ }) => Promise<PasskeyAssertion>;
124
+ }
125
+ /** What `stepUpPasskey` resolves to: the WebAuthn assertion, base64url fields. */
126
+ export interface PasskeyAssertion {
127
+ id: string;
128
+ clientDataJSON: string;
129
+ authenticatorData: string;
130
+ signature: string;
131
+ userHandle: string | null;
120
132
  }
121
133
  export declare function loadSignInClient(): Promise<SignInClient | null>;
122
134
  export declare function loadSignIn(): Promise<SignIn | null>;
@@ -135,6 +147,8 @@ export interface SettingsSnapshot {
135
147
  content: ContentLevelState | null;
136
148
  /** Passkeys that sign this person in; null = unknown (older edge, host-supplied identity). */
137
149
  passkeys: number | null;
150
+ /** Service identities this person may mint for; 0 when unknown. */
151
+ serviceGrants: number;
138
152
  }
139
153
  /** Identity the host already knows, so we don't ask the server for it again. */
140
154
  export interface SettingsPrefetchHints {
@@ -1 +1 @@
1
- {"version":3,"file":"settingsClient.d.ts","sourceRoot":"","sources":["../../src/lib/settingsClient.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAwDH,MAAM,WAAW,iBAAiB;IAChC,oEAAoE;IACpE,KAAK,EAAE,MAAM,CAAA;IACb,uEAAuE;IACvE,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,4EAA4E;AAC5E,wBAAsB,eAAe,IAAI,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAYzE;AAED;uEACuE;AACvE,wBAAsB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC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,qBAAqB;IACpC,gEAAgE;IAChE,QAAQ,CAAC,EAAE,IAAI,CAAA;IACf,mEAAmE;IACnE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CACrB;AAID;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,GAAE,qBAA0B,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAG7F"}
@@ -108,7 +108,8 @@ function loadSignInClient() {
108
108
  (m) => typeof m.signIn === "function" ? {
109
109
  signIn: m.signIn,
110
110
  signInWithPasskey: typeof m.signInWithPasskey === "function" ? m.signInWithPasskey : void 0,
111
- addPasskey: typeof m.addPasskey === "function" ? m.addPasskey : void 0
111
+ addPasskey: typeof m.addPasskey === "function" ? m.addPasskey : void 0,
112
+ stepUpPasskey: typeof m.stepUpPasskey === "function" ? m.stepUpPasskey : void 0
112
113
  } : null,
113
114
  () => {
114
115
  signInModule = null;
@@ -147,7 +148,12 @@ async function resolveSettings(hints) {
147
148
  contentPromise,
148
149
  bodyPromise
149
150
  ]);
150
- return { identity, content, passkeys: passkeysFromWhoami(body) };
151
+ return {
152
+ identity,
153
+ content,
154
+ passkeys: passkeysFromWhoami(body),
155
+ serviceGrants: body?.valid && typeof body.serviceGrants === "number" ? body.serviceGrants : 0
156
+ };
151
157
  }
152
158
  function passkeysFromWhoami(body) {
153
159
  return body?.valid && typeof body.passkeys === "number" ? body.passkeys : null;
@@ -1 +1 @@
1
- {"version":3,"file":"settingsClient.js","sources":["../../src/lib/settingsClient.ts"],"sourcesContent":["/**\n * Client for the unified user-settings modal (ConnectedSettings).\n *\n * Two concerns, both cookie-authed against the hadoku.me edge-router, which\n * resolves the `hadoku_session` cookie / `X-Session-Id` header → X-User-Key +\n * X-User-Id for the backend:\n * - display name → POST /session/name (edge-router, self rename)\n * - content level → GET/PUT /prefs/api/v1/content-level (prefs-api)\n *\n * Switching keys goes through the SITE's sign-in client, never a call of ours:\n * see `loadSignIn()`, with `switchKeyHref()` as the fallback.\n *\n * These are same-origin relative paths, so ConnectedSettings is portable to any\n * app served under hadoku.me with zero wiring. Off-origin (e.g. a Storybook or\n * a non-hadoku host) every call resolves to null and the UI degrades to a\n * read-only shell — it never throws.\n *\n * The raw key is never held in the browser (the auth page deliberately drops\n * it), so name + content-level changes go through session identity, not a key\n * header, and no app ever asks for a key at all.\n *\n * WHEN THESE RUN\n * --------------\n * Everything the popout displays is resolved at PAGE LOAD, not on gear-click —\n * see `prefetchSettings()`. Opening settings must cost zero requests. Pinned by\n * `e2e/settings-prefetch.spec.ts` in hadoku-task.\n */\n\n/** Edge-router / prefs-api endpoints (same-origin relative). */\nconst CONTENT_LEVEL_PATH = '/prefs/api/v1/content-level'\nconst SESSION_NAME = '/session/name'\nconst ACCOUNT_DELETE = '/session/account/delete'\nconst SESSION_WHOAMI = '/session/whoami'\n\n/**\n * The ecosystem's shared boot-whoami promise. hadoku_site's `mf-loader.js`\n * kicks `GET /session/whoami` in parallel with the micro-frontend's module\n * import and parks the promise here precisely so the app it loads doesn't\n * resolve identity a second time; @wolffm/prefs-client already consumes it\n * under the same name. Reading it is what makes settings' identity free.\n *\n * Absent outside that shell (standalone vite, Capacitor, Storybook) — there we\n * fetch, and publish the result under the same key so the next reader is free\n * too.\n */\nconst WHOAMI_GLOBAL = '__hadokuWhoami'\n\n/**\n * Raw whoami body, as both mf-loader and this module see it off the wire.\n *\n * `contentLevel` / `maxContentLevel` are OPTIONAL because the shape is\n * versioned by whatever edge-router is deployed, not by this bundle. They\n * arrive from edge-router ≥ the 2026-08-07 change, which reports the level\n * `authGate` had already resolved to stamp X-Hadoku-Content-Level. When they\n * are absent we fall back to the standalone GET — see resolveSettings.\n *\n * `passkeys` (edge-router ≥ 2026-10-28) counts the passkeys that sign this\n * session in. Absent means unknown, never none.\n */\ninterface WhoamiBody {\n valid?: boolean\n userType?: Tier\n name?: string | null\n contentLevel?: number\n maxContentLevel?: number\n passkeys?: number\n}\n\n// Hard timeout on every settings request. Without it, a request throttled by\n// the browser (e.g. the tab going to the background) leaves the caller's\n// \"saving\" flag stuck true — which disabled the content-level pills until the\n// tab regained focus. AbortSignal.timeout guarantees the promise settles.\nconst REQUEST_TIMEOUT_MS = 8000\n\n/** Session-id header the same way whoami() sends it (cookie is the fallback). */\nfunction sessionHeaders(extra?: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json', ...extra }\n const sid = typeof window !== 'undefined' ? localStorage.getItem('hadoku_session_id') : null\n if (sid) headers['X-Session-Id'] = sid\n return headers\n}\n\nexport interface ContentLevelState {\n /** Current global content-visibility level (1 = safest default). */\n level: number\n /** Highest level this caller's tier may select (friend=3, admin=4). */\n maxLevel: number\n}\n\n/** GET the caller's current content level + tier ceiling. null on error. */\nexport async function getContentLevel(): Promise<ContentLevelState | null> {\n try {\n const res = await fetch(CONTENT_LEVEL_PATH, {\n credentials: 'same-origin',\n headers: sessionHeaders(),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return null\n return (await res.json()) as ContentLevelState\n } catch {\n return null\n }\n}\n\n/** PUT a new content level. Server clamps to the tier ceiling → 400 if out of\n * range. Returns the stored state on success, null on any failure. */\nexport async function setContentLevel(level: number): Promise<ContentLevelState | null> {\n try {\n const res = await fetch(CONTENT_LEVEL_PATH, {\n method: 'PUT',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: JSON.stringify({ level }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return null\n const stored = (await res.json()) as ContentLevelState\n patchSnapshot(prev => ({ ...prev, content: stored }))\n return stored\n } catch {\n return null\n }\n}\n\n/** Delete the signed-in member's own account (edge-router refuses any key\n * someone was handed). True when it is gone; the session cookie is cleared. */\nexport async function deleteOwnAccount(): Promise<boolean> {\n try {\n const res = await fetch(ACCOUNT_DELETE, {\n method: 'POST',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: '{}',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return false\n return ((await res.json()) as { deleted?: boolean }).deleted === true\n } catch {\n return false\n }\n}\n\n/**\n * POST a new display name for the signed-in user. Answers the stored name (may\n * differ from the request for wp-* protected keys), or why it was refused: the\n * server's own words where it gave any (\"That display name is already taken\"),\n * so the editor can say them.\n */\nexport type RenameResult = { ok: true; name: string | null } | { ok: false; error: string }\n\nexport async function setDisplayName(name: string): Promise<RenameResult> {\n try {\n const res = await fetch(SESSION_NAME, {\n method: 'POST',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: JSON.stringify({ name }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: unknown } | null\n const said = typeof body?.error === 'string' ? body.error : null\n return { ok: false, error: said ?? `Not saved (${res.status})` }\n }\n const body = (await res.json()) as { ok: boolean; name: string | null }\n patchSnapshot(prev => ({ ...prev, identity: { ...prev.identity, name: body.name } }))\n return { ok: true, name: body.name }\n } catch {\n return { ok: false, error: 'Not saved: no connection' }\n }\n}\n\n/**\n * The hadoku tier ladder, LOW to HIGH: `public < member < friend < service < wife < admin`.\n * `member` is a self-signed-up account (a passkey, no key), cardtable only.\n * Mirrors TIER_RANK in @wolffm/worker-utils, which this browser bundle cannot\n * import (it would pull hono into the client). A tier missing here does not\n * error — it fails the union and, worse, drops out of every `Record<Tier, …>`\n * lookup, so the caller renders as if unrecognised. Keep it complete.\n */\nexport type Tier = 'public' | 'member' | 'friend' | 'service' | 'wife' | 'admin'\n\nexport interface Identity {\n userType: Tier\n name: string | null\n}\n\n/**\n * The page's one whoami body, resolved at most once no matter how many callers.\n *\n * Under the hadoku.me shell this costs NO request: mf-loader kicks whoami in\n * parallel with the micro-frontend's module import and parks the promise on\n * WHOAMI_GLOBAL for exactly this reason (@wolffm/prefs-client reads the same\n * key). Elsewhere — standalone vite, Capacitor, Storybook — we fetch once and\n * publish under the same key so the next reader is free too.\n *\n * Resolves to null rather than throwing on any failure.\n */\nfunction sharedWhoami(): Promise<WhoamiBody | null> {\n const g = globalThis as { [WHOAMI_GLOBAL]?: Promise<WhoamiBody | null> }\n g[WHOAMI_GLOBAL] ??= fetch(SESSION_WHOAMI, {\n credentials: 'same-origin',\n headers: sessionHeaders(),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n .then(res => (res.ok ? (res.json() as Promise<WhoamiBody>) : null))\n .catch(() => null)\n return g[WHOAMI_GLOBAL]\n}\n\n/**\n * Resolve the signed-in caller's tier + display name from the edge-router.\n * Returns { userType: 'public', name: null } for anonymous / off-origin / any\n * failure — never throws, so ConnectedSettings can render unconditionally.\n */\nexport async function whoami(): Promise<Identity> {\n if (typeof window === 'undefined') return { userType: 'public', name: null }\n try {\n const body = await sharedWhoami()\n if (!body?.valid) return { userType: 'public', name: null }\n return { userType: body.userType ?? 'public', name: body.name ?? null }\n } catch {\n return { userType: 'public', name: null }\n }\n}\n\n/**\n * Where a \"Switch key\" control sends the user when the inline sign-in client\n * (`loadSignIn()`) can't be loaded: the site's sign-in page, which brings them\n * back here afterwards.\n *\n * A browser session is created ONLY by /auth (hadoku_site, 2026-10-25): every\n * render of that page carries an edge-signed funnel token and the device\n * fingerprint, and /session/create alerts on — and will refuse — a sign-in\n * without them. So an app never posts a key itself.\n *\n * `switch=1` stops /auth from sending an already signed-in visitor straight\n * back, which would make switching impossible. `return` is this page's path,\n * query and hash; /auth redirects there with the new session cookie, and the\n * shell's mf-loader resyncs the localStorage mirror (hadoku_session_id /\n * hadoku_user_type) from /session/whoami on that load, so nothing here writes it.\n */\nexport function switchKeyHref(): string {\n return (\n '/auth?switch=1&return=' +\n encodeURIComponent(window.location.pathname + window.location.search + window.location.hash)\n )\n}\n\n/** What the site's sign-in client resolves to on success. */\nexport interface SignInResult {\n valid: boolean\n userType?: string\n sessionId?: string\n}\n\n/** `signIn` from hadoku.me's `/auth/sign-in.js`. Resolves on success; throws an\n * `Error` carrying the server's message on a refused or empty key. */\nexport type SignIn = (key: string) => Promise<SignInResult>\n\n/**\n * The site serves its sign-in page's own client as a module, so an app can sign\n * in INLINE on the same code path as /auth: a fresh funnel token per call, the\n * device fingerprint, and the `/session/create` post that sets the cookie (and\n * writes the hadoku_session_id / hadoku_user_type mirror). This package never\n * posts /session/create itself — a direct post would skip the fingerprint and\n * read as off-funnel — and it does not vendor a copy.\n *\n * The specifier is a VARIABLE on purpose. A literal `import('/auth/sign-in.js')`\n * would have every bundler that re-bundles this package (hadoku_site's build\n * among them) try to resolve the path at build time; this one is only ever\n * resolved by the browser, against whatever origin the page is on. For the\n * same reason it is typed here (`SignIn`) rather than by an ambient module\n * declaration, which only a literal specifier would pick up.\n *\n * The module starts collecting the fingerprint as soon as it evaluates, so call\n * this when a sign-in form OPENS, not when it submits. Memoised; resolves to\n * null when the module can't be loaded (a dev server that isn't hadoku.me),\n * which is the caller's cue to fall back to `switchKeyHref()`.\n */\nconst SIGN_IN_MODULE = '/auth/sign-in.js'\nlet signInModule: Promise<SignInClient | null> | null = null\n\n/**\n * The whole sign-in client. The passkey half is optional: a site build from\n * before it exports only `signIn`, and the passkey controls then fall back to\n * the /auth page (`passkeyHref()`), as a missing module does.\n */\nexport interface SignInClient {\n signIn: SignIn\n /** Like `signIn`, with a passkey in place of the key. Throws Error(message).\n * `signal` cancels the open prompt. */\n signInWithPasskey?: (opts?: { signal?: AbortSignal }) => Promise<SignInResult>\n /** Saves a passkey for the signed-in person on this device. Throws Error(message). */\n addPasskey?: (opts?: { signal?: AbortSignal }) => Promise<{ saved: boolean; passkeys: number }>\n}\n\nexport function loadSignInClient(): Promise<SignInClient | null> {\n signInModule ??= import(/* @vite-ignore */ SIGN_IN_MODULE).then(\n (m: Partial<Record<keyof SignInClient, unknown>>) =>\n typeof m.signIn === 'function'\n ? {\n signIn: m.signIn as SignIn,\n signInWithPasskey:\n typeof m.signInWithPasskey === 'function'\n ? (m.signInWithPasskey as SignInClient['signInWithPasskey'])\n : undefined,\n addPasskey:\n typeof m.addPasskey === 'function'\n ? (m.addPasskey as SignInClient['addPasskey'])\n : undefined\n }\n : null,\n () => {\n // Let a later open retry: a failed fetch is not cached by the browser.\n signInModule = null\n return null\n }\n )\n return signInModule\n}\n\nexport function loadSignIn(): Promise<SignIn | null> {\n return loadSignInClient().then(c => c?.signIn ?? null)\n}\n\n/** Whether this browser can use a passkey at all (WebAuthn present). */\nexport function passkeysSupported(): boolean {\n return typeof window !== 'undefined' && 'PublicKeyCredential' in window\n}\n\n/**\n * The /auth page's passkey flows, for when the sign-in client can't be\n * loaded: `add` saves one for the signed-in visitor, `signin` is the page with\n * its passkey button. Both come back here afterwards.\n */\nexport function passkeyHref(mode: 'add' | 'signin'): string {\n if (mode === 'signin') return switchKeyHref()\n return (\n '/auth?passkey=add&return=' +\n encodeURIComponent(window.location.pathname + window.location.search + window.location.hash)\n )\n}\n\n/* ------------------------------------------------------------------ *\n * Prefetch\n * ------------------------------------------------------------------ */\n\n/** Everything the settings popout displays, resolved together. */\nexport interface SettingsSnapshot {\n identity: Identity\n /** null = public caller (no pill) or the request failed. */\n content: ContentLevelState | null\n /** Passkeys that sign this person in; null = unknown (older edge, host-supplied identity). */\n passkeys: number | null\n}\n\n/** Identity the host already knows, so we don't ask the server for it again. */\nexport interface SettingsPrefetchHints {\n /** Caller's tier. When supplied, whoami is skipped entirely. */\n userType?: Tier\n /** Caller's display name. Only meaningful alongside `userType`. */\n name?: string | null\n}\n\nlet snapshot: Promise<SettingsSnapshot> | null = null\n\n/**\n * Resolve — once per page load — everything the settings popout shows.\n *\n * This is THE entry point, and it is called from ConnectedSettings' MOUNT, not\n * from its open handler. Settings data is user identity: it is known at boot,\n * it doesn't change while the page is up, and making the gear the trigger left\n * the panel on screen but blank for a round trip (measured on prod: whoami\n * 167ms and content-level 186ms, issued concurrently). It now rides along with\n * the app's own boot traffic and the click costs nothing.\n *\n * Idempotent and shared: every caller after the first gets the same promise, so\n * N mounted consumers still produce at most one whoami for the whole page.\n * Mutations below write through to it rather than invalidating, so a remount\n * never shows a value the user just changed.\n *\n * Against a current edge-router this issues NO requests of its own at all — the\n * level rides on the whoami the shell already had in flight. See\n * resolveSettings for the fallback when it doesn't.\n */\nexport function prefetchSettings(hints: SettingsPrefetchHints = {}): Promise<SettingsSnapshot> {\n snapshot ??= resolveSettings(hints)\n return snapshot\n}\n\nasync function resolveSettings(hints: SettingsPrefetchHints): Promise<SettingsSnapshot> {\n // The whoami body, not just the adapted identity — edge-router carries the\n // content level on it (see below), and reading the raw body is how we get at\n // it without a second request.\n //\n // Skipped entirely when the host supplied identity: that prop exists for apps\n // that CANNOT reach /session/whoami (conjure sits behind a path-prefixed shim\n // where it 404s), so asking anyway would spend a request to learn nothing.\n const selfResolving = hints.userType === undefined && typeof window !== 'undefined'\n const bodyPromise = selfResolving ? sharedWhoami() : Promise.resolve(null)\n\n const identityPromise: Promise<Identity> =\n hints.userType !== undefined\n ? Promise.resolve({ userType: hints.userType, name: hints.name ?? null })\n : whoami()\n\n // PREFERRED PATH: take the level straight off whoami.\n //\n // edge-router's authGate has already resolved it (registry key → userId →\n // prefs D1) to stamp X-Hadoku-Content-Level, so reporting it on whoami costs\n // it nothing — and it saves us a proxied round trip to prefs-api that\n // measured 132-420ms against prod. Better still, whoami is in flight before\n // this bundle has even loaded, so the value is here the moment we ask.\n //\n // FALLBACK: the standalone GET, for any edge-router older than the\n // 2026-08-07 change, and for callers not behind it at all (Capacitor,\n // Storybook, a non-hadoku host). Gated on identity because the pill is\n // hidden for public callers — fetching an anonymous visitor's level is a\n // guaranteed-wasted request on every page view. `hadoku_user_type` is\n // written by the loader before anything mounts, so where it already says\n // \"signed in\" the fallback goes out concurrently rather than behind whoami.\n const contentPromise = bodyPromise.then(body => {\n const carried = contentFromWhoami(body)\n if (carried) return carried\n if (looksSignedIn(hints.userType)) return getContentLevel()\n return identityPromise.then(id => (id.userType === 'public' ? null : getContentLevel()))\n })\n\n const [identity, content, body] = await Promise.all([\n identityPromise,\n contentPromise,\n bodyPromise\n ])\n return { identity, content, passkeys: passkeysFromWhoami(body) }\n}\n\nfunction passkeysFromWhoami(body: WhoamiBody | null): number | null {\n return body?.valid && typeof body.passkeys === 'number' ? body.passkeys : null\n}\n\n/**\n * Adapt the content level off a whoami body, or null if that edge-router\n * doesn't report it.\n *\n * Both fields are required, and both must be numbers: a body carrying a level\n * without its ceiling would render a pill with zero segments — worse than the\n * fallback fetch, because it looks like a working control that offers nothing.\n */\nfunction contentFromWhoami(body: WhoamiBody | null): ContentLevelState | null {\n if (!body?.valid) return null\n const { contentLevel, maxContentLevel } = body\n if (typeof contentLevel !== 'number' || typeof maxContentLevel !== 'number') return null\n if (maxContentLevel < 1) return null\n return { level: contentLevel, maxLevel: maxContentLevel }\n}\n\n/** Best-effort \"is this caller signed in?\" from state available synchronously. */\nfunction looksSignedIn(hinted?: Tier): boolean {\n if (hinted !== undefined) return hinted !== 'public'\n if (typeof window === 'undefined') return false\n const cached = localStorage.getItem('hadoku_user_type')\n return cached !== null && cached !== 'public'\n}\n\n/** Keep the prefetched snapshot in step with a successful mutation. */\nfunction patchSnapshot(patch: (prev: SettingsSnapshot) => SettingsSnapshot) {\n if (!snapshot) return\n snapshot = snapshot.then(patch)\n}\n"],"names":["body"],"mappings":"AA6BA,MAAM,qBAAqB;AAC3B,MAAM,eAAe;AACrB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAavB,MAAM,gBAAgB;AA2BtB,MAAM,qBAAqB;AAG3B,SAAS,eAAe,OAAwD;AAC9E,QAAM,UAAkC,EAAE,gBAAgB,oBAAoB,GAAG,MAAA;AACjF,QAAM,MAAM,OAAO,WAAW,cAAc,aAAa,QAAQ,mBAAmB,IAAI;AACxF,MAAI,IAAK,SAAQ,cAAc,IAAI;AACnC,SAAO;AACT;AAUA,eAAsB,kBAAqD;AACzE,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,oBAAoB;AAAA,MAC1C,aAAa;AAAA,MACb,SAAS,eAAA;AAAA,MACT,QAAQ,YAAY,QA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AAI;AAAA,IAClD;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACD,SAAO,EAAE,UAAU,SAAS,UAAU,mBAAmB,IAAI,EAAA;AAC/D;AAEA,SAAS,mBAAmB,MAAwC;AAClE,SAAO,MAAM,SAAS,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;AAC5E;AAUA,SAAS,kBAAkB,MAAmD;AAC5E,MAAI,CAAC,MAAM,MAAO,QAAO;AACzB,QAAM,EAAE,cAAc,gBAAA,IAAoB;AAC1C,MAAI,OAAO,iBAAiB,YAAY,OAAO,oBAAoB,SAAU,QAAO;AACpF,MAAI,kBAAkB,EAAG,QAAO;AAChC,SAAO,EAAE,OAAO,cAAc,UAAU,gBAAA;AAC1C;AAGA,SAAS,cAAc,QAAwB;AAC7C,MAAI,WAAW,OAAW,QAAO,WAAW;AAC5C,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAM,SAAS,aAAa,QAAQ,kBAAkB;AACtD,SAAO,WAAW,QAAQ,WAAW;AACvC;AAGA,SAAS,cAAc,OAAqD;AAC1E,MAAI,CAAC,SAAU;AACf,aAAW,SAAS,KAAK,KAAK;AAChC;"}
1
+ {"version":3,"file":"settingsClient.js","sources":["../../src/lib/settingsClient.ts"],"sourcesContent":["/**\n * Client for the unified user-settings modal (ConnectedSettings).\n *\n * Two concerns, both cookie-authed against the hadoku.me edge-router, which\n * resolves the `hadoku_session` cookie / `X-Session-Id` header → X-User-Key +\n * X-User-Id for the backend:\n * - display name → POST /session/name (edge-router, self rename)\n * - content level → GET/PUT /prefs/api/v1/content-level (prefs-api)\n *\n * Switching keys goes through the SITE's sign-in client, never a call of ours:\n * see `loadSignIn()`, with `switchKeyHref()` as the fallback.\n *\n * These are same-origin relative paths, so ConnectedSettings is portable to any\n * app served under hadoku.me with zero wiring. Off-origin (e.g. a Storybook or\n * a non-hadoku host) every call resolves to null and the UI degrades to a\n * read-only shell — it never throws.\n *\n * The raw key is never held in the browser (the auth page deliberately drops\n * it), so name + content-level changes go through session identity, not a key\n * header, and no app ever asks for a key at all.\n *\n * WHEN THESE RUN\n * --------------\n * Everything the popout displays is resolved at PAGE LOAD, not on gear-click —\n * see `prefetchSettings()`. Opening settings must cost zero requests. Pinned by\n * `e2e/settings-prefetch.spec.ts` in hadoku-task.\n */\n\n/** Edge-router / prefs-api endpoints (same-origin relative). */\nconst CONTENT_LEVEL_PATH = '/prefs/api/v1/content-level'\nconst SESSION_NAME = '/session/name'\nconst ACCOUNT_DELETE = '/session/account/delete'\nconst SESSION_WHOAMI = '/session/whoami'\n\n/**\n * The ecosystem's shared boot-whoami promise. hadoku_site's `mf-loader.js`\n * kicks `GET /session/whoami` in parallel with the micro-frontend's module\n * import and parks the promise here precisely so the app it loads doesn't\n * resolve identity a second time; @wolffm/prefs-client already consumes it\n * under the same name. Reading it is what makes settings' identity free.\n *\n * Absent outside that shell (standalone vite, Capacitor, Storybook) — there we\n * fetch, and publish the result under the same key so the next reader is free\n * too.\n */\nconst WHOAMI_GLOBAL = '__hadokuWhoami'\n\n/**\n * Raw whoami body, as both mf-loader and this module see it off the wire.\n *\n * `contentLevel` / `maxContentLevel` are OPTIONAL because the shape is\n * versioned by whatever edge-router is deployed, not by this bundle. They\n * arrive from edge-router ≥ the 2026-08-07 change, which reports the level\n * `authGate` had already resolved to stamp X-Hadoku-Content-Level. When they\n * are absent we fall back to the standalone GET — see resolveSettings.\n *\n * `passkeys` (edge-router ≥ 2026-10-28) counts the passkeys that sign this\n * session in. Absent means unknown, never none.\n *\n * `serviceGrants` (edge-router ≥ 2026-10-31) counts the service identities\n * this person may mint their own credentials for; Service access shows only\n * above zero.\n */\ninterface WhoamiBody {\n valid?: boolean\n userType?: Tier\n name?: string | null\n contentLevel?: number\n maxContentLevel?: number\n passkeys?: number\n serviceGrants?: number\n}\n\n// Hard timeout on every settings request. Without it, a request throttled by\n// the browser (e.g. the tab going to the background) leaves the caller's\n// \"saving\" flag stuck true — which disabled the content-level pills until the\n// tab regained focus. AbortSignal.timeout guarantees the promise settles.\nconst REQUEST_TIMEOUT_MS = 8000\n\n/** Session-id header the same way whoami() sends it (cookie is the fallback). */\nfunction sessionHeaders(extra?: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json', ...extra }\n const sid = typeof window !== 'undefined' ? localStorage.getItem('hadoku_session_id') : null\n if (sid) headers['X-Session-Id'] = sid\n return headers\n}\n\nexport interface ContentLevelState {\n /** Current global content-visibility level (1 = safest default). */\n level: number\n /** Highest level this caller's tier may select (friend=3, admin=4). */\n maxLevel: number\n}\n\n/** GET the caller's current content level + tier ceiling. null on error. */\nexport async function getContentLevel(): Promise<ContentLevelState | null> {\n try {\n const res = await fetch(CONTENT_LEVEL_PATH, {\n credentials: 'same-origin',\n headers: sessionHeaders(),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return null\n return (await res.json()) as ContentLevelState\n } catch {\n return null\n }\n}\n\n/** PUT a new content level. Server clamps to the tier ceiling → 400 if out of\n * range. Returns the stored state on success, null on any failure. */\nexport async function setContentLevel(level: number): Promise<ContentLevelState | null> {\n try {\n const res = await fetch(CONTENT_LEVEL_PATH, {\n method: 'PUT',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: JSON.stringify({ level }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return null\n const stored = (await res.json()) as ContentLevelState\n patchSnapshot(prev => ({ ...prev, content: stored }))\n return stored\n } catch {\n return null\n }\n}\n\n/** Delete the signed-in member's own account (edge-router refuses any key\n * someone was handed). True when it is gone; the session cookie is cleared. */\nexport async function deleteOwnAccount(): Promise<boolean> {\n try {\n const res = await fetch(ACCOUNT_DELETE, {\n method: 'POST',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: '{}',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) return false\n return ((await res.json()) as { deleted?: boolean }).deleted === true\n } catch {\n return false\n }\n}\n\n/**\n * POST a new display name for the signed-in user. Answers the stored name (may\n * differ from the request for wp-* protected keys), or why it was refused: the\n * server's own words where it gave any (\"That display name is already taken\"),\n * so the editor can say them.\n */\nexport type RenameResult = { ok: true; name: string | null } | { ok: false; error: string }\n\nexport async function setDisplayName(name: string): Promise<RenameResult> {\n try {\n const res = await fetch(SESSION_NAME, {\n method: 'POST',\n credentials: 'same-origin',\n headers: sessionHeaders(),\n body: JSON.stringify({ name }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: unknown } | null\n const said = typeof body?.error === 'string' ? body.error : null\n return { ok: false, error: said ?? `Not saved (${res.status})` }\n }\n const body = (await res.json()) as { ok: boolean; name: string | null }\n patchSnapshot(prev => ({ ...prev, identity: { ...prev.identity, name: body.name } }))\n return { ok: true, name: body.name }\n } catch {\n return { ok: false, error: 'Not saved: no connection' }\n }\n}\n\n/**\n * The hadoku tier ladder, LOW to HIGH: `public < member < friend < service < wife < admin`.\n * `member` is a self-signed-up account (a passkey, no key), cardtable only.\n * Mirrors TIER_RANK in @wolffm/worker-utils, which this browser bundle cannot\n * import (it would pull hono into the client). A tier missing here does not\n * error — it fails the union and, worse, drops out of every `Record<Tier, …>`\n * lookup, so the caller renders as if unrecognised. Keep it complete.\n */\nexport type Tier = 'public' | 'member' | 'friend' | 'service' | 'wife' | 'admin'\n\nexport interface Identity {\n userType: Tier\n name: string | null\n}\n\n/**\n * The page's one whoami body, resolved at most once no matter how many callers.\n *\n * Under the hadoku.me shell this costs NO request: mf-loader kicks whoami in\n * parallel with the micro-frontend's module import and parks the promise on\n * WHOAMI_GLOBAL for exactly this reason (@wolffm/prefs-client reads the same\n * key). Elsewhere — standalone vite, Capacitor, Storybook — we fetch once and\n * publish under the same key so the next reader is free too.\n *\n * Resolves to null rather than throwing on any failure.\n */\nfunction sharedWhoami(): Promise<WhoamiBody | null> {\n const g = globalThis as { [WHOAMI_GLOBAL]?: Promise<WhoamiBody | null> }\n g[WHOAMI_GLOBAL] ??= fetch(SESSION_WHOAMI, {\n credentials: 'same-origin',\n headers: sessionHeaders(),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)\n })\n .then(res => (res.ok ? (res.json() as Promise<WhoamiBody>) : null))\n .catch(() => null)\n return g[WHOAMI_GLOBAL]\n}\n\n/**\n * Resolve the signed-in caller's tier + display name from the edge-router.\n * Returns { userType: 'public', name: null } for anonymous / off-origin / any\n * failure — never throws, so ConnectedSettings can render unconditionally.\n */\nexport async function whoami(): Promise<Identity> {\n if (typeof window === 'undefined') return { userType: 'public', name: null }\n try {\n const body = await sharedWhoami()\n if (!body?.valid) return { userType: 'public', name: null }\n return { userType: body.userType ?? 'public', name: body.name ?? null }\n } catch {\n return { userType: 'public', name: null }\n }\n}\n\n/**\n * Where a \"Switch key\" control sends the user when the inline sign-in client\n * (`loadSignIn()`) can't be loaded: the site's sign-in page, which brings them\n * back here afterwards.\n *\n * A browser session is created ONLY by /auth (hadoku_site, 2026-10-25): every\n * render of that page carries an edge-signed funnel token and the device\n * fingerprint, and /session/create alerts on — and will refuse — a sign-in\n * without them. So an app never posts a key itself.\n *\n * `switch=1` stops /auth from sending an already signed-in visitor straight\n * back, which would make switching impossible. `return` is this page's path,\n * query and hash; /auth redirects there with the new session cookie, and the\n * shell's mf-loader resyncs the localStorage mirror (hadoku_session_id /\n * hadoku_user_type) from /session/whoami on that load, so nothing here writes it.\n */\nexport function switchKeyHref(): string {\n return (\n '/auth?switch=1&return=' +\n encodeURIComponent(window.location.pathname + window.location.search + window.location.hash)\n )\n}\n\n/** What the site's sign-in client resolves to on success. */\nexport interface SignInResult {\n valid: boolean\n userType?: string\n sessionId?: string\n}\n\n/** `signIn` from hadoku.me's `/auth/sign-in.js`. Resolves on success; throws an\n * `Error` carrying the server's message on a refused or empty key. */\nexport type SignIn = (key: string) => Promise<SignInResult>\n\n/**\n * The site serves its sign-in page's own client as a module, so an app can sign\n * in INLINE on the same code path as /auth: a fresh funnel token per call, the\n * device fingerprint, and the `/session/create` post that sets the cookie (and\n * writes the hadoku_session_id / hadoku_user_type mirror). This package never\n * posts /session/create itself — a direct post would skip the fingerprint and\n * read as off-funnel — and it does not vendor a copy.\n *\n * The specifier is a VARIABLE on purpose. A literal `import('/auth/sign-in.js')`\n * would have every bundler that re-bundles this package (hadoku_site's build\n * among them) try to resolve the path at build time; this one is only ever\n * resolved by the browser, against whatever origin the page is on. For the\n * same reason it is typed here (`SignIn`) rather than by an ambient module\n * declaration, which only a literal specifier would pick up.\n *\n * The module starts collecting the fingerprint as soon as it evaluates, so call\n * this when a sign-in form OPENS, not when it submits. Memoised; resolves to\n * null when the module can't be loaded (a dev server that isn't hadoku.me),\n * which is the caller's cue to fall back to `switchKeyHref()`.\n */\nconst SIGN_IN_MODULE = '/auth/sign-in.js'\nlet signInModule: Promise<SignInClient | null> | null = null\n\n/**\n * The whole sign-in client. The passkey half is optional: a site build from\n * before it exports only `signIn`, and the passkey controls then fall back to\n * the /auth page (`passkeyHref()`), as a missing module does.\n */\nexport interface SignInClient {\n signIn: SignIn\n /** Like `signIn`, with a passkey in place of the key. Throws Error(message).\n * `signal` cancels the open prompt. */\n signInWithPasskey?: (opts?: { signal?: AbortSignal }) => Promise<SignInResult>\n /** Saves a passkey for the signed-in person on this device. Throws Error(message). */\n addPasskey?: (opts?: { signal?: AbortSignal }) => Promise<{ saved: boolean; passkeys: number }>\n /** A fresh passkey tap from the signed-in person; the assertion to post. Throws Error(message). */\n stepUpPasskey?: (opts?: { signal?: AbortSignal }) => Promise<PasskeyAssertion>\n}\n\n/** What `stepUpPasskey` resolves to: the WebAuthn assertion, base64url fields. */\nexport interface PasskeyAssertion {\n id: string\n clientDataJSON: string\n authenticatorData: string\n signature: string\n userHandle: string | null\n}\n\nexport function loadSignInClient(): Promise<SignInClient | null> {\n signInModule ??= import(/* @vite-ignore */ SIGN_IN_MODULE).then(\n (m: Partial<Record<keyof SignInClient, unknown>>) =>\n typeof m.signIn === 'function'\n ? {\n signIn: m.signIn as SignIn,\n signInWithPasskey:\n typeof m.signInWithPasskey === 'function'\n ? (m.signInWithPasskey as SignInClient['signInWithPasskey'])\n : undefined,\n addPasskey:\n typeof m.addPasskey === 'function'\n ? (m.addPasskey as SignInClient['addPasskey'])\n : undefined,\n stepUpPasskey:\n typeof m.stepUpPasskey === 'function'\n ? (m.stepUpPasskey as SignInClient['stepUpPasskey'])\n : undefined\n }\n : null,\n () => {\n // Let a later open retry: a failed fetch is not cached by the browser.\n signInModule = null\n return null\n }\n )\n return signInModule\n}\n\nexport function loadSignIn(): Promise<SignIn | null> {\n return loadSignInClient().then(c => c?.signIn ?? null)\n}\n\n/** Whether this browser can use a passkey at all (WebAuthn present). */\nexport function passkeysSupported(): boolean {\n return typeof window !== 'undefined' && 'PublicKeyCredential' in window\n}\n\n/**\n * The /auth page's passkey flows, for when the sign-in client can't be\n * loaded: `add` saves one for the signed-in visitor, `signin` is the page with\n * its passkey button. Both come back here afterwards.\n */\nexport function passkeyHref(mode: 'add' | 'signin'): string {\n if (mode === 'signin') return switchKeyHref()\n return (\n '/auth?passkey=add&return=' +\n encodeURIComponent(window.location.pathname + window.location.search + window.location.hash)\n )\n}\n\n/* ------------------------------------------------------------------ *\n * Prefetch\n * ------------------------------------------------------------------ */\n\n/** Everything the settings popout displays, resolved together. */\nexport interface SettingsSnapshot {\n identity: Identity\n /** null = public caller (no pill) or the request failed. */\n content: ContentLevelState | null\n /** Passkeys that sign this person in; null = unknown (older edge, host-supplied identity). */\n passkeys: number | null\n /** Service identities this person may mint for; 0 when unknown. */\n serviceGrants: number\n}\n\n/** Identity the host already knows, so we don't ask the server for it again. */\nexport interface SettingsPrefetchHints {\n /** Caller's tier. When supplied, whoami is skipped entirely. */\n userType?: Tier\n /** Caller's display name. Only meaningful alongside `userType`. */\n name?: string | null\n}\n\nlet snapshot: Promise<SettingsSnapshot> | null = null\n\n/**\n * Resolve — once per page load — everything the settings popout shows.\n *\n * This is THE entry point, and it is called from ConnectedSettings' MOUNT, not\n * from its open handler. Settings data is user identity: it is known at boot,\n * it doesn't change while the page is up, and making the gear the trigger left\n * the panel on screen but blank for a round trip (measured on prod: whoami\n * 167ms and content-level 186ms, issued concurrently). It now rides along with\n * the app's own boot traffic and the click costs nothing.\n *\n * Idempotent and shared: every caller after the first gets the same promise, so\n * N mounted consumers still produce at most one whoami for the whole page.\n * Mutations below write through to it rather than invalidating, so a remount\n * never shows a value the user just changed.\n *\n * Against a current edge-router this issues NO requests of its own at all — the\n * level rides on the whoami the shell already had in flight. See\n * resolveSettings for the fallback when it doesn't.\n */\nexport function prefetchSettings(hints: SettingsPrefetchHints = {}): Promise<SettingsSnapshot> {\n snapshot ??= resolveSettings(hints)\n return snapshot\n}\n\nasync function resolveSettings(hints: SettingsPrefetchHints): Promise<SettingsSnapshot> {\n // The whoami body, not just the adapted identity — edge-router carries the\n // content level on it (see below), and reading the raw body is how we get at\n // it without a second request.\n //\n // Skipped entirely when the host supplied identity: that prop exists for apps\n // that CANNOT reach /session/whoami (conjure sits behind a path-prefixed shim\n // where it 404s), so asking anyway would spend a request to learn nothing.\n const selfResolving = hints.userType === undefined && typeof window !== 'undefined'\n const bodyPromise = selfResolving ? sharedWhoami() : Promise.resolve(null)\n\n const identityPromise: Promise<Identity> =\n hints.userType !== undefined\n ? Promise.resolve({ userType: hints.userType, name: hints.name ?? null })\n : whoami()\n\n // PREFERRED PATH: take the level straight off whoami.\n //\n // edge-router's authGate has already resolved it (registry key → userId →\n // prefs D1) to stamp X-Hadoku-Content-Level, so reporting it on whoami costs\n // it nothing — and it saves us a proxied round trip to prefs-api that\n // measured 132-420ms against prod. Better still, whoami is in flight before\n // this bundle has even loaded, so the value is here the moment we ask.\n //\n // FALLBACK: the standalone GET, for any edge-router older than the\n // 2026-08-07 change, and for callers not behind it at all (Capacitor,\n // Storybook, a non-hadoku host). Gated on identity because the pill is\n // hidden for public callers — fetching an anonymous visitor's level is a\n // guaranteed-wasted request on every page view. `hadoku_user_type` is\n // written by the loader before anything mounts, so where it already says\n // \"signed in\" the fallback goes out concurrently rather than behind whoami.\n const contentPromise = bodyPromise.then(body => {\n const carried = contentFromWhoami(body)\n if (carried) return carried\n if (looksSignedIn(hints.userType)) return getContentLevel()\n return identityPromise.then(id => (id.userType === 'public' ? null : getContentLevel()))\n })\n\n const [identity, content, body] = await Promise.all([\n identityPromise,\n contentPromise,\n bodyPromise\n ])\n return {\n identity,\n content,\n passkeys: passkeysFromWhoami(body),\n serviceGrants: body?.valid && typeof body.serviceGrants === 'number' ? body.serviceGrants : 0\n }\n}\n\nfunction passkeysFromWhoami(body: WhoamiBody | null): number | null {\n return body?.valid && typeof body.passkeys === 'number' ? body.passkeys : null\n}\n\n/**\n * Adapt the content level off a whoami body, or null if that edge-router\n * doesn't report it.\n *\n * Both fields are required, and both must be numbers: a body carrying a level\n * without its ceiling would render a pill with zero segments — worse than the\n * fallback fetch, because it looks like a working control that offers nothing.\n */\nfunction contentFromWhoami(body: WhoamiBody | null): ContentLevelState | null {\n if (!body?.valid) return null\n const { contentLevel, maxContentLevel } = body\n if (typeof contentLevel !== 'number' || typeof maxContentLevel !== 'number') return null\n if (maxContentLevel < 1) return null\n return { level: contentLevel, maxLevel: maxContentLevel }\n}\n\n/** Best-effort \"is this caller signed in?\" from state available synchronously. */\nfunction looksSignedIn(hinted?: Tier): boolean {\n if (hinted !== undefined) return hinted !== 'public'\n if (typeof window === 'undefined') return false\n const cached = localStorage.getItem('hadoku_user_type')\n return cached !== null && cached !== 'public'\n}\n\n/** Keep the prefetched snapshot in step with a successful mutation. */\nfunction patchSnapshot(patch: (prev: SettingsSnapshot) => SettingsSnapshot) {\n if (!snapshot) return\n snapshot = snapshot.then(patch)\n}\n"],"names":["body"],"mappings":"AA6BA,MAAM,qBAAqB;AAC3B,MAAM,eAAe;AACrB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAavB,MAAM,gBAAgB;AAgCtB,MAAM,qBAAqB;AAG3B,SAAS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