cursedauth 0.1.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.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +87 -0
  3. package/dist/account/AccountMenu.d.ts +153 -0
  4. package/dist/account/AccountMenu.d.ts.map +1 -0
  5. package/dist/account/AccountMenu.js +388 -0
  6. package/dist/account/AccountMenu.js.map +1 -0
  7. package/dist/account/AccountNotice.d.ts +35 -0
  8. package/dist/account/AccountNotice.d.ts.map +1 -0
  9. package/dist/account/AccountNotice.js +133 -0
  10. package/dist/account/AccountNotice.js.map +1 -0
  11. package/dist/account/accountNotice.state.d.ts +20 -0
  12. package/dist/account/accountNotice.state.d.ts.map +1 -0
  13. package/dist/account/accountNotice.state.js +55 -0
  14. package/dist/account/accountNotice.state.js.map +1 -0
  15. package/dist/account/avatar.d.ts +37 -0
  16. package/dist/account/avatar.d.ts.map +1 -0
  17. package/dist/account/avatar.js +47 -0
  18. package/dist/account/avatar.js.map +1 -0
  19. package/dist/accountSlot.client.d.ts +113 -0
  20. package/dist/accountSlot.client.d.ts.map +1 -0
  21. package/dist/accountSlot.client.js +330 -0
  22. package/dist/accountSlot.client.js.map +1 -0
  23. package/dist/accountSlots.d.ts +192 -0
  24. package/dist/accountSlots.d.ts.map +1 -0
  25. package/dist/accountSlots.js +274 -0
  26. package/dist/accountSlots.js.map +1 -0
  27. package/dist/auth.d.ts +167 -0
  28. package/dist/auth.d.ts.map +1 -0
  29. package/dist/auth.js +310 -0
  30. package/dist/auth.js.map +1 -0
  31. package/dist/auth.server.d.ts +35 -0
  32. package/dist/auth.server.d.ts.map +1 -0
  33. package/dist/auth.server.js +67 -0
  34. package/dist/auth.server.js.map +1 -0
  35. package/dist/clientDescription.d.ts +186 -0
  36. package/dist/clientDescription.d.ts.map +1 -0
  37. package/dist/clientDescription.js +278 -0
  38. package/dist/clientDescription.js.map +1 -0
  39. package/dist/constantTime.d.ts +35 -0
  40. package/dist/constantTime.d.ts.map +1 -0
  41. package/dist/constantTime.js +46 -0
  42. package/dist/constantTime.js.map +1 -0
  43. package/dist/contentCensus.d.ts +59 -0
  44. package/dist/contentCensus.d.ts.map +1 -0
  45. package/dist/contentCensus.js +55 -0
  46. package/dist/contentCensus.js.map +1 -0
  47. package/dist/index.d.ts +25 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +24 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/mountGatedApp.d.ts +128 -0
  52. package/dist/mountGatedApp.d.ts.map +1 -0
  53. package/dist/mountGatedApp.js +107 -0
  54. package/dist/mountGatedApp.js.map +1 -0
  55. package/dist/runtimeMode.d.ts +28 -0
  56. package/dist/runtimeMode.d.ts.map +1 -0
  57. package/dist/runtimeMode.js +37 -0
  58. package/dist/runtimeMode.js.map +1 -0
  59. package/dist/secureRequest.d.ts +22 -0
  60. package/dist/secureRequest.d.ts.map +1 -0
  61. package/dist/secureRequest.js +27 -0
  62. package/dist/secureRequest.js.map +1 -0
  63. package/dist/sso.d.ts +373 -0
  64. package/dist/sso.d.ts.map +1 -0
  65. package/dist/sso.js +420 -0
  66. package/dist/sso.js.map +1 -0
  67. package/dist/ssoAutoSignIn.d.ts +272 -0
  68. package/dist/ssoAutoSignIn.d.ts.map +1 -0
  69. package/dist/ssoAutoSignIn.js +431 -0
  70. package/dist/ssoAutoSignIn.js.map +1 -0
  71. package/dist/ssoConsumer.server.d.ts +295 -0
  72. package/dist/ssoConsumer.server.d.ts.map +1 -0
  73. package/dist/ssoConsumer.server.js +972 -0
  74. package/dist/ssoConsumer.server.js.map +1 -0
  75. package/dist/stageIdentity.d.ts +72 -0
  76. package/dist/stageIdentity.d.ts.map +1 -0
  77. package/dist/stageIdentity.js +74 -0
  78. package/dist/stageIdentity.js.map +1 -0
  79. package/dist/ui/popover.d.ts +190 -0
  80. package/dist/ui/popover.d.ts.map +1 -0
  81. package/dist/ui/popover.js +351 -0
  82. package/dist/ui/popover.js.map +1 -0
  83. package/dist/userSessions.d.ts +205 -0
  84. package/dist/userSessions.d.ts.map +1 -0
  85. package/dist/userSessions.js +419 -0
  86. package/dist/userSessions.js.map +1 -0
  87. package/package.json +115 -0
  88. package/src/account/AccountMenu.tsx +729 -0
  89. package/src/account/AccountNotice.tsx +223 -0
  90. package/src/account/accountNotice.state.ts +66 -0
  91. package/src/account/avatar.ts +50 -0
  92. package/src/accountSlot.client.ts +362 -0
  93. package/src/accountSlots.ts +305 -0
  94. package/src/auth.server.ts +89 -0
  95. package/src/auth.ts +515 -0
  96. package/src/clientDescription.ts +366 -0
  97. package/src/constantTime.ts +45 -0
  98. package/src/contentCensus.ts +106 -0
  99. package/src/index.ts +58 -0
  100. package/src/mountGatedApp.ts +240 -0
  101. package/src/runtimeMode.ts +37 -0
  102. package/src/secureRequest.ts +25 -0
  103. package/src/sso.ts +767 -0
  104. package/src/ssoAutoSignIn.ts +544 -0
  105. package/src/ssoConsumer.server.ts +1260 -0
  106. package/src/stageIdentity.ts +76 -0
  107. package/src/ui/popover.ts +390 -0
  108. package/src/userSessions.ts +678 -0
