@preventive/triage 1.0.0-alpha.1 → 1.0.0-alpha.11

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 (56) hide show
  1. package/api/reap.ts +79 -0
  2. package/common/save-error-reason.ts +20 -7
  3. package/common/server-info.ts +30 -0
  4. package/out/brotli-fallback.js +1 -1
  5. package/out/client-admin.js +28 -0
  6. package/out/client-managed.js +1 -0
  7. package/out/client-sync.js +16 -13
  8. package/out/graph.js +5 -4
  9. package/out/index.html +4 -15
  10. package/out/prism.js +2 -2
  11. package/out/terminal.js +32 -28
  12. package/out/view.css +1 -1
  13. package/out/view.js +89 -52
  14. package/package.json +70 -54
  15. package/{server → server-common}/origin.ts +5 -5
  16. package/{server → server-e2e}/auth.ts +5 -1
  17. package/{server → server-e2e}/bus-receiver.ts +8 -8
  18. package/server-e2e/cli.js +22 -0
  19. package/{server → server-e2e}/config.ts +21 -8
  20. package/{server → server-e2e}/db-neon.ts +31 -25
  21. package/{server → server-e2e}/db-revision-sql.ts +7 -10
  22. package/{server → server-e2e}/db-stmt.ts +2 -2
  23. package/{server → server-e2e}/db.ts +96 -135
  24. package/{server → server-e2e}/http.ts +97 -9
  25. package/{server → server-e2e}/hub.ts +7 -8
  26. package/{server → server-e2e}/index.ts +67 -43
  27. package/{server → server-e2e}/lifecycle.ts +14 -5
  28. package/{server → server-e2e}/npm-proxy.ts +1 -1
  29. package/{server → server-e2e}/objstore/blob-fs.ts +6 -8
  30. package/{server → server-e2e}/objstore/blob-vercel.ts +69 -36
  31. package/{server → server-e2e}/objstore/blob.ts +24 -9
  32. package/server-e2e/objstore/fetch-mint-guard.ts +74 -0
  33. package/{server → server-e2e}/objstore/handlers.ts +13 -15
  34. package/{server → server-e2e}/objstore/init.ts +47 -13
  35. package/{server → server-e2e}/objstore/reaper.ts +31 -11
  36. package/server-e2e/objstore/rest-deny.ts +28 -0
  37. package/server-e2e/objstore/rest-mint.ts +224 -0
  38. package/{server → server-e2e}/objstore/rest.ts +110 -93
  39. package/{server → server-e2e}/objstore/sign.ts +105 -0
  40. package/{server → server-e2e}/objstore/store-neon.ts +19 -19
  41. package/{server → server-e2e}/objstore/store.ts +98 -118
  42. package/{server → server-e2e}/objstore/tokens.ts +9 -12
  43. package/{server → server-e2e}/peer.ts +7 -9
  44. package/{server → server-e2e}/pubsub.ts +21 -31
  45. package/{server → server-e2e}/sign.ts +12 -14
  46. package/{server → server-e2e}/sse-server.ts +105 -73
  47. package/{server → server-e2e}/sse-session.ts +30 -16
  48. package/{server → server-e2e}/static.ts +22 -17
  49. package/{server → server-e2e}/sync-handlers.ts +172 -117
  50. package/{server → server-e2e}/util.ts +9 -0
  51. package/{server → server-e2e}/ws-server.ts +29 -23
  52. package/strip-types-loader.js +94 -0
  53. /package/{server → server-e2e}/config.example.json +0 -0
  54. /package/{server → server-e2e}/neon-driver.ts +0 -0
  55. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  56. /package/{server → server-e2e}/validation.ts +0 -0
@@ -8,9 +8,10 @@
8
8
  //
9
9
  // One route, POSTs only:
10
10
  //
11
- // POST /api/sync/sse[?id=<sid>]
11
+ // POST /api/sync/sse
12
12
  // Request body:
13
- // { password?: string, — cached client password
13
+ // { id?: string, — session continuation token
14
+ // password?: string, — cached client password
14
15
  // frames?: Array<protocol-frame> — WS-style JSON frames
15
16
  // }
16
17
  // Response:
@@ -25,14 +26,23 @@
25
26
  // carrying the WS protocol's JSON envelopes.
26
27
  //
