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,972 @@
|
|
|
1
|
+
import { createPublicKey } from "node:crypto";
|
|
2
|
+
import { stageIdentityIsLocal } from "./stageIdentity";
|
|
3
|
+
import { SESSION_CLAIMS_KEY } from "./auth.server";
|
|
4
|
+
import { isSecureRequest } from "./secureRequest";
|
|
5
|
+
import { CENSUS_MAX_SUBJECTS, createNonceGuard, kidOfPublicKeyPem, SESSIONS_MAX_PER_APP, verifyCensus, verifyGrant, verifyRevocation, verifySessionsRequest, } from "./sso";
|
|
6
|
+
import { ACCOUNT_DRIFT_STATUS, accountDriftBody, isAccountDrift, MAX_ACCOUNT_SLOTS, normalizeSlot, withSlot, } from "./accountSlots";
|
|
7
|
+
export const SSO_CALLBACK_PATH = "/api/auth/sso/callback";
|
|
8
|
+
export const SSO_START_PATH = "/api/auth/sso/start";
|
|
9
|
+
/**
|
|
10
|
+
* The GLOBAL sign-out door (2026-08-10) — this app's session AND auth's.
|
|
11
|
+
*
|
|
12
|
+
* 🔴 GET, unlike `POST /api/auth/logout` right below it, and the difference is
|
|
13
|
+
* forced: this route ends in a redirect to ANOTHER ORIGIN, so it has to be a
|
|
14
|
+
* top-level navigation the browser drives, and a form POST cannot carry auth's
|
|
15
|
+
* cookie back on the return hop. That re-opens the CSRF surface the POST
|
|
16
|
+
* logout was written to close, and the trade is deliberate: the whole damage a
|
|
17
|
+
* forged sign-out can do is sign somebody out, which they can undo in one
|
|
18
|
+
* click. It is the same shape as OIDC RP-initiated logout for the same reason.
|
|
19
|
+
* Prefetching is not a concern the way it is for `<a href>` — the only caller
|
|
20
|
+
* is `startSsoSignOut`, which navigates from a click handler.
|
|
21
|
+
*
|
|
22
|
+
* The mirror of this constant lives in `ssoAutoSignIn.ts` (browser-side, which
|
|
23
|
+
* must not import `bun:sqlite`); `ssoAutoSignIn.test.ts` pins them equal.
|
|
24
|
+
*/
|
|
25
|
+
export const SSO_SIGNOUT_PATH = "/api/auth/sso/signout";
|
|
26
|
+
/**
|
|
27
|
+
* Where auth pushes a revocation. Server-to-server, not a browser redirect: no
|
|
28
|
+
* cookie, no session, no CSRF surface — the signed ticket IS the authorization,
|
|
29
|
+
* so this route sits OUTSIDE `requireUser` by construction.
|
|
30
|
+
*/
|
|
31
|
+
export const SSO_REVOKE_PATH = "/api/auth/sso/revoke";
|
|
32
|
+
/**
|
|
33
|
+
* Where auth ASKS this app what the named accounts have made here, before it
|
|
34
|
+
* takes their access away (2026-08-10). Same shape as the revoke route — a
|
|
35
|
+
* signed, single-audience ticket IS the authorization, so no cookie and no
|
|
36
|
+
* session — and read-only: it counts rows and answers, never writes.
|
|
37
|
+
*/
|
|
38
|
+
export const SSO_CENSUS_PATH = "/api/auth/sso/census";
|
|
39
|
+
/**
|
|
40
|
+
* Where auth ASKS this app which of an account's sessions are alive here
|
|
41
|
+
* (2026-08-12) — the read half of the fleet-wide Login Sessions list.
|
|
42
|
+
*
|
|
43
|
+
* Same shape and same posture as the two above: a signed, single-audience,
|
|
44
|
+
* 60-second ticket IS the authorization, so no cookie, no session, and the
|
|
45
|
+
* route sits outside `requireUser`. Read-only — ENDING a session is the
|
|
46
|
+
* revocation ticket narrowed by `sid`, never a second door here.
|
|
47
|
+
*
|
|
48
|
+
* 🔴 A new server-to-server path is a new thing an edge gate can silently eat.
|
|
49
|
+
* Five hostnames sit behind Cloudflare Access, whose bypass list is enumerated
|
|
50
|
+
* per path (see `AS-BUILT-cloudflare-access.md`); this path is on it for the
|
|
51
|
+
* same reason `/revoke` and `/census` are, and auth reads any 3xx here as a
|
|
52
|
+
* failure rather than as an empty list.
|
|
53
|
+
*/
|
|
54
|
+
export const SSO_SESSIONS_PATH = "/api/auth/sso/sessions";
|
|
55
|
+
/**
|
|
56
|
+
* The one-shot cookie that carries a signed-out deep link across the grant round
|
|
57
|
+
* trip (2026-08-05). A shared `/play/<name>` link opened signed out used to land
|
|
58
|
+
* on the app's index after the SSO hop, because the callback's redirect target
|
|
59
|
+
* belonged to this module, not to the app. The return path now rides HERE — a
|
|
60
|
+
* cookie on THIS app's own origin, set at `/sso/start`, read at the callback —
|
|
61
|
+
* so it never passes through the auth satellite and can never be smuggled
|
|
62
|
+
* through it into an open redirect. It is validated on the way in AND again on
|
|
63
|
+
* the way back (`sanitizeReturnPath`), so only a same-origin path of this app
|
|
64
|
+
* can ever survive to become a redirect target.
|
|
65
|
+
*/
|
|
66
|
+
export const SSO_RETURN_COOKIE = "sso_return";
|
|
67
|
+
/** Long enough to finish a login (and a 2FA email) at auth, short enough that a
|
|
68
|
+
* stale deep link never resurfaces on a much later, unrelated sign-in. */
|
|
69
|
+
const SSO_RETURN_TTL_SECONDS = 15 * 60;
|
|
70
|
+
/**
|
|
71
|
+
* The one-shot cookie that carries the target ACCOUNT SLOT across the same
|
|
72
|
+
* round trip (2026-08-12).
|
|
73
|
+
*
|
|
74
|
+
* 🔴 It has to be a cookie, for a reason that is easy to miss: the callback URL
|
|
75
|
+
* is the app's REGISTERED `redirect_uri`, matched at auth by exact string, and
|
|
76
|
+
* auth appends nothing but `?grant=`. So there is no way for the hop to tell
|
|
77
|
+
* the callback which slot it was started from — the query param that names the
|
|
78
|
+
* slot everywhere else in the fleet cannot survive a registered redirect. The
|
|
79
|
+
* same one-shot mechanism the deep link already uses carries it instead.
|
|
80
|
+
*
|
|
81
|
+
* Two values, and the difference matters:
|
|
82
|
+
*
|
|
83
|
+
* `add` — "put this person in a NEW slot, keep everyone else signed in".
|
|
84
|
+
* The slot is chosen at the CALLBACK, not here, because the browser
|
|
85
|
+
* can gain or lose a session during the round trip and a number
|
|
86
|
+
* pinned at the start would then evict somebody.
|
|
87
|
+
* `<n>` — "put them in slot n", which is the tab that started the hop.
|
|
88
|
+
*
|
|
89
|
+
* Absent means slot 0: an old cookie jar, an expired one-shot, or a plain first
|
|
90
|
+
* sign-in. All three are the single-account path this fleet already had.
|
|
91
|
+
*
|
|
92
|
+
* Like the slot param itself this is a HINT, never an authorization. The worst
|
|
93
|
+
* a tampered value achieves is landing your own new session in a different slot
|
|
94
|
+
* of your own browser.
|
|
95
|
+
*/
|
|
96
|
+
export const SSO_SLOT_COOKIE = "sso_slot";
|
|
97
|
+
/** The `SSO_SLOT_COOKIE` value meaning "choose a free slot at the callback". */
|
|
98
|
+
const SLOT_COOKIE_ADD = "add";
|
|
99
|
+
/**
|
|
100
|
+
* THE open-redirect gate for every private satellite. The only return target a
|
|
101
|
+
* signed-out deep link may resume to is a same-origin PATH on this app; anything
|
|
102
|
+
* that could send the browser to another origin is refused and the caller falls
|
|
103
|
+
* back to the index. It fails closed by construction — every branch that is not
|
|
104
|
+
* a provably-safe relative path returns null:
|
|
105
|
+
*
|
|
106
|
+
* - absolute URLs (`https://evil.com/x`, `javascript:…`) → not `/`-rooted
|
|
107
|
+
* - protocol-relative `//evil.com` → second char `/`
|
|
108
|
+
* - `\`-smuggled authority (`/\evil.com`, browsers fold `\`→`/`)
|
|
109
|
+
* - control characters (NUL/CR/LF/TAB — header splitting / re-parsing)
|
|
110
|
+
* - percent-encoded slash/backslash/dot that could hide `//` or `..`
|
|
111
|
+
* - `..` path traversal
|
|
112
|
+
*
|
|
113
|
+
* Exported so `ssoConsumer.server.test.ts` can hammer each form directly — an
|
|
114
|
+
* open redirect on every private satellite at once is the primary risk of this
|
|
115
|
+
* change, so it is tested as a unit, not only through the routes.
|
|
116
|
+
*/
|
|
117
|
+
export function sanitizeReturnPath(raw) {
|
|
118
|
+
if (typeof raw !== "string")
|
|
119
|
+
return null;
|
|
120
|
+
if (raw.length === 0 || raw.length > 2048)
|
|
121
|
+
return null;
|
|
122
|
+
// Must be rooted at this origin and be a bare path, not `//authority`.
|
|
123
|
+
if (raw[0] !== "/")
|
|
124
|
+
return null;
|
|
125
|
+
if (raw[1] === "/" || raw[1] === "\\")
|
|
126
|
+
return null;
|
|
127
|
+
// Control chars can split a header or be re-read as an authority separator.
|
|
128
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: refusing them is the point.
|
|
129
|
+
if (/[\u0000-\u001f\u007f]/.test(raw))
|
|
130
|
+
return null;
|
|
131
|
+
// A backslash is normalized to `/` by browsers, so `/\evil.com` becomes
|
|
132
|
+
// `//evil.com`. Refuse the character anywhere in the path.
|
|
133
|
+
if (raw.includes("\\"))
|
|
134
|
+
return null;
|
|
135
|
+
// Percent-encoded slash / backslash / dot can hide `//` or `..` from the
|
|
136
|
+
// checks above after a further decode. No deep link this fleet produces needs
|
|
137
|
+
// them, so refuse rather than guess.
|
|
138
|
+
if (/%2f|%5c|%2e/i.test(raw))
|
|
139
|
+
return null;
|
|
140
|
+
// Traversal in the already-decoded path.
|
|
141
|
+
const path = raw.split(/[?#]/, 1)[0] ?? "";
|
|
142
|
+
if (path.split("/").some((seg) => seg === ".."))
|
|
143
|
+
return null;
|
|
144
|
+
return raw;
|
|
145
|
+
}
|
|
146
|
+
const returnCookieAttributes = (req, maxAge) => [
|
|
147
|
+
"Path=/",
|
|
148
|
+
"HttpOnly",
|
|
149
|
+
// Lax so it survives the cross-site top-level GET the callback arrives as
|
|
150
|
+
// (auth redirects the browser back) — the same reason the session cookie is
|
|
151
|
+
// Lax; see userSessions.ts.
|
|
152
|
+
"SameSite=Lax",
|
|
153
|
+
...(isSecureRequest(req) ? ["Secure"] : []),
|
|
154
|
+
`Max-Age=${maxAge}`,
|
|
155
|
+
].join("; ");
|
|
156
|
+
const setReturnCookie = (req, path) => `${SSO_RETURN_COOKIE}=${encodeURIComponent(path)}; ${returnCookieAttributes(req, SSO_RETURN_TTL_SECONDS)}`;
|
|
157
|
+
const clearReturnCookie = (req) => `${SSO_RETURN_COOKIE}=; ${returnCookieAttributes(req, 0)}`;
|
|
158
|
+
const readReturnCookie = (req) => {
|
|
159
|
+
const cookie = req.headers.get("cookie");
|
|
160
|
+
if (!cookie)
|
|
161
|
+
return null;
|
|
162
|
+
const match = new RegExp(`(?:^|;\\s*)${SSO_RETURN_COOKIE}=([^;]+)`).exec(cookie);
|
|
163
|
+
if (!match?.[1])
|
|
164
|
+
return null;
|
|
165
|
+
try {
|
|
166
|
+
return decodeURIComponent(match[1]);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
/** Is a return cookie present at all (even an undecodable one)? The failure path
|
|
173
|
+
* clears it only when it exists, so a plain failed grant still sets NO cookie —
|
|
174
|
+
* the invariant the callback's other tests rely on. */
|
|
175
|
+
const hasReturnCookie = (req) => new RegExp(`(?:^|;\\s*)${SSO_RETURN_COOKIE}=`).test(req.headers.get("cookie") ?? "");
|
|
176
|
+
/** Same attributes as the return cookie, and for the same reasons: one-shot,
|
|
177
|
+
* HttpOnly, and Lax so it survives the cross-site top-level GET back. */
|
|
178
|
+
const setSlotCookie = (req, value) => `${SSO_SLOT_COOKIE}=${encodeURIComponent(value)}; ${returnCookieAttributes(req, SSO_RETURN_TTL_SECONDS)}`;
|
|
179
|
+
const clearSlotCookie = (req) => `${SSO_SLOT_COOKIE}=; ${returnCookieAttributes(req, 0)}`;
|
|
180
|
+
/** The raw one-shot slot instruction, or null. */
|
|
181
|
+
const readSlotCookie = (req) => {
|
|
182
|
+
const cookie = req.headers.get("cookie");
|
|
183
|
+
if (!cookie)
|
|
184
|
+
return null;
|
|
185
|
+
const match = new RegExp(`(?:^|;\\s*)${SSO_SLOT_COOKIE}=([^;]+)`).exec(cookie);
|
|
186
|
+
if (!match?.[1])
|
|
187
|
+
return null;
|
|
188
|
+
try {
|
|
189
|
+
return decodeURIComponent(match[1]).slice(0, 8);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
const hasSlotCookie = (req) => new RegExp(`(?:^|;\\s*)${SSO_SLOT_COOKIE}=`).test(req.headers.get("cookie") ?? "");
|
|
196
|
+
/** How long a fetched JWKS is trusted before re-reading. Rotation overlap on
|
|
197
|
+
* the auth side is hours, so minutes here costs nothing. */
|
|
198
|
+
const JWKS_TTL_MS = 5 * 60 * 1000;
|
|
199
|
+
/** Floor between forced refreshes (unknown kid), so a garbage grant cannot
|
|
200
|
+
* turn the consumer into a hammer against auth. */
|
|
201
|
+
const JWKS_MIN_REFRESH_GAP_MS = 30 * 1000;
|
|
202
|
+
const noStore = { "cache-control": "no-store" };
|
|
203
|
+
const toUser = (row) => ({
|
|
204
|
+
id: row.id,
|
|
205
|
+
email: row.email,
|
|
206
|
+
name: row.name,
|
|
207
|
+
isAdmin: row.is_admin === 1,
|
|
208
|
+
isOwner: row.is_owner === 1,
|
|
209
|
+
isGranted: row.is_granted === 1,
|
|
210
|
+
});
|
|
211
|
+
/** `http://127.0.0.1:3309` / `http://localhost:3309` → true. Anything else → false. */
|
|
212
|
+
function isLoopbackOrigin(url) {
|
|
213
|
+
try {
|
|
214
|
+
const host = new URL(url).hostname.toLowerCase();
|
|
215
|
+
return host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "[::1]";
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
// Unparseable is not loopback: the safe answer is "this is the real registry",
|
|
219
|
+
// which leaves the audience at the app's own prod key and changes nothing.
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* THE GRANT AUDIENCE — this app's own key, or its LOCAL twin on a staged artifact.
|
|
225
|
+
*
|
|
226
|
+
* ## What this buys, and why it is the audience rather than just the URL
|
|
227
|
+
*
|
|
228
|
+
* Pointing a staged artifact at the local accounts daemon (`appConfig`'s forced
|
|
229
|
+
* `authUrl`) stops it writing sessions into the owner's real registry. That is one
|
|
230
|
+
* direction. This function is the OTHER direction, and it is the half that makes the
|
|
231
|
+
* isolation mutual: a grant minted by `auth-local` carries `aud: "<app>-local"`, and
|
|
232
|
+
* the production deployment of that app verifies `aud: "<app>"` — so a credential
|
|
233
|
+
* minted on this Mac is **structurally unusable against production**, not merely
|
|
234
|
+
* unlikely to be sent there. `<app>-local` additionally has an EMPTY `prodOrigin` in
|
|
235
|
+
* the roster, so even a registry that allows local consumers has no callback for it on
|
|
236
|
+
* the internet. That is the `orch-local` / `station-local` shape, which those two apps
|
|
237
|
+
* have carried since 2026-07-31; this is the thirteen others adopting it without each
|
|
238
|
+
* hand-writing a second `createSsoConsumer` branch.
|
|
239
|
+
*
|
|
240
|
+
* ## Three conditions, all required, and each one closes a different door
|
|
241
|
+
*
|
|
242
|
+
* 1. **the stage marker** — `APP_STAGE_IDENTITY=local`, written only by
|
|
243
|
+
* `smoke/localStage.ts`. Without it an ordinary `bun run dev` shell keeps signing
|
|
244
|
+
* in as `<app>` through the dev-gateway alias (`http://<app>.localhost:3300`),
|
|
245
|
+
* which is registered on the PROD key and deliberately not on the local one — the
|
|
246
|
+
* `*.localhost` exclusion `sso.test.ts` pins. Deriving the switch from "authUrl is
|
|
247
|
+
* loopback" alone would have silently broken gateway sign-in in every app.
|
|
248
|
+
* 2. **a loopback registry** — belt and braces on the marker. A stray marker on a
|
|
249
|
+
* real release cannot move the audience while `authUrl` is the internet.
|
|
250
|
+
* 3. **`<app>-local` is actually in the roster** — so an app whose local door has not
|
|
251
|
+
* been registered keeps its own key and fails visibly at the ROSTER, instead of
|
|
252
|
+
* asking auth for an audience nobody has heard of and getting 400 `unknown app` at
|
|
253
|
+
* the far end of a browser hop. It is also what keeps `station-local` and
|
|
254
|
+
* `orch-local` unchanged when they pass through here: `station-local-local` is not
|
|
255
|
+
* a key, so their explicit audience wins, as it must.
|
|
256
|
+
*
|
|
257
|
+
* 🔴 It moves the AUDIENCE only. `appKey` stays the app's own identity everywhere else
|
|
258
|
+
* — the session `scopes`, the log prefixes, the fleet row — because those are read by
|
|
259
|
+
* app code that has no idea it is on a stage, and a scope string that changed shape
|
|
260
|
+
* under the app would be a permissions bug wearing a stage costume.
|
|
261
|
+
*/
|
|
262
|
+
export function resolveSsoAudience(appKey, authUrl, env = process.env, registered = []) {
|
|
263
|
+
if (!stageIdentityIsLocal(env))
|
|
264
|
+
return appKey;
|
|
265
|
+
if (!isLoopbackOrigin(authUrl))
|
|
266
|
+
return appKey;
|
|
267
|
+
const local = `${appKey}-local`;
|
|
268
|
+
return registered.includes(local) ? local : appKey;
|
|
269
|
+
}
|
|
270
|
+
export function createSsoConsumer(options) {
|
|
271
|
+
const { app: appKey, sessions, db } = options;
|
|
272
|
+
const authUrl = options.authUrl.replace(/\/$/, "");
|
|
273
|
+
/**
|
|
274
|
+
* What this consumer asks auth FOR and verifies grants AGAINST — see
|
|
275
|
+
* {@link resolveSsoAudience}. Equal to `appKey` everywhere except a staged
|
|
276
|
+
* artifact, so the ordinary reading of this file is unchanged.
|
|
277
|
+
*/
|
|
278
|
+
const audience = resolveSsoAudience(appKey, authUrl, options.env ?? process.env, options.registeredAudiences ?? []);
|
|
279
|
+
if (audience !== appKey) {
|
|
280
|
+
console.log(`[${appKey}] SSO audience is "${audience}" — this is a LOCAL STAGE, signing in ` +
|
|
281
|
+
`against ${authUrl}. A grant minted here cannot open the production deployment.`);
|
|
282
|
+
}
|
|
283
|
+
const publicUrl = options.publicUrl.replace(/\/$/, "");
|
|
284
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
285
|
+
const now = options.now ?? Date.now;
|
|
286
|
+
const nonces = createNonceGuard(now);
|
|
287
|
+
const allowedEmails = options.allowedEmails === undefined
|
|
288
|
+
? null
|
|
289
|
+
: new Set(options.allowedEmails.map((e) => e.trim().toLowerCase()).filter((e) => e.length > 0));
|
|
290
|
+
const emailAllowed = (email) => allowedEmails === null || allowedEmails.has(email.trim().toLowerCase());
|
|
291
|
+
db.exec(`CREATE TABLE IF NOT EXISTS sso_users (
|
|
292
|
+
id TEXT PRIMARY KEY,
|
|
293
|
+
email TEXT NOT NULL,
|
|
294
|
+
name TEXT NOT NULL DEFAULT '',
|
|
295
|
+
is_admin INTEGER NOT NULL DEFAULT 0,
|
|
296
|
+
last_login_at TEXT NOT NULL DEFAULT '',
|
|
297
|
+
created_at TEXT NOT NULL,
|
|
298
|
+
updated_at TEXT NOT NULL
|
|
299
|
+
);`);
|
|
300
|
+
// 2026-08-02: the fleet directory needs two more facts per account. Added by
|
|
301
|
+
// ALTER rather than by bumping the CREATE, because every deployed satellite
|
|
302
|
+
// already has this table with rows in it. Both default to 0, so an account
|
|
303
|
+
// that has not signed in since the upgrade simply gets no localhost links
|
|
304
|
+
// and no grant bypass until it does — the safe direction.
|
|
305
|
+
for (const column of ["is_owner", "is_granted"]) {
|
|
306
|
+
try {
|
|
307
|
+
db.exec(`ALTER TABLE sso_users ADD COLUMN ${column} INTEGER NOT NULL DEFAULT 0`);
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
// Already there. sqlite has no ADD COLUMN IF NOT EXISTS, and reading
|
|
311
|
+
// pragma table_info to decide costs more than catching the one error
|
|
312
|
+
// this can throw.
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
// 🔴 One row per ADDRESS, not just per id (2026-08-23). See `reconcileByEmail`
|
|
316
|
+
// for the ghost this removes; the index is what makes it impossible to grow a
|
|
317
|
+
// second one. Created AFTER the sweep, because a live duplicate would refuse
|
|
318
|
+
// the index and leave the table exactly as it was found.
|
|
319
|
+
dropDuplicateSnapshots(db);
|
|
320
|
+
db.exec("CREATE UNIQUE INDEX IF NOT EXISTS sso_users_email ON sso_users (lower(email))");
|
|
321
|
+
// ── Verification keys ───────────────────────────────────────────────────
|
|
322
|
+
const staticKeys = options.publicKeyPem
|
|
323
|
+
? new Map([[kidOfPublicKeyPem(options.publicKeyPem), createPublicKey(options.publicKeyPem)]])
|
|
324
|
+
: null;
|
|
325
|
+
let fetched = new Map();
|
|
326
|
+
let fetchedAt = 0;
|
|
327
|
+
let lastRefreshAttempt = 0;
|
|
328
|
+
async function refreshJwks() {
|
|
329
|
+
lastRefreshAttempt = now();
|
|
330
|
+
try {
|
|
331
|
+
const res = await fetchImpl(`${authUrl}/api/sso/jwks`, {
|
|
332
|
+
signal: AbortSignal.timeout(5000),
|
|
333
|
+
});
|
|
334
|
+
if (!res.ok)
|
|
335
|
+
throw new Error(`jwks answered ${res.status}`);
|
|
336
|
+
const body = (await res.json());
|
|
337
|
+
const next = new Map();
|
|
338
|
+
for (const key of body.keys ?? []) {
|
|
339
|
+
if (typeof key.kid === "string" && typeof key.publicKeyPem === "string") {
|
|
340
|
+
next.set(key.kid, createPublicKey(key.publicKeyPem));
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (next.size === 0)
|
|
344
|
+
throw new Error("jwks contained no usable keys");
|
|
345
|
+
fetched = next;
|
|
346
|
+
fetchedAt = now();
|
|
347
|
+
}
|
|
348
|
+
catch (err) {
|
|
349
|
+
// Stale keys keep verifying; only a rotation while auth is unreachable
|
|
350
|
+
// fails, and it fails CLOSED (unknown kid → refused grant).
|
|
351
|
+
console.warn(`[${appKey}] SSO jwks refresh failed (${String(err)}) — keeping cached keys`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
async function keysFor(kid) {
|
|
355
|
+
if (staticKeys)
|
|
356
|
+
return staticKeys;
|
|
357
|
+
const expired = now() - fetchedAt > JWKS_TTL_MS;
|
|
358
|
+
const unknown = !fetched.has(kid);
|
|
359
|
+
const gapOk = now() - lastRefreshAttempt > JWKS_MIN_REFRESH_GAP_MS;
|
|
360
|
+
if (fetched.size === 0 || ((expired || unknown) && gapOk))
|
|
361
|
+
await refreshJwks();
|
|
362
|
+
return fetched;
|
|
363
|
+
}
|
|
364
|
+
// ── Session resolution ──────────────────────────────────────────────────
|
|
365
|
+
const sessionUser = (c) => {
|
|
366
|
+
const userId = sessions.userIdOf(c.req.raw);
|
|
367
|
+
if (!userId)
|
|
368
|
+
return null;
|
|
369
|
+
const row = db.query("SELECT * FROM sso_users WHERE id = ?").get(userId);
|
|
370
|
+
return row ? toUser(row) : null;
|
|
371
|
+
};
|
|
372
|
+
const userOf = (c) => {
|
|
373
|
+
const claims = c.get(SESSION_CLAIMS_KEY);
|
|
374
|
+
return claims?.ssoUser ?? null;
|
|
375
|
+
};
|
|
376
|
+
/**
|
|
377
|
+
* `requireAdmin` means "admin OR explicitly granted this app" as of
|
|
378
|
+
* 2026-08-02. The flag was the fleet's only way to widen an app past the
|
|
379
|
+
* household default, so opening Notes to one person also handed them the
|
|
380
|
+
* user registry. A per-app grant separates those two decisions; admins keep
|
|
381
|
+
* working with no rows at all, so nothing that passed before now fails.
|
|
382
|
+
*
|
|
383
|
+
* `allowedEmails` is deliberately NOT softened this way — the station pins
|
|
384
|
+
* itself to the owner's address precisely because admin is grantable, and a
|
|
385
|
+
* grant must not be able to reach past that.
|
|
386
|
+
*/
|
|
387
|
+
const adminOrGranted = (user) => !options.requireAdmin || user.isAdmin || user.isGranted;
|
|
388
|
+
/**
|
|
389
|
+
* The WHOLE authorization rule, over a raw `Request`. See `SsoConsumer` for
|
|
390
|
+
* why this is shared rather than re-implemented per door.
|
|
391
|
+
*
|
|
392
|
+
* `requireUser` is defined in terms of it below, which is the point: the two
|
|
393
|
+
* cannot answer differently, because there is only one of them.
|
|
394
|
+
*/
|
|
395
|
+
const authorizeRequest = (req) => {
|
|
396
|
+
const userId = sessions.userIdOf(req);
|
|
397
|
+
if (!userId)
|
|
398
|
+
return null;
|
|
399
|
+
const row = db.query("SELECT * FROM sso_users WHERE id = ?").get(userId);
|
|
400
|
+
const user = row ? toUser(row) : null;
|
|
401
|
+
if (!user)
|
|
402
|
+
return null;
|
|
403
|
+
if (!adminOrGranted(user))
|
|
404
|
+
return null;
|
|
405
|
+
if (!emailAllowed(user.email))
|
|
406
|
+
return null;
|
|
407
|
+
return user;
|
|
408
|
+
};
|
|
409
|
+
/**
|
|
410
|
+
* The handshake door. See `SsoConsumer.verifyHandshake` for why it is an
|
|
411
|
+
* adapter over `authorizeRequest` and must stay one.
|
|
412
|
+
*
|
|
413
|
+
* The URL is a placeholder and is never read: a session is resolved from the
|
|
414
|
+
* `Cookie` header alone, and the upgrade's own URL carries no credential. A
|
|
415
|
+
* constant here is honest about that — reaching for the app's public URL would
|
|
416
|
+
* imply the origin was being checked, which it is not (the browser's
|
|
417
|
+
* same-origin cookie rules are what bound where the cookie can come from).
|
|
418
|
+
*/
|
|
419
|
+
const verifyHandshake = (headers) => authorizeRequest(new Request("http://handshake.invalid/", { headers }));
|
|
420
|
+
const requireUser = async (c, next) => {
|
|
421
|
+
const user = authorizeRequest(c.req.raw);
|
|
422
|
+
if (!user)
|
|
423
|
+
return c.json({ error: "unauthorized" }, 401, noStore);
|
|
424
|
+
/**
|
|
425
|
+
* 🔴 The account behind this browser's slot changed while the page that is
|
|
426
|
+
* asking was already open (owner, 2026-08-15 — see `accountSlots.ts` for
|
|
427
|
+
* the whole failure). The credential is valid and the person is signed in,
|
|
428
|
+
* so this is neither a 401 nor a 403: it is a CONFLICT between the identity
|
|
429
|
+
* the page rendered for and the one this request resolves to, and answering
|
|
430
|
+
* it as anything else is what let a console stay drawn for somebody who was
|
|
431
|
+
* no longer there.
|
|
432
|
+
*
|
|
433
|
+
* It sits INSIDE the authorization above rather than in front of it, and
|
|
434
|
+
* that order is deliberate: an anonymous request must still be told it is
|
|
435
|
+
* anonymous, and drift is only interesting once we know who this actually
|
|
436
|
+
* is — which is also the only way the answer can name them.
|
|
437
|
+
*/
|
|
438
|
+
const expected = sessions.expectedUserOf(c.req.raw);
|
|
439
|
+
if (isAccountDrift(expected, user.id)) {
|
|
440
|
+
return c.json(accountDriftBody(expected ?? "", {
|
|
441
|
+
id: user.id,
|
|
442
|
+
email: user.email,
|
|
443
|
+
name: user.name,
|
|
444
|
+
}), ACCOUNT_DRIFT_STATUS, noStore);
|
|
445
|
+
}
|
|
446
|
+
c.set(SESSION_CLAIMS_KEY, {
|
|
447
|
+
userId: user.id,
|
|
448
|
+
tenantId: "default",
|
|
449
|
+
/**
|
|
450
|
+
* 🔴 `owner` is a scope of its own, not "admin, but more".
|
|
451
|
+
*
|
|
452
|
+
* Several satellites have a surface that is the OWNER's alone — the fleet
|
|
453
|
+
* quota knobs, a spend decision, a limit somebody else's data lives under
|
|
454
|
+
* — and until 2026-08-12 the only signal that crossed into a consumer app
|
|
455
|
+
* was `admin`. An app that wanted owner-only had to re-read `ssoUser`, or
|
|
456
|
+
* (worse, and this is the one that has actually shipped elsewhere) settle
|
|
457
|
+
* for admin and call it close enough. `apps/auth` already draws this
|
|
458
|
+
* distinction on its own routes; this is the same line, made visible to
|
|
459
|
+
* every consumer through the claims they already read.
|
|
460
|
+
*/
|
|
461
|
+
scopes: [appKey, ...(user.isAdmin ? ["admin"] : []), ...(user.isOwner ? ["owner"] : [])],
|
|
462
|
+
ssoUser: user,
|
|
463
|
+
});
|
|
464
|
+
await next();
|
|
465
|
+
};
|
|
466
|
+
return {
|
|
467
|
+
requireUser,
|
|
468
|
+
userOf,
|
|
469
|
+
authorizeRequest,
|
|
470
|
+
verifyHandshake,
|
|
471
|
+
mountSsoRoutes(app) {
|
|
472
|
+
app.get(SSO_START_PATH, (c) => {
|
|
473
|
+
const target = new URL(`${authUrl}/sso/authorize`);
|
|
474
|
+
target.searchParams.set("app", audience);
|
|
475
|
+
target.searchParams.set("redirect_uri", `${publicUrl}${SSO_CALLBACK_PATH}`);
|
|
476
|
+
// "Somebody else wants in" — ask auth for the credential form even
|
|
477
|
+
// though it holds a live session. Without it the hop re-issues a
|
|
478
|
+
// grant for whoever is already signed in there, which is exactly the
|
|
479
|
+
// dead end this fixes. Translated here rather than passed straight
|
|
480
|
+
// through so the app-facing vocabulary stays `switch=1` and auth's
|
|
481
|
+
// protocol vocabulary stays `prompt=login`.
|
|
482
|
+
if (c.req.query("switch") === "1")
|
|
483
|
+
target.searchParams.set("prompt", "login");
|
|
484
|
+
// ── Adding a SECOND account, side by side (2026-08-12) ──────────
|
|
485
|
+
// `switch=1` replaces whoever this tab is. `add=1` does not: it asks
|
|
486
|
+
// auth for its account chooser and lands the result in a FREE slot,
|
|
487
|
+
// so the account already open in the other tab keeps working. That
|
|
488
|
+
// distinction is the whole owner-facing feature — "one tab as owner,
|
|
489
|
+
// another as a test user, at the same time".
|
|
490
|
+
//
|
|
491
|
+
// `prompt=select_account` is OIDC's own word for this and auth
|
|
492
|
+
// implements it as "offer the accounts this browser already holds,
|
|
493
|
+
// with a password form under them". Translated here, like
|
|
494
|
+
// `prompt=login` above, so apps keep saying `add=1`.
|
|
495
|
+
const adding = c.req.query("add") === "1";
|
|
496
|
+
if (adding)
|
|
497
|
+
target.searchParams.set("prompt", "select_account");
|
|
498
|
+
// A specific account the person picked from the menu. Auth mints for
|
|
499
|
+
// that account IF this browser already proved it may (it holds a live
|
|
500
|
+
// auth session for them) and shows the password form if not — so this
|
|
501
|
+
// parameter can never be a way IN, only a way to skip retyping.
|
|
502
|
+
const account = (c.req.query("account") ?? "").slice(0, 64);
|
|
503
|
+
if (account)
|
|
504
|
+
target.searchParams.set("account", account);
|
|
505
|
+
// Stash the signed-out deep link (`?return=`) in a one-shot cookie on
|
|
506
|
+
// THIS origin so the callback can resume it after the round trip. The
|
|
507
|
+
// path never travels to auth, so it can never ride the grant into an
|
|
508
|
+
// open redirect there. A missing or refused return CLEARS any stale
|
|
509
|
+
// cookie, so the fallback is today's "land on the index" rather than a
|
|
510
|
+
// leftover from an earlier attempt.
|
|
511
|
+
const ret = sanitizeReturnPath(c.req.query("return"));
|
|
512
|
+
c.header("set-cookie", ret ? setReturnCookie(c.req.raw, ret) : clearReturnCookie(c.req.raw));
|
|
513
|
+
// And stash where the result should land. Always written, never left
|
|
514
|
+
// stale: a plain hop that inherited an `add` from an abandoned attempt
|
|
515
|
+
// would silently open a second session instead of refreshing this one.
|
|
516
|
+
c.header("set-cookie", setSlotCookie(c.req.raw, adding ? SLOT_COOKIE_ADD : String(sessions.slotOf(c.req.raw))), { append: true });
|
|
517
|
+
return c.redirect(target.toString(), 302);
|
|
518
|
+
});
|
|
519
|
+
// ── Leaving, for real (2026-08-10) ────────────────────────────────
|
|
520
|
+
// Ending this app's cookie was never a sign-out: auth's session
|
|
521
|
+
// outlives it, so the next "Sign in" press — or the automatic hop on
|
|
522
|
+
// the next tab — silently returns the SAME person. This route ends
|
|
523
|
+
// both, in the only order that is safe: this app's session dies here
|
|
524
|
+
// and now (so a failure at the auth hop still leaves this app locked),
|
|
525
|
+
// and auth's dies on the redirect that follows.
|
|
526
|
+
//
|
|
527
|
+
// `redirect_uri` is this app's REGISTERED callback rather than a page
|
|
528
|
+
// of its own. Auth already validates that exact string by exact match
|
|
529
|
+
// against the registry, so the sign-out door adds no second place a
|
|
530
|
+
// redirect target can be registered — auth lands the browser on that
|
|
531
|
+
// URL's origin, not the callback path itself.
|
|
532
|
+
app.get(SSO_SIGNOUT_PATH, (c) => {
|
|
533
|
+
// ── Which sign-out is this? (2026-08-12) ────────────────────────
|
|
534
|
+
// With several accounts in one browser, "sign out" split into two
|
|
535
|
+
// genuinely different actions and conflating them is destructive in
|
|
536
|
+
// one direction: ending the owner's session because a test account
|
|
537
|
+
// left is work lost in a tab nobody touched.
|
|
538
|
+
//
|
|
539
|
+
// default — leave THIS slot. Every other account stays signed in,
|
|
540
|
+
// here and at auth.
|
|
541
|
+
// all=1 — leave every account on this machine. The shared-
|
|
542
|
+
// computer exit, and the only one that ends auth's
|
|
543
|
+
// whole session.
|
|
544
|
+
const all = c.req.query("all") === "1";
|
|
545
|
+
// Read the occupant BEFORE revoking — after, there is nobody to name,
|
|
546
|
+
// and auth needs the id to end that person's auth session alone.
|
|
547
|
+
const leaving = all ? null : sessions.userIdOf(c.req.raw);
|
|
548
|
+
const slot = sessions.slotOf(c.req.raw);
|
|
549
|
+
if (all) {
|
|
550
|
+
for (const cleared of sessions.revokeEverySlot(c.req.raw)) {
|
|
551
|
+
c.header("set-cookie", sessions.clearedCookie(c.req.raw, cleared), { append: true });
|
|
552
|
+
}
|
|
553
|
+
// Even with nothing live here, still clear the slot the request
|
|
554
|
+
// names: a cookie whose row expired is a cookie the browser keeps
|
|
555
|
+
// sending, and the visible result of "sign out" must not be
|
|
556
|
+
// nothing.
|
|
557
|
+
c.header("set-cookie", sessions.clearedCookie(c.req.raw, slot), { append: true });
|
|
558
|
+
}
|
|
559
|
+
else {
|
|
560
|
+
sessions.revoke(c.req.raw);
|
|
561
|
+
c.header("set-cookie", sessions.clearedCookie(c.req.raw, slot), { append: true });
|
|
562
|
+
}
|
|
563
|
+
// An abandoned deep link must not resume for whoever signs in next.
|
|
564
|
+
if (hasReturnCookie(c.req.raw)) {
|
|
565
|
+
c.header("set-cookie", clearReturnCookie(c.req.raw), { append: true });
|
|
566
|
+
}
|
|
567
|
+
if (hasSlotCookie(c.req.raw)) {
|
|
568
|
+
c.header("set-cookie", clearSlotCookie(c.req.raw), { append: true });
|
|
569
|
+
}
|
|
570
|
+
const target = new URL(`${authUrl}/sso/logout`);
|
|
571
|
+
target.searchParams.set("app", audience);
|
|
572
|
+
target.searchParams.set("redirect_uri", `${publicUrl}${SSO_CALLBACK_PATH}`);
|
|
573
|
+
// 🔴 Name the account, so auth ends ONE of its sessions rather than
|
|
574
|
+
// all of them. Without this, signing a test account out of one tab
|
|
575
|
+
// signs the owner out of auth too, and the next hop in their tab
|
|
576
|
+
// silently demands a password. `all=1` deliberately sends no account
|
|
577
|
+
// and gets the old, total behavior.
|
|
578
|
+
if (all)
|
|
579
|
+
target.searchParams.set("all", "1");
|
|
580
|
+
else if (leaving)
|
|
581
|
+
target.searchParams.set("account", leaving);
|
|
582
|
+
return c.redirect(target.toString(), 302);
|
|
583
|
+
});
|
|
584
|
+
app.get(SSO_CALLBACK_PATH, async (c) => {
|
|
585
|
+
const fail = (reason) => {
|
|
586
|
+
// Land the user somewhere visible with the reason — the SPA renders
|
|
587
|
+
// it as a toast next to the sign-in button. Never a bare 400 page.
|
|
588
|
+
// Also drop the return cookie IF one exists: this attempt is over, and
|
|
589
|
+
// a later, unrelated success must not resume a deep link this one
|
|
590
|
+
// failed on. Only when present, so a plain failed grant still sets no
|
|
591
|
+
// cookie at all.
|
|
592
|
+
if (hasReturnCookie(c.req.raw))
|
|
593
|
+
c.header("set-cookie", clearReturnCookie(c.req.raw));
|
|
594
|
+
// Same one-shot discipline for the slot instruction: this attempt
|
|
595
|
+
// is over, and an `add` left behind would make the NEXT ordinary
|
|
596
|
+
// sign-in quietly open a second session instead of refreshing one.
|
|
597
|
+
if (hasSlotCookie(c.req.raw)) {
|
|
598
|
+
c.header("set-cookie", clearSlotCookie(c.req.raw), { append: true });
|
|
599
|
+
}
|
|
600
|
+
return c.redirect(`/?ssoError=${encodeURIComponent(reason)}`, 302);
|
|
601
|
+
};
|
|
602
|
+
const grant = c.req.query("grant") ?? "";
|
|
603
|
+
if (!grant)
|
|
604
|
+
return fail("missing grant");
|
|
605
|
+
// Peek the kid (unverified — only used to decide whether a JWKS
|
|
606
|
+
// refresh is worth it; verification below re-reads it from the same
|
|
607
|
+
// payload under the signature).
|
|
608
|
+
const kid = peekKid(grant);
|
|
609
|
+
const keys = await keysFor(kid ?? "");
|
|
610
|
+
const verdict = verifyGrant(grant, {
|
|
611
|
+
aud: audience,
|
|
612
|
+
keyOf: (k) => keys.get(k) ?? null,
|
|
613
|
+
now,
|
|
614
|
+
});
|
|
615
|
+
if (!verdict.ok)
|
|
616
|
+
return fail(verdict.reason);
|
|
617
|
+
const claims = verdict.claims;
|
|
618
|
+
if (options.requireAdmin && !claims.admin && claims.granted !== true) {
|
|
619
|
+
// Named plainly: the person DID sign in correctly; the account is
|
|
620
|
+
// simply not allowed here, and "invalid grant" would send them to
|
|
621
|
+
// reset a password that works fine.
|
|
622
|
+
return fail("this account does not have access to this app");
|
|
623
|
+
}
|
|
624
|
+
if (!emailAllowed(claims.email)) {
|
|
625
|
+
// Same plainness, same reason — a working password must never be
|
|
626
|
+
// blamed for an allowlist refusal.
|
|
627
|
+
return fail("this account does not have access to this app");
|
|
628
|
+
}
|
|
629
|
+
if (!nonces.consume(claims.nonce, claims.exp))
|
|
630
|
+
return fail("grant already used");
|
|
631
|
+
// ── Which slot does this session land in? (2026-08-12) ──────────
|
|
632
|
+
// The instruction rode a one-shot cookie because a registered
|
|
633
|
+
// redirect_uri cannot carry a query param — see SSO_SLOT_COOKIE.
|
|
634
|
+
const instruction = readSlotCookie(c.req.raw);
|
|
635
|
+
let slot;
|
|
636
|
+
if (instruction === SLOT_COOKIE_ADD) {
|
|
637
|
+
// Chosen HERE rather than at the start, so a browser that gained or
|
|
638
|
+
// lost a session mid-hop still lands somewhere free. `slotToAdd`
|
|
639
|
+
// reuses this person's existing slot when they already have one, so
|
|
640
|
+
// re-adding an account already open is a no-op rather than a
|
|
641
|
+
// duplicate that eats the last free slot.
|
|
642
|
+
const target = sessions.slotToAdd(c.req.raw, claims.id);
|
|
643
|
+
if (target === null) {
|
|
644
|
+
// 🔴 Refuse rather than evict. Somebody's live session is worth
|
|
645
|
+
// more than the convenience of not saying no, and the message
|
|
646
|
+
// names the fix.
|
|
647
|
+
return fail(`this browser is already signed into ${MAX_ACCOUNT_SLOTS} accounts here — sign one out first`);
|
|
648
|
+
}
|
|
649
|
+
slot = target;
|
|
650
|
+
}
|
|
651
|
+
else {
|
|
652
|
+
// A plain hop refreshes the tab that started it. Absent (an expired
|
|
653
|
+
// one-shot, a first sign-in, a build that predates slots) is slot 0
|
|
654
|
+
// — the single-account behavior this fleet already had.
|
|
655
|
+
slot = normalizeSlot(instruction ?? 0);
|
|
656
|
+
}
|
|
657
|
+
upsertUser(db, claims, now);
|
|
658
|
+
// The request is passed so the row records the device and address
|
|
659
|
+
// this session was opened from — the whole substance of the fleet
|
|
660
|
+
// session list. A session that cannot say where it came from is one
|
|
661
|
+
// the owner cannot recognise, and therefore cannot act on.
|
|
662
|
+
//
|
|
663
|
+
// `signIn` rather than create + sessionCookie: those are two calls
|
|
664
|
+
// that must be told the same slot, and being told different ones is
|
|
665
|
+
// silent — a row in slot 2 with a cookie written to slot 0 evicts
|
|
666
|
+
// whoever the person was already using in another tab.
|
|
667
|
+
const issued = sessions.signIn(claims.id, c.req.raw, { slot });
|
|
668
|
+
c.header("set-cookie", issued.cookie, { append: true });
|
|
669
|
+
// Resume the deep link the sign-out interrupted, re-validating on the
|
|
670
|
+
// way back: the cookie is unsigned, and validation is what makes that
|
|
671
|
+
// safe — only a same-origin path of this app can pass, so a tampered
|
|
672
|
+
// cookie is at worst a harmless local path. Consume it either way, so
|
|
673
|
+
// the return is strictly one-shot.
|
|
674
|
+
const back = sanitizeReturnPath(readReturnCookie(c.req.raw));
|
|
675
|
+
c.header("set-cookie", clearReturnCookie(c.req.raw), { append: true });
|
|
676
|
+
c.header("set-cookie", clearSlotCookie(c.req.raw), { append: true });
|
|
677
|
+
// 🔴 The landing URL CARRIES the slot. This is what makes the tab
|
|
678
|
+
// stick to the account it just opened — through a reload, a bookmark
|
|
679
|
+
// and every link inside the app. `withSlot` strips the param for slot
|
|
680
|
+
// 0, so the single-account case keeps the clean URLs it has today.
|
|
681
|
+
return c.redirect(withSlot(back ?? "/", issued.slot), 302);
|
|
682
|
+
});
|
|
683
|
+
// ── The cascade (2026-08-01) ──────────────────────────────────────
|
|
684
|
+
// Disabling or deleting an account at auth used to leave this app's
|
|
685
|
+
// already-minted cookie working until it expired, because request-time
|
|
686
|
+
// auth deliberately never calls auth. So auth pushes the news here.
|
|
687
|
+
//
|
|
688
|
+
// Failure is LOUD (a non-2xx auth can report) rather than a silent 200:
|
|
689
|
+
// the admin page shows which apps confirmed, and "roms did not answer"
|
|
690
|
+
// is the difference between a locked-out account and one that is still
|
|
691
|
+
// playing. It is also idempotent — revoking nobody's sessions twice is
|
|
692
|
+
// a no-op, so auth is free to retry.
|
|
693
|
+
app.post(SSO_REVOKE_PATH, async (c) => {
|
|
694
|
+
const body = await c.req.json().catch(() => null);
|
|
695
|
+
const ticket = body && typeof body.ticket === "string"
|
|
696
|
+
? body.ticket
|
|
697
|
+
: "";
|
|
698
|
+
if (!ticket)
|
|
699
|
+
return c.json({ error: "missing ticket" }, 400, noStore);
|
|
700
|
+
const kid = peekKid(ticket);
|
|
701
|
+
const keys = await keysFor(kid ?? "");
|
|
702
|
+
const verdict = verifyRevocation(ticket, {
|
|
703
|
+
aud: audience,
|
|
704
|
+
keyOf: (k) => keys.get(k) ?? null,
|
|
705
|
+
now,
|
|
706
|
+
});
|
|
707
|
+
if (!verdict.ok) {
|
|
708
|
+
console.warn(`[${appKey}] refused an SSO revocation: ${verdict.reason}`);
|
|
709
|
+
return c.json({ error: verdict.reason }, 401, noStore);
|
|
710
|
+
}
|
|
711
|
+
const { sub, action, sid, nonce, exp } = verdict.claims;
|
|
712
|
+
// Replay protection shares the grant nonce guard: both are 60-second
|
|
713
|
+
// single-use statements from the same issuer, and a replayed
|
|
714
|
+
// revocation is harmless anyway (it re-revokes nothing).
|
|
715
|
+
if (!nonces.consume(nonce, exp)) {
|
|
716
|
+
return c.json({ error: "ticket already used" }, 401, noStore);
|
|
717
|
+
}
|
|
718
|
+
// One session, or all of them (2026-08-12). `sid` narrows the SAME
|
|
719
|
+
// ticket rather than adding a second revocation path — the store
|
|
720
|
+
// scopes the handle to `sub`, so a stale or guessed one can only ever
|
|
721
|
+
// end a session of the account the ticket already names.
|
|
722
|
+
//
|
|
723
|
+
// A handle that matches nothing answers `matched: false` and 200, not
|
|
724
|
+
// an error: the session it named is gone, which is the state the
|
|
725
|
+
// caller asked for. Auth renders the distinction ("already ended")
|
|
726
|
+
// rather than a red failure the owner would re-press.
|
|
727
|
+
if (sid) {
|
|
728
|
+
const matched = sessions.revokeByHandle(sub, sid);
|
|
729
|
+
console.warn(`[${appKey}] SSO revoke of one session for user ${sub}: ${matched ? "ended" : "no live session with that handle"}`);
|
|
730
|
+
return c.json({ ok: true, action, scope: "session", matched }, 200, noStore);
|
|
731
|
+
}
|
|
732
|
+
sessions.revokeAllForUser(sub);
|
|
733
|
+
if (action === "delete") {
|
|
734
|
+
// Drop the snapshot so the account stops showing up in this app's
|
|
735
|
+
// own lists. Rows keyed on the id are ORPHANED, not cascaded —
|
|
736
|
+
// same posture auth's delete already warns about, and the
|
|
737
|
+
// alternative (deleting a household member's save states because
|
|
738
|
+
// their account was tidied up) is unrecoverable.
|
|
739
|
+
db.query("DELETE FROM sso_users WHERE id = ?").run(sub);
|
|
740
|
+
}
|
|
741
|
+
console.warn(`[${appKey}] SSO ${action} applied for user ${sub}`);
|
|
742
|
+
return c.json({ ok: true, action, scope: "user" }, 200, noStore);
|
|
743
|
+
});
|
|
744
|
+
// ── The session list (2026-08-12) ─────────────────────────────────
|
|
745
|
+
// The other read-only twin of the cascade, and the one that makes it
|
|
746
|
+
// usable as a security control rather than a blunt instrument: auth
|
|
747
|
+
// can now show every live session of an account across the whole
|
|
748
|
+
// fleet — device, address, when it started, when it was last used —
|
|
749
|
+
// and end exactly one of them.
|
|
750
|
+
//
|
|
751
|
+
// Unlike the census there is nothing to opt into. Every consumer has a
|
|
752
|
+
// session store (it is how it holds anyone signed in at all), so this
|
|
753
|
+
// route can always answer, and an app that CANNOT answer is a 404 from
|
|
754
|
+
// a build that predates it. Auth renders that as "could not say",
|
|
755
|
+
// never as "no sessions" — a false empty here reads as "nothing is
|
|
756
|
+
// signed in over there", which is the one sentence this feature exists
|
|
757
|
+
// to stop somebody believing.
|
|
758
|
+
app.post(SSO_SESSIONS_PATH, async (c) => {
|
|
759
|
+
const body = await c.req.json().catch(() => null);
|
|
760
|
+
const ticket = body && typeof body.ticket === "string"
|
|
761
|
+
? body.ticket
|
|
762
|
+
: "";
|
|
763
|
+
if (!ticket)
|
|
764
|
+
return c.json({ error: "missing ticket" }, 400, noStore);
|
|
765
|
+
const kid = peekKid(ticket);
|
|
766
|
+
const keys = await keysFor(kid ?? "");
|
|
767
|
+
const verdict = verifySessionsRequest(ticket, {
|
|
768
|
+
aud: audience,
|
|
769
|
+
keyOf: (k) => keys.get(k) ?? null,
|
|
770
|
+
now,
|
|
771
|
+
});
|
|
772
|
+
if (!verdict.ok) {
|
|
773
|
+
console.warn(`[${appKey}] refused an SSO session-list request: ${verdict.reason}`);
|
|
774
|
+
return c.json({ error: verdict.reason }, 401, noStore);
|
|
775
|
+
}
|
|
776
|
+
// Deliberately NOT nonce-consumed, for the census's reason exactly:
|
|
777
|
+
// this route writes nothing, so a replay costs a re-read, and
|
|
778
|
+
// burning the shared nonce guard on a read would make auth's own
|
|
779
|
+
// timeout-and-retry fail on the retry.
|
|
780
|
+
const rows = sessions
|
|
781
|
+
.listForUser(verdict.claims.sub)
|
|
782
|
+
.slice(0, SESSIONS_MAX_PER_APP)
|
|
783
|
+
.map(({ handle, userId, createdAt, lastSeenAt, expiresAt, userAgent, ip, place }) => ({
|
|
784
|
+
handle,
|
|
785
|
+
userId,
|
|
786
|
+
createdAt,
|
|
787
|
+
lastSeenAt,
|
|
788
|
+
expiresAt,
|
|
789
|
+
userAgent,
|
|
790
|
+
ip,
|
|
791
|
+
place,
|
|
792
|
+
}));
|
|
793
|
+
return c.json({ sessions: rows }, 200, noStore);
|
|
794
|
+
});
|
|
795
|
+
// ── The census (2026-08-10) ───────────────────────────────────────
|
|
796
|
+
// The read-only twin of the route above, and the reason it exists: an
|
|
797
|
+
// admin page that can take access away must be able to say what that
|
|
798
|
+
// costs the person. Auth asks here, counts nothing itself, and shows
|
|
799
|
+
// the answer in the confirmation dialog.
|
|
800
|
+
//
|
|
801
|
+
// An app that implements no `contentCensus` answers 200 with
|
|
802
|
+
// `scope: "unknown"` rather than 404 — auth then says "this app could
|
|
803
|
+
// not tell me", which is honest, where a 404 would be indistinguishable
|
|
804
|
+
// from an old deployment that has not been rebuilt yet. Both read as
|
|
805
|
+
// "do not trust a zero here", which is the point.
|
|
806
|
+
app.post(SSO_CENSUS_PATH, async (c) => {
|
|
807
|
+
const body = await c.req.json().catch(() => null);
|
|
808
|
+
const ticket = body && typeof body.ticket === "string"
|
|
809
|
+
? body.ticket
|
|
810
|
+
: "";
|
|
811
|
+
if (!ticket)
|
|
812
|
+
return c.json({ error: "missing ticket" }, 400, noStore);
|
|
813
|
+
const kid = peekKid(ticket);
|
|
814
|
+
const keys = await keysFor(kid ?? "");
|
|
815
|
+
const verdict = verifyCensus(ticket, {
|
|
816
|
+
aud: audience,
|
|
817
|
+
keyOf: (k) => keys.get(k) ?? null,
|
|
818
|
+
now,
|
|
819
|
+
});
|
|
820
|
+
if (!verdict.ok) {
|
|
821
|
+
console.warn(`[${appKey}] refused an SSO census: ${verdict.reason}`);
|
|
822
|
+
return c.json({ error: verdict.reason }, 401, noStore);
|
|
823
|
+
}
|
|
824
|
+
// Deliberately NOT nonce-consumed. This route writes nothing, so a
|
|
825
|
+
// replay costs a re-count and discloses what the same caller could
|
|
826
|
+
// ask for again anyway — and burning the shared nonce guard on a
|
|
827
|
+
// read would make auth's own timeout-and-retry fail on the retry.
|
|
828
|
+
const subs = verdict.claims.subs.slice(0, CENSUS_MAX_SUBJECTS);
|
|
829
|
+
if (!options.contentCensus) {
|
|
830
|
+
return c.json({ census: { scope: "unknown" } }, 200, noStore);
|
|
831
|
+
}
|
|
832
|
+
try {
|
|
833
|
+
const census = await options.contentCensus(subs);
|
|
834
|
+
return c.json({ census }, 200, noStore);
|
|
835
|
+
}
|
|
836
|
+
catch (err) {
|
|
837
|
+
// Loud and non-2xx: auth must report "this app could not answer",
|
|
838
|
+
// never render a silent zero. A zero the owner believes is exactly
|
|
839
|
+
// how somebody's save states get deleted by a dropdown.
|
|
840
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
841
|
+
console.warn(`[${appKey}] content census failed: ${error}`);
|
|
842
|
+
return c.json({ error }, 500, noStore);
|
|
843
|
+
}
|
|
844
|
+
});
|
|
845
|
+
app.get("/api/auth/session", (c) => {
|
|
846
|
+
const user = sessionUser(c);
|
|
847
|
+
// ── What the account switcher needs, answered LOCALLY (2026-08-12)
|
|
848
|
+
// Every account signed in on this browser, from this app's own
|
|
849
|
+
// `sso_users` rows plus its own cookies. No call to auth, which is
|
|
850
|
+
// the fleet's central property: the switcher keeps working while the
|
|
851
|
+
// box hosting auth is asleep, and it costs one sqlite read.
|
|
852
|
+
//
|
|
853
|
+
// Only the slots this browser ALREADY holds are listed. This is not
|
|
854
|
+
// a directory of accounts — an anonymous caller sees an empty list,
|
|
855
|
+
// and a caller in slot 1 sees exactly what their own cookies prove.
|
|
856
|
+
const occupants = sessions.signedInSlots(c.req.raw);
|
|
857
|
+
const accounts = occupants.flatMap(({ slot, userId }) => {
|
|
858
|
+
const row = db
|
|
859
|
+
.query("SELECT id, email, name FROM sso_users WHERE id = ?")
|
|
860
|
+
.get(userId);
|
|
861
|
+
// A slot whose row this app has never seen is skipped rather than
|
|
862
|
+
// rendered nameless: it means a session survived a database reset,
|
|
863
|
+
// and offering an unlabelled button to switch to it is worse than
|
|
864
|
+
// not offering one.
|
|
865
|
+
return row ? [{ slot, id: row.id, email: row.email, name: row.name }] : [];
|
|
866
|
+
});
|
|
867
|
+
const base = {
|
|
868
|
+
accountsUrl: authUrl,
|
|
869
|
+
slot: sessions.slotOf(c.req.raw),
|
|
870
|
+
accounts,
|
|
871
|
+
/** No room to add another without signing one out — the menu says
|
|
872
|
+
* so rather than offering a button that fails at the callback. */
|
|
873
|
+
slotsFull: occupants.length >= MAX_ACCOUNT_SLOTS,
|
|
874
|
+
maxAccounts: MAX_ACCOUNT_SLOTS,
|
|
875
|
+
};
|
|
876
|
+
return c.json(user
|
|
877
|
+
? { authenticated: true, user, ...base }
|
|
878
|
+
: { authenticated: false, ...base }, 200, noStore);
|
|
879
|
+
});
|
|
880
|
+
// POST, not GET: a GET logout is CSRF-able and prefetchable.
|
|
881
|
+
//
|
|
882
|
+
// Slot-scoped like its redirecting sibling: this ends the account the
|
|
883
|
+
// request names and nothing else. It has always ended only THIS app's
|
|
884
|
+
// session (auth's outlives it), so there is no `all=1` here — leaving
|
|
885
|
+
// every account on a shared machine is the door that must also reach
|
|
886
|
+
// auth, and that one has to redirect.
|
|
887
|
+
app.post("/api/auth/logout", (c) => {
|
|
888
|
+
const slot = sessions.slotOf(c.req.raw);
|
|
889
|
+
sessions.revoke(c.req.raw);
|
|
890
|
+
return c.json({ authenticated: false }, 200, {
|
|
891
|
+
"set-cookie": sessions.clearedCookie(c.req.raw, slot),
|
|
892
|
+
...noStore,
|
|
893
|
+
});
|
|
894
|
+
});
|
|
895
|
+
},
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* One account, one row — even when auth re-issues its id (2026-08-23).
|
|
900
|
+
*
|
|
901
|
+
* ── The ghost ───────────────────────────────────────────────────────────────
|
|
902
|
+
* The owner, on family's Permissions screen: *"I notice two entries for
|
|
903
|
+
* smoke@auth.local."* Measured on prod the same day, and he was right — two rows,
|
|
904
|
+
* one address, two different auth ids, one of them last seen on 2026-08-10 and
|
|
905
|
+
* never again. It was **not** a family bug and not a display bug.
|
|
906
|
+
*
|
|
907
|
+
* `upsertUser` conflicts on `id`. So an account whose id at auth CHANGES — the
|
|
908
|
+
* smoke account being rotated by `bun run user -- --smoke --write`, an account
|
|
909
|
+
* recreated by hand, one of the several rows still keyed on an email address from
|
|
910
|
+
* before uuids — arrives as a brand new row and the old one is never touched
|
|
911
|
+
* again by anything. It is invisible to the revocation cascade (which deletes by
|
|
912
|
+
* the id auth still knows) and to the census, so it survives every sign-in,
|
|
913
|
+
* every deploy and every account deletion, forever, in every app that ever saw
|
|
914
|
+
* that person. This one had `is_admin = 1` frozen from before the smoke account
|
|
915
|
+
* was demoted, so family's own people list showed a **ghost administrator**.
|
|
916
|
+
*
|
|
917
|
+
* ── Why it is fixed HERE and not in family ──────────────────────────────────
|
|
918
|
+
* Nineteen apps keep this snapshot from this one function. Family is simply the
|
|
919
|
+
* app with the most rows in it, so it is where a duplicate showed up first.
|
|
920
|
+
*
|
|
921
|
+
* ── Why the newest row wins, and the old id is DROPPED ──────────────────────
|
|
922
|
+
* The id auth is presenting now is the only one that will ever resolve a session
|
|
923
|
+
* again, so the other row is unreachable by construction — it cannot sign in,
|
|
924
|
+
* cannot be revoked and cannot be deleted through the cascade. Dropping it is the
|
|
925
|
+
* only operation that changes what a person sees. 🔴 App rows keyed on the stale
|
|
926
|
+
* id are left ALONE, deliberately: that is the same posture the `delete` cascade
|
|
927
|
+
* already takes ("orphaned, not cascaded"), and deleting somebody's saved work
|
|
928
|
+
* because their account id was reissued is unrecoverable. Measured on prod before
|
|
929
|
+
* shipping this: the stale id appeared in exactly one place in family's whole
|
|
930
|
+
* database — its own `sso_users` row.
|
|
931
|
+
*/
|
|
932
|
+
function dropDuplicateSnapshots(db) {
|
|
933
|
+
// `lower(email)` so two rows differing only in case are one account, which is
|
|
934
|
+
// the same rule `emailAllowed` and auth's own registry already apply.
|
|
935
|
+
db.exec(`DELETE FROM sso_users WHERE rowid NOT IN (
|
|
936
|
+
SELECT rowid FROM (
|
|
937
|
+
SELECT rowid,
|
|
938
|
+
ROW_NUMBER() OVER (
|
|
939
|
+
PARTITION BY lower(email)
|
|
940
|
+
ORDER BY last_login_at DESC, updated_at DESC, rowid DESC
|
|
941
|
+
) AS rn
|
|
942
|
+
FROM sso_users
|
|
943
|
+
) WHERE rn = 1
|
|
944
|
+
)`);
|
|
945
|
+
}
|
|
946
|
+
function upsertUser(db, claims, now) {
|
|
947
|
+
const at = new Date(now()).toISOString();
|
|
948
|
+
// 🔴 The same address under a DIFFERENT id is the ghost described above, and
|
|
949
|
+
// this is the moment it would be created. Clearing it first is what turns the
|
|
950
|
+
// unique index from a constraint that would throw on a legitimate sign-in into
|
|
951
|
+
// one that simply cannot be violated. Scoped to `id <> ?` so an ordinary
|
|
952
|
+
// re-sign-in — by far the common path — deletes nothing and the upsert below
|
|
953
|
+
// updates in place.
|
|
954
|
+
db.query("DELETE FROM sso_users WHERE lower(email) = lower(?) AND id <> ?").run(claims.email, claims.id);
|
|
955
|
+
db.query(`INSERT INTO sso_users (id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at)
|
|
956
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
957
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
958
|
+
email = excluded.email, name = excluded.name, is_admin = excluded.is_admin,
|
|
959
|
+
is_owner = excluded.is_owner, is_granted = excluded.is_granted,
|
|
960
|
+
last_login_at = excluded.last_login_at, updated_at = excluded.updated_at`).run(claims.id, claims.email, claims.name, claims.admin ? 1 : 0, claims.owner === true ? 1 : 0, claims.granted === true ? 1 : 0, at, at, at);
|
|
961
|
+
}
|
|
962
|
+
function peekKid(grant) {
|
|
963
|
+
try {
|
|
964
|
+
const payload = grant.split(".")[0] ?? "";
|
|
965
|
+
const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
966
|
+
return typeof claims.kid === "string" ? claims.kid : null;
|
|
967
|
+
}
|
|
968
|
+
catch {
|
|
969
|
+
return null;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
//# sourceMappingURL=ssoConsumer.server.js.map
|