@@ -0,0 +1,729 @@
1
+ /**
2
+ * The account menu every satellite puts in its header — who you are, and the
3
+ * three things you can do about it.
4
+ *
5
+ * ── Why it exists (2026-08-10, owner report) ────────────────────────────────
6
+ * "I logged out for someone to log in and there wasn't a way to change users."
7
+ * Both halves of that were true, and neither was one app's bug:
8
+ *
9
+ * 1. **Sign out did not sign you out.** Every app ended its OWN cookie and
10
+ * stopped there; auth's session outlived it. The next press of "Sign in" —
11
+ * or the automatic hop on the next page load — traded that surviving
12
+ * session for a fresh grant and returned the SAME person, with no password
13
+ * asked for. There was no sequence of clicks that made a satellite forget
14
+ * you.
15
+ * 2. **Nothing offered to change users.** Even reaching the accounts app by
16
+ * hand did not help: `/sso/authorize` had exactly one answer for a browser
17
+ * with a live session, and it was a grant for that session's user.
18
+ *
19
+ * The fix is one door at each end — `?switch=1` → `prompt=login` at authorize,
20
+ * and `/api/auth/sso/signout` → `/sso/logout` for a sign-out that reaches
21
+ * auth's own session — and THIS is the thing that puts them in front of a
22
+ * person. Eight apps had hand-rolled a name-and-a-dropdown by then, all
23
+ * slightly differently and all with the same two gaps, which is why the menu
24
+ * itself is now shared rather than each app growing two more buttons.
25
+ *
26
+ * ── Why it ships its own stylesheet ─────────────────────────────────────────
27
+ * Same reason as `FleetDirectory`, which it sits beside in every header: the
28
+ * satellites keep per-app Tailwind `@source` lists, so a widget from this
29
+ * package styled with utility classes renders correctly in whichever apps
30
+ * remembered to add a line and silently unstyled in the rest. The machinery is
31
+ * shared with the directory (`../ui/popover`) so the two cannot drift into
32
+ * different ideas of dark mode, or dismiss differently, 8px apart.
33
+ */
34
+ import { lazy, type ReactNode, Suspense, useEffect, useState } from "react";
35
+ import { createPortal } from "react-dom";
36
+ import {
37
+ accountWindowUrl,
38
+ currentAccountSlot,
39
+ setExpectedAccount,
40
+ slotUrl,
41
+ } from "../accountSlot.client";
42
+ import { startSsoSignIn, startSsoSignOut } from "../ssoAutoSignIn";
43
+ import { useHostDark, useInjectedStyles, usePopover, useScrim } from "../ui/popover";
44
+ import { useAccountNotice } from "./accountNotice.state";
45
+
46
+ /**
47
+ * 🔴 LAZY, and that is a byte budget rather than a preference. The banner carries
48
+ * a ~4 KB scoped stylesheet and renders nothing until an account goes wrong, so
49
+ * importing it directly here put it in nineteen apps' ENTRY chunks —
50
+ * `test:gates:artifacts` caught it as `notes` at 581.07 KB against 578. The
51
+ * WATCHING stays eager (`useAccountNotice`), because a component that is not
52
+ * mounted cannot hear the event that would make it appear; only the markup and
53
+ * the styles wait. `Suspense` falls back to nothing: there is no spinner worth
54
+ * showing for a banner nobody asked for.
55
+ */
56
+ const AccountNotice = lazy(() =>
57
+ import("./AccountNotice").then((m) => ({ default: m.AccountNotice })),
58
+ );
59
+ import { accountAvatarUrl, accountInitials } from "./avatar";
60
+
61
+ const STYLE_ID = "sam-style";
62
+ /** The popover's ideal width in px, matching `min(17rem, …)` in {@link STYLES}
63
+ * below — see `anchoredLeft` in `../ui/popover` for why the real number has to
64
+ * be known in JS and not only in CSS.
65
+ *
66
+ * 🔴 It said 240 while the stylesheet had been widened to 17rem, and the
67
+ * comment above it still named the old 15rem. The off-screen clamp is
68
+ * arithmetic over THIS number, so it reserved 240px for a 272px panel and
69
+ * pushed the last 32px of the account menu off the right edge of every screen
70
+ * — the exact defect the clamp exists to prevent, hiding behind a comment that
71
+ * described a width the CSS no longer had. Exported, with {@link STYLES}, so
72
+ * `../ui/panelWidth.test.ts` can assert the two against each other instead of
73
+ * a sentence here promising they match. */
74
+ export const PANEL_WIDTH = 272;
75
+ export const STYLES = `
76
+ .sam{--sam-panel:#ffffff;--sam-border:#d9dde3;--sam-text:#1a1d21;--sam-muted:#68707c;
77
+ --sam-hover:#f2f4f7;--sam-danger:#b42318;--sam-accent:#4f6ef7;--sam-shadow:0 12px 32px rgba(16,18,22,.16);
78
+ font:14px/1.5 ui-sans-serif,system-ui,-apple-system,sans-serif;color:var(--sam-text)}
79
+ .sam[data-dark="true"]{--sam-panel:#181b21;--sam-border:#2c313a;--sam-text:#e6e9ee;--sam-muted:#8b93a1;
80
+ --sam-hover:#22262e;--sam-danger:#f97066;--sam-accent:#7f97ff;--sam-shadow:0 12px 32px rgba(0,0,0,.5)}
81
+ /* 🔴 \`min-width:0\` is what makes \`.sam-who\`'s ellipsis (below) REACHABLE, and
82
+ without it that rule is dead CSS — measured on live roms, 2026-09-08.
83
+
84
+ A flex item's \`min-width\` defaults to \`auto\`, i.e. its min-content width, and
85
+ \`.sam-who\` is \`white-space:nowrap\` — so the launcher's min-content size is the
86
+ WHOLE name, however long. Flex could not shrink it, the name never truncated,
87
+ and the launcher simply overflowed its slot. Where it overflowed was decided by
88
+ the host header's \`justify-content\`: roms right-aligns its account controls, so
89
+ the overflow travelled LEFT and painted the account button on top of the app
90
+ title — 79px of overlap at 320px, 39px at 360px, and the button's own avatar
91
+ starting at x=-26, off the side of the screen. \`document.scrollWidth\` was
92
+ unchanged throughout, which is why nothing anywhere reported it: the row does
93
+ not push the page wide, it collides inside itself.
94
+
95
+ With these two declarations the ellipsis finally does its job — the name gives
96
+ up as much width as the row needs and gives up the last of it entirely, leaving
97
+ the avatar and its caret, which is the right phone-shaped answer for an account
98
+ control anyway. Nothing changes at a width that already fit (measured: 430px
99
+ identical before and after), because flex only shrinks an item that has to.
100
+ \`max-width:100%\` keeps the wrapper from being the new floor now that the
101
+ launcher inside it can shrink.
102
+
103
+ The header that found it asserts the outcome rather than this mechanism —
104
+ apps/roms/__smoke/headerFit.spec.ts, which measures real boxes in a real
105
+ browser at four phone widths. It is the only kind of check that can see this. */
106
+ .sam-wrap{position:relative;display:inline-block;min-width:0;max-width:100%}
107
+ .sam-launch{display:inline-flex;align-items:center;gap:7px;max-width:min(14rem,100%);height:34px;
108
+ min-width:0;padding:0 8px 0 4px;
109
+ border:1px solid transparent;border-radius:999px;background:transparent;color:inherit;cursor:pointer;
110
+ font:inherit;font-size:13px}
111
+ @media (pointer:coarse){.sam-launch{height:44px}}
112
+ /* The circle. --sam-av is the ONE size knob: the ring, the glyph and the initials all
113
+ derive from it, so the launcher and the panel head cannot drift apart. */
114
+ .sam-av{--sam-av:26px;flex:none;display:inline-flex;align-items:center;justify-content:center;
115
+ width:var(--sam-av);height:var(--sam-av);border-radius:50%;overflow:hidden;
116
+ background:color-mix(in srgb,var(--sam-accent,#4f6ef7) 16%,transparent);
117
+ color:var(--sam-accent,#4f6ef7);font-size:calc(var(--sam-av) * .42);font-weight:650;
118
+ line-height:1;letter-spacing:.02em;user-select:none}
119
+ .sam-av img{width:100%;height:100%;object-fit:cover;display:block}
120
+ .sam-head .sam-av{--sam-av:40px}
121
+ .sam-launch:hover,.sam-launch[aria-expanded="true"]{background:var(--sam-hover);border-color:var(--sam-border)}
122
+ /* \`min-width:0\` for the same reason as \`.sam-launch\` above, one level down: this
123
+ is itself a flex item, so its \`auto\` minimum is the un-wrappable name and the
124
+ ellipsis below it could never fire. All three levels of the chain have to
125
+ allow shrinking or none of them does — the launcher stops overflowing its
126
+ header while the LABEL goes on overflowing the launcher, which is a collision
127
+ that has merely moved one control to the right. Measured: the first attempt at
128
+ this fix did exactly that, and headerFit.spec.ts is what said so. */
129
+ .sam-who{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
130
+ .sam-caret{flex:none;opacity:.6;font-size:10px}
131
+ /* 🔴 \`left\` and \`top\` are BOTH set inline by usePopoverPosition, and the panel
132
+ is PORTALED to <body> — see \`anchoredTop\`. \`fixed\` because the panel is no
133
+ longer inside the launcher, and NO default \`top\`, because a hardcoded
134
+ "always below" is what put the fleet launcher's panel off the bottom of the
135
+ screen (E22, 2026-09-09). This menu shares the control, so it shares the fix. */
136
+ .sam-pop{position:fixed;right:auto;z-index:2147482000;width:min(17rem,calc(100vw - 32px));
137
+ background:var(--sam-panel);border:1px solid var(--sam-border);border-radius:12px;box-shadow:var(--sam-shadow);
138
+ padding:6px;display:flex;flex-direction:column;gap:1px}
139
+ .sam-head{display:flex;align-items:center;gap:10px;padding:8px 8px 10px;
140
+ border-bottom:1px solid var(--sam-border);margin-bottom:5px}
141
+ .sam-head-text{min-width:0;flex:1}
142
+ .sam-name{font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
143
+ .sam-sub{font-size:11.5px;color:var(--sam-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
144
+ /* 🔴 44px, the designer's number for a menu row (2026-08-19). display:flex rather
145
+ than block so the min-height actually centres the label instead of leaving it
146
+ glued to the top of a taller box. */
147
+ .sam-item{display:flex;align-items:center;width:100%;min-height:44px;text-align:left;
148
+ padding:7px 10px;border:0;border-radius:8px;background:transparent;color:inherit;font:inherit;
149
+ font-size:13px;cursor:pointer;text-decoration:none}
150
+ .sam-item:hover{background:var(--sam-hover)}
151
+ .sam-item[data-tone="danger"]{color:var(--sam-danger)}
152
+ .sam-hint{font-size:11px;color:var(--sam-muted);padding:1px 8px 4px}
153
+ .sam-rule{height:1px;background:var(--sam-border);margin:5px 0}
154
+ .sam-label{font-size:10.5px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;
155
+ color:var(--sam-muted);padding:4px 8px 3px}
156
+ /* One row per other account: a big target that SWITCHES, plus a small one that
157
+ opens a second window. Grid rather than flex so the switch button gets every
158
+ pixel the open button does not, and long addresses ellipsize instead of
159
+ pushing the ⧉ off the panel. */
160
+ .sam-acct{display:grid;grid-template-columns:1fr auto;align-items:stretch;gap:1px;border-radius:8px}
161
+ .sam-acct:hover{background:var(--sam-hover)}
162
+ .sam-acct .sam-item{display:block;border-radius:8px 0 0 8px;padding-top:6px;padding-bottom:6px}
163
+ .sam-acct-who{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
164
+ .sam-acct-sub{display:block;font-size:11px;color:var(--sam-muted);overflow:hidden;
165
+ text-overflow:ellipsis;white-space:nowrap}
166
+ .sam-open{flex:none;width:44px;border:0;border-radius:0 8px 8px 0;background:transparent;
167
+ color:var(--sam-muted);cursor:pointer;font:inherit;font-size:13px}
168
+ .sam-open:hover{background:var(--sam-hover);color:var(--sam-text)}
169
+ .sam-badge{font-size:10px;font-weight:600;color:var(--sam-muted);border:1px solid var(--sam-border);
170
+ border-radius:5px;padding:0 4px;margin-left:6px;vertical-align:1px}
171
+ `;
172
+
173
+ export interface AccountMenuProps {
174
+ /** What to call the signed-in person — `user.name || user.email`. */
175
+ name: string;
176
+ /** Shown under the name in the panel when it adds something the name does
177
+ * not already say (i.e. skipped when it IS the name). */
178
+ email?: string;
179
+ /**
180
+ * The accounts origin the SERVER advertises (`session.accountsUrl`).
181
+ *
182
+ * Empty or absent means this app is not an SSO door — the local vault
183
+ * daemon and the owner-password apps answer exactly that, on purpose. The
184
+ * three SSO items then render nothing at all, because there is no accounts
185
+ * satellite to manage anything at, nobody to switch to, and no second
186
+ * session to end. Such an app passes `onSignOut` and gets a menu with its
187
+ * own sign-out in it.
188
+ */
189
+ accountsUrl?: string | null;
190
+ /**
191
+ * App-specific entries, rendered above the account block. For the things
192
+ * only that app has — "Lock the vault", "Engine settings".
193
+ *
194
+ * A render prop rather than plain children so an item can dismiss the menu
195
+ * it lives in. Wrapping the children in a click handler here would do the
196
+ * same job and be a lint suppression plus a guess about which clicks meant
197
+ * "done"; handing the caller `close` costs one argument and guesses nothing.
198
+ * `.sam-item` is the class to put on each entry.
199
+ */
200
+ children?: (close: () => void) => ReactNode;
201
+ /**
202
+ * Replaces the GLOBAL sign-out. Pass it only when this app is not an SSO
203
+ * door: the whole point of the shared menu is that "Sign out" means the same
204
+ * thing everywhere, and an app that overrides it re-opens the gap this
205
+ * component exists to close. To run app cleanup and still leave properly,
206
+ * use `onLeave`.
207
+ */
208
+ onSignOut?: () => void | Promise<void>;
209
+ /**
210
+ * Run immediately before this browser stops being this person's — on BOTH
211
+ * "Switch user" and "Sign out".
212
+ *
213
+ * For the app-local state that a session cookie does not cover: notes holds
214
+ * decrypted secrets in memory and locks them here. Both doors need it and
215
+ * for the same reason, so it is one hook rather than two — a cleanup wired
216
+ * to sign-out alone would leak the moment somebody switched instead.
217
+ *
218
+ * Synchronous on purpose: what follows is a full-page navigation, so a
219
+ * promise would be abandoned mid-flight. Anything that must survive belongs
220
+ * on the server.
221
+ */
222
+ onLeave?: () => void;
223
+ /** Overrides for the consumer's mounted paths. Defaults are correct for
224
+ * every app that mounts `cursedauth/sso-consumer` normally. */
225
+ startPath?: string;
226
+ signOutPath?: string;
227
+ /**
228
+ * The other accounts this browser holds, if the app already has them.
229
+ *
230
+ * Optional because the menu can ask for itself: with this absent it reads
231
+ * `/api/auth/session` the first time it is OPENED, so eighteen apps inherit
232
+ * the switcher without threading a prop through eighteen headers. An app
233
+ * that already has the data (it made that same call to render its shell)
234
+ * passes it and saves the round trip.
235
+ */
236
+ accounts?: BrowserAccount[];
237
+ /** Where the menu asks, when `accounts` is not given. */
238
+ sessionPath?: string;
239
+ /**
240
+ * This account's id — what the shared profile picture is keyed on.
241
+ *
242
+ * Optional, and when it is absent the menu asks `/api/auth/session` for it. That is
243
+ * the whole reason eighteen apps inherited the picture with no per-app edit: the
244
+ * owner's ask was *"only have to set it once"*, and a required prop would have made
245
+ * it "set it once and then wire it eighteen times". An app that already holds the
246
+ * session (most of them do — they rendered a name from it) passes it and saves the
247
+ * request.
248
+ */
249
+ userId?: string;
250
+ }
251
+
252
+ /** One account signed in on this browser, as `/api/auth/session` reports it. */
253
+ export interface BrowserAccount {
254
+ slot: number;
255
+ id: string;
256
+ email: string;
257
+ name: string;
258
+ }
259
+
260
+ /** What `/api/auth/session` answers, in the part this component reads. */
261
+ interface BrowserAccountsResponse {
262
+ slot?: number;
263
+ accounts?: BrowserAccount[];
264
+ slotsFull?: boolean;
265
+ /** Who this browser is, in this app. Read only for `user.id` — the avatar key. */
266
+ user?: { id?: string };
267
+ }
268
+
269
+ const SESSION_PATH = "/api/auth/session";
270
+
271
+ /**
272
+ * The accounts this browser holds, fetched once per menu opening.
273
+ *
274
+ * Never throws and never renders an error: a switcher that cannot list the
275
+ * other accounts degrades to the menu that shipped before it existed, which is
276
+ * a working menu. There is nothing here worth interrupting somebody over —
277
+ * they came to press "Sign out".
278
+ */
279
+ /**
280
+ * One in-flight request per path per page, shared by every instance.
281
+ *
282
+ * The menu reads the session at MOUNT now (it used to wait for the panel to open) because
283
+ * the profile picture is drawn in the CLOSED launcher — a menu that learns who it belongs
284
+ * to only once you click it would paint initials and then swap to a face. A module-level
285
+ * cache is what keeps that from becoming N requests when a page renders the menu twice.
286
+ */
287
+ const sessionProbes = new Map<string, Promise<BrowserAccountsResponse | null>>();
288
+
289
+ /**
290
+ * Forget what the probe learned.
291
+ *
292
+ * Exported for tests, and named for what it is rather than hidden behind an underscore:
293
+ * a page-lifetime cache is correct in a browser (the session can only change through a
294
+ * navigation, which remounts everything) and wrong in a test file, where ten renders share
295
+ * one module. Without this, the second test's fetch mock is never called and its
296
+ * assertions wait on the FIRST test's answer.
297
+ */
298
+ export function resetAccountSessionProbe(): void {
299
+ sessionProbes.clear();
300
+ }
301
+
302
+ function probeSession(path: string): Promise<BrowserAccountsResponse | null> {
303
+ const existing = sessionProbes.get(path);
304
+ if (existing) return existing;
305
+ const probe = fetch(path, { credentials: "same-origin" })
306
+ .then((res) => (res.ok ? (res.json() as Promise<BrowserAccountsResponse>) : null))
307
+ .catch(() => null);
308
+ sessionProbes.set(path, probe);
309
+ return probe;
310
+ }
311
+
312
+ function useBrowserAccounts(
313
+ sessionPath: string,
314
+ provided?: BrowserAccount[],
315
+ providedUserId?: string,
316
+ ): { accounts: BrowserAccount[]; slot: number; slotsFull: boolean; userId?: string } {
317
+ const [fetched, setFetched] = useState<BrowserAccountsResponse | null>(null);
318
+ // Nothing left to learn: the caller handed over both halves.
319
+ const complete = Boolean(provided && providedUserId);
320
+
321
+ useEffect(() => {
322
+ if (complete) return;
323
+ let live = true;
324
+ void probeSession(sessionPath).then((body) => {
325
+ if (live && body) setFetched(body);
326
+ });
327
+ return () => {
328
+ live = false;
329
+ };
330
+ }, [complete, sessionPath]);
331
+
332
+ return {
333
+ accounts: provided ?? fetched?.accounts ?? [],
334
+ // The tab is the authority on its own slot; the server's answer is only a
335
+ // fallback for a tab that has not installed the client module.
336
+ slot: currentAccountSlot() || (fetched?.slot ?? 0),
337
+ slotsFull: fetched?.slotsFull ?? false,
338
+ ...((providedUserId ?? fetched?.user?.id)
339
+ ? { userId: providedUserId ?? fetched?.user?.id }
340
+ : {}),
341
+ };
342
+ }
343
+
344
+ /**
345
+ * One picture fetch per URL per page, shared by every instance — the launcher and the panel
346
+ * head are two `AccountAvatar`s of the same person.
347
+ */
348
+ const pictureProbes = new Map<string, Promise<Blob | null>>();
349
+
350
+ /** Forget the fetched pictures. Exported for the same reason as its session sibling. */
351
+ export function resetAccountPictureProbe(): void {
352
+ pictureProbes.clear();
353
+ }
354
+
355
+ function probePicture(src: string): Promise<Blob | null> {
356
+ const existing = pictureProbes.get(src);
357
+ if (existing) return existing;
358
+ const probe = fetch(src, { cache: "no-cache" })
359
+ // 🔴 A NON-EMPTY blob, not `res.ok`. "This account has no picture" answers **204**
360
+ // (see `apps/auth/src/server/avatars.ts`: a 404 is a browser console line on every
361
+ // signed-in page in the fleet), and 204 is `ok` with a zero-byte body. Reading `ok`
362
+ // here would mint an object URL for nothing and draw a broken circle.
363
+ .then((res) => (res.status === 200 ? res.blob() : null))
364
+ .then((blob) => (blob && blob.size > 0 ? blob : null))
365
+ .catch(() => null);
366
+ pictureProbes.set(src, probe);
367
+ return probe;
368
+ }
369
+
370
+ /**
371
+ * The circle: the account's picture, or its initials.
372
+ *
373
+ * 🔴 It FETCHES the bytes rather than pointing an `<img>` at them, and that is not a style
374
+ * choice — it is what a browser smoke found on the first deploy (2026-08-22). Most accounts
375
+ * have no picture, and back then `GET /avatar/:id` answered **404** for those: a 404 on an
376
+ * `<img>` is a `Failed to load resource` in the console **on every signed-in page of every
377
+ * app in the fleet**. `routeCheck` fails a route that logs a console error, correctly, so
378
+ * nine of life's nine signed-in routes went red at once.
379
+ *
380
+ * That route has answered **204** since 2026-08-22 (`apps/auth/src/server/avatars.ts`), so
381
+ * the 404 above is HISTORY — but the fetch is not. A 204 is silent for a `fetch` and is
382
+ * `net::ERR_ABORTED` for an `<img>`, which cannot decode a zero-byte body. So the server's
383
+ * status and this client's fetch are two halves of ONE decision, and changing either half
384
+ * alone re-opens the bug in the other. `AccountMenu.test.tsx` pins both halves.
385
+ *
386
+ * The response is `no-cache` with an ETag, so this is one conditional request per page that
387
+ * usually answers 304 — and changing your picture shows up everywhere on the next load
388
+ * rather than whenever a max-age happened to run out.
389
+ */
390
+ function AccountAvatar({
391
+ name,
392
+ email,
393
+ accountsUrl,
394
+ userId,
395
+ }: {
396
+ name: string;
397
+ email?: string;
398
+ accountsUrl?: string | null;
399
+ userId?: string;
400
+ }) {
401
+ const src = accountAvatarUrl(accountsUrl, userId);
402
+ const [picture, setPicture] = useState<string | null>(null);
403
+ useEffect(() => {
404
+ setPicture(null);
405
+ if (!src) return;
406
+ let live = true;
407
+ let objectUrl: string | null = null;
408
+ void probePicture(src).then((blob) => {
409
+ if (!live || !blob) return;
410
+ objectUrl = URL.createObjectURL(blob);
411
+ setPicture(objectUrl);
412
+ });
413
+ return () => {
414
+ live = false;
415
+ // The blob stays in the page's memory until it is revoked, and a header that
416
+ // remounts on every navigation would leak one copy per navigation.
417
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
418
+ };
419
+ }, [src]);
420
+ return (
421
+ <span className="sam-av" aria-hidden="true">
422
+ {picture ? <img src={picture} alt="" /> : accountInitials(name, email)}
423
+ </span>
424
+ );
425
+ }
426
+
427
+ /**
428
+ * The header account menu. Renders a name button; the panel carries whatever
429
+ * the app passed as `children`, then the account block.
430
+ */
431
+ export function AccountMenu({
432
+ name,
433
+ email,
434
+ accountsUrl,
435
+ children,
436
+ onSignOut,
437
+ onLeave,
438
+ startPath,
439
+ signOutPath,
440
+ accounts,
441
+ sessionPath = SESSION_PATH,
442
+ userId,
443
+ }: AccountMenuProps) {
444
+ useInjectedStyles(STYLE_ID, STYLES);
445
+ const dark = useHostDark();
446
+ const { open, close, toggle, wrapRef, panelRef, position } =
447
+ usePopover<HTMLSpanElement>(PANEL_WIDTH);
448
+ // The dim behind the panel — shared with the app switcher it sits beside, so the two
449
+ // cannot end up with different ideas of what "open over the page" looks like.
450
+ useScrim(open, close, dark);
451
+ const sso = Boolean(accountsUrl);
452
+ const browser = useBrowserAccounts(sessionPath, accounts, userId);
453
+ /**
454
+ * 🔴 Tell the request layer who this page was drawn for (2026-08-23).
455
+ *
456
+ * This one line is what gives nineteen apps the account-drift guard with no
457
+ * per-app edit, and this component is where it belongs for a reason that is
458
+ * not convenience: the menu is the thing on screen that NAMES the account, so
459
+ * the id it renders and the id every request asserts are by construction the
460
+ * same id. Anywhere else they could drift apart, which is the class of bug
461
+ * being closed. See `accountSlots.ts`.
462
+ */
463
+ useEffect(() => {
464
+ setExpectedAccount(browser.userId ?? null);
465
+ }, [browser.userId]);
466
+ const [notice, setNotice] = useAccountNotice();
467
+ const others = browser.accounts.filter((row) => row.slot !== browser.slot);
468
+ const several = browser.accounts.length > 1;
469
+
470
+ /**
471
+ * Make THIS tab that account.
472
+ *
473
+ * A full navigation rather than a state change: the slot is resolved from
474
+ * the URL at boot, so the honest way to change it is to load the page as
475
+ * that account. It also means the tab's `sessionStorage` and its patched
476
+ * `fetch` are rebuilt together, instead of drifting apart.
477
+ */
478
+ const switchTo = (slot: number) => {
479
+ close();
480
+ onLeave?.();
481
+ const here = `${globalThis.location?.pathname ?? "/"}${globalThis.location?.search ?? ""}`;
482
+ globalThis.location?.assign(slotUrl(here, slot));
483
+ };
484
+
485
+ return (
486
+ <span className="sam sam-wrap" data-dark={dark ? "true" : "false"} ref={wrapRef}>
487
+ {/* Nothing at all until the account goes wrong — and then it is fetched.
488
+ It lives here rather than in each app's shell because "here" is the
489
+ one component all nineteen already mount. */}
490
+ {notice ? (
491
+ <Suspense fallback={null}>
492
+ <AccountNotice
493
+ notice={notice}
494
+ onDismiss={() => setNotice(null)}
495
+ {...(accountsUrl ? { accountsUrl } : {})}
496
+ {...(startPath ? { startPath } : {})}
497
+ signedInAs={name}
498
+ />
499
+ </Suspense>
500
+ ) : null}
501
+ <button
502
+ type="button"
503
+ className="sam-launch"
504
+ aria-expanded={open}
505
+ aria-haspopup="true"
506
+ // The visible text is just the name, which reads as a label with no
507
+ // verb — "curt@…" tells a screen reader nothing about what pressing it
508
+ // does. The label CONTAINS the visible text, so the visible-label rule
509
+ // still holds.
510
+ // 🔴 No `title=`. A native tooltip is the OPERATING SYSTEM's: it takes
511
+ // one to two seconds to appear and no CSS can theme or hurry it, which
512
+ // is the exact complaint unit 11 removed 118 of them for — and this one
513
+ // survived, in shared code, in nineteen app headers. The `aria-label`
514
+ // above already carries the sentence for anyone who needs it, and the
515
+ // visible name is the label for everyone else.
516
+ aria-label={`Signed in as ${name}`}
517
+ onClick={toggle}
518
+ >
519
+ <AccountAvatar
520
+ name={name}
521
+ {...(email ? { email } : {})}
522
+ {...(accountsUrl ? { accountsUrl } : {})}
523
+ {...(browser.userId ? { userId: browser.userId } : {})}
524
+ />
525
+ <span className="sam-who">{name}</span>
526
+ <span className="sam-caret" aria-hidden="true">
527
+ ▾
528
+ </span>
529
+ </button>
530
+ {open &&
531
+ typeof document !== "undefined" &&
532
+ createPortal(
533
+ // 🔴 PORTALED to <body> for the same reason as the app switcher beside
534
+ // it: a header or sidebar that establishes a stacking context renders
535
+ // this panel UNDERNEATH itself no matter how large the z-index. The two
536
+ // controls share `usePopover`, so they share the escape too.
537
+ //
538
+ // `sam` travels with the panel — the palette variables and the dark
539
+ // rule are defined on `.sam`, which is no longer an ancestor.
540
+ <div
541
+ ref={panelRef}
542
+ className="sam sam-pop"
543
+ data-dark={dark ? "true" : "false"}
544
+ data-placement={position?.placement ?? "below"}
545
+ role="menu"
546
+ style={
547
+ position
548
+ ? { left: `${Math.round(position.left)}px`, top: `${Math.round(position.top)}px` }
549
+ : { left: 0, top: 0, visibility: "hidden" }
550
+ }
551
+ >
552
+ <div className="sam-head">
553
+ <AccountAvatar
554
+ name={name}
555
+ {...(email ? { email } : {})}
556
+ {...(accountsUrl ? { accountsUrl } : {})}
557
+ {...(browser.userId ? { userId: browser.userId } : {})}
558
+ />
559
+ <div className="sam-head-text">
560
+ <div className="sam-name">
561
+ {name}
562
+ {/* Which of several accounts this tab is. Shown ONLY when there
563
+ is more than one, because "Account 1" beside a lone name is
564
+ a number that answers a question nobody asked — and hiding
565
+ it is what keeps the single-account menu unchanged. */}
566
+ {several ? <span className="sam-badge">Account {browser.slot + 1}</span> : null}
567
+ </div>
568
+ {email && email !== name ? <div className="sam-sub">{email}</div> : null}
569
+ </div>
570
+ </div>
571
+ {children?.(close)}
572
+ {sso ? (
573
+ <>
574
+ {/* ── The other accounts open in this browser (2026-08-12) ──
575
+ Each row is two targets on purpose. The wide one makes THIS
576
+ tab that person, which is the Google-style switch. The ⧉
577
+ opens a SECOND window still signed in as them, which is the
578
+ thing the owner actually asked for — owner in one window,
579
+ a test account in another, both live. */}
580
+ {others.length > 0 ? (
581
+ <>
582
+ <div className="sam-rule" />
583
+ <div className="sam-label">Also signed in here</div>
584
+ {others.map((account) => (
585
+ <div className="sam-acct" key={account.id}>
586
+ <button
587
+ type="button"
588
+ className="sam-item"
589
+ onClick={() => switchTo(account.slot)}
590
+ >
591
+ <span className="sam-acct-who">{account.name || account.email}</span>
592
+ {account.name && account.name !== account.email ? (
593
+ <span className="sam-acct-sub">{account.email}</span>
594
+ ) : null}
595
+ </button>
596
+ <button
597
+ type="button"
598
+ className="sam-open"
599
+ title={`Open a new window as ${account.name || account.email}`}
600
+ aria-label={`Open a new window as ${account.name || account.email}`}
601
+ onClick={() => {
602
+ close();
603
+ globalThis.open?.(accountWindowUrl(account.slot), "_blank", "noopener");
604
+ }}
605
+ >
606
+ ⧉
607
+ </button>
608
+ </div>
609
+ ))}
610
+ <div className="sam-rule" />
611
+ </>
612
+ ) : null}
613
+ {/* Passwords, 2FA and (for the owner) the user list live at
614
+ accounts — this app has no such surface by design. */}
615
+ <a className="sam-item" href={accountsUrl ?? "#"} onClick={close}>
616
+ Manage account
617
+ </a>
618
+ {/* 🔴 The owner asked for the picture to be changeable from the thing
619
+ it is drawn in: "The Account page can be accessible through it, plus
620
+ the ability to update your picture." It is a link to the account
621
+ page's own section rather than a picker here, because the picture is
622
+ the ACCOUNT's and every app would otherwise need an uploader. */}
623
+ <a
624
+ className="sam-item"
625
+ href={`${accountsUrl ?? ""}#/account/picture`}
626
+ onClick={close}
627
+ >
628
+ Change your picture
629
+ </a>
630
+ {/* 🔴 Two different doors, and the difference is the feature.
631
+ "Add" keeps everyone signed in; "Switch user" replaces this
632
+ tab's account, which is what somebody handing the laptop
633
+ over wants. Offering only one of them is how this menu got
634
+ written in the first place. */}
635
+ {browser.slotsFull ? (
636
+ <p className="sam-hint">
637
+ This browser is holding all the accounts it can. Sign one out to add another.
638
+ </p>
639
+ ) : (
640
+ <button
641
+ type="button"
642
+ className="sam-item"
643
+ onClick={() => {
644
+ close();
645
+ startSsoSignIn({ addAccount: true, ...(startPath ? { startPath } : {}) });
646
+ }}
647
+ >
648
+ Add another account
649
+ </button>
650
+ )}
651
+ <button
652
+ type="button"
653
+ className="sam-item"
654
+ onClick={() => {
655
+ close();
656
+ onLeave?.();
657
+ startSsoSignIn({ switchUser: true, ...(startPath ? { startPath } : {}) });
658
+ }}
659
+ >
660
+ Switch user
661
+ </button>
662
+ <p className="sam-hint">
663
+ Add keeps everyone signed in. Switch replaces this tab&apos;s account.
664
+ </p>
665
+ </>
666
+ ) : null}
667
+ {/* Rendered only when there is something it can actually END: an
668
+ accounts session, or an app-supplied sign-out. A dev open loop has
669
+ neither, and a "Sign out" there would navigate to a route nothing
670
+ mounts — a button that lies, which is the exact class of defect
671
+ this component was written to remove. */}
672
+ {sso || onSignOut ? (
673
+ <button
674
+ type="button"
675
+ className="sam-item"
676
+ data-tone="danger"
677
+ onClick={() => {
678
+ close();
679
+ onLeave?.();
680
+ if (onSignOut) {
681
+ void onSignOut();
682
+ return;
683
+ }
684
+ startSsoSignOut(signOutPath ? { signOutPath } : {});
685
+ }}
686
+ >
687
+ {several ? `Sign out ${name}` : "Sign out"}
688
+ </button>
689
+ ) : null}
690
+ {/* The shared-machine exit, and ONLY when there is more than one
691
+ account to leave. 🔴 It is a separate button rather than the
692
+ default because ending every session when a test account signs
693
+ out of one tab loses work in a window nobody touched — the
694
+ destructive direction, so it has to be asked for by name. */}
695
+ {sso && several ? (
696
+ <button
697
+ type="button"
698
+ className="sam-item"
699
+ data-tone="danger"
700
+ onClick={() => {
701
+ close();
702
+ onLeave?.();
703
+ startSsoSignOut({ allAccounts: true, ...(signOutPath ? { signOutPath } : {}) });
704
+ }}
705
+ >
706
+ Sign out of all accounts
707
+ </button>
708
+ ) : null}
709
+ {sso ? (
710
+ <p className="sam-hint">
711
+ {several
712
+ ? "Signing out leaves this account only; the others stay signed in."
713
+ : "Ends your session here and at accounts."}
714
+ </p>
715
+ ) : null}
716
+ </div>,
717
+ document.body,
718
+ )}
719
+ </span>
720
+ );
721
+ }
722
+
723
+ /* Re-exported through the menu's own subpath, deliberately: `account-ui` is
724
+ * already the one import every app header has, and a second entry point for a
725
+ * banner the menu mounts for you would invite an app to mount it twice. Auth
726
+ * itself is the only caller that wants it standalone — it has no AccountMenu,
727
+ * because it IS the accounts app. */
728
+ export { AccountNotice, type AccountNoticeProps } from "./AccountNotice";
729
+ export { useAccountNotice, type AccountNoticeState } from "./accountNotice.state";