27
28
  // Continuation: each POST replaces the previous POST's response as the
28
- // session's downstream channel. If the `?id=<sid>` in the URL matches
29
- // a session this replica knows, the session continues (new outbound
30
- // stream attached, old one end()ed). If the id is unknown (different
31
- // replica picked up the POST, or session expired), a fresh session
32
- // with a new id is created and announced via the first `session`
33
- // event; the client uses the new id on all subsequent POSTs and re-
34
- // sends its subscribe frames on the next POST (its `frames` carry the
35
- // signed subscribes — they always do, see client/sync/sse-transport.ts).
29
+ // session's downstream channel. If the body's `id` matches a session
30
+ // this replica knows, the session continues (new outbound stream
31
+ // attached, old one end()ed). If the id is unknown (different replica
32
+ // picked up the POST, or session expired), a fresh session with a new
33
+ // id is created and announced via the first `session` event; the
34
+ // client uses the new id on all subsequent POSTs and re-sends its
35
+ // subscribe frames on the next POST (its `frames` carry the signed
36
+ // subscribes — they always do, see client/sync/sse-transport.ts).
37
+ //
38
+ // The id rides the JSON body, NOT the URL: the sid is a live bearer
39
+ // capability (whoever presents it attaches to the session's downstream
40
+ // and inherits its operator-auth flag), and a query-string token leaks
41
+ // into proxy / LB access logs — the same reason the objstore bearer
42
+ // tokens ride the Authorization header, never the URL. A legacy
43
+ // `?id=<sid>` query form is still ACCEPTED (older client bundles sent
44
+ // it; rejecting would churn them through a fresh session per POST),
45
+ // but current clients never emit it.
36
46
  //
37
47
  // Why POSTs only: a long-lived GET pins the client to one replica via
38
48
  // TCP affinity, which would mean POSTs from the same client must be
@@ -47,17 +57,35 @@ import { type PeerConnectionDeps, setupPeerConnection } from './ws-server.ts'
47
57
  import { SseSession } from './sse-session.ts'
48
58
  import { errMsg, randomId } from './util.ts'
49
59
 
50
- // Same prefix the WS upgrade lives under (server/http.ts WS_UPGRADE_PATH
60
+ // Same prefix the WS upgrade lives under (server-e2e/http.ts WS_UPGRADE_PATH
51
61
  // = '/api/sync'); subroute keeps the SSE plane sibling to the upgrade
52
62
  // path so the same `location` block routes both.
53
63
  export const SSE_OPEN_PATH = '/api/sync/sse'
54
64
 
