@preventive/triage 1.0.0-alpha.3 → 1.0.0-alpha.30

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 (183) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/api/reap.ts +17 -0
  3. package/cli.js +6 -0
  4. package/client/finding-link.js +305 -0
  5. package/client/linked-findings.d.ts +1 -0
  6. package/client/linked-findings.js +111 -0
  7. package/common/bundle-commit.d.ts +1 -0
  8. package/common/bundle-commit.js +4 -0
  9. package/common/bundle-metadata.d.ts +10 -0
  10. package/common/bundle-metadata.js +182 -0
  11. package/common/bundle-reasons.d.ts +2 -0
  12. package/common/bundle-reasons.js +21 -0
  13. package/common/bundle-source-links.d.ts +5 -0
  14. package/common/bundle-source-links.js +82 -0
  15. package/common/bundle-sources.d.ts +3 -0
  16. package/common/bundle-sources.js +284 -0
  17. package/common/bundle-stats.js +41 -0
  18. package/common/bundle-tabs.js +1 -0
  19. package/common/code-language.js +51 -0
  20. package/common/default-scan-models.ts +30 -0
  21. package/common/finding-id.js +47 -0
  22. package/common/github-issue-labels.d.ts +1 -0
  23. package/common/github-issue-labels.js +11 -0
  24. package/common/github-pr.ts +56 -0
  25. package/common/managed/comments.ts +34 -0
  26. package/common/managed/permissions.ts +35 -0
  27. package/common/managed/report-content.ts +42 -0
  28. package/common/managed/report-filter.ts +108 -0
  29. package/common/managed/roles.ts +28 -0
  30. package/common/managed/routes.d.ts +2 -0
  31. package/common/managed/routes.js +124 -0
  32. package/common/managed/scan-models.ts +6 -0
  33. package/common/managed/triage.ts +83 -0
  34. package/common/save-error-reason.ts +20 -7
  35. package/common/scan-server.ts +13 -0
  36. package/common/server-info.ts +35 -0
  37. package/common/utf8.d.ts +3 -0
  38. package/common/utf8.js +45 -0
  39. package/out/brotli-fallback.js +3 -3
  40. package/out/client-managed-import.js +81 -0
  41. package/out/client-managed.js +167 -0
  42. package/out/client-sync.js +16 -13
  43. package/out/github-issue-authorized.html +3 -0
  44. package/out/github-issue-authorized.js +1 -0
  45. package/out/graph.js +30 -4
  46. package/out/index.html +55 -8
  47. package/out/prism.js +2 -2
  48. package/out/stasis.svg +20 -0
  49. package/out/terminal.js +273 -39
  50. package/out/view.css +1 -1
  51. package/out/view.js +259 -63
  52. package/package.json +205 -57
  53. package/server-common/database-config.ts +16 -0
  54. package/server-common/initialize.ts +18 -0
  55. package/server-common/npm-advisories.ts +101 -0
  56. package/{server → server-common}/origin.ts +5 -5
  57. package/server-common/reap.ts +48 -0
  58. package/server-common/scan-config.ts +19 -0
  59. package/server-common/standalone.ts +29 -0
  60. package/server-common/storage-crypto.ts +182 -0
  61. package/server-common/storage-log.ts +38 -0
  62. package/server-common/vercel-blob.ts +102 -0
  63. package/server-e2e/app.ts +486 -0
  64. package/{server → server-e2e}/auth.ts +5 -1
  65. package/{server → server-e2e}/bus-receiver.ts +2 -1
  66. package/{server → server-e2e}/cli.js +9 -4
  67. package/{server → server-e2e}/config.ts +56 -35
  68. package/{server → server-e2e}/db-neon.ts +2 -2
  69. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  70. package/{server → server-e2e}/db-stmt.ts +2 -2
  71. package/{server → server-e2e}/db.ts +7 -7
  72. package/{server → server-e2e}/http.ts +110 -12
  73. package/{server → server-e2e}/hub.ts +40 -9
  74. package/server-e2e/index.ts +17 -0
  75. package/server-e2e/lifecycle.ts +95 -0
  76. package/{server → server-e2e}/neon-driver.ts +2 -2
  77. package/{server → server-e2e}/npm-proxy.ts +11 -144
  78. package/{server → server-e2e}/objstore/blob-fs.ts +2 -2
  79. package/{server → server-e2e}/objstore/blob-vercel.ts +13 -117
  80. package/{server → server-e2e}/objstore/blob.ts +9 -2
  81. package/server-e2e/objstore/fetch-mint-guard.ts +74 -0
  82. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  83. package/{server → server-e2e}/objstore/init.ts +35 -18
  84. package/{server → server-e2e}/objstore/reaper.ts +31 -11
  85. package/server-e2e/objstore/rest-deny.ts +28 -0
  86. package/server-e2e/objstore/rest-mint.ts +224 -0
  87. package/{server → server-e2e}/objstore/rest.ts +58 -33
  88. package/{server → server-e2e}/objstore/sign.ts +105 -0
  89. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  90. package/{server → server-e2e}/objstore/store.ts +7 -7
  91. package/{server → server-e2e}/objstore/tokens.ts +1 -1
  92. package/{server → server-e2e}/pubsub.ts +12 -9
  93. package/{server → server-e2e}/sign.ts +4 -4
  94. package/{server → server-e2e}/sse-server.ts +102 -68
  95. package/{server → server-e2e}/sse-session.ts +28 -8
  96. package/{server → server-e2e}/static.ts +31 -21
  97. package/server-e2e/sync-handlers.ts +408 -0
  98. package/{server → server-e2e}/util.ts +9 -0
  99. package/{server → server-e2e}/ws-server.ts +20 -9
  100. package/server-managed/activity.ts +231 -0
  101. package/server-managed/avatar-store.ts +12 -0
  102. package/server-managed/blob-store.ts +17 -0
  103. package/server-managed/brotli.ts +10 -0
  104. package/server-managed/bundle-advisories.ts +53 -0
  105. package/server-managed/bundle-advisory-inventory.ts +75 -0
  106. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  107. package/server-managed/bundle-build-diagnostics.js +23 -0
  108. package/server-managed/bundle-build-leases.ts +41 -0
  109. package/server-managed/bundle-build-worker.js +54 -0
  110. package/server-managed/bundle-build.ts +168 -0
  111. package/server-managed/bundle-cache.ts +166 -0
  112. package/server-managed/bundle-catalog.ts +29 -0
  113. package/server-managed/bundle-store.ts +24 -0
  114. package/server-managed/bundle-summary-cache.ts +116 -0
  115. package/server-managed/bundle.ts +104 -0
  116. package/server-managed/cache-storage.ts +19 -0
  117. package/server-managed/cli.js +21 -0
  118. package/server-managed/combined.ts +46 -0
  119. package/server-managed/comments.ts +151 -0
  120. package/server-managed/config.ts +149 -0
  121. package/server-managed/content-access.ts +15 -0
  122. package/server-managed/crypto.ts +25 -0
  123. package/server-managed/db-methods.ts +1517 -0
  124. package/server-managed/db-neon.ts +277 -0
  125. package/server-managed/db-schema.ts +206 -0
  126. package/server-managed/db-table-names.ts +22 -0
  127. package/server-managed/db.ts +120 -0
  128. package/server-managed/github-app.ts +385 -0
  129. package/server-managed/github-errors.ts +49 -0
  130. package/server-managed/github-issue-oauth.ts +48 -0
  131. package/server-managed/github-issues.ts +152 -0
  132. package/server-managed/github-metadata.ts +98 -0
  133. package/server-managed/github-oauth.ts +199 -0
  134. package/server-managed/github-pulls.ts +227 -0
  135. package/server-managed/http-response.ts +18 -0
  136. package/server-managed/http.ts +2350 -0
  137. package/server-managed/import-triage.ts +51 -0
  138. package/server-managed/index.ts +175 -0
  139. package/server-managed/managed-issues.ts +47 -0
  140. package/server-managed/management-catalog.ts +45 -0
  141. package/server-managed/management.ts +86 -0
  142. package/server-managed/object-storage-disk.ts +144 -0
  143. package/server-managed/object-storage-vercel.ts +60 -0
  144. package/server-managed/object-storage.ts +71 -0
  145. package/server-managed/package-entry-points.ts +51 -0
  146. package/server-managed/public-workspace.ts +146 -0
  147. package/server-managed/repo-path.ts +21 -0
  148. package/server-managed/report-migration.ts +35 -0
  149. package/server-managed/report-query.ts +10 -0
  150. package/server-managed/report-response.ts +16 -0
  151. package/server-managed/report-sources.ts +166 -0
  152. package/server-managed/repository-browser.ts +139 -0
  153. package/server-managed/repository-discovery.ts +82 -0
  154. package/server-managed/repository-policy.ts +27 -0
  155. package/server-managed/revisions.ts +35 -0
  156. package/server-managed/session.ts +78 -0
  157. package/server-managed/slugs.ts +38 -0
  158. package/server-managed/solidity-entry-points.ts +69 -0
  159. package/server-managed/sql-postgres.ts +31 -0
  160. package/server-managed/sql.ts +72 -0
  161. package/server-managed/static.ts +28 -0
  162. package/server-managed/storage-command.ts +16 -0
  163. package/server-managed/storage-db.ts +175 -0
  164. package/server-managed/storage-encryption.ts +211 -0
  165. package/server-managed/storage-maintenance.ts +223 -0
  166. package/server-managed/storage-payload.ts +72 -0
  167. package/server-managed/storage-stores.ts +81 -0
  168. package/server-managed/storage.ts +58 -0
  169. package/server-managed/team-catalog.ts +7 -0
  170. package/server-managed/team-feed.ts +173 -0
  171. package/server-managed/team-reports.ts +219 -0
  172. package/server-managed/triage-response.ts +16 -0
  173. package/server-managed/uploads.ts +65 -0
  174. package/server-managed/workspace-shares.ts +162 -0
  175. package/server.ts +50 -0
  176. package/server/index.ts +0 -477
  177. package/server/lifecycle.ts +0 -204
  178. package/server/sync-handlers.ts +0 -320
  179. /package/{LICENSE → LICENSE-MIT} +0 -0
  180. /package/{server → server-e2e}/config.example.json +0 -0
  181. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  182. /package/{server → server-e2e}/peer.ts +0 -0
  183. /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
