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
package/dist/auth.js ADDED
@@ -0,0 +1,310 @@
1
+ // ── The satellite auth boundary (client half) ────────────────────────────────────────
2
+ //
3
+ // This file and its server twin (`auth.server.ts`) are the ONLY places that know how a
4
+ // satellite authenticates. Application code codes against `useSatelliteAuth()` and never
5
+ // learns which adapter is underneath — so adopting real auth is an adapter swap, not an
6
+ // app rewrite.
7
+ //
8
+ // FORWARD PATH — what replaces each member when real auth is adopted (cc has shipped all
9
+ // of this; see the repo CLAUDE.md and the build spec §12 for the full flip procedure):
10
+ //
11
+ // client adapter `createCcSessionStore` + `CCSessionProvider` + `createAccountClient`,
12
+ // all exported from `cursedbelt/react`. The session store MUST live at
13
+ // module scope and be read through `token()` per request — a token held
14
+ // in React state hands the client a stale closure (a documented cc
15
+ // footgun). That is why `token()` is a function on this interface and
16
+ // not a string field.
17
+ // server middleware cc's guard mixin routes: pass the satellite's EXISTING Hono app to
18
+ // `composeServer({ app, ctx, services })` from
19
+ // `cursedbelt/src/server/mixins`, with `createLocalGuardServices`
20
+ // from `cursedbelt/src/server/runtime/localHost.ts`.
21
+ // user provisioning INVITATION-GATED SIGNUP ONLY — `AccountService.inviteMember` →
22
+ // `POST /api/guard/invitations/accept`, invite token in the
23
+ // `x-cc-invitation` header. Never enable open signup.
24
+ // password reset `POST /api/guard/accounts/:id/password`
25
+ //
26
+ // At that point `@node-rs/argon2` becomes a real dependency, and the app's identity lives
27
+ // in its OWN `<dataRoot>/registry.db` — never the machine-wide `cc-registry.db`.
28
+ //
29
+ // FORBIDDEN, now and then: `cursedbelt/react`'s `AuthGate` and `sessionAuth`, and
30
+ // app-generator's `auth-login*.ts` / `bin/invite.ts`. Those are cc's legacy scaffold,
31
+ // disclosed debt, slated for deletion — never extend them.
32
+ //
33
+ // NOTE: `fractals` has no auth surface of any kind and must never import this module.
34
+ // The boundary exists for `roms`, the private satellite.
35
+ import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useRef, useState, } from "react";
36
+ import { isProductionRuntime } from "./runtimeMode";
37
+ import { clearSsoAutoState, decideSsoAutoSignIn, lastSsoAttemptAt, ssoErrorFromLocation, ssoSignedOutHere, startSsoSignIn, startSsoSignOut, } from "./ssoAutoSignIn";
38
+ // Re-exported through THIS subpath on purpose: `cursedauth/auth`
39
+ // is already the one client-side auth import every satellite has, and a second
40
+ // entry point for five lines of the same boundary is how two conventions start.
41
+ export { clearSsoAutoState, decideSsoAutoSignIn, lastSsoAttemptAt, markSsoSignedOut, SSO_ATTEMPT_COOLDOWN_MS, SSO_SIGNOUT_PATH, SSO_START_PATH, ssoErrorFromLocation, ssoSignedOutHere, startSsoSignIn, startSsoSignOut, suppressSsoAutoSignIn, takeSsoError, useSsoAutoSignIn, useSsoErrorNotice, } from "./ssoAutoSignIn";
42
+ const SatelliteAuthContext = createContext(null);
43
+ export function SatelliteAuthProvider({ adapter, children }) {
44
+ const auth = adapter.useSession();
45
+ return createElement(SatelliteAuthContext.Provider, { value: auth }, children);
46
+ }
47
+ export function useSatelliteAuth() {
48
+ const auth = useContext(SatelliteAuthContext);
49
+ if (!auth) {
50
+ throw new Error("useSatelliteAuth() was called outside <SatelliteAuthProvider>. Wrap the app in a " +
51
+ "provider and give it an adapter.");
52
+ }
53
+ return auth;
54
+ }
55
+ /** The principal a password-only app is signed in AS. There is exactly one. */
56
+ export const OWNER_USER = { id: "owner", email: "", displayName: "Owner" };
57
+ export function createOwnerPasswordAdapter(options = {}) {
58
+ const base = options.basePath ?? "/api/auth";
59
+ const http = options.fetchImpl ?? fetch;
60
+ return {
61
+ id: "owner-password",
62
+ credential: "password",
63
+ useSession() {
64
+ const [status, setStatus] = useState("loading");
65
+ // One probe on mount. `useEffect` rather than a render-time fetch so a
66
+ // double render (StrictMode) cannot fire two logins-worth of requests.
67
+ useEffect(() => {
68
+ let cancelled = false;
69
+ void (async () => {
70
+ try {
71
+ const res = await http(`${base}/session`, { credentials: "same-origin" });
72
+ const body = (await res.json());
73
+ if (!cancelled)
74
+ setStatus(body?.authenticated ? "authenticated" : "anonymous");
75
+ }
76
+ catch {
77
+ // A failed probe is not a session. Treating an unreachable server as
78
+ // "anonymous" shows the sign-in form, which is both the safe default
79
+ // and the screen from which the owner can retry.
80
+ if (!cancelled)
81
+ setStatus("anonymous");
82
+ }
83
+ })();
84
+ return () => {
85
+ cancelled = true;
86
+ };
87
+ // `base` and `http` are fixed when the adapter is constructed, so this
88
+ // runs exactly once per mount — which is the intent: one session probe,
89
+ // not one per render.
90
+ }, [base, http]);
91
+ const signIn = useCallback(async (_email, password) => {
92
+ const res = await http(`${base}/login`, {
93
+ method: "POST",
94
+ credentials: "same-origin",
95
+ headers: { "content-type": "application/json" },
96
+ body: JSON.stringify({ password }),
97
+ });
98
+ if (!res.ok) {
99
+ const body = (await res.json().catch(() => null));
100
+ throw new Error(body?.error ?? "Could not sign in");
101
+ }
102
+ setStatus("authenticated");
103
+ }, [base, http]);
104
+ const signOut = useCallback(async () => {
105
+ // The status flips even if the request fails: the cookie is HttpOnly, so
106
+ // a client that believes it is signed in while the server disagrees is
107
+ // strictly worse than the reverse — the next API call simply 401s and
108
+ // the owner sees the sign-in form.
109
+ try {
110
+ await http(`${base}/logout`, { method: "POST", credentials: "same-origin" });
111
+ }
112
+ finally {
113
+ setStatus("anonymous");
114
+ }
115
+ }, [base, http]);
116
+ return useMemo(() => ({
117
+ status,
118
+ user: status === "authenticated" ? OWNER_USER : null,
119
+ signIn,
120
+ signOut,
121
+ token: () => null,
122
+ }), [status, signIn, signOut]);
123
+ },
124
+ };
125
+ }
126
+ // Deliberately generic (2026-09-14). This is a published package; a mock identity
127
+ // is not the place to put a real person's address, and nothing reads the value.
128
+ const MOCK_USER = {
129
+ id: "mock-user",
130
+ email: "dev@example.com",
131
+ displayName: "Dev User",
132
+ };
133
+ /** Token the mock hands out, so a dev API call carries a recognizably fake credential. */
134
+ export const MOCK_SESSION_TOKEN = "mock-session-token";
135
+ export const MOCK_ADAPTER_IN_PRODUCTION = "createMockAuthAdapter() was reached in a production build. " +
136
+ "A satellite that needs auth must not ship the mock — wire the real adapter first.";
137
+ /**
138
+ * Development stand-in: authenticated immediately, no server involved.
139
+ *
140
+ * It REFUSES TO EXIST in a production build. This is a hard requirement, not a nicety —
141
+ * an adapter that reports `authenticated` unconditionally on a public subdomain is an
142
+ * open door. In a Vite production bundle `import.meta.env.DEV` is compiled to `false`, so
143
+ * this throw cannot be switched off from the outside.
144
+ */
145
+ export function createMockAuthAdapter(options = {}) {
146
+ if (isProductionRuntime())
147
+ throw new Error(MOCK_ADAPTER_IN_PRODUCTION);
148
+ const user = options.user ?? MOCK_USER;
149
+ const startsSignedIn = options.initialStatus !== "anonymous";
150
+ return {
151
+ id: "mock",
152
+ useSession() {
153
+ const [signedIn, setSignedIn] = useState(startsSignedIn);
154
+ const signIn = useCallback(async () => {
155
+ setSignedIn(true);
156
+ }, []);
157
+ const signOut = useCallback(async () => {
158
+ setSignedIn(false);
159
+ }, []);
160
+ return useMemo(() => ({
161
+ status: signedIn ? "authenticated" : "anonymous",
162
+ user: signedIn ? user : null,
163
+ signIn,
164
+ signOut,
165
+ token: () => (signedIn ? MOCK_SESSION_TOKEN : null),
166
+ }), [signedIn, signIn, signOut, user]);
167
+ },
168
+ };
169
+ }
170
+ export async function fetchSsoSession(fetchImpl = fetch, basePath = "/api/auth") {
171
+ const res = await fetchImpl(`${basePath}/session`, { credentials: "same-origin" });
172
+ if (!res.ok)
173
+ return { authenticated: false };
174
+ return (await res.json());
175
+ }
176
+ /**
177
+ * The adapter for a satellite whose users live at the accounts satellite
178
+ * (`apps/auth`). There is no password form here to render — `credential:
179
+ * "sso"` tells the sign-in surface to draw ONE button, and `signIn()` performs
180
+ * a full-page navigation to `/api/auth/sso/start` (a redirect chain cannot be
181
+ * ridden by `fetch`; the browser itself must carry the auth cookie across
182
+ * origins and follow the grant back). The email/password arguments exist on the
183
+ * interface for the other adapters and are ignored here.
184
+ *
185
+ * Since 2026-08-01 the button usually presses itself: an anonymous probe at an
186
+ * SSO door starts the hop immediately and `status` STAYS `"loading"` across the
187
+ * navigation, so the shell shows its loading view rather than flashing a
188
+ * sign-in screen at someone who is already signed in. `"anonymous"` now means
189
+ * something stronger than it did — the automatic path was tried and declined,
190
+ * so the surface it renders is the one that can actually help.
191
+ */
192
+ export function createSsoRedirectAdapter(options = {}) {
193
+ const base = options.basePath ?? "/api/auth";
194
+ const http = options.fetchImpl ?? fetch;
195
+ const autoSignIn = options.autoSignIn !== false;
196
+ return {
197
+ id: "sso-redirect",
198
+ credential: "sso",
199
+ useSession() {
200
+ const [status, setStatus] = useState("loading");
201
+ const [user, setUser] = useState(null);
202
+ // Set when the automatic hop has been launched. The page is unloading,
203
+ // so the honest status is still "loading" — see `resolvedStatus` below.
204
+ const [redirecting, setRedirecting] = useState(false);
205
+ // An explicit sign-out must not be undone by the automatic path on the
206
+ // very next render. A ref rather than state: it is read inside the
207
+ // effect's async body, and it must never schedule a render of its own.
208
+ const signedOutHere = useRef(false);
209
+ // What the SERVER said its accounts origin is. Kept in state rather than
210
+ // read from a config constant because a door that is NOT an SSO door
211
+ // answers with an empty one on purpose (the local vault daemon), and the
212
+ // UI decides what to offer from that answer alone.
213
+ const [accountsUrl, setAccountsUrl] = useState(null);
214
+ useEffect(() => {
215
+ let cancelled = false;
216
+ void (async () => {
217
+ try {
218
+ const info = await fetchSsoSession(http, base);
219
+ if (cancelled)
220
+ return;
221
+ setAccountsUrl(info.accountsUrl ?? null);
222
+ if (info.authenticated && info.user) {
223
+ setUser({
224
+ id: info.user.id,
225
+ email: info.user.email,
226
+ displayName: info.user.name || info.user.email,
227
+ isAdmin: info.user.isAdmin,
228
+ isOwner: info.user.isOwner,
229
+ });
230
+ // A confirmed session retires both guards: the attempt worked,
231
+ // and whatever sign-out came before it is over.
232
+ clearSsoAutoState();
233
+ setStatus("authenticated");
234
+ return;
235
+ }
236
+ const decision = decideSsoAutoSignIn({
237
+ authenticated: false,
238
+ accountsUrl: info.accountsUrl,
239
+ ssoError: ssoErrorFromLocation(),
240
+ signedOut: signedOutHere.current || ssoSignedOutHere(),
241
+ lastAttemptAt: lastSsoAttemptAt(),
242
+ now: Date.now(),
243
+ enabled: autoSignIn,
244
+ });
245
+ if (decision.start) {
246
+ setRedirecting(true);
247
+ startSsoSignIn({ startPath: `${base}/sso/start`, automatic: true });
248
+ return;
249
+ }
250
+ setStatus("anonymous");
251
+ }
252
+ catch {
253
+ // A failed probe is not a session — same posture as the owner
254
+ // adapter: show the sign-in surface, from which retry is one click.
255
+ // Deliberately NOT an auto-start: an unreachable server is exactly
256
+ // the case where bouncing to another origin loses the error.
257
+ if (!cancelled)
258
+ setStatus("anonymous");
259
+ }
260
+ })();
261
+ return () => {
262
+ cancelled = true;
263
+ };
264
+ }, [base, http, autoSignIn]);
265
+ const signIn = useCallback(async () => {
266
+ // Deliberately a navigation, not a fetch — and deliberately never
267
+ // resolving: the page is about to unload. An explicit press clears
268
+ // the guards, so it works even after a sign-out or a failed hop.
269
+ signedOutHere.current = false;
270
+ startSsoSignIn({ startPath: `${base}/sso/start` });
271
+ await new Promise(() => { });
272
+ }, [base]);
273
+ const signOut = useCallback(async () => {
274
+ // A NAVIGATION, not a fetch, and it deliberately never resolves — the
275
+ // page is about to unload. It has to be: this ends auth's session as
276
+ // well as this app's, and a cross-origin cookie cannot be cleared by
277
+ // a same-origin `fetch`. Before 2026-08-10 this posted to `/logout`
278
+ // and stopped there, which ended this app's cookie only — auth's
279
+ // session outlived it, so the next hop signed the same person
280
+ // straight back in with no password asked for, and there was no
281
+ // sequence of clicks that let anybody else use the machine.
282
+ signedOutHere.current = true;
283
+ startSsoSignOut({ signOutPath: `${base}/sso/signout` });
284
+ await new Promise(() => { });
285
+ }, [base]);
286
+ const switchUser = useCallback(async () => {
287
+ // Same shape as `signIn`, plus the flag that makes accounts show its
288
+ // form instead of re-issuing a grant for the session it already holds.
289
+ signedOutHere.current = false;
290
+ startSsoSignIn({ startPath: `${base}/sso/start`, switchUser: true });
291
+ await new Promise(() => { });
292
+ }, [base]);
293
+ // The page is on its way to accounts, so "loading" is the honest answer
294
+ // and the shell keeps showing its spinner. Reporting "anonymous" here
295
+ // would flash the sign-in screen for the length of one navigation —
296
+ // which is the entire thing this feature exists to remove.
297
+ const resolvedStatus = redirecting ? "loading" : status;
298
+ return useMemo(() => ({
299
+ status: resolvedStatus,
300
+ user,
301
+ signIn,
302
+ signOut,
303
+ switchUser,
304
+ accountsUrl,
305
+ token: () => null,
306
+ }), [resolvedStatus, user, signIn, signOut, switchUser, accountsUrl]);
307
+ },
308
+ };
309
+ }
310
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,EAAE;AACF,uFAAuF;AACvF,yFAAyF;AACzF,wFAAwF;AACxF,eAAe;AACf,EAAE;AACF,yFAAyF;AACzF,uFAAuF;AACvF,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C,cAAc,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,WAAW,CAAC,CAChE,CAAC;QACH,CAAC;KACD,CAAC;AACH,CAAC"}
@@ -0,0 +1,35 @@
1
+ import type { Context, MiddlewareHandler } from "hono";
2
+ export interface SessionClaims {
3
+ userId: string;
4
+ tenantId: string;
5
+ scopes: string[];
6
+ }
7
+ /** Hono middleware. Rejects with 401 unless a valid session is present. */
8
+ export type RequireSession = MiddlewareHandler;
9
+ /** Verifies a bearer token. Rejects (or throws) when the token is not a live session. */
10
+ export type SessionVerifier = (token: string) => Promise<SessionClaims>;
11
+ /** Context key the middleware stores verified claims under. */
12
+ export declare const SESSION_CLAIMS_KEY = "satelliteSession";
13
+ /** Claims for the current request, or null on an unauthenticated one. */
14
+ export declare function getSessionClaims(c: Context): SessionClaims | null;
15
+ /** Extracts a bearer token from an Authorization header, or null. */
16
+ export declare function bearerToken(header: string | undefined | null): string | null;
17
+ /**
18
+ * The real gate: 401 unless the request carries a bearer token `verify` accepts. A
19
+ * verifier that throws is treated as a rejection — a broken verifier must fail closed,
20
+ * never open.
21
+ */
22
+ export declare function createRequireSession(verify: SessionVerifier): RequireSession;
23
+ export declare const DEV_REQUIRE_SESSION_IN_PRODUCTION: string;
24
+ /** Claims the dev pass-through injects, so downstream code always sees a session. */
25
+ export declare const DEV_SESSION_CLAIMS: SessionClaims;
26
+ /**
27
+ * Development pass-through: every request is allowed and carries {@link DEV_SESSION_CLAIMS}.
28
+ *
29
+ * It throws AT CONSTRUCTION in production — i.e. at server boot, loudly, rather than
30
+ * silently serving a private app to the internet. The satellite it guards (`roms`) is
31
+ * additionally kept undeployable by a descriptive-only deploy block; this is the second
32
+ * lock on the same door.
33
+ */
34
+ export declare function createDevRequireSession(): RequireSession;
35
+ //# sourceMappingURL=auth.server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.server.d.ts","sourceRoot":"","sources":["../src/auth.server.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAQ,MAAM,MAAM,CAAC;AAG7D,MAAM,WAAW,aAAa;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,2EAA2E;AAC3E,MAAM,MAAM,cAAc,GAAG,iBAAiB,CAAC;AAE/C,yFAAyF;AACzF,MAAM,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,aAAa,CAAC,CAAC;AAExE,+DAA+D;AAC/D,eAAO,MAAM,kBAAkB,qBAAqB,CAAC;AAErD,yEAAyE;AACzE,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,aAAa,GAAG,IAAI,CAEjE;AAQD,qEAAqE;AACrE,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAI5E;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,eAAe,GAAG,cAAc,CAc5E;AAED,eAAO,MAAM,iCAAiC,QAGL,CAAC;AAE1C,qFAAqF;AACrF,eAAO,MAAM,kBAAkB,EAAE,aAIhC,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,IAAI,cAAc,CAMxD"}
@@ -0,0 +1,67 @@
1
+ import { isProductionRuntime } from "./runtimeMode";
2
+ /** Context key the middleware stores verified claims under. */
3
+ export const SESSION_CLAIMS_KEY = "satelliteSession";
4
+ /** Claims for the current request, or null on an unauthenticated one. */
5
+ export function getSessionClaims(c) {
6
+ return c.get(SESSION_CLAIMS_KEY) ?? null;
7
+ }
8
+ const unauthorized = (c) => c.json({ error: "unauthorized" }, 401, {
9
+ "www-authenticate": 'Bearer realm="satellite"',
10
+ "cache-control": "no-store",
11
+ });
12
+ /** Extracts a bearer token from an Authorization header, or null. */
13
+ export function bearerToken(header) {
14
+ if (!header)
15
+ return null;
16
+ const match = /^Bearer[ \t]+(\S+)$/i.exec(header.trim());
17
+ return match ? match[1] : null;
18
+ }
19
+ /**
20
+ * The real gate: 401 unless the request carries a bearer token `verify` accepts. A
21
+ * verifier that throws is treated as a rejection — a broken verifier must fail closed,
22
+ * never open.
23
+ */
24
+ export function createRequireSession(verify) {
25
+ return async (c, next) => {
26
+ const token = bearerToken(c.req.header("authorization"));
27
+ if (!token)
28
+ return unauthorized(c);
29
+ let claims;
30
+ try {
31
+ claims = await verify(token);
32
+ }
33
+ catch {
34
+ return unauthorized(c);
35
+ }
36
+ if (!claims?.userId)
37
+ return unauthorized(c);
38
+ c.set(SESSION_CLAIMS_KEY, claims);
39
+ await next();
40
+ };
41
+ }
42
+ export const DEV_REQUIRE_SESSION_IN_PRODUCTION = "createDevRequireSession() was reached in a production build. " +
43
+ "A satellite that needs auth must not ship the dev pass-through — wire the real " +
44
+ "verifier (createRequireSession) first.";
45
+ /** Claims the dev pass-through injects, so downstream code always sees a session. */
46
+ export const DEV_SESSION_CLAIMS = {
47
+ userId: "dev-user",
48
+ tenantId: "dev",
49
+ scopes: ["*"],
50
+ };
51
+ /**
52
+ * Development pass-through: every request is allowed and carries {@link DEV_SESSION_CLAIMS}.
53
+ *
54
+ * It throws AT CONSTRUCTION in production — i.e. at server boot, loudly, rather than
55
+ * silently serving a private app to the internet. The satellite it guards (`roms`) is
56
+ * additionally kept undeployable by a descriptive-only deploy block; this is the second
57
+ * lock on the same door.
58
+ */
59
+ export function createDevRequireSession() {
60
+ if (isProductionRuntime())
61
+ throw new Error(DEV_REQUIRE_SESSION_IN_PRODUCTION);
62
+ return async (c, next) => {
63
+ c.set(SESSION_CLAIMS_KEY, DEV_SESSION_CLAIMS);
64
+ await next();
65
+ };
66
+ }
67
+ //# sourceMappingURL=auth.server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.server.js","sourceRoot":"","sources":["../src/auth.server.ts"],"names":[],"mappings":"AAMA,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AE,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC;QAC5C,CAAC,CAAC,GAAG,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAAC;QAClC,MAAM,IAAI,EAAE,CAAC;IACd,CAAC,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,iCAAiC,GAC7C,+DAA+D;IAC/D,iFAAiF;IACjF,wCAAwC,CAAC;AAE1C,qFAAqF;AACrF,MAAM,CAAC,MAAM,kBAAkB,GAAkB;IAChD,MAAM,EAAE,UAAU;IAClB,QAAQ,EAAE,KAAK;IACf,MAAM,EAAE,CAAC,GAAG,CAAC;CACb,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,UAAU,uBAAuB;IACtC,IAAI,mBAAmB,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;IAC9E,OAAO,KAAK,EAAE,CAAU,EAAE,IAAU,EAAE,EAAE;QACvC,CAAC,CAAC,GAAG,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,CAAC;QAC9C,MAAM,IAAI,EAAE,CAAC;IACd,CAAC,CAAC;AACH,CAAC"}
@@ -0,0 +1,186 @@
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
+ /** A request described the way a person would describe it: what and from where. */
42
+ export interface ClientDescription {
43
+ ip: string;
44
+ device: string;
45
+ }
46
+ /** How much of a user-agent is worth keeping. Long enough for the non-browser
47
+ * clients (curl, a smoke, a script) to still be identifiable, short enough
48
+ * that a hostile 8KB header cannot be stored per session row. */
49
+ export declare const MAX_USER_AGENT_BYTES = 200;
50
+ /**
51
+ * The shape of the thing on the other end, split so each half can be RECOGNISED
52
+ * on its own.
53
+ *
54
+ * `browser` and `platform` are separate fields rather than one label because
55
+ * they change independently and mean different things to the reader: a new
56
+ * browser on your usual Mac is a browser you installed, and your usual browser
57
+ * on a platform you have never used is somebody else.
58
+ */
59
+ export interface DeviceParts {
60
+ /** "Chrome", "Safari", … or "" when the client is not a known browser. */
61
+ browser: string;
62
+ /** "macOS", "iPhone", "Windows", … or "" when nothing said. */
63
+ platform: string;
64
+ /** What KIND of thing it is, for the one-word answer. */
65
+ form: "phone" | "tablet" | "computer" | "bot" | "unknown";
66
+ }
67
+ /**
68
+ * Where the request came from, as far as the edge could tell.
69
+ *
70
+ * 🔴 Every field can be empty, and empty means NOT KNOWN rather than "nowhere".
71
+ * `country` arrives on every Cloudflare-proxied request for free; the rest
72
+ * (`city`, `region`, `postalCode`, `timezone`, `continent`) only arrive when
73
+ * the zone's *Add visitor location headers* managed transform is on, or when a
74
+ * caller supplies an origin-side lookup — see `clientFactsOf`. A renderer must
75
+ * therefore degrade by dropping fields, never by printing "unknown, unknown".
76
+ */
77
+ export interface ClientPlace {
78
+ /** ISO-3166 alpha-2, e.g. "US". */
79
+ country: string;
80
+ /** "Texas", "England", … */
81
+ region: string;
82
+ /** "Austin", "London", … */
83
+ city: string;
84
+ postalCode: string;
85
+ /** IANA name, e.g. "America/Chicago". */
86
+ timezone: string;
87
+ /** "NA", "EU", … */
88
+ continent: string;
89
+ }
90
+ /** Everything one request says about its client, in the shape it is STORED. */
91
+ export interface ClientFacts extends DeviceParts, ClientPlace {
92
+ /** The caller's address, or "" when nothing said. */
93
+ ip: string;
94
+ /**
95
+ * The address with its host part dropped — `73.12.44.x`, `2600:1700:a1::x`.
96
+ *
97
+ * This, not `ip`, is what "the network you usually sign in from" compares:
98
+ * a home connection changes its address on a lease renewal and its /24
99
+ * almost never, so comparing addresses would mark half the owner's own
100
+ * sign-ins as new and train him to ignore the flag.
101
+ */
102
+ network: string;
103
+ /** Verbatim, bounded, never parsed after this point. */
104
+ userAgent: string;
105
+ /** `browser` + `platform` as one phrase — "Chrome on macOS". */
106
+ device: string;
107
+ }
108
+ /**
109
+ * Enough of a user-agent to recognize your own laptop, and no more.
110
+ *
111
+ * Deliberately not a UA-parsing library and deliberately not exhaustive: these
112
+ * values exist so the owner can tell "my Mac" from "something else", and a
113
+ * wrong guess between two Chromium forks costs nothing.
114
+ */
115
+ export declare function deviceParts(userAgent: string | null | undefined): DeviceParts;
116
+ /** `browser` and `platform` as the phrase a person would say. */
117
+ export declare function describeDeviceParts(parts: DeviceParts, fallback?: string): string;
118
+ /** Enough of a user-agent to recognize your own laptop, as one phrase. */
119
+ export declare function describeDevice(userAgent: string | null | undefined): string;
120
+ /**
121
+ * Where Cloudflare says the request came from.
122
+ *
123
+ * `cf-ipcountry` is sent on every proxied request by default. The rest require
124
+ * the zone's *Add visitor location headers* managed transform; until it is on
125
+ * they are simply absent, which is why every field is independently optional
126
+ * and why `clientFactsOf` takes an origin-side lookup as the second source.
127
+ */
128
+ export declare function clientPlaceOf(request: Request | undefined): ClientPlace;
129
+ /** An empty place — the honest answer for a request nothing is known about. */
130
+ export declare const UNKNOWN_PLACE: ClientPlace;
131
+ /** Is anything at all known about where this came from? */
132
+ export declare const placeIsKnown: (place: ClientPlace) => boolean;
133
+ /**
134
+ * A place as a person would name it — "Austin, Texas, US".
135
+ *
136
+ * Degrades by dropping fields rather than by printing placeholders: a request
137
+ * we only have a country for reads "US", and one we know nothing about reads
138
+ * "" so the caller can choose its own words for absence.
139
+ */
140
+ export declare function describePlace(place: ClientPlace): string;
141
+ /**
142
+ * The caller's address as far as this box can tell, or `""` when nothing said.
143
+ *
144
+ * `x-forwarded-for` is the FIRST hop, because nginx appends and a client may
145
+ * send its own header — so the leftmost entry is attacker-controlled but is
146
+ * also the only one that means anything on a correctly-configured proxy.
147
+ *
148
+ * Empty string rather than a phrase, because this is the STORAGE shape: a row
149
+ * that says nothing must be distinguishable from one that says "unknown", and
150
+ * only the rendering half should be choosing English. `describeClient` is the
151
+ * rendering half.
152
+ */
153
+ export declare function clientAddressOf(request: Request): string;
154
+ /**
155
+ * The address with its host part dropped — the unit "my usual network" is
156
+ * measured in. See `ClientFacts.network` for why an exact address is the wrong
157
+ * comparison.
158
+ *
159
+ * IPv4 keeps three octets (/24); IPv6 keeps three hextets (/48), which is the
160
+ * smallest block a residential customer is normally delegated whole.
161
+ */
162
+ export declare function ipNetworkOf(ip: string): string;
163
+ /**
164
+ * An origin-side answer to "where is this address", for the fields Cloudflare
165
+ * only sends when the managed transform is on. See `ipGeo.ts`.
166
+ */
167
+ export type PlaceLookup = (ip: string) => ClientPlace | null;
168
+ /**
169
+ * Everything one request says about its client.
170
+ *
171
+ * 🔴 The edge WINS over the lookup, field by field. Cloudflare places the
172
+ * address it actually terminated the connection from, against data it refreshes
173
+ * continuously; a local table is a monthly snapshot of somebody else's
174
+ * measurement. Merging per-field rather than choosing one source whole is what
175
+ * lets a zone with only `cf-ipcountry` still get a city.
176
+ */
177
+ export declare function clientFactsOf(request: Request | undefined, options?: {
178
+ lookup?: PlaceLookup;
179
+ }): ClientFacts;
180
+ /** The whole client as one sentence — address, place, device. */
181
+ export declare function describeClientFacts(facts: ClientFacts): string;
182
+ /** The user-agent as it should be STORED — verbatim, bounded, never parsed. */
183
+ export declare const clientUserAgentOf: (request: Request) => string;
184
+ /** Both halves, rendered for a human. */
185
+ export declare function describeClient(request: Request): ClientDescription;
186
+ //# sourceMappingURL=clientDescription.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clientDescription.d.ts","sourceRoot":"","sources":["../src/clientDescription.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,mFAAmF;AACnF,MAAM,WAAW,iBAAiB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;CACf;AAED;;kEAEkE;AAClE,eAAO,MAAM,oBAAoB,MAAM,CAAC;AAMxC;;;;;;;;GAQG;AACH,MAAM,WAAW,WAAW;IAC3B,0EAA0E;IAC1E,OAAO,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,QAAQ,EAAE,MAAM,CAAC;IACjB,yDAAyD;IACzD,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,UAAU,GAAG,KAAK,GAAG,SAAS,CAAC;CAC1D;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,WAAW;I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