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,366 @@
1
+ /**
2
+ * Who is on the other end of a request, described the way a person would
3
+ * describe it: what device, what browser, from where.
4
+ *
5
+ * ── Why it is here and not in `apps/auth` (2026-08-12) ──────────────────────
6
+ * It WAS in `apps/auth/src/server/notifications.ts`, whose header said, in as
7
+ * many words: *"It lives in this app rather than in a shared package because
8
+ * auth is its only consumer — the moment a second app needs it, it moves rather
9
+ * than being copied."* The session list is that second consumer, and it is not
10
+ * in auth: `userSessions.ts` stamps a device and an address onto every session
11
+ * row in every satellite, so the describer has to sit at or below the kit.
12
+ *
13
+ * cwip/cursedbelt would be the home the moment something that is NOT a
14
+ * satellite needs it. Today every consumer is one — the kit's own session store
15
+ * and the accounts app that reads it — and the kit is the lowest layer that
16
+ * both can see.
17
+ *
18
+ * ── The facts became STRUCTURED (2026-08-25, owner) ─────────────────────────
19
+ * The owner's ask: *"in the emails cursedalchemy sends about login attempts I
20
+ * want to be able to tell it was me more confidently — by seeing it was the
21
+ * expected type of device, like a Mac, the expected browser like Chrome, at the
22
+ * right city."* You cannot answer "is this my usual browser?" from the sentence
23
+ * `"Chrome on macOS · 73.12.44.9 · US"`, because comparing sentences compares
24
+ * the address too and every sentence is then new. So the single string became
25
+ * `ClientFacts` — one FIELD per thing a person recognises separately (browser,
26
+ * platform, city, region, country, network) — and the sentence became a
27
+ * rendering of it. `apps/auth/src/server/familiarity.ts` is the consumer that
28
+ * needed the split, and every stored row now carries the fields as well as the
29
+ * sentence.
30
+ *
31
+ * 🔴 **Nothing here authorizes anything.** Every value is attacker-influenced
32
+ * (a user-agent is whatever the client typed; the leftmost `x-forwarded-for`
33
+ * entry is client-supplied on any proxy that appends rather than replaces; the
34
+ * `cf-*` headers are Cloudflare's only for traffic that actually came through
35
+ * Cloudflare, and a request that reached an origin directly can send whatever
36
+ * it likes). They are shown to the account's OWN owner as a hint for
37
+ * recognising their own devices. "Possibly spoofed" is an acceptable property
38
+ * for that and would not be for anything else — in particular, a recognised
39
+ * device must never relax a check, only reassure a reader.
40
+ */
41
+
42
+ /** A request described the way a person would describe it: what and from where. */
43
+ export interface ClientDescription {
44
+ ip: string;
45
+ device: string;
46
+ }
47
+
48
+ /** How much of a user-agent is worth keeping. Long enough for the non-browser
49
+ * clients (curl, a smoke, a script) to still be identifiable, short enough
50
+ * that a hostile 8KB header cannot be stored per session row. */
51
+ export const MAX_USER_AGENT_BYTES = 200;
52
+
53
+ /** How much of any single client-supplied fact is stored. A city name is short;
54
+ * a header claiming to be one is whatever the sender typed. */
55
+ const MAX_FACT_BYTES = 64;
56
+
57
+ /**
58
+ * The shape of the thing on the other end, split so each half can be RECOGNISED
59
+ * on its own.
60
+ *
61
+ * `browser` and `platform` are separate fields rather than one label because
62
+ * they change independently and mean different things to the reader: a new
63
+ * browser on your usual Mac is a browser you installed, and your usual browser
64
+ * on a platform you have never used is somebody else.
65
+ */
66
+ export interface DeviceParts {
67
+ /** "Chrome", "Safari", … or "" when the client is not a known browser. */
68
+ browser: string;
69
+ /** "macOS", "iPhone", "Windows", … or "" when nothing said. */
70
+ platform: string;
71
+ /** What KIND of thing it is, for the one-word answer. */
72
+ form: "phone" | "tablet" | "computer" | "bot" | "unknown";
73
+ }
74
+
75
+ /**
76
+ * Where the request came from, as far as the edge could tell.
77
+ *
78
+ * 🔴 Every field can be empty, and empty means NOT KNOWN rather than "nowhere".
79
+ * `country` arrives on every Cloudflare-proxied request for free; the rest
80
+ * (`city`, `region`, `postalCode`, `timezone`, `continent`) only arrive when
81
+ * the zone's *Add visitor location headers* managed transform is on, or when a
82
+ * caller supplies an origin-side lookup — see `clientFactsOf`. A renderer must
83
+ * therefore degrade by dropping fields, never by printing "unknown, unknown".
84
+ */
85
+ export interface ClientPlace {
86
+ /** ISO-3166 alpha-2, e.g. "US". */
87
+ country: string;
88
+ /** "Texas", "England", … */
89
+ region: string;
90
+ /** "Austin", "London", … */
91
+ city: string;
92
+ postalCode: string;
93
+ /** IANA name, e.g. "America/Chicago". */
94
+ timezone: string;
95
+ /** "NA", "EU", … */
96
+ continent: string;
97
+ }
98
+
99
+ /** Everything one request says about its client, in the shape it is STORED. */
100
+ export interface ClientFacts extends DeviceParts, ClientPlace {
101
+ /** The caller's address, or "" when nothing said. */
102
+ ip: string;
103
+ /**
104
+ * The address with its host part dropped — `73.12.44.x`, `2600:1700:a1::x`.
105
+ *
106
+ * This, not `ip`, is what "the network you usually sign in from" compares:
107
+ * a home connection changes its address on a lease renewal and its /24
108
+ * almost never, so comparing addresses would mark half the owner's own
109
+ * sign-ins as new and train him to ignore the flag.
110
+ */
111
+ network: string;
112
+ /** Verbatim, bounded, never parsed after this point. */
113
+ userAgent: string;
114
+ /** `browser` + `platform` as one phrase — "Chrome on macOS". */
115
+ device: string;
116
+ }
117
+
118
+ /** Control characters, which a header must never carry into a log line, a
119
+ * database row or a mail body. */
120
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: stripping them from a client-supplied header is exactly the point.
121
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/g;
122
+
123
+ /** A trimmed, bounded, control-character-free copy of a client-supplied value. */
124
+ const fact = (value: string | null | undefined): string =>
125
+ (value ?? "").replace(CONTROL_CHARACTERS, "").trim().slice(0, MAX_FACT_BYTES);
126
+
127
+ /**
128
+ * A header Cloudflare percent-encodes when the value is not ASCII (a city like
129
+ * `Zürich` arrives as `Z%C3%BCrich`). Decoded when it decodes, kept verbatim
130
+ * when it does not — a malformed escape is a value, not an exception.
131
+ */
132
+ function decodedFact(value: string | null | undefined): string {
133
+ const raw = fact(value);
134
+ if (!raw.includes("%")) return raw;
135
+ try {
136
+ return fact(decodeURIComponent(raw));
137
+ } catch {
138
+ return raw;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Enough of a user-agent to recognize your own laptop, and no more.
144
+ *
145
+ * Deliberately not a UA-parsing library and deliberately not exhaustive: these
146
+ * values exist so the owner can tell "my Mac" from "something else", and a
147
+ * wrong guess between two Chromium forks costs nothing.
148
+ */
149
+ export function deviceParts(userAgent: string | null | undefined): DeviceParts {
150
+ const ua = (userAgent ?? "").trim();
151
+ if (!ua) return { browser: "", platform: "", form: "unknown" };
152
+ const browser = /\bEdg\//.test(ua)
153
+ ? "Edge"
154
+ : /\bOPR\//.test(ua)
155
+ ? "Opera"
156
+ : /\bFirefox\//.test(ua)
157
+ ? "Firefox"
158
+ : /\bChrome\//.test(ua)
159
+ ? "Chrome"
160
+ : // Safari LAST: every Chromium UA also claims to be Safari.
161
+ /\bSafari\//.test(ua)
162
+ ? "Safari"
163
+ : "";
164
+ const platform = /\biPhone\b/.test(ua)
165
+ ? "iPhone"
166
+ : /\biPad\b/.test(ua)
167
+ ? "iPad"
168
+ : /\bAndroid\b/.test(ua)
169
+ ? "Android"
170
+ : /\bMac OS X\b|\bMacintosh\b/.test(ua)
171
+ ? "macOS"
172
+ : /\bWindows\b/.test(ua)
173
+ ? "Windows"
174
+ : /\bLinux\b/.test(ua)
175
+ ? "Linux"
176
+ : "";
177
+ // A crawler that says so is worth naming: it is the single most common
178
+ // non-person on a public satellite, and reading "an unknown device" for it
179
+ // costs the reader the one glance that would have explained the row.
180
+ const robot = /\bbot\b|crawler|spider|curl\/|wget\/|python-requests|Bun\//i.test(ua);
181
+ const form: DeviceParts["form"] = robot
182
+ ? "bot"
183
+ : platform === "iPhone" || (platform === "Android" && /\bMobile\b/.test(ua))
184
+ ? "phone"
185
+ : platform === "iPad"
186
+ ? "tablet"
187
+ : platform
188
+ ? "computer"
189
+ : "unknown";
190
+ return { browser, platform, form };
191
+ }
192
+
193
+ /** `browser` and `platform` as the phrase a person would say. */
194
+ export function describeDeviceParts(parts: DeviceParts, fallback = ""): string {
195
+ if (parts.browser && parts.platform) return `${parts.browser} on ${parts.platform}`;
196
+ if (parts.browser) return parts.browser;
197
+ if (parts.platform) return parts.platform;
198
+ // A non-browser client (curl, a smoke, a script) — say so plainly rather
199
+ // than dressing it up as a device.
200
+ return fallback.slice(0, 60) || "an unknown device";
201
+ }
202
+
203
+ /** Enough of a user-agent to recognize your own laptop, as one phrase. */
204
+ export function describeDevice(userAgent: string | null | undefined): string {
205
+ const ua = (userAgent ?? "").trim();
206
+ if (!ua) return "an unknown device";
207
+ return describeDeviceParts(deviceParts(ua), ua);
208
+ }
209
+
210
+ /**
211
+ * Where Cloudflare says the request came from.
212
+ *
213
+ * `cf-ipcountry` is sent on every proxied request by default. The rest require
214
+ * the zone's *Add visitor location headers* managed transform; until it is on
215
+ * they are simply absent, which is why every field is independently optional
216
+ * and why `clientFactsOf` takes an origin-side lookup as the second source.
217
+ */
218
+ export function clientPlaceOf(request: Request | undefined): ClientPlace {
219
+ const header = (name: string) => request?.headers.get(name);
220
+ return {
221
+ // A country is two letters and a continent is two; bounded far tighter
222
+ // than a place name, because a 64-character "country" in a row or a mail
223
+ // body is nothing but a sender's padding.
224
+ country: fact(header("cf-ipcountry")).slice(0, 8).toUpperCase(),
225
+ region: decodedFact(header("cf-region")),
226
+ city: decodedFact(header("cf-ipcity")),
227
+ postalCode: fact(header("cf-postal-code")),
228
+ timezone: fact(header("cf-timezone")),
229
+ continent: fact(header("cf-ipcontinent")).slice(0, 4).toUpperCase(),
230
+ };
231
+ }
232
+
233
+ /** An empty place — the honest answer for a request nothing is known about. */
234
+ export const UNKNOWN_PLACE: ClientPlace = {
235
+ country: "",
236
+ region: "",
237
+ city: "",
238
+ postalCode: "",
239
+ timezone: "",
240
+ continent: "",
241
+ };
242
+
243
+ /** Is anything at all known about where this came from? */
244
+ export const placeIsKnown = (place: ClientPlace): boolean =>
245
+ Boolean(place.city || place.region || place.country);
246
+
247
+ /**
248
+ * A place as a person would name it — "Austin, Texas, US".
249
+ *
250
+ * Degrades by dropping fields rather than by printing placeholders: a request
251
+ * we only have a country for reads "US", and one we know nothing about reads
252
+ * "" so the caller can choose its own words for absence.
253
+ */
254
+ export function describePlace(place: ClientPlace): string {
255
+ // `ZZ` is the dataset's "no country" marker and what Cloudflare sends for a
256
+ // client it cannot place; printing it would be printing a bug.
257
+ const country = place.country === "ZZ" || place.country === "XX" ? "" : place.country;
258
+ // A region that repeats the city ("Singapore, Singapore") is noise.
259
+ const region =
260
+ place.region && place.region.toLowerCase() !== place.city.toLowerCase() ? place.region : "";
261
+ return [place.city, region, country].filter(Boolean).join(", ");
262
+ }
263
+
264
+ /**
265
+ * The caller's address as far as this box can tell, or `""` when nothing said.
266
+ *
267
+ * `x-forwarded-for` is the FIRST hop, because nginx appends and a client may
268
+ * send its own header — so the leftmost entry is attacker-controlled but is
269
+ * also the only one that means anything on a correctly-configured proxy.
270
+ *
271
+ * Empty string rather than a phrase, because this is the STORAGE shape: a row
272
+ * that says nothing must be distinguishable from one that says "unknown", and
273
+ * only the rendering half should be choosing English. `describeClient` is the
274
+ * rendering half.
275
+ */
276
+ export function clientAddressOf(request: Request): string {
277
+ const forwarded = request.headers.get("x-forwarded-for") ?? "";
278
+ const first = (forwarded.split(",")[0] ?? "").trim();
279
+ const ip = first || request.headers.get("cf-connecting-ip") || "";
280
+ // Bounded for the same reason the user-agent is: it lands in a database row
281
+ // and a header is whatever the client sent.
282
+ return ip.slice(0, 60);
283
+ }
284
+
285
+ /**
286
+ * The address with its host part dropped — the unit "my usual network" is
287
+ * measured in. See `ClientFacts.network` for why an exact address is the wrong
288
+ * comparison.
289
+ *
290
+ * IPv4 keeps three octets (/24); IPv6 keeps three hextets (/48), which is the
291
+ * smallest block a residential customer is normally delegated whole.
292
+ */
293
+ export function ipNetworkOf(ip: string): string {
294
+ const address = (ip ?? "").trim();
295
+ if (!address) return "";
296
+ if (address.includes(":")) {
297
+ const hextets = address.split(":");
298
+ // `::` collapses zero groups, so a short address is already its own
299
+ // prefix — expanding it here would invent digits the client never sent.
300
+ const kept = hextets.slice(0, 3).filter((part) => part !== "");
301
+ return kept.length ? `${kept.join(":")}::x` : address;
302
+ }
303
+ const octets = address.split(".");
304
+ if (octets.length !== 4) return address;
305
+ return `${octets.slice(0, 3).join(".")}.x`;
306
+ }
307
+
308
+ /**
309
+ * An origin-side answer to "where is this address", for the fields Cloudflare
310
+ * only sends when the managed transform is on. See `ipGeo.ts`.
311
+ */
312
+ export type PlaceLookup = (ip: string) => ClientPlace | null;
313
+
314
+ /**
315
+ * Everything one request says about its client.
316
+ *
317
+ * 🔴 The edge WINS over the lookup, field by field. Cloudflare places the
318
+ * address it actually terminated the connection from, against data it refreshes
319
+ * continuously; a local table is a monthly snapshot of somebody else's
320
+ * measurement. Merging per-field rather than choosing one source whole is what
321
+ * lets a zone with only `cf-ipcountry` still get a city.
322
+ */
323
+ export function clientFactsOf(
324
+ request: Request | undefined,
325
+ options: { lookup?: PlaceLookup } = {},
326
+ ): ClientFacts {
327
+ const ip = request ? clientAddressOf(request) : "";
328
+ const userAgent = request ? clientUserAgentOf(request) : "";
329
+ const parts = deviceParts(userAgent);
330
+ const edge = clientPlaceOf(request);
331
+ const local = ip && options.lookup ? (options.lookup(ip) ?? UNKNOWN_PLACE) : UNKNOWN_PLACE;
332
+ const place: ClientPlace = {
333
+ country: edge.country || local.country,
334
+ region: edge.region || local.region,
335
+ city: edge.city || local.city,
336
+ postalCode: edge.postalCode || local.postalCode,
337
+ timezone: edge.timezone || local.timezone,
338
+ continent: edge.continent || local.continent,
339
+ };
340
+ return {
341
+ ip,
342
+ network: ipNetworkOf(ip),
343
+ userAgent,
344
+ device: describeDeviceParts(parts, userAgent),
345
+ ...parts,
346
+ ...place,
347
+ };
348
+ }
349
+
350
+ /** The whole client as one sentence — address, place, device. */
351
+ export function describeClientFacts(facts: ClientFacts): string {
352
+ const place = describePlace(facts);
353
+ return [facts.ip || "an unknown address", place, facts.device].filter(Boolean).join(" · ");
354
+ }
355
+
356
+ /** The user-agent as it should be STORED — verbatim, bounded, never parsed. */
357
+ export const clientUserAgentOf = (request: Request): string =>
358
+ (request.headers.get("user-agent") ?? "").slice(0, MAX_USER_AGENT_BYTES);
359
+
360
+ /** Both halves, rendered for a human. */
361
+ export function describeClient(request: Request): ClientDescription {
362
+ return {
363
+ ip: clientAddressOf(request) || "an unknown address",
364
+ device: describeDevice(request.headers.get("user-agent")),
365
+ };
366
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Comparing two secrets without leaking how far the comparison got.
3
+ *
4
+ * ## Why this module exists (2026-08-07)
5
+ *
6
+ * There were **two** implementations of this in the platform this was cut from — one in
7
+ * `ownerAuth.server.ts` (node `timingSafeEqual`, padding both sides to a common
8
+ * length) and one in the roms<->hobbies bridge, deleted 2026-08-25 (a pure-JS accumulator). Both were
9
+ * correct; neither knew about the other. Adding roms' manifest-sync token would
10
+ * have made three, and three copies of a primitive whose failure mode is
11
+ * *silent* — a version that returns early still passes every functional test and
12
+ * is simply a timing oracle — is how the fleet ends up with one good one and two
13
+ * that quietly rotted.
14
+ *
15
+ * ## Why the pure-JS form is canonical rather than `crypto.timingSafeEqual`
16
+ *
17
+ * `timingSafeEqual` **throws** on unequal lengths, so every caller has to
18
+ * remember to pad first — and a caller that forgets has converted a comparison
19
+ * into an exception whose presence is itself the oracle. This form has no such
20
+ * trap: the length difference is folded into the accumulator, the loop always
21
+ * runs the longer of the two, and there is no input that makes it exit early. It
22
+ * also carries no node-builtin dependency, so the contract modules that both a
23
+ * server and a browser bundle can reach may use it.
24
+ */
25
+
26
+ /**
27
+ * True when `a` and `b` are the same string, in time that does not depend on
28
+ * where they first differ.
29
+ *
30
+ * Note the honest limit, so nobody expects more than it gives: the *lengths* are
31
+ * still observable through the loop count. That is fine for the things this is
32
+ * used on — tokens and signatures of fixed length — and no constant-time compare
33
+ * of variable-length inputs can do better without hashing first.
34
+ */
35
+ export function constantTimeEqual(a: string, b: string): boolean {
36
+ const encoder = new TextEncoder();
37
+ const ab = encoder.encode(a);
38
+ const bb = encoder.encode(b);
39
+ // Fold the length difference INTO the accumulator instead of early-returning,
40
+ // so a wrong-length token is not distinguishable by timing from a wrong one.
41
+ let diff = ab.length ^ bb.length;
42
+ const len = Math.max(ab.length, bb.length);
43
+ for (let i = 0; i < len; i++) diff |= (ab[i] ?? 0) ^ (bb[i] ?? 0);
44
+ return diff === 0;
45
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The consumer side of the content census — how an app answers "what has this
3
+ * account made in you?" without hand-writing a counting loop per satellite.
4
+ *
5
+ * ── Why a helper and not five lines per app ─────────────────────────────────
6
+ * Every implementation is the same shape: a list of tables keyed on the auth
7
+ * user id, one `COUNT(*)` each. Five apps hand-writing that means five places
8
+ * to interpolate a table name into SQL, five places to forget that a table is
9
+ * created lazily and does not exist in a fresh database, and five chances for
10
+ * one of them to return a row for an account it was not asked about. Each of
11
+ * those failures produces a NUMBER on the owner's confirmation dialog, and a
12
+ * wrong number there is worse than no number — it is the one they act on.
13
+ *
14
+ * So the counting lives here, once:
15
+ * • table and column names are validated as bare identifiers before they can
16
+ * reach a query string (they cannot be bound as parameters);
17
+ * • a table that does not exist yet counts as zero rather than throwing,
18
+ * because an app whose owner has never used a feature genuinely has none;
19
+ * • only the ids that were asked about come back.
20
+ *
21
+ * @see `ssoConsumer.server.ts` for the route, and `sso.ts` for the ticket.
22
+ */
23
+ import type { Database } from "bun:sqlite";
24
+ import type { ContentCensus, ContentCensusUser } from "./sso";
25
+
26
+ /** One kind of thing an app keeps per account. */
27
+ export interface CensusCounter {
28
+ /** Stable machine id — `save-states`. Never shown to anybody. */
29
+ kind: string;
30
+ /** How the owner should read it, PLURAL and lowercase: "save states". It is
31
+ * rendered as "34 save states", so a singular label reads as a bug. */
32
+ label: string;
33
+ /** The table holding one row per thing. */
34
+ table: string;
35
+ /** The column carrying the auth user id. Defaults to `user_id`. */
36
+ column?: string;
37
+ /** Extra SQL predicate, ANDed in — e.g. excluding soft-deleted rows. Written
38
+ * by the app, never by a request; no value from the wire reaches it. */
39
+ where?: string;
40
+ }
41
+
42
+ /** Bare identifiers only. A table name cannot be a bound parameter, so this is
43
+ * the gate that keeps one from being anything but a name. */
44
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
45
+
46
+ const tableExists = (db: Database, table: string): boolean =>
47
+ (db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table) ?? null) !==
48
+ null;
49
+
50
+ /**
51
+ * Build a `contentCensus` implementation from a list of tables.
52
+ *
53
+ * Counts only — the census is entitled to how MANY rows an account has, never
54
+ * to what they say. Pass it straight to `createSsoConsumer({ contentCensus })`.
55
+ */
56
+ export function countingCensus(
57
+ db: Database,
58
+ counters: readonly CensusCounter[],
59
+ options: { note?: string } = {},
60
+ ): (userIds: string[]) => ContentCensus {
61
+ for (const counter of counters) {
62
+ // Thrown at CONSTRUCTION, not per request: a bad identifier is a typo in
63
+ // this app's own source, and it should stop the app from booting rather
64
+ // than surface as a mysterious 500 the first time the owner opens a
65
+ // confirmation dialog.
66
+ if (!IDENTIFIER.test(counter.table)) {
67
+ throw new Error(`census counter "${counter.kind}": ${counter.table} is not a table name`);
68
+ }
69
+ if (counter.column !== undefined && !IDENTIFIER.test(counter.column)) {
70
+ throw new Error(`census counter "${counter.kind}": ${counter.column} is not a column name`);
71
+ }
72
+ }
73
+
74
+ return (userIds) => {
75
+ const users: ContentCensusUser[] = [];
76
+ for (const userId of userIds) {
77
+ const items: ContentCensusUser["items"] = [];
78
+ for (const counter of counters) {
79
+ if (!tableExists(db, counter.table)) continue;
80
+ const column = counter.column ?? "user_id";
81
+ const row = db
82
+ .query(
83
+ `SELECT COUNT(*) AS n FROM ${counter.table} WHERE ${column} = ?${
84
+ counter.where ? ` AND (${counter.where})` : ""
85
+ }`,
86
+ )
87
+ .get(userId) as { n?: number } | null;
88
+ const count = typeof row?.n === "number" ? row.n : 0;
89
+ if (count > 0) items.push({ kind: counter.kind, label: counter.label, count });
90
+ }
91
+ users.push({ userId, items, total: items.reduce((sum, item) => sum + item.count, 0) });
92
+ }
93
+ return { scope: "per-user", users, ...(options.note ? { note: options.note } : {}) };
94
+ };
95
+ }
96
+
97
+ /**
98
+ * The answer for an app whose data belongs to NOBODY in particular — one shared
99
+ * corpus, library or tree.
100
+ *
101
+ * It is a real answer, not a shrug, and saying it explicitly is the whole point:
102
+ * "nothing here is attributed to an individual account" tells the owner that
103
+ * closing the app costs the person their access and nothing else, where silence
104
+ * would read as "could not find out" and stall the decision.
105
+ */
106
+ export const sharedCensus = (note: string) => (): ContentCensus => ({ scope: "shared", note });
package/src/index.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * cursedauth — the server half of "sign in through the accounts app".
3
+ *
4
+ * This barrel is SERVER-ONLY: it reaches `bun:sqlite` transitively, so a browser
5
+ * bundle that imports it pulls a database driver into the client graph. The
6
+ * browser halves have their own subpaths and no server import between them:
7
+ *
8
+ * cursedauth/auth React hooks + `startSsoSignIn`
9
+ * cursedauth/account-ui the account menu
10
+ * cursedauth/account-slot-client multi-account slot switching in the browser
11
+ *
12
+ * 🔴 What this package is NOT. It is the app's side of SSO — the consumer. It
13
+ * never holds a password, never mints a grant, and has no user table of its own
14
+ * beyond a local snapshot of whoever has signed in here. The identity provider
15
+ * is a separate service reached over HTTPS at `authUrl`; this package's only
16
+ * knowledge of it is that URL and its public key.
17
+ */
18
+ export {
19
+ createSsoConsumer,
20
+ resolveSsoAudience,
21
+ sanitizeReturnPath,
22
+ SSO_CALLBACK_PATH,
23
+ SSO_CENSUS_PATH,
24
+ SSO_RETURN_COOKIE,
25
+ SSO_REVOKE_PATH,
26
+ SSO_SESSIONS_PATH,
27
+ SSO_SIGNOUT_PATH,
28
+ SSO_SLOT_COOKIE,
29
+ SSO_START_PATH,
30
+ type SsoConsumer,
31
+ type SsoConsumerOptions,
32
+ type SsoUser,
33
+ } from "./ssoConsumer.server";
34
+ export {
35
+ createUserSessionStore,
36
+ type SessionRecord,
37
+ type SignedIn,
38
+ type SignInOptions,
39
+ type SlotOccupant,
40
+ type UserSessionStore,
41
+ type UserSessionStoreOptions,
42
+ } from "./userSessions";
43
+ export {
44
+ DEFAULT_GATE_PATH,
45
+ type GatedMountPlan,
46
+ gatedMountReport,
47
+ type Mounter,
48
+ mountGatedApp,
49
+ type SessionGate,
50
+ } from "./mountGatedApp";
51
+ export { type CensusCounter, countingCensus, sharedCensus } from "./contentCensus";
52
+ export {
53
+ LOCAL_AUTH_URL,
54
+ STAGE_IDENTITY_ENV,
55
+ stageIdentityIsLocal,
56
+ } from "./stageIdentity";
57
+ export type { ContentCensus, ContentCensusUser } from "./sso";
58
+ export { getSessionClaims, SESSION_CLAIMS_KEY, type SessionClaims } from "./auth.server";