65
+ // Cadence of the server-driven keepalive sweep: every tick we write a `:`
66
+ // comment to each open session's downstream so intermediary proxies don't
67
+ // idle-close it (nginx et al. default to a ~60s read timeout). This is the
68
+ // server's own liveness upkeep — the client no longer POSTs a periodic ping
69
+ // (which forced a stream takeover every tick).
70
+ //
71
+ // Reaping model (replaces the old POST-driven idle timer): a session is
72
+ // dropped on its downstream response `close` — clean disconnect, or a
73
+ // half-open socket the per-session TCP keepalive forces closed (see
74
+ // SseSession.SOCKET_KEEPALIVE_MS) — NOT by this sweep. We intentionally
75
+ // trust connection-level liveness. The one topology this can't see is a
76
+ // buffering / TLS-terminating proxy that holds the upstream open after the
77
+ // real client vanished (keepalive then probes the proxy hop, not the
78
+ // client); such a session lingers until `maxSessions`, the hard backstop.
79
+ // This is the same exposure the WS heartbeat already has (its ping only
80
+ // proves the proxy↔server hop too), not a new class of leak.
81
+ const KEEPALIVE_SWEEP_MS = 30_000
82
+
55
83
  export type SseServerDeps = {
56
84
  // The WS dispatch is the cohesive unit; SSE just provides another
57
85
  // transport into it. Closure over the same handler / hub / objstore
58
86
  // / track / debug surface the WS path uses.
59
87
  peerDeps: PeerConnectionDeps
60
- // Shutdown gate. Mirror of the REST + WS branches in server/http.ts:
88
+ // Shutdown gate. Mirror of the REST + WS branches in server-e2e/http.ts:
61
89
  // an SSE POST arriving on an existing keep-alive socket after
62
90
  // SIGTERM should be rejected, not dispatched against a draining DB.
63
91
  isShuttingDown: () => boolean
@@ -65,17 +93,11 @@ export type SseServerDeps = {
65
93
  // 503 the open request. Caps the SSE-side equivalent of `wss.clients`.
66
94
  maxSessions: number
67
95
  // Max body size for one POST. Matches the WS `maxPayload` in
68
- // server/index.ts so the SSE plane can't accept frames the WS plane
96
+ // server-e2e/index.ts so the SSE plane can't accept frames the WS plane
69
97
  // would reject. The POST body envelope can hold multiple frames so
70
98
  // the per-frame budget is the same as the WS plane after the
71
99
  // dispatcher splits them.
72
100
  maxBodyBytes: number
73
- // Idle timeout for a session with no inbound POSTs. Detects the
74
- // wandered-off browser tab the WS heartbeat sweep handles via
75
- // ping/pong on real sockets. The client's JSON ping/pong heartbeat
76
- // (every 15s) is the steady-state liveness signal; this is the
77
- // hard ceiling.
78
- sessionIdleMs: number
79
101
  debug: boolean
80
102
  }
81
103
 
@@ -86,48 +108,37 @@ export type SseServer = {
86
108
  // Iterates active sessions. Lifecycle's graceful-shutdown loop
87
109
  // reads this to close SSE sessions alongside WS clients.
88
110
  sessions: () => Iterable<SseSession>
111
+ // The keepalive-sweep timer. Lifecycle clears it on shutdown (parity
112
+ // with the WS heartbeat timer) so a tick can't fire mid-teardown.
113
+ keepaliveTimer: ReturnType<typeof setInterval>
89
114
  }
90
115
 
91
116
  // Inbound POST body. Every field optional — an empty-body POST is a
92
117
  // valid "wake the session" probe (the response stream rides on every
93
118
  // POST), and a body that carries only `password` or only `frames` is
94
- // a normal partial update.
119
+ // a normal partial update. `id` is the session continuation token
120
+ // (see the header's "Continuation" note for why it rides the body).
95
121
  type SseBody = {
122
+ id?: unknown
96
123
  password?: unknown
97
124
  frames?: unknown
98
125
  }
99
126
 
100
127
  export function installSseServer(deps: SseServerDeps): SseServer {
101
- const { peerDeps, isShuttingDown, maxSessions, maxBodyBytes, sessionIdleMs, debug } = deps
128
+ const { peerDeps, isShuttingDown, maxSessions, maxBodyBytes, debug } = deps
102
129
 
103
130
  // Active SSE sessions, keyed by the random session id `createSession`
104
- // mints on the first POST that lacks a `?id=` (or whose id this
105
- // replica doesn't recognise) and that subsequent POSTs echo back to
106
- // continue the session. Bounded by `maxSessions` — over the cap, new
107
- // POSTs get a 503. POSTs against an unknown id are NOT 404'd — they
108
- // mint a fresh session instead, so a multi-replica deployment doesn't
109
- // require sticky LB routing to recover.
131
+ // mints on the first POST that carries no continuation id (or whose
132
+ // id this replica doesn't recognise) and that subsequent POSTs echo
133
+ // back (body `id` field) to continue the session. Bounded by
134
+ // `maxSessions` — over the cap, new POSTs get a 503. POSTs against an
135
+ // unknown id are NOT 404'd — they mint a fresh session instead, so a
136
+ // multi-replica deployment doesn't require sticky LB routing to
137
+ // recover.
110
138
  const sessions = new Map<string, SseSession>()
111
- // Per-session idle timer handle. Reset on every inbound POST; fires
112
- // after `sessionIdleMs` of silence to close a stranded session.
113
- const idleTimers = new Map<string, ReturnType<typeof setTimeout>>()
114
-
115
- function armIdleTimer(sid: string, session: SseSession): void {
116
- clearTimeout(idleTimers.get(sid))
117
- if (sessionIdleMs <= 0) return
118
- const t = setTimeout(() => {
119
- if (debug) console.warn(`sse: session ${sid.slice(0, 8)}… idle ${sessionIdleMs}ms → close`)
120
- try { session.terminate() } catch {}
121
- }, sessionIdleMs)
122
- t.unref?.()
123
- idleTimers.set(sid, t)
124
- }
125
139
 
126
140
  function dropSession(sid: string): void {
127
141
  sessions.delete(sid)
128
- const t = idleTimers.get(sid)
129
- if (t) clearTimeout(t)
130
- idleTimers.delete(sid)
131
142
  }
132
143
 
133
144
  function writeSseHeaders(res: ServerResponse): void {
@@ -149,7 +160,7 @@ export function installSseServer(deps: SseServerDeps): SseServer {
149
160
  res.write('retry: 1000\n\n')
150
161
  }
151
162
 
152
- function createSession(res: ServerResponse, req: HttpRequest): { sid: string; session: SseSession } | null {
163
+ function createSession(res: ServerResponse, req: HttpRequest): SseSession | null {
153
164
  if (sessions.size >= maxSessions) {
154
165
  if (debug) console.warn(`sse: refused open — sessions ${sessions.size} >= ${maxSessions}`)
155
166
  return null
@@ -158,7 +169,6 @@ export function installSseServer(deps: SseServerDeps): SseServer {
158
169
  const sid = randomId()
159
170
  const session = new SseSession(res)
160
171
  sessions.set(sid, session)
161
- armIdleTimer(sid, session)
162
172
  session.on('close', () => { dropSession(sid) })
163
173
  // Announce the continuation token BEFORE the dispatcher emits its
164
174
  // `challenge` frame so the client latches the id first and the
@@ -168,11 +178,10 @@ export function installSseServer(deps: SseServerDeps): SseServer {
168
178
  session.writeEvent('session', sid)
169
179
  // Hand the session to the shared WS connection setup so it joins
170
180
  // the same Peer / dispatcher / hub lifecycle as a real WebSocket.
171
- // `setupPeerConnection` sends the protocol `challenge` frame as
172
- // its first action; that re-uses the normal default-named SSE
173
- // message channel.
181
+ // `setupPeerConnection`'s first action is the protocol `challenge`
182
+ // frame, on the default-named SSE channel.
174
183
  setupPeerConnection(session as unknown as WebSocket, req, peerDeps)
175
- return { sid, session }
184
+ return session
176
185
  }
177
186
 
178
187
  // Drives a POST body's `password` and `frames` through the shared
@@ -255,6 +264,12 @@ export function installSseServer(deps: SseServerDeps): SseServer {
255
264
  return
256
265
  }
257
266
  }
267
+ // Resolve the continuation token: the JSON body's `id` is the
268
+ // canonical carrier; the `?id=` query form is the legacy
269
+ // fallback for older client bundles (see the header note — a
270
+ // query sid leaks into access logs). Body wins when both are
271
+ // present (current clients only ever send one).
272
+ const sid = parseSid(body.id) ?? sidFromUrl
258
273
  // Look up the session by id (if the client sent one). If found
259
274
  // and alive, attach the new response and dispatch. If not (or
260
275
  // session is closed), mint a fresh one — the response stream
@@ -269,19 +284,16 @@ export function installSseServer(deps: SseServerDeps): SseServer {
269
284
  // through to createSession with `res` still header-virgin, so
270
285
  // the new session can writeSseHeaders without ERR_HTTP_HEADERS_SENT.
271
286
  let session: SseSession | null = null
272
- let sid: string | null = null
273
- if (sidFromUrl) {
274
- const existing = sessions.get(sidFromUrl)
287
+ if (sid) {
288
+ const existing = sessions.get(sid)
275
289
  if (existing && existing.readyState === existing.OPEN && existing.attachResponse(res)) {
276
290
  writeSseHeaders(res)
277
291
  session = existing
278
- sid = sidFromUrl
279
- armIdleTimer(sid, session)
280
292
  }
281
293
  }
282
294
  if (!session) {
283
- const created = createSession(res, req)
284
- if (!created) {
295
+ session = createSession(res, req)
296
+ if (!session) {
285
297
  // Cap exceeded; createSession already logged. Response
286
298
  // headers not yet written by writeSseHeaders, so send a
287
299
  // 503 JSON instead.
@@ -289,8 +301,6 @@ export function installSseServer(deps: SseServerDeps): SseServer {
289
301
  res.end(JSON.stringify({ error: 'too-many-sessions' }))
290
302
  return
291
303
  }
292
- session = created.session
293
- sid = created.sid
294
304
  }
295
305
  dispatchBody(session, body)
296
306
  // Do NOT res.end() — the response stays open as the session's
@@ -324,29 +334,51 @@ export function installSseServer(deps: SseServerDeps): SseServer {
324
334
  return true
325
335
  }
326
336
 
327
- return { handle, sessions: () => sessions.values() }
337
+ // Server-driven keepalive sweep. Writes a `:` comment to every open
338
+ // session's downstream so proxies don't idle-close it. `unref` so it can't
339
+ // by itself hold the event loop open (parity with the WS heartbeat timer);
340
+ // skipped during shutdown so a tick can't write to a session the close
341
+ // loop is tearing down. Dead-session reaping is the response `close` event
342
+ // (see SseSession.wireResponse + the per-session TCP keepalive), NOT this
343
+ // sweep — so a half-open client is dropped without ever POSTing.
344
+ const keepaliveTimer = setInterval(() => {
345
+ if (isShuttingDown()) return
346
+ for (const session of sessions.values()) {
347
+ try { session.ping() } catch {}
348
+ }
349
+ }, KEEPALIVE_SWEEP_MS)
350
+ keepaliveTimer.unref?.()
351
+
352
+ return { handle, sessions: () => sessions.values(), keepaliveTimer }
328
353
  }
329
354
 
330
- // Bare-bones query parse for `id=<base64url>`. Avoids URLSearchParams
331
- // (which decodes percent-escapes) — `randomId()` mints a 22-char
332
- // base64url string, and the client echoes it back unchanged, so no
333
- // escapes are possible on the legitimate path. The {1,64} bound is a
355
+ // Shape gate for a continuation token from either carrier (body `id`
356
+ // field or the legacy `?id=` query). The {1,64} bound is a
334
357
  // deliberately lenient sanity gate: anything outside the base64url
335
- // alphabet is rejected (and a missing id is treated as "no id"); a
336
- // client that sent a sid this regex doesn't recognise just gets a
337
- // fresh session minted by createSession, no failure mode. The wide
338
- // length window means a future randomId-length change here doesn't
339
- // silently break old clients that round-trip a longer or shorter
340
- // token. Returns null on missing / malformed.
358
+ // alphabet is rejected; an unrecognised sid just gets a fresh session
359
+ // from createSession (no failure mode), and the wide length window
360
+ // keeps a future randomId-length change from silently breaking old
361
+ // clients that round-trip a longer/shorter token. Returns null on
362
+ // missing / non-string / malformed.
363
+ function parseSid(v: unknown): string | null {
364
+ if (typeof v !== 'string') return null
365
+ if (!/^[A-Za-z0-9_-]{1,64}$/u.test(v)) return null
366
+ return v
367
+ }
368
+
369
+ // Bare-bones query parse for the LEGACY `id=<base64url>` carrier
370
+ // (older client bundles; current clients send the sid in the POST
371
+ // body — see the header's "Continuation" note). Avoids URLSearchParams
372
+ // (which decodes percent-escapes) — `randomId()` mints a 22-char
373
+ // base64url string echoed back unchanged, so no escapes are possible
374
+ // on the legitimate path.
341
375
  function parseSidQuery(query: string | undefined): string | null {
342
376
  if (typeof query !== 'string') return null
343
377
  for (const part of query.split('&')) {
344
378
  const eq = part.indexOf('=')
345
379
  if (eq <= 0) continue
346
380
  if (part.slice(0, eq) !== 'id') continue
347
- const v = part.slice(eq + 1)
348
- if (!/^[A-Za-z0-9_-]{1,64}$/u.test(v)) return null
349
- return v
381
+ return parseSid(part.slice(eq + 1))
350
382
  }
351
383
  return null
352
384
  }
@@ -28,6 +28,20 @@ import { EventEmitter } from 'node:events'
28
28
  import type { Buffer } from 'node:buffer'
29
29
  import type { ServerResponse } from 'node:http'
30
30
 
31
+ // TCP keepalive idle delay for the downstream socket. With the client no
32
+ // longer POSTing a periodic ping (see client/sync/socket-transport.ts), a
33
+ // QUIET session whose client vanished without a FIN (crash, NAT/idle drop)
34
+ // has no application-level liveness signal — so we lean on the kernel:
35
+ // after this much idle the kernel starts probing, and a dead half-open
36
+ // socket surfaces as a `close`/`error` here. Node's `setKeepAlive` sets
37
+ // only TCP_KEEPIDLE (the delay to the FIRST probe), not the probe
38
+ // interval/count — so full teardown is this delay PLUS the OS's
39
+ // TCP_KEEPINTVL × TCP_KEEPCNT (~minutes on Linux defaults), still bounded
40
+ // and far below the kernel's hours-long default-off behaviour. `maxSessions`
41
+ // is the hard backstop. Behind a TLS-terminating / buffering proxy this
42
+ // probes the proxy hop, not the client — see the reaping note in sse-server.ts.
43
+ const SOCKET_KEEPALIVE_MS = 30_000
44
+
31
45
  export class SseSession extends EventEmitter {
32
46
  static readonly CONNECTING = 0
33
47
  static readonly OPEN = 1
@@ -62,21 +76,19 @@ export class SseSession extends EventEmitter {
62
76
  // spurious session 'error' that operators read as a real transport
63
77
  // failure on a healthy session.
64
78
  private wireResponse(res: ServerResponse): void {
79
+ // Probe half-open downstreams at the kernel level (see SOCKET_KEEPALIVE_MS).
80
+ // A failed probe trips the `close`/`error` handlers below, which is how a
81
+ // dead-but-quiet SSE client is reaped now that there's no client ping.
82
+ try { res.socket?.setKeepAlive(true, SOCKET_KEEPALIVE_MS) } catch {}
65
83
  res.on('close', () => {
66
- // Only the *current* response's close terminates the session. A
67
- // swapped-out previous response closes naturally during takeover
68
- // and must not knock the session offline.
69
- if (res !== this.currentRes) return
84
+ if (res !== this.currentRes) return // current-response guard (see above)
70
85
  if (this.readyState === SseSession.CLOSED) return
71
86
  this.readyState = SseSession.CLOSED
72
87
  this.currentRes = null
73
88
  this.emit('close')
74
89
  })
75
90
  res.on('error', (err: Error) => {
76
- // Same identity guard as close: drained-out previous responses
77
- // may emit RST/EPIPE during flush and we don't want those to
78
- // pseudo-fail the healthy session that's now on a new response.
79
- if (res !== this.currentRes) return
91
+ if (res !== this.currentRes) return // current-response guard (see above)
80
92
  this.emit('error', err)
81
93
  })
82
94
  }
@@ -148,9 +160,8 @@ export class SseSession extends EventEmitter {
148
160
  // double-emit), which means without the explicit emit here neither
149
161
  // sse-server's dropSession cleanup nor setupPeerConnection's
150
162
  // unsubscribeAll/peers.delete would run on any server-initiated
151
- // teardown — sessions / hub.subscribers / idleTimers would leak per
152
- // close. The wireResponse guard then ensures the later async fire
153
- // is a no-op.
163
+ // teardown — the sessions map / hub.subscribers would leak per close.
164
+ // The wireResponse guard then ensures the later async fire is a no-op.
154
165
  close(code?: number, reason?: string): void {
155
166
  if (this.readyState === SseSession.CLOSED) return
156
167
  const res = this.currentRes
@@ -179,11 +190,14 @@ export class SseSession extends EventEmitter {
179
190
  this.emit('close')
180
191
  }
181
192
 
182
- // The heartbeat sweep ping()s every WS client to detect dead sockets
183
- // via the unanswered-pong path. SSE has no `pong` equivalent, so we
184
- // write a comment line that keeps the channel alive across proxies
185
- // without expecting a reply. The per-session idle timeout in
186
- // sse-server.ts owns the dead-client detection.
193
+ // Server-driven keepalive, called on the SSE keepalive sweep in
194
+ // sse-server.ts. SSE has no `pong` equivalent, so we write a `:` comment
195
+ // line — ignored by the client parser — that keeps the downstream from
196
+ // being idle-closed by intermediary proxies (nginx et al. default to a
197
+ // ~60s read timeout). Dead-client detection is the response `close` event
198
+ // (clean disconnect, or a half-open socket the TCP keepalive in
199
+ // `wireResponse` forces closed), NOT this write: a `:`-comment write to a
200
+ // half-open socket just buffers, it doesn't synchronously throw.
187
201
  ping(): void {
188
202
  if (this.readyState !== SseSession.OPEN) return
189
203
  const res = this.currentRes
@@ -64,15 +64,24 @@ const COMPRESSIBLE = new Set(['.html', '.css', '.js', '.svg', '.webmanifest'])
64
64
  // navigated `image/svg+xml` icon into something script-executable.
65
65
  // `no-referrer` keeps URLs of this (potentially sensitive) viewer out
66
66
  // of outbound Referer headers, and `same-origin` CORP stops other
67
- // origins embedding these bytes. CSP is deliberately NOT here: the
68
- // HTML documents carry their own per-page `<meta http-equiv>` policy
69
- // (and the three pages differ), so a blanket header CSP would just AND
70
- // against the meta one and risk breaking a page — non-document assets
71
- // get their own flat CSP via `StaticEntry.csp` instead.
67
+ // origins embedding these bytes. COOP `same-origin` severs the
68
+ // window.opener link to any cross-origin opener/popup (so an external
69
+ // `target=_blank` GitHub/Claude link can't reach back into this context),
70
+ // and COEP `require-corp` bars the document from loading any cross-origin
71
+ // subresource that doesn't opt in via CORP/CORS. Together they also make
72
+ // the page cross-origin-isolated. Safe here because the bundle is fully
73
+ // same-origin (no external scripts/images/fonts/iframes) — switch COEP to
74
+ // `credentialless` if a cross-origin resource is ever added. CSP is
75
+ // deliberately NOT here: the HTML documents carry their own per-page
76
+ // `<meta http-equiv>` policy (and the three pages differ), so a blanket
77
+ // header CSP would just AND against the meta one and risk breaking a page
78
+ // — non-document assets get their own flat CSP via `StaticEntry.csp`.
72
79
  const SECURITY_HEADERS = {
73
80
  'x-content-type-options': 'nosniff',
74
81
  'referrer-policy': 'no-referrer',
75
82
  'cross-origin-resource-policy': 'same-origin',
83
+ 'cross-origin-opener-policy': 'same-origin',
84
+ 'cross-origin-embedder-policy': 'require-corp',
76
85
  } as const
77
86
 
78
87
  type StaticEntry = {
@@ -169,11 +178,9 @@ function buildEntry(staticDir: string, name: string): StaticEntry {
169
178
  const ext = extname(name)
170
179
  const raw = readFileSync(join(staticDir, name))
171
180
  const type = CONTENT_TYPE[ext] ?? 'application/octet-stream'
172
- // HTML: lift `<link rel="(module)preload" …>` into a Link header
173
- // and drop the tags from the served body so the bytes ship without
174
- // the now-redundant in-body hint. ETag + compression run against
175
- // the stripped body — the on-disk file and the served body diverge
176
- // by exactly the lifted tags.
181
+ // HTML: lift `<link rel="(module)preload" …>` into a Link header and
182
+ // drop the tags from the served body. ETag + compression run against
183
+ // the stripped body (see the header note on the divergence).
177
184
  let identity = raw
178
185
  let link: string | null = null
179
186
  if (ext === '.html') {
@@ -273,13 +280,11 @@ function isUnsafeAttr(s: string): boolean {
273
280
  return /[\r\n",;<>]/u.test(s)
274
281
  }
275
282
 
276
- // Find character ranges in `html` whose contents are NOT real HTML
277
- // content: comment bodies and script / noscript raw-text bodies. A
278
- // `<link>` whose match offset falls inside any range is preserved
279
- // verbatim (no header lift). Heuristic: a real HTML parser is
280
- // overkill here — the build emits clean, well-formed markup; this is
281
- // defence against the build (or a hand edit) accidentally mentioning
282
- // `<link rel="preload">` somewhere it isn't meant to fire.
283
+ // Char ranges in `html` whose contents are NOT real HTML content:
284
+ // comment bodies and script / noscript raw-text bodies. A `<link>`
285
+ // whose match offset falls in any range is preserved verbatim (no
286
+ // header lift — see the call site for why). Heuristic, not a real
287
+ // parser: the build emits clean, well-formed markup.
283
288
  function findSkipRanges(html: string): Array<[number, number]> {
284
289
  const ranges: Array<[number, number]> = []
285
290
  const patterns = [