@@ -171,7 +181,7 @@ export function installSseServer(deps: SseServerDeps): SseServer {
171
181
  // `setupPeerConnection`'s first action is the protocol `challenge`
172
182
  // frame, on the default-named SSE channel.
173
183
  setupPeerConnection(session as unknown as WebSocket, req, peerDeps)
174
- return { sid, session }
184
+ return session
175
185
  }
176
186
 
177
187
  // Drives a POST body's `password` and `frames` through the shared
@@ -254,6 +264,12 @@ export function installSseServer(deps: SseServerDeps): SseServer {
254
264
  return
255
265
  }
256
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
257
273
  // Look up the session by id (if the client sent one). If found
258
274
  // and alive, attach the new response and dispatch. If not (or
259
275
  // session is closed), mint a fresh one — the response stream
@@ -268,19 +284,16 @@ export function installSseServer(deps: SseServerDeps): SseServer {
268
284
  // through to createSession with `res` still header-virgin, so
269
285
  // the new session can writeSseHeaders without ERR_HTTP_HEADERS_SENT.
270
286
  let session: SseSession | null = null
271
- let sid: string | null = null
272
- if (sidFromUrl) {
273
- const existing = sessions.get(sidFromUrl)
287
+ if (sid) {
288
+ const existing = sessions.get(sid)
274
289
  if (existing && existing.readyState === existing.OPEN && existing.attachResponse(res)) {
275
290
  writeSseHeaders(res)
276
291
  session = existing
277
- sid = sidFromUrl
278
- armIdleTimer(sid, session)
279
292
  }
280
293
  }
281
294
  if (!session) {
282
- const created = createSession(res, req)
283
- if (!created) {
295
+ session = createSession(res, req)
296
+ if (!session) {
284
297
  // Cap exceeded; createSession already logged. Response
285
298
  // headers not yet written by writeSseHeaders, so send a
286
299
  // 503 JSON instead.
@@ -288,8 +301,6 @@ export function installSseServer(deps: SseServerDeps): SseServer {
288
301
  res.end(JSON.stringify({ error: 'too-many-sessions' }))
289
302
  return
290
303
  }
291
- session = created.session
292
- sid = created.sid
293
304
  }
294
305
  dispatchBody(session, body)
295
306
  // Do NOT res.end() — the response stays open as the session's
@@ -323,28 +334,51 @@ export function installSseServer(deps: SseServerDeps): SseServer {
323
334
  return true
324
335
  }
325
336
 
326
- 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 }
353
+ }
354
+
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
357
+ // deliberately lenient sanity gate: anything outside the base64url
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
327
367
  }
328
368
 
329
- // Bare-bones query parse for `id=<base64url>`. Avoids URLSearchParams
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
330
372
  // (which decodes percent-escapes) — `randomId()` mints a 22-char
331
373
  // base64url string echoed back unchanged, so no escapes are possible
332
- // on the legitimate path. The {1,64} bound is a deliberately lenient
333
- // sanity gate: anything outside the base64url alphabet is rejected; an
334
- // unrecognised sid just gets a fresh session from createSession (no
335
- // failure mode), and the wide length window keeps a future
336
- // randomId-length change from silently breaking old clients that
337
- // round-trip a longer/shorter token. Returns null on missing /
338
- // malformed.
374
+ // on the legitimate path.
339
375
  function parseSidQuery(query: string | undefined): string | null {
340
376
  if (typeof query !== 'string') return null
341
377
  for (const part of query.split('&')) {
342
378
  const eq = part.indexOf('=')
343
379
  if (eq <= 0) continue
344
380
  if (part.slice(0, eq) !== 'id') continue
345
- const v = part.slice(eq + 1)
346
- if (!/^[A-Za-z0-9_-]{1,64}$/u.test(v)) return null
347
- return v
381
+ return parseSid(part.slice(eq + 1))
348
382
  }
349
383
  return null
350
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,6 +76,10 @@ 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
84
  if (res !== this.currentRes) return // current-response guard (see above)
67
85
  if (this.readyState === SseSession.CLOSED) return
@@ -142,9 +160,8 @@ export class SseSession extends EventEmitter {
142
160
  // double-emit), which means without the explicit emit here neither
143
161
  // sse-server's dropSession cleanup nor setupPeerConnection's
144
162
  // unsubscribeAll/peers.delete would run on any server-initiated
145
- // teardown — sessions / hub.subscribers / idleTimers would leak per
146
- // close. The wireResponse guard then ensures the later async fire
147
- // 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.
148
165
  close(code?: number, reason?: string): void {
149
166
  if (this.readyState === SseSession.CLOSED) return
150
167
  const res = this.currentRes
@@ -173,11 +190,14 @@ export class SseSession extends EventEmitter {
173
190
  this.emit('close')
174
191
  }
175
192
 
176
- // The heartbeat sweep ping()s every WS client to detect dead sockets
177
- // via the unanswered-pong path. SSE has no `pong` equivalent, so we
178
- // write a comment line that keeps the channel alive across proxies
179
- // without expecting a reply. The per-session idle timeout in
180
- // 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.
181
201
  ping(): void {
182
202
  if (this.readyState !== SseSession.OPEN) return
183
203
  const res = this.currentRes
@@ -6,8 +6,8 @@
6
6
  // `join(staticDir, dirent.name)` from `readdirSync` at boot — the
7
7
  // request URL is only used as a Map key, never joined with the
8
8
  // filesystem — so the handler has no path-traversal surface at all:
9
- // `..`, percent-encoded slashes, nested subpaths and absolute-form
10
- // URIs all just produce a key that isn't in the map and 404.
9
+ // `..`, percent-encoded slashes and absolute-form URIs all just
10
+ // produce a key that isn't in the map and 404.
11
11
  //
12
12
  // Compression: every entry whose extension is in COMPRESSIBLE gets
13
13
  // pre-computed brotli + gzip at boot. The handler picks brotli over
@@ -38,6 +38,7 @@ import { readFileSync, readdirSync } from 'node:fs'
38
38
  import { createHash } from 'node:crypto'
39
39
  import { brotliCompressSync, gzipSync, constants as zlibConstants } from 'node:zlib'
40
40
  import { extname, join } from 'node:path'
41
+ import { scanServerHtml } from '../server-common/scan-config.ts'
41
42
 
42
43
  // MIME types for extensions the production UI bundle currently
43
44
  // emits. Anything else falls through to `application/octet-stream`
@@ -64,15 +65,24 @@ const COMPRESSIBLE = new Set(['.html', '.css', '.js', '.svg', '.webmanifest'])
64
65
  // navigated `image/svg+xml` icon into something script-executable.
65
66
  // `no-referrer` keeps URLs of this (potentially sensitive) viewer out
66
67
  // 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.
68
+ // origins embedding these bytes. COOP `same-origin` severs the
69
+ // window.opener link to any cross-origin opener/popup (so an external
70
+ // `target=_blank` GitHub/Claude link can't reach back into this context),
71
+ // and COEP `require-corp` bars the document from loading any cross-origin
72
+ // subresource that doesn't opt in via CORP/CORS. Together they also make
73
+ // the page cross-origin-isolated. Safe here because the bundle is fully
74
+ // same-origin (no external scripts/images/fonts/iframes) — switch COEP to
75
+ // `credentialless` if a cross-origin resource is ever added. CSP is
76
+ // deliberately NOT here: the HTML documents carry their own per-page
77
+ // `<meta http-equiv>` policy (and the three pages differ), so a blanket
78
+ // header CSP would just AND against the meta one and risk breaking a page
79
+ // — non-document assets get their own flat CSP via `StaticEntry.csp`.
72
80
  const SECURITY_HEADERS = {
73
81
  'x-content-type-options': 'nosniff',
74
82
  'referrer-policy': 'no-referrer',
75
83
  'cross-origin-resource-policy': 'same-origin',
84
+ 'cross-origin-opener-policy': 'same-origin',
85
+ 'cross-origin-embedder-policy': 'require-corp',
76
86
  } as const
77
87
 
78
88
  type StaticEntry = {
@@ -93,8 +103,10 @@ export type StaticHandler = (req: HttpRequest, res: ServerResponse) => boolean
93
103
  // caller falls through to its next route. Missing `staticDir`
94
104
  // (pre-build case) logs a warning and returns a handler that always
95
105
  // answers false; the API/WS planes are unaffected.
96
- export function loadStatic(staticDir: string): StaticHandler {
97
- const files = readStaticFiles(staticDir)
106
+ type StaticOptions = { transformIndex?: (html: string) => string, indexOnly?: boolean }
107
+
108
+ export function loadStatic(staticDir: string, deepviewScanServer: string | null = null, options: StaticOptions = {}): StaticHandler {
109
+ const files = readStaticFiles(staticDir, deepviewScanServer, options)
98
110
  return function handleStatic(req: HttpRequest, res: ServerResponse): boolean {
99
111
  if (req.method !== 'GET' && req.method !== 'HEAD') return false
100
112
  if (typeof req.url !== 'string') return false
@@ -142,7 +154,7 @@ export function loadStatic(staticDir: string): StaticHandler {
142
154
  }
143
155
  }
144
156
 
145
- function readStaticFiles(staticDir: string): ReadonlyMap<string, StaticEntry> {
157
+ function readStaticFiles(staticDir: string, deepviewScanServer: string | null, options: StaticOptions): ReadonlyMap<string, StaticEntry> {
146
158
  const files = new Map<string, StaticEntry>()
147
159
  let entries
148
160
  try { entries = readdirSync(staticDir, { withFileTypes: true }) } catch (err) {
@@ -156,18 +168,17 @@ function readStaticFiles(staticDir: string): ReadonlyMap<string, StaticEntry> {
156
168
  throw err
157
169
  }
158
170
  for (const entry of entries) {
159
- // `isFile()` filters subdirectories, symlinks, FIFOs etc. The
160
- // build emits a flat tree; dropping anything else keeps the
161
- // surface minimal even if a stray non-file sneaks in.
162
- if (!entry.isFile()) continue
163
- files.set(entry.name, buildEntry(staticDir, entry.name))
171
+ // Exclude subdirectories, symlinks and non-file entries.
172
+ if (!entry.isFile() || (options.indexOnly && entry.name !== 'index.html')) continue
173
+ files.set(entry.name, buildEntry(staticDir, entry.name, deepviewScanServer, options.transformIndex))
164
174
  }
165
175
  return files
166
176
  }
167
177
 
168
- function buildEntry(staticDir: string, name: string): StaticEntry {
178
+ function buildEntry(staticDir: string, name: string, deepviewScanServer: string | null = null, transformIndex: (html: string) => string = html => html): StaticEntry {
169
179
  const ext = extname(name)
170
- const raw = readFileSync(join(staticDir, name))
180
+ const source = readFileSync(join(staticDir, name))
181
+ const raw = name === 'index.html' ? Buffer.from(transformIndex(scanServerHtml(source.toString('utf8'), deepviewScanServer))) : source
171
182
  const type = CONTENT_TYPE[ext] ?? 'application/octet-stream'
172
183
  // HTML: lift `<link rel="(module)preload" …>` into a Link header and
173
184
  // drop the tags from the served body. ETag + compression run against
@@ -183,13 +194,12 @@ function buildEntry(staticDir: string, name: string): StaticEntry {
183
194
  // collision-resistance against the ~tens of files we load.
184
195
  const etag = `"${createHash('sha256').update(identity).digest('hex').slice(0, 32)}"`
185
196
  const isCompressible = COMPRESSIBLE.has(ext)
186
- // Brotli quality 11 is the maximum — slow at compress time but
187
- // we pay it once at boot and ship the smaller bytes on every
188
- // request thereafter. text mode tells the encoder we're working
197
+ // Brotli quality 9 limits boot-time compression work, including on
198
+ // serverless cold starts. Text mode tells the encoder we're working
189
199
  // on UTF-8 text (every COMPRESSIBLE entry is text-shaped).
190
200
  const br = isCompressible ? brotliCompressSync(identity, {
191
201
  params: {
192
- [zlibConstants.BROTLI_PARAM_QUALITY]: 11,
202
+ [zlibConstants.BROTLI_PARAM_QUALITY]: 9,
193
203
  [zlibConstants.BROTLI_PARAM_MODE]: zlibConstants.BROTLI_MODE_TEXT,
194
204
  },
195
205
  }) : null