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.
- package/LICENSE +21 -0
- package/README.md +87 -0
- package/dist/account/AccountMenu.d.ts +153 -0
- package/dist/account/AccountMenu.d.ts.map +1 -0
- package/dist/account/AccountMenu.js +388 -0
- package/dist/account/AccountMenu.js.map +1 -0
- package/dist/account/AccountNotice.d.ts +35 -0
- package/dist/account/AccountNotice.d.ts.map +1 -0
- package/dist/account/AccountNotice.js +133 -0
- package/dist/account/AccountNotice.js.map +1 -0
- package/dist/account/accountNotice.state.d.ts +20 -0
- package/dist/account/accountNotice.state.d.ts.map +1 -0
- package/dist/account/accountNotice.state.js +55 -0
- package/dist/account/accountNotice.state.js.map +1 -0
- package/dist/account/avatar.d.ts +37 -0
- package/dist/account/avatar.d.ts.map +1 -0
- package/dist/account/avatar.js +47 -0
- package/dist/account/avatar.js.map +1 -0
- package/dist/accountSlot.client.d.ts +113 -0
- package/dist/accountSlot.client.d.ts.map +1 -0
- package/dist/accountSlot.client.js +330 -0
- package/dist/accountSlot.client.js.map +1 -0
- package/dist/accountSlots.d.ts +192 -0
- package/dist/accountSlots.d.ts.map +1 -0
- package/dist/accountSlots.js +274 -0
- package/dist/accountSlots.js.map +1 -0
- package/dist/auth.d.ts +167 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +310 -0
- package/dist/auth.js.map +1 -0
- package/dist/auth.server.d.ts +35 -0
- package/dist/auth.server.d.ts.map +1 -0
- package/dist/auth.server.js +67 -0
- package/dist/auth.server.js.map +1 -0
- package/dist/clientDescription.d.ts +186 -0
- package/dist/clientDescription.d.ts.map +1 -0
- package/dist/clientDescription.js +278 -0
- package/dist/clientDescription.js.map +1 -0
- package/dist/constantTime.d.ts +35 -0
- package/dist/constantTime.d.ts.map +1 -0
- package/dist/constantTime.js +46 -0
- package/dist/constantTime.js.map +1 -0
- package/dist/contentCensus.d.ts +59 -0
- package/dist/contentCensus.d.ts.map +1 -0
- package/dist/contentCensus.js +55 -0
- package/dist/contentCensus.js.map +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/dist/mountGatedApp.d.ts +128 -0
- package/dist/mountGatedApp.d.ts.map +1 -0
- package/dist/mountGatedApp.js +107 -0
- package/dist/mountGatedApp.js.map +1 -0
- package/dist/runtimeMode.d.ts +28 -0
- package/dist/runtimeMode.d.ts.map +1 -0
- package/dist/runtimeMode.js +37 -0
- package/dist/runtimeMode.js.map +1 -0
- package/dist/secureRequest.d.ts +22 -0
- package/dist/secureRequest.d.ts.map +1 -0
- package/dist/secureRequest.js +27 -0
- package/dist/secureRequest.js.map +1 -0
- package/dist/sso.d.ts +373 -0
- package/dist/sso.d.ts.map +1 -0
- package/dist/sso.js +420 -0
- package/dist/sso.js.map +1 -0
- package/dist/ssoAutoSignIn.d.ts +272 -0
- package/dist/ssoAutoSignIn.d.ts.map +1 -0
- package/dist/ssoAutoSignIn.js +431 -0
- package/dist/ssoAutoSignIn.js.map +1 -0
- package/dist/ssoConsumer.server.d.ts +295 -0
- package/dist/ssoConsumer.server.d.ts.map +1 -0
- package/dist/ssoConsumer.server.js +972 -0
- package/dist/ssoConsumer.server.js.map +1 -0
- package/dist/stageIdentity.d.ts +72 -0
- package/dist/stageIdentity.d.ts.map +1 -0
- package/dist/stageIdentity.js +74 -0
- package/dist/stageIdentity.js.map +1 -0
- package/dist/ui/popover.d.ts +190 -0
- package/dist/ui/popover.d.ts.map +1 -0
- package/dist/ui/popover.js +351 -0
- package/dist/ui/popover.js.map +1 -0
- package/dist/userSessions.d.ts +205 -0
- package/dist/userSessions.d.ts.map +1 -0
- package/dist/userSessions.js +419 -0
- package/dist/userSessions.js.map +1 -0
- package/package.json +115 -0
- package/src/account/AccountMenu.tsx +729 -0
- package/src/account/AccountNotice.tsx +223 -0
- package/src/account/accountNotice.state.ts +66 -0
- package/src/account/avatar.ts +50 -0
- package/src/accountSlot.client.ts +362 -0
- package/src/accountSlots.ts +305 -0
- package/src/auth.server.ts +89 -0
- package/src/auth.ts +515 -0
- package/src/clientDescription.ts +366 -0
- package/src/constantTime.ts +45 -0
- package/src/contentCensus.ts +106 -0
- package/src/index.ts +58 -0
- package/src/mountGatedApp.ts +240 -0
- package/src/runtimeMode.ts +37 -0
- package/src/secureRequest.ts +25 -0
- package/src/sso.ts +767 -0
- package/src/ssoAutoSignIn.ts +544 -0
- package/src/ssoConsumer.server.ts +1260 -0
- package/src/stageIdentity.ts +76 -0
- package/src/ui/popover.ts +390 -0
- package/src/userSessions.ts +678 -0
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser half of account slots: which account THIS TAB is, and how every
|
|
3
|
+
* request it makes says so (2026-08-12).
|
|
4
|
+
*
|
|
5
|
+
* ── Why a tab can have its own account at all ───────────────────────────────
|
|
6
|
+
* Cookies are per-origin, so two tabs of one app share one cookie jar and
|
|
7
|
+
* cannot each hold a different session. What they CAN each hold is a different
|
|
8
|
+
* `sessionStorage` — that storage is per-tab by definition, survives reloads
|
|
9
|
+
* and in-app navigation, and dies with the tab. So the jar holds every account
|
|
10
|
+
* (see `accountSlots.ts`), and the tab remembers WHICH of them it is.
|
|
11
|
+
*
|
|
12
|
+
* ── Two channels, and why both ──────────────────────────────────────────────
|
|
13
|
+
* - **`sessionStorage`** is the tab's memory. It is what makes the choice
|
|
14
|
+
* survive a reload and every click inside the app.
|
|
15
|
+
* - **The `?authuser=` URL param** is how a slot ENTERS a tab: the SSO
|
|
16
|
+
* callback lands on it, "open this account in a new window" links to it, and
|
|
17
|
+
* a bookmark restores it. It is read once, at boot, and then re-asserted on
|
|
18
|
+
* the URL so what the address bar says is true.
|
|
19
|
+
*
|
|
20
|
+
* The URL wins at boot when both are present, because the URL is what the
|
|
21
|
+
* person just navigated to.
|
|
22
|
+
*
|
|
23
|
+
* ── What the fetch patch is for, and its one limit ──────────────────────────
|
|
24
|
+
* These apps are SPAs: the document is static HTML that needs no session, and
|
|
25
|
+
* everything that does comes back through `fetch`. So attaching one header to
|
|
26
|
+
* same-origin `fetch` covers the authenticated surface completely, without
|
|
27
|
+
* every route constant in eighteen apps growing a query parameter — which is
|
|
28
|
+
* the change nobody would apply consistently, and one missed call site is a
|
|
29
|
+
* request that silently acts as the wrong account.
|
|
30
|
+
*
|
|
31
|
+
* 🔴 The limit: a same-origin SUBRESOURCE that needs the session — an `<img>`,
|
|
32
|
+
* a `<video>`, a download, an EventSource — is not a `fetch` and carries no
|
|
33
|
+
* header. Those must be built with `slotUrl()`. In this fleet almost nothing is
|
|
34
|
+
* affected, because media is served by binary-server against signed tokens
|
|
35
|
+
* rather than a session cookie, but an app that adds a session-gated `<img>`
|
|
36
|
+
* has to say so in the URL.
|
|
37
|
+
*
|
|
38
|
+
* ── Slot 0 costs nothing ────────────────────────────────────────────────────
|
|
39
|
+
* Every function here short-circuits at slot 0: no storage write, no URL
|
|
40
|
+
* rewrite, no patched `fetch`, no header. The overwhelmingly common case — one
|
|
41
|
+
* account — behaves exactly as it did before this file existed, which is also
|
|
42
|
+
* why nothing in the fleet had to change to adopt it.
|
|
43
|
+
*/
|
|
44
|
+
import {
|
|
45
|
+
ACCOUNT_DRIFT_STATUS,
|
|
46
|
+
ACCOUNT_SLOT_HEADER,
|
|
47
|
+
ACCOUNT_SLOT_PARAM,
|
|
48
|
+
ACCOUNT_USER_HEADER,
|
|
49
|
+
type AccountDriftBody,
|
|
50
|
+
isAccountDriftBody,
|
|
51
|
+
normalizeSlot,
|
|
52
|
+
slotFromUrl,
|
|
53
|
+
withSlot,
|
|
54
|
+
} from "./accountSlots";
|
|
55
|
+
|
|
56
|
+
/** Per-tab, like the SSO auto-sign-in guards next door and for the same
|
|
57
|
+
* reason: it must never be a reason a DIFFERENT tab acts as somebody else. */
|
|
58
|
+
export const ACCOUNT_SLOT_KEY = "satellite.account.slot.v1";
|
|
59
|
+
|
|
60
|
+
/** Set once `installAccountSlot` has run, so a second call is a no-op rather
|
|
61
|
+
* than a second layer of patched `fetch` wrapping the first. */
|
|
62
|
+
const INSTALLED = Symbol.for("satellite.accountSlot.installed");
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Every storage access is wrapped. Safari's private mode throws on ACCESS, not
|
|
66
|
+
* on write, and a tab that cannot remember its slot must degrade to the primary
|
|
67
|
+
* account — never to an exception on the way to first paint.
|
|
68
|
+
*/
|
|
69
|
+
function readStoredSlot(): number | null {
|
|
70
|
+
try {
|
|
71
|
+
const raw = globalThis.sessionStorage?.getItem(ACCOUNT_SLOT_KEY);
|
|
72
|
+
return raw === null || raw === undefined ? null : normalizeSlot(raw);
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function storeSlot(slot: number): void {
|
|
79
|
+
try {
|
|
80
|
+
globalThis.sessionStorage?.setItem(ACCOUNT_SLOT_KEY, String(slot));
|
|
81
|
+
} catch {
|
|
82
|
+
// See above. A tab that cannot remember is still a tab that works.
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Which account this tab is acting as.
|
|
88
|
+
*
|
|
89
|
+
* URL first (that is how a slot arrives), then the tab's memory, then 0. Safe
|
|
90
|
+
* to call before `installAccountSlot`, and safe to call on a server (no
|
|
91
|
+
* `location`, no storage → 0).
|
|
92
|
+
*/
|
|
93
|
+
export function currentAccountSlot(): number {
|
|
94
|
+
try {
|
|
95
|
+
const fromUrl = slotFromUrl(globalThis.location?.href ?? "");
|
|
96
|
+
if (fromUrl !== null) return fromUrl;
|
|
97
|
+
} catch {
|
|
98
|
+
// A location that cannot be read is not a slot.
|
|
99
|
+
}
|
|
100
|
+
return readStoredSlot() ?? 0;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* `url` with this tab's account on it.
|
|
105
|
+
*
|
|
106
|
+
* For the things a header cannot reach: a session-gated `<img src>`, an
|
|
107
|
+
* `EventSource`, a download link, an `<a>` to another page of this app. Slot 0
|
|
108
|
+
* returns the URL untouched.
|
|
109
|
+
*/
|
|
110
|
+
export function slotUrl(url: string, slot: number = currentAccountSlot()): string {
|
|
111
|
+
return withSlot(url, slot);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* A URL that opens `slot` — in this app, in another tab or window.
|
|
116
|
+
*
|
|
117
|
+
* The owner-facing point of the whole feature: "open my test account beside my
|
|
118
|
+
* own". Always absolute, because the caller is about to hand it to
|
|
119
|
+
* `window.open` or an `<a target="_blank">`.
|
|
120
|
+
*/
|
|
121
|
+
export function accountWindowUrl(slot: number, path = "/"): string {
|
|
122
|
+
const origin = globalThis.location?.origin ?? "";
|
|
123
|
+
return `${origin}${withSlot(path, slot)}`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/* ── The expected account ────────────────────────────────────────────────────
|
|
127
|
+
*
|
|
128
|
+
* See `accountSlots.ts` for the failure this closes. In short: another tab can
|
|
129
|
+
* replace this slot's occupant while this tab is still showing a page it drew
|
|
130
|
+
* for the previous one, and nothing tells it. The page states who it rendered
|
|
131
|
+
* for; the server compares and answers 409.
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/** Who this PAGE believes it is. Module scope, not storage: it is a property of
|
|
135
|
+
* the rendered document, and a reload re-derives it from the session. */
|
|
136
|
+
let expectedAccount: string | null = null;
|
|
137
|
+
|
|
138
|
+
/** The event a drift refusal raises. One name, so the shared banner and any app
|
|
139
|
+
* that wants its own reaction listen to the same thing. */
|
|
140
|
+
export const ACCOUNT_DRIFT_EVENT = "satellite:account-drift";
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Declare who this page rendered for.
|
|
144
|
+
*
|
|
145
|
+
* Called once from the shared session surfaces — `useSatelliteAuth`'s SSO
|
|
146
|
+
* adapter and `AccountMenu` — so no app wires this up for itself. Passing an
|
|
147
|
+
* empty string or null clears it (signed out).
|
|
148
|
+
*
|
|
149
|
+
* 🔴 Calling this INSTALLS the fetch patch even at slot 0, which is the whole
|
|
150
|
+
* point: slot 0 is where the eviction happens, because it is the slot every
|
|
151
|
+
* ordinary sign-in takes. Everything else about "slot 0 costs nothing" is
|
|
152
|
+
* unchanged — an app that never declares an expectation never gets a patch.
|
|
153
|
+
*/
|
|
154
|
+
export function setExpectedAccount(userId: string | null): void {
|
|
155
|
+
const next = userId && userId.length > 0 ? userId : null;
|
|
156
|
+
if (next === expectedAccount) return;
|
|
157
|
+
expectedAccount = next;
|
|
158
|
+
if (next !== null) installAccountSlot();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Who this page said it was. */
|
|
162
|
+
export function currentExpectedAccount(): string | null {
|
|
163
|
+
return expectedAccount;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Announce a drift, at most once per page.
|
|
168
|
+
*
|
|
169
|
+
* Once is deliberate and load-bearing: a dashboard fires a dozen requests at
|
|
170
|
+
* mount and every one of them will be refused with the same body, so an
|
|
171
|
+
* un-latched event would stack a dozen identical banners. The page is now
|
|
172
|
+
* lying about who it is and the only cure is a navigation, so a second telling
|
|
173
|
+
* adds nothing.
|
|
174
|
+
*/
|
|
175
|
+
let driftAnnounced = false;
|
|
176
|
+
|
|
177
|
+
function announceDrift(detail: AccountDriftBody): void {
|
|
178
|
+
if (driftAnnounced) return;
|
|
179
|
+
driftAnnounced = true;
|
|
180
|
+
try {
|
|
181
|
+
globalThis.dispatchEvent?.(new CustomEvent(ACCOUNT_DRIFT_EVENT, { detail }));
|
|
182
|
+
} catch {
|
|
183
|
+
// No DOM (a test, a server render). The response still returns unchanged
|
|
184
|
+
// to its caller, which is the half that must never depend on this.
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Read one response for a drift refusal, without consuming it.
|
|
190
|
+
*
|
|
191
|
+
* 🔴 `res.clone()` is not optional. The caller owns this body and will read it;
|
|
192
|
+
* reading it here first would hand them a locked stream — a fetch wrapper that
|
|
193
|
+
* breaks every JSON parse in the app is a far worse bug than the one being
|
|
194
|
+
* detected. A clone that cannot be made or parsed is simply not a drift.
|
|
195
|
+
*/
|
|
196
|
+
function watchForDrift(res: Response): Response {
|
|
197
|
+
if (res.status !== ACCOUNT_DRIFT_STATUS || driftAnnounced) return res;
|
|
198
|
+
try {
|
|
199
|
+
void res
|
|
200
|
+
.clone()
|
|
201
|
+
.json()
|
|
202
|
+
.then((body) => {
|
|
203
|
+
if (isAccountDriftBody(body)) announceDrift(body);
|
|
204
|
+
})
|
|
205
|
+
.catch(() => {});
|
|
206
|
+
} catch {
|
|
207
|
+
// An opaque or already-consumed response is not something to inspect.
|
|
208
|
+
}
|
|
209
|
+
return res;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Tests only — forget the page's expectation and let a drift be announced again. */
|
|
213
|
+
export function resetExpectedAccountForTests(): void {
|
|
214
|
+
expectedAccount = null;
|
|
215
|
+
driftAnnounced = false;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export interface InstallAccountSlotOptions {
|
|
219
|
+
/**
|
|
220
|
+
* Rewrite the address bar so it names the slot. On by default: a URL that
|
|
221
|
+
* silently means "account 2" is one the person cannot copy, bookmark or
|
|
222
|
+
* reopen, and cannot tell apart from the other window.
|
|
223
|
+
*/
|
|
224
|
+
syncUrl?: boolean;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Resolve this tab's slot, remember it, put it on the URL, and make every
|
|
229
|
+
* same-origin `fetch` carry it. Returns the slot.
|
|
230
|
+
*
|
|
231
|
+
* Call once, as early as the app can — before the first data fetch, or that
|
|
232
|
+
* request answers as the wrong account. Idempotent.
|
|
233
|
+
*/
|
|
234
|
+
export function installAccountSlot(options: InstallAccountSlotOptions = {}): number {
|
|
235
|
+
const slot = currentAccountSlot();
|
|
236
|
+
storeSlot(slot);
|
|
237
|
+
|
|
238
|
+
if (options.syncUrl !== false && slot !== 0) {
|
|
239
|
+
try {
|
|
240
|
+
const href = globalThis.location?.href ?? "";
|
|
241
|
+
if (href && slotFromUrl(href) === null) {
|
|
242
|
+
globalThis.history?.replaceState(null, "", withSlot(href, slot));
|
|
243
|
+
}
|
|
244
|
+
} catch {
|
|
245
|
+
// A history API that refuses is cosmetic here — the tab still knows.
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const scope = globalThis as typeof globalThis & { [INSTALLED]?: boolean };
|
|
250
|
+
// 🔴 Slot 0 installs nothing UNLESS the page has declared who it rendered for.
|
|
251
|
+
// The original rule — "slot 0 costs nothing" — is what makes this module free
|
|
252
|
+
// for the fleet's ordinary single-account use, and it still holds for any app
|
|
253
|
+
// that never calls `setExpectedAccount`. But slot 0 is precisely where an
|
|
254
|
+
// account gets replaced underneath an open tab (it is the slot every ordinary
|
|
255
|
+
// sign-in takes), so refusing to install there would exempt the common case
|
|
256
|
+
// from the guard written for it.
|
|
257
|
+
if ((slot === 0 && expectedAccount === null) || scope[INSTALLED]) return slot;
|
|
258
|
+
scope[INSTALLED] = true;
|
|
259
|
+
|
|
260
|
+
const original = globalThis.fetch;
|
|
261
|
+
if (typeof original !== "function") return slot;
|
|
262
|
+
unpatched = original;
|
|
263
|
+
|
|
264
|
+
function withAccountSlot(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
|
265
|
+
let sameOrigin = false;
|
|
266
|
+
try {
|
|
267
|
+
const href =
|
|
268
|
+
typeof input === "string"
|
|
269
|
+
? input
|
|
270
|
+
: input instanceof URL
|
|
271
|
+
? input.href
|
|
272
|
+
: (input as Request).url;
|
|
273
|
+
sameOrigin = new URL(href, globalThis.location?.href).origin === globalThis.location?.origin;
|
|
274
|
+
} catch {
|
|
275
|
+
sameOrigin = false;
|
|
276
|
+
}
|
|
277
|
+
// 🔴 Same-origin ONLY. A custom header on a cross-origin request forces a
|
|
278
|
+
// CORS preflight the other end never agreed to, which would break every
|
|
279
|
+
// third-party call an app makes — and the slot means nothing there anyway,
|
|
280
|
+
// since it selects among cookies of THIS origin.
|
|
281
|
+
if (!sameOrigin) return original(input, init);
|
|
282
|
+
|
|
283
|
+
const inherited =
|
|
284
|
+
init?.headers ?? (input instanceof Request ? (input as Request).headers : undefined);
|
|
285
|
+
const headers = new Headers(inherited);
|
|
286
|
+
// Never override a caller that set it deliberately — an app asking on
|
|
287
|
+
// behalf of a specific account knows better than the tab's default.
|
|
288
|
+
if (!headers.has(ACCOUNT_SLOT_HEADER)) headers.set(ACCOUNT_SLOT_HEADER, String(slot));
|
|
289
|
+
// Read at REQUEST time, not at install time: the expectation is declared
|
|
290
|
+
// once the session resolves, which is after the first fetch has already
|
|
291
|
+
// gone out. A value closed over at install would be null forever.
|
|
292
|
+
if (expectedAccount !== null && !headers.has(ACCOUNT_USER_HEADER)) {
|
|
293
|
+
headers.set(ACCOUNT_USER_HEADER, expectedAccount);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (input instanceof Request && !init) {
|
|
297
|
+
return original(new Request(input, { headers })).then(watchForDrift);
|
|
298
|
+
}
|
|
299
|
+
return original(input, { ...init, headers }).then(watchForDrift);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// 🔴 `Object.assign` rather than a bare replacement: `fetch` carries side
|
|
303
|
+
// properties (React 19 puts `preconnect` on it) and a wrapper that drops
|
|
304
|
+
// them breaks whatever reads them — silently, and far from here.
|
|
305
|
+
globalThis.fetch = Object.assign(withAccountSlot, original);
|
|
306
|
+
|
|
307
|
+
return slot;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* The `fetch` this module replaced, for the ONE request shape the patch cannot serve.
|
|
312
|
+
*
|
|
313
|
+
* 🔴 Why this exists (2026-09-07). The patch attaches its header to same-origin requests
|
|
314
|
+
* only, and the comment above says why: a custom header on a cross-origin request forces a
|
|
315
|
+
* preflight the other end never agreed to. That reasoning has a hole, and it cost the ROM
|
|
316
|
+
* player. A **same-origin request that REDIRECTS cross-origin** is same-origin when the
|
|
317
|
+
* patch sees it and cross-origin by the time the browser acts, and the browser replays the
|
|
318
|
+
* headers at the new host — so it preflights after all:
|
|
319
|
+
*
|
|
320
|
+
* Access to fetch at 'https://binary-server…/media/roms/rom/…' (redirected from
|
|
321
|
+
* 'https://roms…/_nes-roms/…') has been blocked by CORS policy: Request header field
|
|
322
|
+
* x-account-slot is not allowed by Access-Control-Allow-Headers in preflight response.
|
|
323
|
+
*
|
|
324
|
+
* That is the fleet's whole media pattern — app URL → signed redirect → binary-server — so
|
|
325
|
+
* every app reading bytes that way was affected, not only roms. binary-server now answers
|
|
326
|
+
* the preflight (`src/server.ts::preflight`), which is the fix that covers callers this
|
|
327
|
+
* module has never heard of. This export is the other half: a caller that KNOWS its URL
|
|
328
|
+
* redirects to a foreign origin can keep its request a simple GET and skip the preflight
|
|
329
|
+
* round-trip entirely, which is what `apps/roms`' `fetchRomResponse` documented needing
|
|
330
|
+
* since 2026-07-30 — a paragraph that could not enforce itself.
|
|
331
|
+
*
|
|
332
|
+
* The slot is not lost by using this: these URLs authorize with a signed token in the URL,
|
|
333
|
+
* not with a session, so there is nothing for the header to select. Do NOT reach for it to
|
|
334
|
+
* silence an ordinary preflight — for a real API call the header is the point.
|
|
335
|
+
*/
|
|
336
|
+
let unpatched: typeof fetch | null = null;
|
|
337
|
+
export function fetchWithoutAccountSlot(
|
|
338
|
+
input: RequestInfo | URL,
|
|
339
|
+
init?: RequestInit,
|
|
340
|
+
): Promise<Response> {
|
|
341
|
+
// Before `installAccountSlot` runs, `globalThis.fetch` IS the original — so the
|
|
342
|
+
// fallback is correct rather than merely convenient, and this is safe to call from a
|
|
343
|
+
// module that loads in either order.
|
|
344
|
+
return (unpatched ?? globalThis.fetch)(input, init);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Undo the patch and forget the tab's slot. Tests only — an app that wanted
|
|
348
|
+
* this would be asking for a tab whose account changes underneath it. */
|
|
349
|
+
export function resetAccountSlotForTests(originalFetch?: typeof fetch): void {
|
|
350
|
+
const scope = globalThis as typeof globalThis & { [INSTALLED]?: boolean };
|
|
351
|
+
scope[INSTALLED] = false;
|
|
352
|
+
unpatched = null;
|
|
353
|
+
resetExpectedAccountForTests();
|
|
354
|
+
if (originalFetch) globalThis.fetch = originalFetch;
|
|
355
|
+
try {
|
|
356
|
+
globalThis.sessionStorage?.removeItem(ACCOUNT_SLOT_KEY);
|
|
357
|
+
} catch {
|
|
358
|
+
// Nothing stored is nothing to clear.
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export { ACCOUNT_SLOT_HEADER, ACCOUNT_SLOT_PARAM, ACCOUNT_USER_HEADER };
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Account SLOTS — how one browser holds several signed-in accounts at once,
|
|
3
|
+
* and how a single request says which of them it is acting as.
|
|
4
|
+
*
|
|
5
|
+
* ── The ask (2026-08-12, owner) ─────────────────────────────────────────────
|
|
6
|
+
* "I want one tab on my main account and another tab on a different account
|
|
7
|
+
* simultaneously, so I can do what I need as owner and see what other user
|
|
8
|
+
* types see." The same mechanism answers the household case the fleet already
|
|
9
|
+
* had — two people sharing a laptop who each want their own session without
|
|
10
|
+
* one of them typing a password every swap.
|
|
11
|
+
*
|
|
12
|
+
* ── Why slots, and not any of the alternatives ──────────────────────────────
|
|
13
|
+
* A cookie is per-ORIGIN, not per-tab, so "two accounts at once" cannot be two
|
|
14
|
+
* values of one cookie name. Three shapes were on the table:
|
|
15
|
+
*
|
|
16
|
+
* 1. **One cookie holding a jar of sessions, plus an index.** Rejected: every
|
|
17
|
+
* account's credential then rides in one value, so a single parse bug or a
|
|
18
|
+
* single truncated header loses or crosses ALL of them, and revoking one
|
|
19
|
+
* means rewriting the others' cookie.
|
|
20
|
+
* 2. **A bearer token in `sessionStorage`** (per-tab for free). Rejected: no
|
|
21
|
+
* cookie means top-level navigations, `<img>`/`<video>` fetches, downloads
|
|
22
|
+
* and EventSource all arrive anonymous. This fleet serves media and whole
|
|
23
|
+
* page loads behind the session; it would have authenticated the XHR layer
|
|
24
|
+
* only, which is the half that is easiest to notice working.
|
|
25
|
+
* 3. **N independent cookies, one per slot, and a selector on the request.**
|
|
26
|
+
* What this is, and what Google does. Each slot is a wholly separate
|
|
27
|
+
* opaque session id with its own row, so it is independently revocable,
|
|
28
|
+
* independently expiring, and a break in one cannot reach another.
|
|
29
|
+
*
|
|
30
|
+
* ── The selector is a HINT, never an authorization ──────────────────────────
|
|
31
|
+
* 🔴 The slot chooses WHICH OF THIS BROWSER'S OWN COOKIES to read, and nothing
|
|
32
|
+
* else. It is attacker-writable — anybody can put `?authuser=3` on a link — and
|
|
33
|
+
* that is fine precisely because the worst it achieves is making you act as an
|
|
34
|
+
* account you are *already signed into on this machine*. It can never
|
|
35
|
+
* manufacture access to an account with no cookie in that slot: an empty slot
|
|
36
|
+
* resolves to null and the request is anonymous. Nothing downstream may treat
|
|
37
|
+
* the slot number as identity; resolve it to a user through the store, always.
|
|
38
|
+
*
|
|
39
|
+
* The one real consequence is confusion — acting as B when you meant A — so
|
|
40
|
+
* every surface that renders a non-zero slot must say whose it is. That is why
|
|
41
|
+
* `AccountMenu` shows the account name unconditionally and why the URL carries
|
|
42
|
+
* the slot visibly rather than hiding it in a header alone.
|
|
43
|
+
*
|
|
44
|
+
* ── Why slot 0 is the bare cookie name ──────────────────────────────────────
|
|
45
|
+
* `roms_session` (slot 0), `roms_session__1`, `roms_session__2`. Slot 0 keeps
|
|
46
|
+
* the exact name, value and semantics every app already ships, so every live
|
|
47
|
+
* session in the fleet stays signed in across this change and every call site
|
|
48
|
+
* that never mentions a slot behaves byte-identically. There is no migration
|
|
49
|
+
* because there is nothing to migrate — multi-account is purely additive, and
|
|
50
|
+
* a browser that never opens a second account never sends a second cookie.
|
|
51
|
+
*
|
|
52
|
+
* ── Why the param is `authuser` ─────────────────────────────────────────────
|
|
53
|
+
* It is the name Google's account switcher has used for twenty years, so it is
|
|
54
|
+
* recognisable in a URL, and it is distinctive enough that no satellite's own
|
|
55
|
+
* query strings collide with it (`u` would have).
|
|
56
|
+
*
|
|
57
|
+
* This module is deliberately dependency-free so the browser half
|
|
58
|
+
* (`accountSlot.client.ts`) and the server half (`userSessions.ts`) share ONE
|
|
59
|
+
* definition of the vocabulary. Two copies of "which slot is this?" is the bug
|
|
60
|
+
* where a tab renders one account and writes as another.
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* How many accounts one browser may be signed into at once, per app.
|
|
65
|
+
*
|
|
66
|
+
* Bounded because every slot's cookie rides on EVERY request to the origin,
|
|
67
|
+
* including images and polls. Five is well past the owner's stated need (an
|
|
68
|
+
* owner account plus a test account per role) and still under 500 bytes of
|
|
69
|
+
* header. Remembered accounts — the chooser list — are a separate, larger cap:
|
|
70
|
+
* being offered an account to switch to costs nothing per request.
|
|
71
|
+
*/
|
|
72
|
+
export const MAX_ACCOUNT_SLOTS = 5;
|
|
73
|
+
|
|
74
|
+
/** Highest slot number that exists, for the loops that sweep all of them. */
|
|
75
|
+
export const MAX_SLOT_INDEX = MAX_ACCOUNT_SLOTS - 1;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The query parameter a URL uses to name its slot.
|
|
79
|
+
*
|
|
80
|
+
* 🔴 It has to be in the URL and not only in a header. A header can be attached
|
|
81
|
+
* to `fetch`, and nothing else: a full page load, a bookmark, a link opened in
|
|
82
|
+
* a new tab, an `<img src>` and a download all carry the URL alone. Putting the
|
|
83
|
+
* slot there is what makes "open this account in a second window" work at all,
|
|
84
|
+
* and it is what makes the second window survive a reload.
|
|
85
|
+
*/
|
|
86
|
+
export const ACCOUNT_SLOT_PARAM = "authuser";
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The header a same-origin `fetch` uses instead, when rewriting the URL would
|
|
90
|
+
* be worse.
|
|
91
|
+
*
|
|
92
|
+
* Both are read, URL first. The header exists because an SPA's API calls are
|
|
93
|
+
* built from route constants all over an app, and threading a query param
|
|
94
|
+
* through every one of them is the change no app would apply consistently —
|
|
95
|
+
* one missed call site is a request that silently acts as the wrong account.
|
|
96
|
+
*/
|
|
97
|
+
export const ACCOUNT_SLOT_HEADER = "x-account-slot";
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* A slot number this code is willing to use, from anything at all.
|
|
101
|
+
*
|
|
102
|
+
* Everything that is not a whole number inside the range becomes 0 — the
|
|
103
|
+
* default account — rather than throwing or refusing the request. A garbled
|
|
104
|
+
* `?authuser=` must degrade to "your main account", never to an error page:
|
|
105
|
+
* the value arrives from URLs people edit, share and truncate.
|
|
106
|
+
*/
|
|
107
|
+
export function normalizeSlot(raw: unknown): number {
|
|
108
|
+
const n = typeof raw === "number" ? raw : Number.parseInt(String(raw ?? ""), 10);
|
|
109
|
+
if (!Number.isInteger(n) || n < 0 || n > MAX_SLOT_INDEX) return 0;
|
|
110
|
+
return n;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* `true` only for a value that really named a slot, so callers can tell
|
|
115
|
+
* "explicitly slot 0" from "said nothing".
|
|
116
|
+
*
|
|
117
|
+
* The distinction matters exactly once, and it is load-bearing: the SSO
|
|
118
|
+
* callback has to know whether the hop was told to land in a specific slot or
|
|
119
|
+
* whether it should pick one, and `normalizeSlot` alone answers 0 to both.
|
|
120
|
+
*/
|
|
121
|
+
export function isExplicitSlot(raw: unknown): boolean {
|
|
122
|
+
if (raw === null || raw === undefined || raw === "") return false;
|
|
123
|
+
const n = typeof raw === "number" ? raw : Number.parseInt(String(raw), 10);
|
|
124
|
+
return Number.isInteger(n) && n >= 0 && n <= MAX_SLOT_INDEX;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The cookie name for one slot of one app.
|
|
129
|
+
*
|
|
130
|
+
* Slot 0 is the base name unchanged — see the header for why that is the whole
|
|
131
|
+
* migration story. The `__` separator cannot collide with the base name in a
|
|
132
|
+
* cookie header: a regex anchored on `<base>=` will not match `<base>__1=`.
|
|
133
|
+
*/
|
|
134
|
+
export function slotCookieName(base: string, slot: number): string {
|
|
135
|
+
const n = normalizeSlot(slot);
|
|
136
|
+
return n === 0 ? base : `${base}__${n}`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Every cookie name this app could be holding a session under, slot order. */
|
|
140
|
+
export function allSlotCookieNames(base: string): string[] {
|
|
141
|
+
return Array.from({ length: MAX_ACCOUNT_SLOTS }, (_, slot) => slotCookieName(base, slot));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* The slot a URL names, or null if it names none.
|
|
146
|
+
*
|
|
147
|
+
* Accepts a full URL or a path — the SPA calls it with `location.href` and the
|
|
148
|
+
* server calls it with the request URL, and neither should have to normalize
|
|
149
|
+
* first. A malformed URL is "names none", never a throw.
|
|
150
|
+
*/
|
|
151
|
+
export function slotFromUrl(url: string): number | null {
|
|
152
|
+
// 🔴 The hash is cut FIRST. The fleet's SPAs are hash-routed, so
|
|
153
|
+
// `/index.html#/login?authuser=3` is extremely reachable — and everything
|
|
154
|
+
// after the `#` is a client route the browser never sends to a server.
|
|
155
|
+
// Reading it here would make the server's answer depend on a string it was
|
|
156
|
+
// not given, and make the client's answer depend on whether the app happens
|
|
157
|
+
// to put the param before or after the fragment.
|
|
158
|
+
const beforeHash = url.split("#", 1)[0] ?? "";
|
|
159
|
+
const query = beforeHash.indexOf("?");
|
|
160
|
+
if (query === -1) return null;
|
|
161
|
+
const raw = new URLSearchParams(beforeHash.slice(query + 1)).get(ACCOUNT_SLOT_PARAM);
|
|
162
|
+
return isExplicitSlot(raw) ? normalizeSlot(raw) : null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* `url` with the slot named on it — or with it REMOVED for slot 0.
|
|
167
|
+
*
|
|
168
|
+
* Slot 0 gets a clean URL on purpose. The overwhelmingly common case is one
|
|
169
|
+
* account, and a fleet whose every address grew a `?authuser=0` would have
|
|
170
|
+
* made a multi-account feature nobody asked for visible to everybody who did
|
|
171
|
+
* not want it. It also keeps existing bookmarks, smokes and shared links
|
|
172
|
+
* character-for-character what they already are.
|
|
173
|
+
*/
|
|
174
|
+
export function withSlot(url: string, slot: number): string {
|
|
175
|
+
const n = normalizeSlot(slot);
|
|
176
|
+
// An empty string is not a URL and must not become one. `new URL("", base)`
|
|
177
|
+
// happily answers the base itself, so without this guard a caller with
|
|
178
|
+
// nothing to rewrite gets handed `/?authuser=1` — a navigation to the index.
|
|
179
|
+
if (url === "") return url;
|
|
180
|
+
// Resolved against a base so a bare path works; the base is dropped again
|
|
181
|
+
// below by rebuilding from the parts we were actually given.
|
|
182
|
+
const base = "http://slot.invalid";
|
|
183
|
+
let parsed: URL;
|
|
184
|
+
try {
|
|
185
|
+
parsed = new URL(url, base);
|
|
186
|
+
} catch {
|
|
187
|
+
return url;
|
|
188
|
+
}
|
|
189
|
+
if (n === 0) parsed.searchParams.delete(ACCOUNT_SLOT_PARAM);
|
|
190
|
+
else parsed.searchParams.set(ACCOUNT_SLOT_PARAM, String(n));
|
|
191
|
+
const absolute = /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith("//");
|
|
192
|
+
return absolute ? parsed.toString() : `${parsed.pathname}${parsed.search}${parsed.hash}`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/* ═══════════════ Identity drift: the page renders as A, the request acts as B ═══
|
|
196
|
+
*
|
|
197
|
+
* ── The failure (owner, 2026-08-15) ─────────────────────────────────────────
|
|
198
|
+
* Signed in as `curtwphillips@gmail.com` on the auth admin page, he tried to
|
|
199
|
+
* grant another account access to family and was refused: *"The app let me stay
|
|
200
|
+
* for curtwphillips@gmail.com but the request treated me as a different user. I
|
|
201
|
+
* was allowed to keep using the UI for auth manage users area."*
|
|
202
|
+
*
|
|
203
|
+
* That is the slot mechanism working exactly as designed and producing a lie.
|
|
204
|
+
* The cookie jar is per-ORIGIN, so a slot's occupant can be replaced by ANOTHER
|
|
205
|
+
* TAB — sign a second account in, sign one out, let one expire — while the first
|
|
206
|
+
* tab is still showing a page it rendered minutes ago for whoever used to be
|
|
207
|
+
* there. Nothing tells the open tab. It keeps drawing the old name in the header,
|
|
208
|
+
* its reads answer as the new person, and its writes are refused by a rule the
|
|
209
|
+
* screen says does not apply. The owner-gated route answers `403` with an EMPTY
|
|
210
|
+
* body by design (it must not tell a non-owner who the owner is), so the console
|
|
211
|
+
* looked authorized and said nothing at all.
|
|
212
|
+
*
|
|
213
|
+
* 🔴 The tab CANNOT detect this on its own. Session cookies are `HttpOnly`, and
|
|
214
|
+
* slot 0 — where the eviction is most likely, because it is the slot every
|
|
215
|
+
* ordinary sign-in takes — installs no client machinery at all.
|
|
216
|
+
*
|
|
217
|
+
* ── The fix: state the expectation, and let the server answer it ────────────
|
|
218
|
+
* The page knows exactly one thing the server does not: WHO IT RENDERED FOR. So
|
|
219
|
+
* it says so on every request, and the server compares. This is an `If-Match` on
|
|
220
|
+
* identity, and it gets `If-Match`'s status — **409 Conflict**: the request is
|
|
221
|
+
* well-formed and the credential is valid, but it conflicts with the current
|
|
222
|
+
* state of the browser's session. Never 401 (the person is signed in) and never
|
|
223
|
+
* 403 (they are not forbidden — they are somebody else now).
|
|
224
|
+
*
|
|
225
|
+
* The header is a HINT in exactly the sense the slot is: it can only ever make a
|
|
226
|
+
* request FAIL. A forged or stale value costs the sender their own request, and
|
|
227
|
+
* nothing downstream may read it as identity — the user is still resolved from
|
|
228
|
+
* the cookie, always, and the comparison happens after.
|
|
229
|
+
*/
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The account id the CLIENT believes it is acting as — the one it drew on
|
|
233
|
+
* screen. Attached by the patched `fetch` in `accountSlot.client.ts`.
|
|
234
|
+
*
|
|
235
|
+
* 🔴 Never an authorization. It cannot widen access, name a different account
|
|
236
|
+
* or select a cookie; the only outcome it can produce that the request would
|
|
237
|
+
* not otherwise have had is {@link ACCOUNT_DRIFT_STATUS}.
|
|
238
|
+
*/
|
|
239
|
+
export const ACCOUNT_USER_HEADER = "x-account-user";
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* 409 Conflict — the credential is good, the identity behind it moved.
|
|
243
|
+
*
|
|
244
|
+
* Deliberately not 401 (which the SPAs answer by bouncing to a sign-in hop, and
|
|
245
|
+
* there is nothing to sign in to — the browser holds a perfectly good session)
|
|
246
|
+
* and not 403 (which reads as "you may not", and is the answer that produced
|
|
247
|
+
* the silent failure this exists to stop).
|
|
248
|
+
*/
|
|
249
|
+
export const ACCOUNT_DRIFT_STATUS = 409;
|
|
250
|
+
|
|
251
|
+
/** The machine-readable `error` a drift refusal carries, so a client can tell it
|
|
252
|
+
* apart from every other 409 an app already answers (a full slot jar, a name
|
|
253
|
+
* collision, an edit conflict). */
|
|
254
|
+
export const ACCOUNT_DRIFT_CODE = "account_changed";
|
|
255
|
+
|
|
256
|
+
/** Who a drift refusal says you actually are now. Addresses and names only —
|
|
257
|
+
* the same facts `/api/auth/session` already hands this browser about a slot
|
|
258
|
+
* it is holding, so this publishes nothing new. */
|
|
259
|
+
export interface AccountDriftActual {
|
|
260
|
+
id: string;
|
|
261
|
+
email: string;
|
|
262
|
+
name: string;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** The canonical drift body. One shape, so every consumer and the accounts app
|
|
266
|
+
* itself cannot answer this in two dialects. */
|
|
267
|
+
export interface AccountDriftBody {
|
|
268
|
+
error: typeof ACCOUNT_DRIFT_CODE;
|
|
269
|
+
/** Who the CLIENT said it was rendering for, echoed back so a banner can name
|
|
270
|
+
* both sides without having to have kept its own copy. */
|
|
271
|
+
expected: string;
|
|
272
|
+
actual: AccountDriftActual;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function accountDriftBody(expected: string, actual: AccountDriftActual): AccountDriftBody {
|
|
276
|
+
return { error: ACCOUNT_DRIFT_CODE, expected, actual };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** `true` for a body that is a drift refusal. Total — anything at all may be
|
|
280
|
+
* passed in, because this is called on a parsed response body. */
|
|
281
|
+
export function isAccountDriftBody(body: unknown): body is AccountDriftBody {
|
|
282
|
+
if (typeof body !== "object" || body === null) return false;
|
|
283
|
+
const b = body as Record<string, unknown>;
|
|
284
|
+
return (
|
|
285
|
+
b.error === ACCOUNT_DRIFT_CODE &&
|
|
286
|
+
typeof b.expected === "string" &&
|
|
287
|
+
typeof b.actual === "object" &&
|
|
288
|
+
b.actual !== null &&
|
|
289
|
+
typeof (b.actual as Record<string, unknown>).id === "string"
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* The one rule, so the client's guess and the server's verdict cannot disagree.
|
|
295
|
+
*
|
|
296
|
+
* Drift is only ever declared when BOTH sides are known and they differ. An
|
|
297
|
+
* absent expectation (an old build, a subresource, a non-`fetch` caller, an app
|
|
298
|
+
* that never mounted the client module) is NOT drift — the guard has to be
|
|
299
|
+
* additive or it would start refusing requests the fleet has always allowed.
|
|
300
|
+
*/
|
|
301
|
+
export function isAccountDrift(expected: string | null, actual: string | null): boolean {
|
|
302
|
+
return (
|
|
303
|
+
expected !== null && expected !== "" && actual !== null && actual !== "" && expected !== actual
|
|
304
|
+
);
|
|
305
|
+
}
|