@hadoku/task-ui-components 4.20.7 → 4.21.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/dist/components/ConnectedSettings.d.ts.map +1 -1
- package/dist/components/ConnectedSettings.js +78 -2
- package/dist/components/ConnectedSettings.js.map +1 -1
- package/dist/lib/settingsClient.d.ts +6 -2
- package/dist/lib/settingsClient.d.ts.map +1 -1
- package/dist/lib/settingsClient.js +17 -0
- package/dist/lib/settingsClient.js.map +1 -1
- package/package.json +1 -1
- package/src/components/ConnectedSettings.tsx +98 -1
- package/src/lib/settingsClient.ts +22 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConnectedSettings.d.ts","sourceRoot":"","sources":["../../src/components/ConnectedSettings.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,KAAmD,MAAM,OAAO,CAAA;AAEvE,OAAO,
|
|
1
|
+
{"version":3,"file":"ConnectedSettings.d.ts","sourceRoot":"","sources":["../../src/components/ConnectedSettings.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,KAAmD,MAAM,OAAO,CAAA;AAEvE,OAAO,EAWL,KAAK,IAAI,EACV,MAAM,uBAAuB,CAAA;AAC9B,OAAO,mBAAmB,CAAA;AAE1B,MAAM,WAAW,sBAAsB;IACrC;;;;;;+EAM2E;IAC3E,QAAQ,CAAC,EAAE,IAAI,CAAA;IACf,uEAAuE;IACvE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,mEAAmE;IACnE,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,CAAA;IAC5C;;;;;;8BAM0B;IAC1B,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAA;CAC3B;AA0ED,wBAAgB,iBAAiB,CAAC,EAChC,QAAQ,EAAE,YAAY,EACtB,IAAI,EAAE,QAAQ,EACd,YAAY,EACZ,QAAQ,EACT,EAAE,sBAAsB,qBAumBxB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { jsxs, jsx, Fragment } from "react/jsx-runtime";
|
|
2
2
|
import { useState, useRef, useCallback, useEffect } from "react";
|
|
3
3
|
import { SettingsIcon } from "./ThemeIcons.js";
|
|
4
|
-
import { prefetchSettings, setDisplayName, loadSignIn, switchKeyHref, loadSignInClient, passkeyHref, setContentLevel, passkeysSupported } from "../lib/settingsClient.js";
|
|
4
|
+
import { prefetchSettings, setDisplayName, loadSignIn, switchKeyHref, loadSignInClient, passkeyHref, setContentLevel, passkeysSupported, deleteOwnAccount } from "../lib/settingsClient.js";
|
|
5
5
|
/* empty css */
|
|
6
6
|
function untilAborted(signal) {
|
|
7
7
|
return new Promise((_, reject) => {
|
|
@@ -24,11 +24,35 @@ const PASSKEY_DOT = {
|
|
|
24
24
|
background: "var(--color-primary)",
|
|
25
25
|
pointerEvents: "none"
|
|
26
26
|
};
|
|
27
|
+
const PASSKEY_PULSE_CLASS = "settings-popout__btn--pulse";
|
|
28
|
+
const PASSKEY_PULSE_STYLE_ID = "settings-passkey-pulse";
|
|
29
|
+
const PASSKEY_PULSE_CSS = `
|
|
30
|
+
@keyframes settings-passkey-pulse {
|
|
31
|
+
0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 70%, transparent); }
|
|
32
|
+
70% { box-shadow: 0 0 0 8px color-mix(in srgb, var(--color-primary) 0%, transparent); }
|
|
33
|
+
100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 0%, transparent); }
|
|
34
|
+
}
|
|
35
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
36
|
+
.${PASSKEY_PULSE_CLASS}:not(:disabled) {
|
|
37
|
+
animation: settings-passkey-pulse 1.6s ease-out infinite;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
`;
|
|
41
|
+
function usePasskeyPulseStyle(active) {
|
|
42
|
+
useEffect(() => {
|
|
43
|
+
if (!active || document.getElementById(PASSKEY_PULSE_STYLE_ID)) return;
|
|
44
|
+
const el = document.createElement("style");
|
|
45
|
+
el.id = PASSKEY_PULSE_STYLE_ID;
|
|
46
|
+
el.textContent = PASSKEY_PULSE_CSS;
|
|
47
|
+
document.head.appendChild(el);
|
|
48
|
+
}, [active]);
|
|
49
|
+
}
|
|
27
50
|
const TIER_LABEL = {
|
|
28
51
|
admin: "Administrator",
|
|
29
52
|
wife: "Wife",
|
|
30
53
|
service: "Service",
|
|
31
54
|
friend: "Friend",
|
|
55
|
+
member: "Member",
|
|
32
56
|
public: "Guest"
|
|
33
57
|
};
|
|
34
58
|
function ConnectedSettings({
|
|
@@ -53,6 +77,8 @@ function ConnectedSettings({
|
|
|
53
77
|
const [passkeySaved, setPasskeySaved] = useState(false);
|
|
54
78
|
const [passkeyCount, setPasskeyCount] = useState(null);
|
|
55
79
|
const [passkeyError, setPasskeyError] = useState(null);
|
|
80
|
+
const [deleteStage, setDeleteStage] = useState("idle");
|
|
81
|
+
const [deleteError, setDeleteError] = useState(null);
|
|
56
82
|
const passkeyCtl = useRef(null);
|
|
57
83
|
const cancelPasskey = useCallback((reason) => passkeyCtl.current?.abort(reason), []);
|
|
58
84
|
const [content, setContent] = useState(null);
|
|
@@ -60,6 +86,7 @@ function ConnectedSettings({
|
|
|
60
86
|
const [resolving, setResolving] = useState(true);
|
|
61
87
|
const showContentPill = userType !== "public";
|
|
62
88
|
const needsPasskey = !resolving && userType !== "public" && passkeyCount === 0 && !passkeySaved && passkeysSupported();
|
|
89
|
+
usePasskeyPulseStyle(needsPasskey);
|
|
63
90
|
useEffect(() => {
|
|
64
91
|
if (userTypeProp !== void 0) setUserType(userTypeProp);
|
|
65
92
|
}, [userTypeProp]);
|
|
@@ -407,7 +434,7 @@ function ConnectedSettings({
|
|
|
407
434
|
"button",
|
|
408
435
|
{
|
|
409
436
|
type: "button",
|
|
410
|
-
className: `settings-popout__btn${needsPasskey ?
|
|
437
|
+
className: `settings-popout__btn${needsPasskey ? ` settings-popout__btn--primary ${PASSKEY_PULSE_CLASS}` : ""}`,
|
|
411
438
|
disabled: passkeyMode !== null || passkeySaved,
|
|
412
439
|
onClick: () => {
|
|
413
440
|
savePasskey().catch(reportErr);
|
|
@@ -437,6 +464,55 @@ function ConnectedSettings({
|
|
|
437
464
|
) }),
|
|
438
465
|
passkeyError && /* @__PURE__ */ jsx("span", { className: "settings-popout__error", role: "alert", children: passkeyError })
|
|
439
466
|
] }),
|
|
467
|
+
!resolving && userType === "member" && /* @__PURE__ */ jsxs("section", { className: "settings-popout__row settings-popout__row--stack", children: [
|
|
468
|
+
/* @__PURE__ */ jsxs("span", { className: "settings-popout__inline", children: [
|
|
469
|
+
/* @__PURE__ */ jsx("span", { className: "settings-popout__label settings-popout__label--grow", children: "Account" }),
|
|
470
|
+
deleteStage === "idle" ? /* @__PURE__ */ jsx(
|
|
471
|
+
"button",
|
|
472
|
+
{
|
|
473
|
+
type: "button",
|
|
474
|
+
className: "settings-popout__btn",
|
|
475
|
+
onClick: () => {
|
|
476
|
+
setDeleteError(null);
|
|
477
|
+
setDeleteStage("confirm");
|
|
478
|
+
},
|
|
479
|
+
children: "Delete account"
|
|
480
|
+
}
|
|
481
|
+
) : /* @__PURE__ */ jsx(
|
|
482
|
+
"button",
|
|
483
|
+
{
|
|
484
|
+
type: "button",
|
|
485
|
+
className: "settings-popout__btn",
|
|
486
|
+
disabled: deleteStage === "busy",
|
|
487
|
+
onClick: () => setDeleteStage("idle"),
|
|
488
|
+
children: "Keep"
|
|
489
|
+
}
|
|
490
|
+
)
|
|
491
|
+
] }),
|
|
492
|
+
deleteStage !== "idle" && /* @__PURE__ */ jsx("span", { className: "settings-popout__inline", children: /* @__PURE__ */ jsx(
|
|
493
|
+
"button",
|
|
494
|
+
{
|
|
495
|
+
type: "button",
|
|
496
|
+
className: "settings-popout__btn settings-popout__btn--primary",
|
|
497
|
+
disabled: deleteStage === "busy",
|
|
498
|
+
onClick: () => {
|
|
499
|
+
setDeleteStage("busy");
|
|
500
|
+
deleteOwnAccount().then((deleted) => {
|
|
501
|
+
if (!deleted) {
|
|
502
|
+
setDeleteError("Account not deleted");
|
|
503
|
+
setDeleteStage("confirm");
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
localStorage.removeItem("hadoku_session_id");
|
|
507
|
+
localStorage.removeItem("hadoku_user_type");
|
|
508
|
+
window.location.assign("/");
|
|
509
|
+
}).catch(reportErr);
|
|
510
|
+
},
|
|
511
|
+
children: deleteStage === "busy" ? "Deleting…" : "Delete for good"
|
|
512
|
+
}
|
|
513
|
+
) }),
|
|
514
|
+
deleteError && /* @__PURE__ */ jsx("span", { className: "settings-popout__error", role: "alert", children: deleteError })
|
|
515
|
+
] }),
|
|
440
516
|
children && /* @__PURE__ */ jsx("section", { className: "settings-popout__row settings-popout__row--stack settings-popout__app", children })
|
|
441
517
|
] })
|
|
442
518
|
] });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConnectedSettings.js","sources":["../../src/components/ConnectedSettings.tsx"],"sourcesContent":["/**\n * ConnectedSettings — the unified per-user settings control for the hadoku\n * ecosystem: a gear button that opens a popout housing everything that is a\n * property of the PERSON (not the app):\n * - current access tier (read-only, friendly label)\n * - display name (inline edit → POST /session/name)\n * - global content-visibility level (tiered pill → PUT /prefs/api/v1/content-level)\n * - switch key (an inline sign-in form, on the site's own sign-in client)\n *\n * \"Connected\" (parallel to ConnectedThemePicker): it self-wires to the\n * hadoku.me edge-router via same-origin fetches (see lib/settingsClient), so\n * dropping `<ConnectedSettings />` into any app under hadoku.me needs zero\n * props. Identity is resolved via whoami() unless the host passes `userType` /\n * `name` (avoids a redundant fetch when the app already knows).\n *\n * All of that is resolved AT MOUNT via `prefetchSettings()`, never on\n * gear-click — opening the popout must cost zero requests. See the effect\n * below, and `e2e/settings-prefetch.spec.ts` in hadoku-task, which fails if the\n * fetch moves back behind the click.\n *\n * Mirrors ThemePicker's controlled-popout pattern: owns its own `open` state +\n * a full-viewport overlay for click-outside dismiss. The content pill renders\n * `maxLevel` segments (friend ⇒ 3, admin ⇒ 4) and is hidden for public callers.\n * maxLevel comes from the server so the tier ceiling is never trusted from the\n * client.\n */\nimport React, { useCallback, useEffect, useRef, useState } from 'react'\nimport { SettingsIcon } from './ThemeIcons'\nimport {\n prefetchSettings,\n setContentLevel,\n setDisplayName,\n loadSignIn,\n loadSignInClient,\n passkeyHref,\n passkeysSupported,\n switchKeyHref,\n type ContentLevelState,\n type Tier\n} from '../lib/settingsClient'\nimport '../app-header.css'\n\nexport interface ConnectedSettingsProps {\n /** Caller's tier. Omit to self-resolve via whoami().\n *\n * This exists for apps that CANNOT reach `/session/whoami` — conjure sits\n * behind a path-prefixed shim that serves nothing outside `/conjure`, so\n * whoami 404s and the tier would fall back to guest. It is an identity\n * hint, not a way to present a different tier than the edge assigns: every\n * gate that matters is enforced server-side off the edge-stamped tier. */\n userType?: Tier\n /** Display name. Omit to self-resolve via whoami(). Same rationale. */\n name?: string | null\n /** Notify the host (e.g. a \"Signed in as …\" label) of a rename. */\n onNameChange?: (name: string | null) => void\n /** App-specific settings rendered as a final section in the same popout, so\n * an app with its own preferences keeps ONE unified gear instead of a second\n * control. Shown under an \"App preferences\" divider.\n *\n * This slot is deliberately unconstrained — put whatever the app needs in\n * it. The constraint is only that it lands AFTER the four canonical rows and\n * cannot change them. */\n children?: React.ReactNode\n}\n\n/** Rejects once `signal` aborts, so a call that ignores the signal (an older\n * site client, a prompt that never settles) still lets the UI go. */\nfunction untilAborted(signal: AbortSignal): Promise<never> {\n return new Promise((_, reject) => {\n const fail = () => reject(new Error('cancelled'))\n if (signal.aborted) fail()\n else signal.addEventListener('abort', fail, { once: true })\n })\n}\n\n/** Abort reason when the popout closes: a dismissal, not an error to show. */\nconst CLOSED = 'closed'\n\n/** Rejection sink for fire-and-forget settings actions. The client helpers\n * already resolve to null on failure (state reflects it), so this only trips\n * on truly unexpected throws — log rather than swallow silently. */\nfunction reportErr(err: unknown) {\n // task-ui-components v2 dropped its logger; keep the package dependency-free.\n console.error('[ConnectedSettings] action failed', (err as Error)?.message ?? err)\n}\n\n/** Inline, not in app-header.css: every app runs this component from the\n * site's shared vendor module, but compiles app-header.css into its own\n * stylesheet at ITS build, so a new rule reaches an app only when it rebuilds. */\nconst PASSKEY_DOT: React.CSSProperties = {\n position: 'absolute',\n top: 2,\n right: 2,\n width: 8,\n height: 8,\n borderRadius: '50%',\n background: 'var(--color-primary)',\n pointerEvents: 'none'\n}\n\nconst TIER_LABEL: Record<Tier, string> = {\n admin: 'Administrator',\n wife: 'Wife',\n service: 'Service',\n friend: 'Friend',\n public: 'Guest'\n}\n\nexport function ConnectedSettings({\n userType: userTypeProp,\n name: nameProp,\n onNameChange,\n children\n}: ConnectedSettingsProps) {\n const [open, setOpen] = useState(false)\n const rootRef = useRef<HTMLDivElement>(null)\n\n // Identity — from props if supplied, else resolved lazily via whoami().\n const [userType, setUserType] = useState<Tier>(userTypeProp ?? 'public')\n const [resolvedName, setResolvedName] = useState<string | null>(nameProp ?? null)\n\n // Name editing\n const [nameDraft, setNameDraft] = useState(resolvedName ?? '')\n const [editingName, setEditingName] = useState(false)\n const [nameSaving, setNameSaving] = useState(false)\n const [displayName, setLocalName] = useState<string | null>(resolvedName)\n\n // Key swap. The draft lives only in this state and the input: it is never\n // logged, stored or sent anywhere but the site's sign-in client.\n const [keyFormOpen, setKeyFormOpen] = useState(false)\n const [keyDraft, setKeyDraft] = useState('')\n const [keyBusy, setKeyBusy] = useState(false)\n const [keyError, setKeyError] = useState<string | null>(null)\n\n // Passkeys, through the same site client: save one while signed in, or\n // sign in with one from the key form. One prompt at a time, and always\n // cancellable: a password manager can dismiss the browser's prompt without\n // ever answering it, so Cancel, closing the popout and the site client's own\n // time limit each end the wait.\n const [passkeyMode, setPasskeyMode] = useState<'save' | 'signin' | null>(null)\n const [passkeySaved, setPasskeySaved] = useState(false)\n // How many passkeys sign this person in, from whoami; null = unknown.\n const [passkeyCount, setPasskeyCount] = useState<number | null>(null)\n const [passkeyError, setPasskeyError] = useState<string | null>(null)\n const passkeyCtl = useRef<AbortController | null>(null)\n const cancelPasskey = useCallback((reason?: string) => passkeyCtl.current?.abort(reason), [])\n\n // Content level\n const [content, setContent] = useState<ContentLevelState | null>(null)\n const [levelSaving, setLevelSaving] = useState(false)\n\n // One flag for the whole prefetch, not one per request — the panel body\n // reveals when everything has settled, so nothing pops in a beat late. In\n // practice the user never sees it: the prefetch starts at mount and is long\n // done by the time the gear is clicked. It only shows if they click within\n // the first moments of the page.\n const [resolving, setResolving] = useState(true)\n\n // Everyone who is SIGNED IN, expressed as \"not public\" rather than as a list\n // of tiers. The list form (`=== 'admin' || === 'friend' || === 'service'`)\n // is an exact-match allowlist: it silently excluded `wife` the moment that\n // tier existed, which is the failure the rank model is meant to prevent.\n // There is no rank helper in this bundle, but \"above public\" needs none.\n const showContentPill = userType !== 'public'\n\n // Signed in on a key with no passkey: the gear carries a dot and Save passkey\n // is the primary action until one is saved. Unknown counts never prompt.\n const needsPasskey =\n !resolving &&\n userType !== 'public' &&\n passkeyCount === 0 &&\n !passkeySaved &&\n passkeysSupported()\n\n // Keep local identity in sync when the host controls it via props.\n useEffect(() => {\n if (userTypeProp !== undefined) setUserType(userTypeProp)\n }, [userTypeProp])\n useEffect(() => {\n if (nameProp !== undefined) {\n setResolvedName(nameProp)\n setLocalName(nameProp)\n setNameDraft(nameProp ?? '')\n }\n }, [nameProp])\n\n // Resolve everything the panel shows AT MOUNT — not on open.\n //\n // This used to be gated on `open`, which made the gear the trigger for\n // whoami + content-level (167ms / 186ms on prod, concurrent) — a round trip\n // the user waited out with the panel already on screen and blank. Nothing\n // about that data depends on the click:\n // it's the signed-in user's own identity, settled at boot and unchanged for\n // the life of the page. So it rides along with the app's boot traffic, and\n // clicking the gear costs zero requests. `e2e/settings-prefetch.spec.ts` in\n // hadoku-task pins that.\n //\n // The client memoises across callers, so mounting this in several places (or\n // remounting it) does not multiply requests, and on hadoku.me the identity\n // half is free — it awaits the whoami the shell already had in flight.\n useEffect(() => {\n let live = true\n prefetchSettings({ userType: userTypeProp, name: nameProp })\n .then(({ identity, content: state, passkeys }) => {\n if (!live) return\n setPasskeyCount(passkeys)\n // Props stay authoritative: the host passed them because it can see an\n // identity this component can't resolve for itself.\n if (userTypeProp === undefined) {\n setUserType(identity.userType)\n setResolvedName(identity.name)\n setLocalName(identity.name)\n setNameDraft(identity.name ?? '')\n }\n if (state) setContent(state)\n })\n .catch(reportErr)\n .finally(() => {\n if (live) setResolving(false)\n })\n return () => {\n live = false\n }\n // Hints are read once, on the first mount that gets there — the prefetch is\n // page-scoped and a later prop change cannot un-issue it. Identity changes\n // arrive through the sync effects above, and a key swap reloads the page.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n // Escape closes.\n useEffect(() => {\n if (!open) return\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') setOpen(false)\n }\n window.addEventListener('keydown', onKey)\n return () => window.removeEventListener('keydown', onKey)\n }, [open])\n\n const saveName = useCallback(async () => {\n const trimmed = nameDraft.trim()\n if (!trimmed || trimmed === displayName) {\n setEditingName(false)\n return\n }\n setNameSaving(true)\n const stored = await setDisplayName(trimmed)\n setNameSaving(false)\n if (stored !== null) {\n setLocalName(stored)\n setNameDraft(stored)\n onNameChange?.(stored)\n }\n setEditingName(false)\n }, [nameDraft, displayName, onNameChange])\n\n // Open the form AND start loading the site's sign-in client, which begins its\n // fingerprint collection as it evaluates — so it is ready by submit. Where the\n // client cannot load at all (not on hadoku.me), the page-level /auth flow is\n // the only way to sign in, so go there.\n const openKeyForm = useCallback(() => {\n setKeyFormOpen(true)\n setKeyError(null)\n loadSignIn()\n .then(signIn => {\n if (!signIn) window.location.assign(switchKeyHref())\n })\n .catch(reportErr)\n }, [])\n\n const submitKey = useCallback(async () => {\n setKeyBusy(true)\n setKeyError(null)\n const signIn = await loadSignIn()\n if (!signIn) {\n window.location.assign(switchKeyHref())\n return\n }\n try {\n await signIn(keyDraft)\n } catch (err) {\n // A refused key is an inline error, never a redirect.\n setKeyError((err as Error)?.message || 'Invalid key')\n setKeyBusy(false)\n return\n }\n // The page now acts for a different identity: everything must re-mount.\n // Busy stays on through the reload so the form can't be resubmitted.\n window.location.reload()\n }, [keyDraft])\n\n const savePasskey = useCallback(async () => {\n const ctl = new AbortController()\n passkeyCtl.current = ctl\n setPasskeyMode('save')\n setPasskeyError(null)\n try {\n const client = await Promise.race([loadSignInClient(), untilAborted(ctl.signal)])\n if (!client?.addPasskey) {\n window.location.assign(passkeyHref('add'))\n return\n }\n await Promise.race([client.addPasskey({ signal: ctl.signal }), untilAborted(ctl.signal)])\n setPasskeySaved(true)\n } catch (err) {\n if (ctl.signal.reason !== CLOSED) {\n setPasskeyError(\n ctl.signal.aborted ? 'Passkey not saved' : (err as Error)?.message || 'Passkey not saved'\n )\n }\n } finally {\n if (passkeyCtl.current === ctl) passkeyCtl.current = null\n setPasskeyMode(null)\n }\n }, [])\n\n const signInWithPasskey = useCallback(async () => {\n const ctl = new AbortController()\n passkeyCtl.current = ctl\n setPasskeyMode('signin')\n setKeyBusy(true)\n setKeyError(null)\n let leaving = false\n try {\n const client = await Promise.race([loadSignInClient(), untilAborted(ctl.signal)])\n if (!client?.signInWithPasskey) {\n leaving = true\n window.location.assign(passkeyHref('signin'))\n return\n }\n await Promise.race([\n client.signInWithPasskey({ signal: ctl.signal }),\n untilAborted(ctl.signal)\n ])\n // The page now acts for a different identity: everything must re-mount.\n // Busy stays on through the reload so nothing can be resubmitted.\n leaving = true\n window.location.reload()\n } catch (err) {\n if (ctl.signal.reason !== CLOSED) {\n setKeyError(\n ctl.signal.aborted\n ? 'Passkey sign-in cancelled'\n : (err as Error)?.message || 'Passkey sign-in cancelled'\n )\n }\n } finally {\n if (passkeyCtl.current === ctl) passkeyCtl.current = null\n if (!leaving) {\n setPasskeyMode(null)\n setKeyBusy(false)\n }\n }\n }, [])\n\n // Closing the popout (or leaving the page) abandons an open prompt.\n useEffect(() => {\n if (!open) cancelPasskey(CLOSED)\n }, [open, cancelPasskey])\n useEffect(() => () => cancelPasskey(CLOSED), [cancelPasskey])\n\n const pickLevel = useCallback(\n async (level: number) => {\n if (!content || level === content.level || levelSaving) return\n const prev = content\n setContent({ ...content, level }) // optimistic\n setLevelSaving(true)\n const result = await setContentLevel(level)\n setLevelSaving(false)\n setContent(result ?? prev) // adopt server truth, or revert\n },\n [content, levelSaving]\n )\n\n // No caller-supplied class on the root. The four rows below are the\n // platform's, not the app's, and a className here is enough to restyle or\n // hide any of them — which is the drift this component exists to prevent.\n // Apps extend via `children`, never by reaching into this markup.\n return (\n <div className=\"settings-popout\" ref={rootRef}>\n <button\n type=\"button\"\n className=\"app-header__icon-btn settings-toggle-btn\"\n aria-label={needsPasskey ? 'User settings, no passkey saved' : 'User settings'}\n style={needsPasskey ? { position: 'relative' } : undefined}\n aria-expanded={open}\n onClick={() => setOpen(v => !v)}\n >\n <SettingsIcon />\n {needsPasskey && (\n <span className=\"settings-toggle-btn__dot\" style={PASSKEY_DOT} aria-hidden=\"true\" />\n )}\n </button>\n\n {open && <div className=\"settings-popout__overlay\" onClick={() => setOpen(false)} />}\n\n {open && (\n <div className=\"settings-popout__panel\" role=\"dialog\" aria-label=\"User settings\">\n <div className=\"settings-popout__header\">Settings</div>\n\n {/* Access tier. While resolving, the state still says 'public' —\n rendering \"Guest\" there would be a wrong answer that corrects\n itself a moment later, which reads exactly like the lag this\n placeholder exists to remove. */}\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Access tier</span>\n {resolving ? (\n <span className=\"settings-popout__value\">…</span>\n ) : (\n <span className={`settings-popout__tier settings-popout__tier--${userType}`}>\n {TIER_LABEL[userType]}\n </span>\n )}\n </section>\n\n {/* Display name */}\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Display name</span>\n {resolving ? (\n <span className=\"settings-popout__value\">…</span>\n ) : editingName ? (\n <span className=\"settings-popout__inline\">\n <input\n className=\"settings-popout__input\"\n value={nameDraft}\n maxLength={64}\n autoFocus\n disabled={nameSaving}\n onChange={e => setNameDraft(e.target.value)}\n onKeyDown={e => {\n if (e.key === 'Enter') {\n saveName().catch(reportErr)\n }\n if (e.key === 'Escape') {\n // The edit's Escape, not the popout's (window listener).\n e.stopPropagation()\n setEditingName(false)\n setNameDraft(displayName ?? '')\n }\n }}\n />\n <button\n type=\"button\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={nameSaving}\n onClick={() => {\n saveName().catch(reportErr)\n }}\n >\n {nameSaving ? '…' : 'Save'}\n </button>\n </span>\n ) : (\n <button\n type=\"button\"\n className=\"settings-popout__value settings-popout__value--editable\"\n aria-label=\"Edit display name\"\n onClick={() => {\n setNameDraft(displayName ?? '')\n setEditingName(true)\n }}\n >\n {displayName || 'Unnamed'}\n </button>\n )}\n </section>\n\n {/* Content visibility level. Held back until the first-open fetch\n settles, so it lands in the same paint as the tier and name\n rather than a round trip behind them. `content` is fetched\n concurrently with whoami(), so by then it is already here. */}\n {!resolving && showContentPill && (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__label\">Content visibility</span>\n {content ? (\n <>\n <div\n className=\"settings-popout__pill\"\n role=\"radiogroup\"\n aria-label=\"Content visibility level\"\n >\n {Array.from({ length: content.maxLevel }, (_, i) => i + 1).map(lvl => (\n <button\n key={lvl}\n type=\"button\"\n role=\"radio\"\n aria-checked={lvl === content.level}\n aria-label={`Level ${lvl}`}\n className={`settings-popout__seg${\n lvl <= content.level ? ' settings-popout__seg--filled' : ''\n }`}\n disabled={levelSaving}\n onClick={() => {\n pickLevel(lvl).catch(reportErr)\n }}\n >\n {lvl}\n </button>\n ))}\n </div>\n <span className=\"settings-popout__hint\">\n Higher levels reveal more mature content across apps. Level 1 is\n safe-for-everyone.\n </span>\n </>\n ) : (\n // Not \"Loading…\" — the fetch has already settled by the time\n // this section renders at all, so a null here means it failed.\n <span className=\"settings-popout__hint\">Currently unavailable.</span>\n )}\n </section>\n )}\n\n {/* Switch key. Signs in inline through the SITE's sign-in client\n (the /auth page's own code path), never a post of ours. A real\n <form> with a username + current-password pair, so password\n managers offer and save the key. */}\n {keyFormOpen ? (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <form\n className=\"settings-popout__key-form\"\n onSubmit={e => {\n e.preventDefault()\n submitKey().catch(reportErr)\n }}\n >\n <input\n type=\"text\"\n name=\"username\"\n autoComplete=\"username\"\n value=\"hadoku\"\n readOnly\n hidden\n />\n <label className=\"settings-popout__label\" htmlFor=\"settings-popout-key\">\n Access key\n </label>\n <span className=\"settings-popout__inline\">\n <input\n id=\"settings-popout-key\"\n className=\"settings-popout__input\"\n type=\"password\"\n name=\"password\"\n autoComplete=\"current-password\"\n autoCapitalize=\"none\"\n spellCheck={false}\n autoFocus\n value={keyDraft}\n disabled={keyBusy}\n aria-invalid={keyError !== null}\n aria-describedby={keyError ? 'settings-popout-key-error' : undefined}\n onChange={e => setKeyDraft(e.target.value)}\n />\n <button\n type=\"submit\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={keyBusy}\n >\n {keyBusy ? 'Signing in…' : 'Sign in'}\n </button>\n </span>\n {passkeysSupported() && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={keyBusy}\n onClick={() => {\n signInWithPasskey().catch(reportErr)\n }}\n >\n {passkeyMode === 'signin' ? 'Waiting for passkey…' : 'Use a passkey'}\n </button>\n </span>\n )}\n {/* Cancel on a line of its own: in the row it would slide under\n the pointer, and a double click would cancel what it started. */}\n {passkeyMode === 'signin' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => cancelPasskey()}\n >\n Cancel\n </button>\n </span>\n )}\n {keyError && (\n <span\n id=\"settings-popout-key-error\"\n className=\"settings-popout__error\"\n role=\"alert\"\n >\n {keyError}\n </span>\n )}\n </form>\n </section>\n ) : (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__inline\">\n <span className=\"settings-popout__label settings-popout__label--grow\">\n Access key\n </span>\n {/* Signed-in people only: the site refuses to save one for anyone else. */}\n {!resolving && userType !== 'public' && passkeysSupported() && (\n <button\n type=\"button\"\n className={`settings-popout__btn${needsPasskey ? ' settings-popout__btn--primary' : ''}`}\n disabled={passkeyMode !== null || passkeySaved}\n onClick={() => {\n savePasskey().catch(reportErr)\n }}\n >\n {passkeySaved\n ? 'Passkey saved'\n : passkeyMode === 'save'\n ? 'Saving…'\n : 'Save passkey'}\n </button>\n )}\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={passkeyMode === 'save'}\n onClick={openKeyForm}\n >\n Switch key\n </button>\n </span>\n {/* Its own line, so nothing moves under a double click. */}\n {passkeyMode === 'save' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => cancelPasskey()}\n >\n Cancel\n </button>\n </span>\n )}\n {passkeyError && (\n <span className=\"settings-popout__error\" role=\"alert\">\n {passkeyError}\n </span>\n )}\n </section>\n )}\n\n {/* App-specific settings (optional) — same popout, one gear. */}\n {children && (\n <section className=\"settings-popout__row settings-popout__row--stack settings-popout__app\">\n {children}\n </section>\n )}\n </div>\n )}\n </div>\n )\n}\n"],"names":[],"mappings":";;;;;AAmEA,SAAS,aAAa,QAAqC;AACzD,SAAO,IAAI,QAAQ,CAAC,GAAG,WAAW;AAChC,UAAM,OAAO,MAAM,OAAO,IAAI,MAAM,WAAW,CAAC;AAChD,QAAI,OAAO,QAAS,MAAA;AAAA,gBACR,iBAAiB,SAAS,MAAM,EAAE,MAAM,MAAM;AAAA,EAC5D,CAAC;AACH;AAGA,MAAM,SAAS;AAKf,SAAS,UAAU,KAAc;AAE/B,UAAQ,MAAM,qCAAsC,KAAe,WAAW,GAAG;AACnF;AAKA,MAAM,cAAmC;AAAA,EACvC,UAAU;AAAA,EACV,KAAK;A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AAA,EAAA,GAEJ;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"ConnectedSettings.js","sources":["../../src/components/ConnectedSettings.tsx"],"sourcesContent":["/**\n * ConnectedSettings — the unified per-user settings control for the hadoku\n * ecosystem: a gear button that opens a popout housing everything that is a\n * property of the PERSON (not the app):\n * - current access tier (read-only, friendly label)\n * - display name (inline edit → POST /session/name)\n * - global content-visibility level (tiered pill → PUT /prefs/api/v1/content-level)\n * - switch key (an inline sign-in form, on the site's own sign-in client)\n *\n * \"Connected\" (parallel to ConnectedThemePicker): it self-wires to the\n * hadoku.me edge-router via same-origin fetches (see lib/settingsClient), so\n * dropping `<ConnectedSettings />` into any app under hadoku.me needs zero\n * props. Identity is resolved via whoami() unless the host passes `userType` /\n * `name` (avoids a redundant fetch when the app already knows).\n *\n * All of that is resolved AT MOUNT via `prefetchSettings()`, never on\n * gear-click — opening the popout must cost zero requests. See the effect\n * below, and `e2e/settings-prefetch.spec.ts` in hadoku-task, which fails if the\n * fetch moves back behind the click.\n *\n * Mirrors ThemePicker's controlled-popout pattern: owns its own `open` state +\n * a full-viewport overlay for click-outside dismiss. The content pill renders\n * `maxLevel` segments (friend ⇒ 3, admin ⇒ 4) and is hidden for public callers.\n * maxLevel comes from the server so the tier ceiling is never trusted from the\n * client.\n */\nimport React, { useCallback, useEffect, useRef, useState } from 'react'\nimport { SettingsIcon } from './ThemeIcons'\nimport {\n deleteOwnAccount,\n prefetchSettings,\n setContentLevel,\n setDisplayName,\n loadSignIn,\n loadSignInClient,\n passkeyHref,\n passkeysSupported,\n switchKeyHref,\n type ContentLevelState,\n type Tier\n} from '../lib/settingsClient'\nimport '../app-header.css'\n\nexport interface ConnectedSettingsProps {\n /** Caller's tier. Omit to self-resolve via whoami().\n *\n * This exists for apps that CANNOT reach `/session/whoami` — conjure sits\n * behind a path-prefixed shim that serves nothing outside `/conjure`, so\n * whoami 404s and the tier would fall back to guest. It is an identity\n * hint, not a way to present a different tier than the edge assigns: every\n * gate that matters is enforced server-side off the edge-stamped tier. */\n userType?: Tier\n /** Display name. Omit to self-resolve via whoami(). Same rationale. */\n name?: string | null\n /** Notify the host (e.g. a \"Signed in as …\" label) of a rename. */\n onNameChange?: (name: string | null) => void\n /** App-specific settings rendered as a final section in the same popout, so\n * an app with its own preferences keeps ONE unified gear instead of a second\n * control. Shown under an \"App preferences\" divider.\n *\n * This slot is deliberately unconstrained — put whatever the app needs in\n * it. The constraint is only that it lands AFTER the four canonical rows and\n * cannot change them. */\n children?: React.ReactNode\n}\n\n/** Rejects once `signal` aborts, so a call that ignores the signal (an older\n * site client, a prompt that never settles) still lets the UI go. */\nfunction untilAborted(signal: AbortSignal): Promise<never> {\n return new Promise((_, reject) => {\n const fail = () => reject(new Error('cancelled'))\n if (signal.aborted) fail()\n else signal.addEventListener('abort', fail, { once: true })\n })\n}\n\n/** Abort reason when the popout closes: a dismissal, not an error to show. */\nconst CLOSED = 'closed'\n\n/** Rejection sink for fire-and-forget settings actions. The client helpers\n * already resolve to null on failure (state reflects it), so this only trips\n * on truly unexpected throws — log rather than swallow silently. */\nfunction reportErr(err: unknown) {\n // task-ui-components v2 dropped its logger; keep the package dependency-free.\n console.error('[ConnectedSettings] action failed', (err as Error)?.message ?? err)\n}\n\n/** Inline, not in app-header.css: every app runs this component from the\n * site's shared vendor module, but compiles app-header.css into its own\n * stylesheet at ITS build, so a new rule reaches an app only when it rebuilds. */\nconst PASSKEY_DOT: React.CSSProperties = {\n position: 'absolute',\n top: 2,\n right: 2,\n width: 8,\n height: 8,\n borderRadius: '50%',\n background: 'var(--color-primary)',\n pointerEvents: 'none'\n}\n\n/** Save passkey pulses while the dot is asking for it. Keyframes cannot be\n * inline, so the rule is injected once into the document instead, for the\n * same reason PASSKEY_DOT is inline. */\nconst PASSKEY_PULSE_CLASS = 'settings-popout__btn--pulse'\nconst PASSKEY_PULSE_STYLE_ID = 'settings-passkey-pulse'\nconst PASSKEY_PULSE_CSS = `\n@keyframes settings-passkey-pulse {\n 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 70%, transparent); }\n 70% { box-shadow: 0 0 0 8px color-mix(in srgb, var(--color-primary) 0%, transparent); }\n 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 0%, transparent); }\n}\n@media (prefers-reduced-motion: no-preference) {\n .${PASSKEY_PULSE_CLASS}:not(:disabled) {\n animation: settings-passkey-pulse 1.6s ease-out infinite;\n }\n}\n`\n\nfunction usePasskeyPulseStyle(active: boolean) {\n useEffect(() => {\n if (!active || document.getElementById(PASSKEY_PULSE_STYLE_ID)) return\n const el = document.createElement('style')\n el.id = PASSKEY_PULSE_STYLE_ID\n el.textContent = PASSKEY_PULSE_CSS\n document.head.appendChild(el)\n }, [active])\n}\n\nconst TIER_LABEL: Record<Tier, string> = {\n admin: 'Administrator',\n wife: 'Wife',\n service: 'Service',\n friend: 'Friend',\n member: 'Member',\n public: 'Guest'\n}\n\nexport function ConnectedSettings({\n userType: userTypeProp,\n name: nameProp,\n onNameChange,\n children\n}: ConnectedSettingsProps) {\n const [open, setOpen] = useState(false)\n const rootRef = useRef<HTMLDivElement>(null)\n\n // Identity — from props if supplied, else resolved lazily via whoami().\n const [userType, setUserType] = useState<Tier>(userTypeProp ?? 'public')\n const [resolvedName, setResolvedName] = useState<string | null>(nameProp ?? null)\n\n // Name editing\n const [nameDraft, setNameDraft] = useState(resolvedName ?? '')\n const [editingName, setEditingName] = useState(false)\n const [nameSaving, setNameSaving] = useState(false)\n const [displayName, setLocalName] = useState<string | null>(resolvedName)\n\n // Key swap. The draft lives only in this state and the input: it is never\n // logged, stored or sent anywhere but the site's sign-in client.\n const [keyFormOpen, setKeyFormOpen] = useState(false)\n const [keyDraft, setKeyDraft] = useState('')\n const [keyBusy, setKeyBusy] = useState(false)\n const [keyError, setKeyError] = useState<string | null>(null)\n\n // Passkeys, through the same site client: save one while signed in, or\n // sign in with one from the key form. One prompt at a time, and always\n // cancellable: a password manager can dismiss the browser's prompt without\n // ever answering it, so Cancel, closing the popout and the site client's own\n // time limit each end the wait.\n const [passkeyMode, setPasskeyMode] = useState<'save' | 'signin' | null>(null)\n const [passkeySaved, setPasskeySaved] = useState(false)\n // How many passkeys sign this person in, from whoami; null = unknown.\n const [passkeyCount, setPasskeyCount] = useState<number | null>(null)\n const [passkeyError, setPasskeyError] = useState<string | null>(null)\n // Delete account: one click arms it, a second, separate button confirms.\n const [deleteStage, setDeleteStage] = useState<'idle' | 'confirm' | 'busy'>('idle')\n const [deleteError, setDeleteError] = useState<string | null>(null)\n const passkeyCtl = useRef<AbortController | null>(null)\n const cancelPasskey = useCallback((reason?: string) => passkeyCtl.current?.abort(reason), [])\n\n // Content level\n const [content, setContent] = useState<ContentLevelState | null>(null)\n const [levelSaving, setLevelSaving] = useState(false)\n\n // One flag for the whole prefetch, not one per request — the panel body\n // reveals when everything has settled, so nothing pops in a beat late. In\n // practice the user never sees it: the prefetch starts at mount and is long\n // done by the time the gear is clicked. It only shows if they click within\n // the first moments of the page.\n const [resolving, setResolving] = useState(true)\n\n // Everyone who is SIGNED IN, expressed as \"not public\" rather than as a list\n // of tiers. The list form (`=== 'admin' || === 'friend' || === 'service'`)\n // is an exact-match allowlist: it silently excluded `wife` the moment that\n // tier existed, which is the failure the rank model is meant to prevent.\n // There is no rank helper in this bundle, but \"above public\" needs none.\n const showContentPill = userType !== 'public'\n\n // Signed in on a key with no passkey: the gear carries a dot and Save passkey\n // is the primary action until one is saved. Unknown counts never prompt.\n const needsPasskey =\n !resolving &&\n userType !== 'public' &&\n passkeyCount === 0 &&\n !passkeySaved &&\n passkeysSupported()\n usePasskeyPulseStyle(needsPasskey)\n\n // Keep local identity in sync when the host controls it via props.\n useEffect(() => {\n if (userTypeProp !== undefined) setUserType(userTypeProp)\n }, [userTypeProp])\n useEffect(() => {\n if (nameProp !== undefined) {\n setResolvedName(nameProp)\n setLocalName(nameProp)\n setNameDraft(nameProp ?? '')\n }\n }, [nameProp])\n\n // Resolve everything the panel shows AT MOUNT — not on open.\n //\n // This used to be gated on `open`, which made the gear the trigger for\n // whoami + content-level (167ms / 186ms on prod, concurrent) — a round trip\n // the user waited out with the panel already on screen and blank. Nothing\n // about that data depends on the click:\n // it's the signed-in user's own identity, settled at boot and unchanged for\n // the life of the page. So it rides along with the app's boot traffic, and\n // clicking the gear costs zero requests. `e2e/settings-prefetch.spec.ts` in\n // hadoku-task pins that.\n //\n // The client memoises across callers, so mounting this in several places (or\n // remounting it) does not multiply requests, and on hadoku.me the identity\n // half is free — it awaits the whoami the shell already had in flight.\n useEffect(() => {\n let live = true\n prefetchSettings({ userType: userTypeProp, name: nameProp })\n .then(({ identity, content: state, passkeys }) => {\n if (!live) return\n setPasskeyCount(passkeys)\n // Props stay authoritative: the host passed them because it can see an\n // identity this component can't resolve for itself.\n if (userTypeProp === undefined) {\n setUserType(identity.userType)\n setResolvedName(identity.name)\n setLocalName(identity.name)\n setNameDraft(identity.name ?? '')\n }\n if (state) setContent(state)\n })\n .catch(reportErr)\n .finally(() => {\n if (live) setResolving(false)\n })\n return () => {\n live = false\n }\n // Hints are read once, on the first mount that gets there — the prefetch is\n // page-scoped and a later prop change cannot un-issue it. Identity changes\n // arrive through the sync effects above, and a key swap reloads the page.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n // Escape closes.\n useEffect(() => {\n if (!open) return\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') setOpen(false)\n }\n window.addEventListener('keydown', onKey)\n return () => window.removeEventListener('keydown', onKey)\n }, [open])\n\n const saveName = useCallback(async () => {\n const trimmed = nameDraft.trim()\n if (!trimmed || trimmed === displayName) {\n setEditingName(false)\n return\n }\n setNameSaving(true)\n const stored = await setDisplayName(trimmed)\n setNameSaving(false)\n if (stored !== null) {\n setLocalName(stored)\n setNameDraft(stored)\n onNameChange?.(stored)\n }\n setEditingName(false)\n }, [nameDraft, displayName, onNameChange])\n\n // Open the form AND start loading the site's sign-in client, which begins its\n // fingerprint collection as it evaluates — so it is ready by submit. Where the\n // client cannot load at all (not on hadoku.me), the page-level /auth flow is\n // the only way to sign in, so go there.\n const openKeyForm = useCallback(() => {\n setKeyFormOpen(true)\n setKeyError(null)\n loadSignIn()\n .then(signIn => {\n if (!signIn) window.location.assign(switchKeyHref())\n })\n .catch(reportErr)\n }, [])\n\n const submitKey = useCallback(async () => {\n setKeyBusy(true)\n setKeyError(null)\n const signIn = await loadSignIn()\n if (!signIn) {\n window.location.assign(switchKeyHref())\n return\n }\n try {\n await signIn(keyDraft)\n } catch (err) {\n // A refused key is an inline error, never a redirect.\n setKeyError((err as Error)?.message || 'Invalid key')\n setKeyBusy(false)\n return\n }\n // The page now acts for a different identity: everything must re-mount.\n // Busy stays on through the reload so the form can't be resubmitted.\n window.location.reload()\n }, [keyDraft])\n\n const savePasskey = useCallback(async () => {\n const ctl = new AbortController()\n passkeyCtl.current = ctl\n setPasskeyMode('save')\n setPasskeyError(null)\n try {\n const client = await Promise.race([loadSignInClient(), untilAborted(ctl.signal)])\n if (!client?.addPasskey) {\n window.location.assign(passkeyHref('add'))\n return\n }\n await Promise.race([client.addPasskey({ signal: ctl.signal }), untilAborted(ctl.signal)])\n setPasskeySaved(true)\n } catch (err) {\n if (ctl.signal.reason !== CLOSED) {\n setPasskeyError(\n ctl.signal.aborted ? 'Passkey not saved' : (err as Error)?.message || 'Passkey not saved'\n )\n }\n } finally {\n if (passkeyCtl.current === ctl) passkeyCtl.current = null\n setPasskeyMode(null)\n }\n }, [])\n\n const signInWithPasskey = useCallback(async () => {\n const ctl = new AbortController()\n passkeyCtl.current = ctl\n setPasskeyMode('signin')\n setKeyBusy(true)\n setKeyError(null)\n let leaving = false\n try {\n const client = await Promise.race([loadSignInClient(), untilAborted(ctl.signal)])\n if (!client?.signInWithPasskey) {\n leaving = true\n window.location.assign(passkeyHref('signin'))\n return\n }\n await Promise.race([\n client.signInWithPasskey({ signal: ctl.signal }),\n untilAborted(ctl.signal)\n ])\n // The page now acts for a different identity: everything must re-mount.\n // Busy stays on through the reload so nothing can be resubmitted.\n leaving = true\n window.location.reload()\n } catch (err) {\n if (ctl.signal.reason !== CLOSED) {\n setKeyError(\n ctl.signal.aborted\n ? 'Passkey sign-in cancelled'\n : (err as Error)?.message || 'Passkey sign-in cancelled'\n )\n }\n } finally {\n if (passkeyCtl.current === ctl) passkeyCtl.current = null\n if (!leaving) {\n setPasskeyMode(null)\n setKeyBusy(false)\n }\n }\n }, [])\n\n // Closing the popout (or leaving the page) abandons an open prompt.\n useEffect(() => {\n if (!open) cancelPasskey(CLOSED)\n }, [open, cancelPasskey])\n useEffect(() => () => cancelPasskey(CLOSED), [cancelPasskey])\n\n const pickLevel = useCallback(\n async (level: number) => {\n if (!content || level === content.level || levelSaving) return\n const prev = content\n setContent({ ...content, level }) // optimistic\n setLevelSaving(true)\n const result = await setContentLevel(level)\n setLevelSaving(false)\n setContent(result ?? prev) // adopt server truth, or revert\n },\n [content, levelSaving]\n )\n\n // No caller-supplied class on the root. The four rows below are the\n // platform's, not the app's, and a className here is enough to restyle or\n // hide any of them — which is the drift this component exists to prevent.\n // Apps extend via `children`, never by reaching into this markup.\n return (\n <div className=\"settings-popout\" ref={rootRef}>\n <button\n type=\"button\"\n className=\"app-header__icon-btn settings-toggle-btn\"\n aria-label={needsPasskey ? 'User settings, no passkey saved' : 'User settings'}\n style={needsPasskey ? { position: 'relative' } : undefined}\n aria-expanded={open}\n onClick={() => setOpen(v => !v)}\n >\n <SettingsIcon />\n {needsPasskey && (\n <span className=\"settings-toggle-btn__dot\" style={PASSKEY_DOT} aria-hidden=\"true\" />\n )}\n </button>\n\n {open && <div className=\"settings-popout__overlay\" onClick={() => setOpen(false)} />}\n\n {open && (\n <div className=\"settings-popout__panel\" role=\"dialog\" aria-label=\"User settings\">\n <div className=\"settings-popout__header\">Settings</div>\n\n {/* Access tier. While resolving, the state still says 'public' —\n rendering \"Guest\" there would be a wrong answer that corrects\n itself a moment later, which reads exactly like the lag this\n placeholder exists to remove. */}\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Access tier</span>\n {resolving ? (\n <span className=\"settings-popout__value\">…</span>\n ) : (\n <span className={`settings-popout__tier settings-popout__tier--${userType}`}>\n {TIER_LABEL[userType]}\n </span>\n )}\n </section>\n\n {/* Display name */}\n <section className=\"settings-popout__row\">\n <span className=\"settings-popout__label\">Display name</span>\n {resolving ? (\n <span className=\"settings-popout__value\">…</span>\n ) : editingName ? (\n <span className=\"settings-popout__inline\">\n <input\n className=\"settings-popout__input\"\n value={nameDraft}\n maxLength={64}\n autoFocus\n disabled={nameSaving}\n onChange={e => setNameDraft(e.target.value)}\n onKeyDown={e => {\n if (e.key === 'Enter') {\n saveName().catch(reportErr)\n }\n if (e.key === 'Escape') {\n // The edit's Escape, not the popout's (window listener).\n e.stopPropagation()\n setEditingName(false)\n setNameDraft(displayName ?? '')\n }\n }}\n />\n <button\n type=\"button\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={nameSaving}\n onClick={() => {\n saveName().catch(reportErr)\n }}\n >\n {nameSaving ? '…' : 'Save'}\n </button>\n </span>\n ) : (\n <button\n type=\"button\"\n className=\"settings-popout__value settings-popout__value--editable\"\n aria-label=\"Edit display name\"\n onClick={() => {\n setNameDraft(displayName ?? '')\n setEditingName(true)\n }}\n >\n {displayName || 'Unnamed'}\n </button>\n )}\n </section>\n\n {/* Content visibility level. Held back until the first-open fetch\n settles, so it lands in the same paint as the tier and name\n rather than a round trip behind them. `content` is fetched\n concurrently with whoami(), so by then it is already here. */}\n {!resolving && showContentPill && (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__label\">Content visibility</span>\n {content ? (\n <>\n <div\n className=\"settings-popout__pill\"\n role=\"radiogroup\"\n aria-label=\"Content visibility level\"\n >\n {Array.from({ length: content.maxLevel }, (_, i) => i + 1).map(lvl => (\n <button\n key={lvl}\n type=\"button\"\n role=\"radio\"\n aria-checked={lvl === content.level}\n aria-label={`Level ${lvl}`}\n className={`settings-popout__seg${\n lvl <= content.level ? ' settings-popout__seg--filled' : ''\n }`}\n disabled={levelSaving}\n onClick={() => {\n pickLevel(lvl).catch(reportErr)\n }}\n >\n {lvl}\n </button>\n ))}\n </div>\n <span className=\"settings-popout__hint\">\n Higher levels reveal more mature content across apps. Level 1 is\n safe-for-everyone.\n </span>\n </>\n ) : (\n // Not \"Loading…\" — the fetch has already settled by the time\n // this section renders at all, so a null here means it failed.\n <span className=\"settings-popout__hint\">Currently unavailable.</span>\n )}\n </section>\n )}\n\n {/* Switch key. Signs in inline through the SITE's sign-in client\n (the /auth page's own code path), never a post of ours. A real\n <form> with a username + current-password pair, so password\n managers offer and save the key. */}\n {keyFormOpen ? (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <form\n className=\"settings-popout__key-form\"\n onSubmit={e => {\n e.preventDefault()\n submitKey().catch(reportErr)\n }}\n >\n <input\n type=\"text\"\n name=\"username\"\n autoComplete=\"username\"\n value=\"hadoku\"\n readOnly\n hidden\n />\n <label className=\"settings-popout__label\" htmlFor=\"settings-popout-key\">\n Access key\n </label>\n <span className=\"settings-popout__inline\">\n <input\n id=\"settings-popout-key\"\n className=\"settings-popout__input\"\n type=\"password\"\n name=\"password\"\n autoComplete=\"current-password\"\n autoCapitalize=\"none\"\n spellCheck={false}\n autoFocus\n value={keyDraft}\n disabled={keyBusy}\n aria-invalid={keyError !== null}\n aria-describedby={keyError ? 'settings-popout-key-error' : undefined}\n onChange={e => setKeyDraft(e.target.value)}\n />\n <button\n type=\"submit\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={keyBusy}\n >\n {keyBusy ? 'Signing in…' : 'Sign in'}\n </button>\n </span>\n {passkeysSupported() && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={keyBusy}\n onClick={() => {\n signInWithPasskey().catch(reportErr)\n }}\n >\n {passkeyMode === 'signin' ? 'Waiting for passkey…' : 'Use a passkey'}\n </button>\n </span>\n )}\n {/* Cancel on a line of its own: in the row it would slide under\n the pointer, and a double click would cancel what it started. */}\n {passkeyMode === 'signin' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => cancelPasskey()}\n >\n Cancel\n </button>\n </span>\n )}\n {keyError && (\n <span\n id=\"settings-popout-key-error\"\n className=\"settings-popout__error\"\n role=\"alert\"\n >\n {keyError}\n </span>\n )}\n </form>\n </section>\n ) : (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__inline\">\n <span className=\"settings-popout__label settings-popout__label--grow\">\n Access key\n </span>\n {/* Signed-in people only: the site refuses to save one for anyone else. */}\n {!resolving && userType !== 'public' && passkeysSupported() && (\n <button\n type=\"button\"\n className={`settings-popout__btn${needsPasskey ? ` settings-popout__btn--primary ${PASSKEY_PULSE_CLASS}` : ''}`}\n disabled={passkeyMode !== null || passkeySaved}\n onClick={() => {\n savePasskey().catch(reportErr)\n }}\n >\n {passkeySaved\n ? 'Passkey saved'\n : passkeyMode === 'save'\n ? 'Saving…'\n : 'Save passkey'}\n </button>\n )}\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={passkeyMode === 'save'}\n onClick={openKeyForm}\n >\n Switch key\n </button>\n </span>\n {/* Its own line, so nothing moves under a double click. */}\n {passkeyMode === 'save' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => cancelPasskey()}\n >\n Cancel\n </button>\n </span>\n )}\n {passkeyError && (\n <span className=\"settings-popout__error\" role=\"alert\">\n {passkeyError}\n </span>\n )}\n </section>\n )}\n\n {/* A self-made account (member) can delete itself. The confirm is a\n separate button on its own line, so a double click on Delete\n never confirms. */}\n {!resolving && userType === 'member' && (\n <section className=\"settings-popout__row settings-popout__row--stack\">\n <span className=\"settings-popout__inline\">\n <span className=\"settings-popout__label settings-popout__label--grow\">Account</span>\n {deleteStage === 'idle' ? (\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n onClick={() => {\n setDeleteError(null)\n setDeleteStage('confirm')\n }}\n >\n Delete account\n </button>\n ) : (\n <button\n type=\"button\"\n className=\"settings-popout__btn\"\n disabled={deleteStage === 'busy'}\n onClick={() => setDeleteStage('idle')}\n >\n Keep\n </button>\n )}\n </span>\n {deleteStage !== 'idle' && (\n <span className=\"settings-popout__inline\">\n <button\n type=\"button\"\n className=\"settings-popout__btn settings-popout__btn--primary\"\n disabled={deleteStage === 'busy'}\n onClick={() => {\n setDeleteStage('busy')\n deleteOwnAccount()\n .then(deleted => {\n if (!deleted) {\n setDeleteError('Account not deleted')\n setDeleteStage('confirm')\n return\n }\n localStorage.removeItem('hadoku_session_id')\n localStorage.removeItem('hadoku_user_type')\n window.location.assign('/')\n })\n .catch(reportErr)\n }}\n >\n {deleteStage === 'busy' ? 'Deleting…' : 'Delete for good'}\n </button>\n </span>\n )}\n {deleteError && (\n <span className=\"settings-popout__error\" role=\"alert\">\n {deleteError}\n </span>\n )}\n </section>\n )}\n\n {/* App-specific settings (optional) — same popout, one gear. */}\n {children && (\n <section className=\"settings-popout__row settings-popout__row--stack settings-popout__app\">\n {children}\n </section>\n )}\n </div>\n )}\n </div>\n )\n}\n"],"names":[],"mappings":";;;;;AAoEA,SAAS,aAAa,QAAqC;AACzD,SAAO,IAAI,QAAQ,CAAC,GAAG,WAAW;AAChC,UAAM,OAAO,MAAM,OAAO,IAAI,MAAM,WAAW,CAAC;AAChD,QAAI,OAAO,QAAS,MAAA;AAAA,gBACR,iBAAiB,SAAS,MAAM,EAAE,MAAM,MAAM;AAAA,EAC5D,CAAC;AACH;AAGA,MAAM,SAAS;AAKf,SAAS,UAAU,KAAc;AAE/B,UAAQ,MAAM,qCAAsC,KAAe,WAAW,GAAG;AACnF;AAKA,MAAM,cAAmC;AAAA,EACvC,UAAU;AAAA,EACV,KAAK;AAAA,EACL,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,eA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A,6BAAa,WAAW,mBAAmB;AAC3C,6BAAa,WAAW,kBAAkB;AAC1C,uBAAO,SAAS,OAAO,GAAG;AAAA,cAC5B,CAAC,EACA,MAAM,SAAS;AAAA,YACpB;AAAA,YAEC,UAAA,gBAAgB,SAAS,cAAc;AAAA,UAAA;AAAA,QAAA,GAE5C;AAAA,QAED,eACC,oBAAC,QAAA,EAAK,WAAU,0BAAyB,MAAK,SAC3C,UAAA,YAAA,CACH;AAAA,MAAA,GAEJ;AAAA,MAID,YACC,oBAAC,WAAA,EAAQ,WAAU,yEAChB,SAAA,CACH;AAAA,IAAA,EAAA,CAEJ;AAAA,EAAA,GAEJ;AAEJ;"}
|
|
@@ -36,17 +36,21 @@ export declare function getContentLevel(): Promise<ContentLevelState | null>;
|
|
|
36
36
|
/** PUT a new content level. Server clamps to the tier ceiling → 400 if out of
|
|
37
37
|
* range. Returns the stored state on success, null on any failure. */
|
|
38
38
|
export declare function setContentLevel(level: number): Promise<ContentLevelState | null>;
|
|
39
|
+
/** Delete the signed-in member's own account (edge-router refuses any key
|
|
40
|
+
* someone was handed). True when it is gone; the session cookie is cleared. */
|
|
41
|
+
export declare function deleteOwnAccount(): Promise<boolean>;
|
|
39
42
|
/** POST a new display name for the signed-in user. Returns the stored name
|
|
40
43
|
* (may differ from the request for wp-* protected keys) or null on failure. */
|
|
41
44
|
export declare function setDisplayName(name: string): Promise<string | null>;
|
|
42
45
|
/**
|
|
43
|
-
* The hadoku tier ladder, LOW to HIGH: `public < friend < service < wife < admin`.
|
|
46
|
+
* The hadoku tier ladder, LOW to HIGH: `public < member < friend < service < wife < admin`.
|
|
47
|
+
* `member` is a self-signed-up account (a passkey, no key), cardtable only.
|
|
44
48
|
* Mirrors TIER_RANK in @wolffm/worker-utils, which this browser bundle cannot
|
|
45
49
|
* import (it would pull hono into the client). A tier missing here does not
|
|
46
50
|
* error — it fails the union and, worse, drops out of every `Record<Tier, …>`
|
|
47
51
|
* lookup, so the caller renders as if unrecognised. Keep it complete.
|
|
48
52
|
*/
|
|
49
|
-
export type Tier = 'public' | 'friend' | 'service' | 'wife' | 'admin';
|
|
53
|
+
export type Tier = 'public' | 'member' | 'friend' | 'service' | 'wife' | 'admin';
|
|
50
54
|
export interface Identity {
|
|
51
55
|
userType: Tier;
|
|
52
56
|
name: string | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settingsClient.d.ts","sourceRoot":"","sources":["../../src/lib/settingsClient.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;
|
|
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,CAgBtF;AAED;gFACgF;AAChF,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,OAAO,CAAC,CAczD;AAED;gFACgF;AAChF,wBAAsB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAgBzE;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,IAAI,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAAA;AAEhF,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,IAAI,CAAA;IACd,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CACpB;AAyBD;;;;GAIG;AACH,wBAAsB,MA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AE,MAAM,GAAG,IAAI,CAAA;CACxB;AAED,gFAAgF;AAChF,MAAM,WAAW,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"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const CONTENT_LEVEL_PATH = "/prefs/api/v1/content-level";
|
|
2
2
|
const SESSION_NAME = "/session/name";
|
|
3
|
+
const ACCOUNT_DELETE = "/session/account/delete";
|
|
3
4
|
const SESSION_WHOAMI = "/session/whoami";
|
|
4
5
|
const WHOAMI_GLOBAL = "__hadokuWhoami";
|
|
5
6
|
const REQUEST_TIMEOUT_MS = 8e3;
|
|
@@ -39,6 +40,21 @@ async function setContentLevel(level) {
|
|
|
39
40
|
return null;
|
|
40
41
|
}
|
|
41
42
|
}
|
|
43
|
+
async function deleteOwnAccount() {
|
|
44
|
+
try {
|
|
45
|
+
const res = await fetch(ACCOUNT_DELETE, {
|
|
46
|
+
method: "POST",
|
|
47
|
+
credentials: "same-origin",
|
|
48
|
+
headers: sessionHeaders(),
|
|
49
|
+
body: "{}",
|
|
50
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
51
|
+
});
|
|
52
|
+
if (!res.ok) return false;
|
|
53
|
+
return (await res.json()).deleted === true;
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
42
58
|
async function setDisplayName(name) {
|
|
43
59
|
try {
|
|
44
60
|
const res = await fetch(SESSION_NAME, {
|
|
@@ -150,6 +166,7 @@ function patchSnapshot(patch) {
|
|
|
150
166
|
snapshot = snapshot.then(patch);
|
|
151
167
|
}
|
|
152
168
|
export {
|
|
169
|
+
deleteOwnAccount,
|
|
153
170
|
getContentLevel,
|
|
154
171
|
loadSignIn,
|
|
155
172
|
loadSignInClient,
|
|
@@ -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 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/** POST a new display name for the signed-in user. Returns the stored name\n * (may differ from the request for wp-* protected keys) or null on failure. */\nexport async function setDisplayName(name: string): Promise<string | null> {\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) return null\n const body = (await res.json()) as { ok: boolean; name: string | null }\n patchSnapshot(prev => ({ ...prev, identity: { ...prev.identity, name: body.name } }))\n return body.name\n } catch {\n return null\n }\n}\n\n/**\n * The hadoku tier ladder, LOW to HIGH: `public < friend < service < wife < admin`.\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' | '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;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,QAAQ,kBAAkB;AAAA,IAAA,CAC/C;AACD,QAAI,CAAC,IAAI,GAAI,QAAO;AACpB,WAAQ,MAAM,IAAI,KAAA;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIA,eAAsB,gBAAgB,OAAkD;AACt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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/** POST a new display name for the signed-in user. Returns the stored name\n * (may differ from the request for wp-* protected keys) or null on failure. */\nexport async function setDisplayName(name: string): Promise<string | null> {\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) return null\n const body = (await res.json()) as { ok: boolean; name: string | null }\n patchSnapshot(prev => ({ ...prev, identity: { ...prev.identity, name: body.name } }))\n return body.name\n } catch {\n return null\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,oB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K,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;"}
|
package/package.json
CHANGED
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
|
28
28
|
import { SettingsIcon } from './ThemeIcons'
|
|
29
29
|
import {
|
|
30
|
+
deleteOwnAccount,
|
|
30
31
|
prefetchSettings,
|
|
31
32
|
setContentLevel,
|
|
32
33
|
setDisplayName,
|
|
@@ -98,11 +99,40 @@ const PASSKEY_DOT: React.CSSProperties = {
|
|
|
98
99
|
pointerEvents: 'none'
|
|
99
100
|
}
|
|
100
101
|
|
|
102
|
+
/** Save passkey pulses while the dot is asking for it. Keyframes cannot be
|
|
103
|
+
* inline, so the rule is injected once into the document instead, for the
|
|
104
|
+
* same reason PASSKEY_DOT is inline. */
|
|
105
|
+
const PASSKEY_PULSE_CLASS = 'settings-popout__btn--pulse'
|
|
106
|
+
const PASSKEY_PULSE_STYLE_ID = 'settings-passkey-pulse'
|
|
107
|
+
const PASSKEY_PULSE_CSS = `
|
|
108
|
+
@keyframes settings-passkey-pulse {
|
|
109
|
+
0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 70%, transparent); }
|
|
110
|
+
70% { box-shadow: 0 0 0 8px color-mix(in srgb, var(--color-primary) 0%, transparent); }
|
|
111
|
+
100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 0%, transparent); }
|
|
112
|
+
}
|
|
113
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
114
|
+
.${PASSKEY_PULSE_CLASS}:not(:disabled) {
|
|
115
|
+
animation: settings-passkey-pulse 1.6s ease-out infinite;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
`
|
|
119
|
+
|
|
120
|
+
function usePasskeyPulseStyle(active: boolean) {
|
|
121
|
+
useEffect(() => {
|
|
122
|
+
if (!active || document.getElementById(PASSKEY_PULSE_STYLE_ID)) return
|
|
123
|
+
const el = document.createElement('style')
|
|
124
|
+
el.id = PASSKEY_PULSE_STYLE_ID
|
|
125
|
+
el.textContent = PASSKEY_PULSE_CSS
|
|
126
|
+
document.head.appendChild(el)
|
|
127
|
+
}, [active])
|
|
128
|
+
}
|
|
129
|
+
|
|
101
130
|
const TIER_LABEL: Record<Tier, string> = {
|
|
102
131
|
admin: 'Administrator',
|
|
103
132
|
wife: 'Wife',
|
|
104
133
|
service: 'Service',
|
|
105
134
|
friend: 'Friend',
|
|
135
|
+
member: 'Member',
|
|
106
136
|
public: 'Guest'
|
|
107
137
|
}
|
|
108
138
|
|
|
@@ -142,6 +172,9 @@ export function ConnectedSettings({
|
|
|
142
172
|
// How many passkeys sign this person in, from whoami; null = unknown.
|
|
143
173
|
const [passkeyCount, setPasskeyCount] = useState<number | null>(null)
|
|
144
174
|
const [passkeyError, setPasskeyError] = useState<string | null>(null)
|
|
175
|
+
// Delete account: one click arms it, a second, separate button confirms.
|
|
176
|
+
const [deleteStage, setDeleteStage] = useState<'idle' | 'confirm' | 'busy'>('idle')
|
|
177
|
+
const [deleteError, setDeleteError] = useState<string | null>(null)
|
|
145
178
|
const passkeyCtl = useRef<AbortController | null>(null)
|
|
146
179
|
const cancelPasskey = useCallback((reason?: string) => passkeyCtl.current?.abort(reason), [])
|
|
147
180
|
|
|
@@ -171,6 +204,7 @@ export function ConnectedSettings({
|
|
|
171
204
|
passkeyCount === 0 &&
|
|
172
205
|
!passkeySaved &&
|
|
173
206
|
passkeysSupported()
|
|
207
|
+
usePasskeyPulseStyle(needsPasskey)
|
|
174
208
|
|
|
175
209
|
// Keep local identity in sync when the host controls it via props.
|
|
176
210
|
useEffect(() => {
|
|
@@ -607,7 +641,7 @@ export function ConnectedSettings({
|
|
|
607
641
|
{!resolving && userType !== 'public' && passkeysSupported() && (
|
|
608
642
|
<button
|
|
609
643
|
type="button"
|
|
610
|
-
className={`settings-popout__btn${needsPasskey ?
|
|
644
|
+
className={`settings-popout__btn${needsPasskey ? ` settings-popout__btn--primary ${PASSKEY_PULSE_CLASS}` : ''}`}
|
|
611
645
|
disabled={passkeyMode !== null || passkeySaved}
|
|
612
646
|
onClick={() => {
|
|
613
647
|
savePasskey().catch(reportErr)
|
|
@@ -649,6 +683,69 @@ export function ConnectedSettings({
|
|
|
649
683
|
</section>
|
|
650
684
|
)}
|
|
651
685
|
|
|
686
|
+
{/* A self-made account (member) can delete itself. The confirm is a
|
|
687
|
+
separate button on its own line, so a double click on Delete
|
|
688
|
+
never confirms. */}
|
|
689
|
+
{!resolving && userType === 'member' && (
|
|
690
|
+
<section className="settings-popout__row settings-popout__row--stack">
|
|
691
|
+
<span className="settings-popout__inline">
|
|
692
|
+
<span className="settings-popout__label settings-popout__label--grow">Account</span>
|
|
693
|
+
{deleteStage === 'idle' ? (
|
|
694
|
+
<button
|
|
695
|
+
type="button"
|
|
696
|
+
className="settings-popout__btn"
|
|
697
|
+
onClick={() => {
|
|
698
|
+
setDeleteError(null)
|
|
699
|
+
setDeleteStage('confirm')
|
|
700
|
+
}}
|
|
701
|
+
>
|
|
702
|
+
Delete account
|
|
703
|
+
</button>
|
|
704
|
+
) : (
|
|
705
|
+
<button
|
|
706
|
+
type="button"
|
|
707
|
+
className="settings-popout__btn"
|
|
708
|
+
disabled={deleteStage === 'busy'}
|
|
709
|
+
onClick={() => setDeleteStage('idle')}
|
|
710
|
+
>
|
|
711
|
+
Keep
|
|
712
|
+
</button>
|
|
713
|
+
)}
|
|
714
|
+
</span>
|
|
715
|
+
{deleteStage !== 'idle' && (
|
|
716
|
+
<span className="settings-popout__inline">
|
|
717
|
+
<button
|
|
718
|
+
type="button"
|
|
719
|
+
className="settings-popout__btn settings-popout__btn--primary"
|
|
720
|
+
disabled={deleteStage === 'busy'}
|
|
721
|
+
onClick={() => {
|
|
722
|
+
setDeleteStage('busy')
|
|
723
|
+
deleteOwnAccount()
|
|
724
|
+
.then(deleted => {
|
|
725
|
+
if (!deleted) {
|
|
726
|
+
setDeleteError('Account not deleted')
|
|
727
|
+
setDeleteStage('confirm')
|
|
728
|
+
return
|
|
729
|
+
}
|
|
730
|
+
localStorage.removeItem('hadoku_session_id')
|
|
731
|
+
localStorage.removeItem('hadoku_user_type')
|
|
732
|
+
window.location.assign('/')
|
|
733
|
+
})
|
|
734
|
+
.catch(reportErr)
|
|
735
|
+
}}
|
|
736
|
+
>
|
|
737
|
+
{deleteStage === 'busy' ? 'Deleting…' : 'Delete for good'}
|
|
738
|
+
</button>
|
|
739
|
+
</span>
|
|
740
|
+
)}
|
|
741
|
+
{deleteError && (
|
|
742
|
+
<span className="settings-popout__error" role="alert">
|
|
743
|
+
{deleteError}
|
|
744
|
+
</span>
|
|
745
|
+
)}
|
|
746
|
+
</section>
|
|
747
|
+
)}
|
|
748
|
+
|
|
652
749
|
{/* App-specific settings (optional) — same popout, one gear. */}
|
|
653
750
|
{children && (
|
|
654
751
|
<section className="settings-popout__row settings-popout__row--stack settings-popout__app">
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
/** Edge-router / prefs-api endpoints (same-origin relative). */
|
|
30
30
|
const CONTENT_LEVEL_PATH = '/prefs/api/v1/content-level'
|
|
31
31
|
const SESSION_NAME = '/session/name'
|
|
32
|
+
const ACCOUNT_DELETE = '/session/account/delete'
|
|
32
33
|
const SESSION_WHOAMI = '/session/whoami'
|
|
33
34
|
|
|
34
35
|
/**
|
|
@@ -121,6 +122,24 @@ export async function setContentLevel(level: number): Promise<ContentLevelState
|
|
|
121
122
|
}
|
|
122
123
|
}
|
|
123
124
|
|
|
125
|
+
/** Delete the signed-in member's own account (edge-router refuses any key
|
|
126
|
+
* someone was handed). True when it is gone; the session cookie is cleared. */
|
|
127
|
+
export async function deleteOwnAccount(): Promise<boolean> {
|
|
128
|
+
try {
|
|
129
|
+
const res = await fetch(ACCOUNT_DELETE, {
|
|
130
|
+
method: 'POST',
|
|
131
|
+
credentials: 'same-origin',
|
|
132
|
+
headers: sessionHeaders(),
|
|
133
|
+
body: '{}',
|
|
134
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
135
|
+
})
|
|
136
|
+
if (!res.ok) return false
|
|
137
|
+
return ((await res.json()) as { deleted?: boolean }).deleted === true
|
|
138
|
+
} catch {
|
|
139
|
+
return false
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
124
143
|
/** POST a new display name for the signed-in user. Returns the stored name
|
|
125
144
|
* (may differ from the request for wp-* protected keys) or null on failure. */
|
|
126
145
|
export async function setDisplayName(name: string): Promise<string | null> {
|
|
@@ -142,13 +161,14 @@ export async function setDisplayName(name: string): Promise<string | null> {
|
|
|
142
161
|
}
|
|
143
162
|
|
|
144
163
|
/**
|
|
145
|
-
* The hadoku tier ladder, LOW to HIGH: `public < friend < service < wife < admin`.
|
|
164
|
+
* The hadoku tier ladder, LOW to HIGH: `public < member < friend < service < wife < admin`.
|
|
165
|
+
* `member` is a self-signed-up account (a passkey, no key), cardtable only.
|
|
146
166
|
* Mirrors TIER_RANK in @wolffm/worker-utils, which this browser bundle cannot
|
|
147
167
|
* import (it would pull hono into the client). A tier missing here does not
|
|
148
168
|
* error — it fails the union and, worse, drops out of every `Record<Tier, …>`
|
|
149
169
|
* lookup, so the caller renders as if unrecognised. Keep it complete.
|
|
150
170
|
*/
|
|
151
|
-
export type Tier = 'public' | 'friend' | 'service' | 'wife' | 'admin'
|
|
171
|
+
export type Tier = 'public' | 'member' | 'friend' | 'service' | 'wife' | 'admin'
|
|
152
172
|
|
|
153
173
|
export interface Identity {
|
|
154
174
|
userType: Tier
|