Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

fix(api): stop engine.io from closing slow attach upgrades (#3222)

Vitusd0de1b21309f
diff --git a/apps/api/README.md b/apps/api/README.md
index dc77434a0..6c84ad6b8 100644
--- a/apps/api/README.md
+++ b/apps/api/README.md
@@ -550,6 +550,39 @@ Notification connections check local user existence before joining rooms.
A failed user lookup closes the transport before room admission so Socket.IO can
retry after recovery. Unknown users and invalid credentials are rejected.
+## WebSocket upgrades on the shared HTTP server
+
+Socket.IO notifications at `/api/socket.io/` and the exec attach proxy both
+listen on the API's HTTP server, so each upgrade reaches both. The notification
+gateway disables engine.io's `destroyUpgrade` cleanup, which ends any upgrade
+outside its own path that has written nothing after one second: a legitimate
+attach handshake waits for the Box to resume and for the runner to answer.
+`main.ts` closes upgrades on every other path itself.
+
+```mermaid
+sequenceDiagram
+ participant C as Client
+ participant H as http.Server
+ participant E as engine.io (Socket.IO)
+ participant M as main.ts
+ participant R as Runner
+ C->>H: GET …/attach (Upgrade)
+ H->>E: upgrade(req, socket)
+ Note over E: not /api/socket.io/, no action
+ H->>M: upgrade(req, socket)
+ M->>M: authenticate, resume Box, audit
+ M->>R: forward the upgrade
+ R-->>C: 101 on the same socket
+```
+
+Node removes the HTTP server's socket `error` listener when it emits `upgrade`,
+so the attach handler owns the client socket from that moment: a client reset
+during authentication, Box resume or lookup ends the handshake without an audit
+record or a runner request. The same handler bounds the handshake with 120
+seconds, the four 30-second waits `ensureReady` can make before the runner
+answers. On expiry the client receives `504 Gateway Timeout` and both
+connections close; the deadline ends as soon as the runner answers.
+
## Box startup timeouts
REST creation persists the Box before waiting up to 30 seconds for `STARTED`.
diff --git a/apps/api/src/boxlite-rest/attach-handshake.ts b/apps/api/src/boxlite-rest/attach-handshake.ts
new file mode 100644
index 000000000..64d39c416
--- /dev/null
+++ b/apps/api/src/boxlite-rest/attach-handshake.ts
@@ -0,0 +1,81 @@
+/*
+ * SPDX-License-Identifier: AGPL-3.0
+ * Copyright (c) 2026 BoxLite AI
+ */
+
+import { Logger } from '@nestjs/common'
+import type { ClientRequest } from 'node:http'
+import type { Socket } from 'node:net'
+
+// `ensureReady` can wait for the state lock, for STOPPED, for the lock again and for
+// STARTED, `AUTO_RESUME_TIMEOUT_SECONDS` each, before the runner answers the upgrade.
+export const ATTACH_HANDSHAKE_TIMEOUT_MS = 120_000
+
+const logger = new Logger('AttachHandshake')
+
+/** Answers an upgrade request that will not be upgraded, then closes the socket. */
+export function respondAndClose(socket: Socket, status: number, reason: string): void {
+ try {
+ socket.write(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
+ } catch {
+ // Socket may already be torn down — ignore.
+ }
+ socket.destroy()
+}
+
+// A socket `error` always follows `destroy(error)`, which already marked the socket
+// destroyed; this handler exists so the event has a listener.
+function onSocketError(this: Socket): void {
+ this.destroy()
+}
+
+/**
+ * Owns the client socket of one attach upgrade from the `upgrade` event until httpxy
+ * takes it over, and bounds the whole handshake. Node drops the HTTP server's socket
+ * `error` listener before emitting `upgrade`, and httpxy installs its own only once the
+ * runner request starts; an `error` in between would otherwise exit the process.
+ */
+export class AttachHandshake {
+ private proxyReq?: ClientRequest
+ private readonly timer: NodeJS.Timeout
+
+ constructor(private readonly socket: Socket) {
+ socket.on('error', onSocketError)
+ socket.once('close', this.release)
+ this.timer = setTimeout(() => this.expire(), ATTACH_HANDSHAKE_TIMEOUT_MS)
+ this.timer.unref()
+ }
+
+ /**
+ * httpxy owns the socket's `error` from here, and the handshake ends when the runner
+ * request does. Called from the proxy's `proxyReqWs` event, after httpxy installed
+ * its own handler.
+ */
+ bind(proxyReq: ClientRequest): void {
+ this.socket.removeListener('error', onSocketError)
+ this.proxyReq = proxyReq
+ proxyReq.once('upgrade', this.release)
+ proxyReq.once('response', this.release)
+ proxyReq.once('error', this.release)
+ proxyReq.once('close', this.release)
+ }
+
+ private readonly release = (): void => {
+ clearTimeout(this.timer)
+ this.socket.removeListener('error', onSocketError)
+ this.socket.removeListener('close', this.release)
+ this.proxyReq?.removeListener('upgrade', this.release)
+ this.proxyReq?.removeListener('response', this.release)
+ this.proxyReq?.removeListener('error', this.release)
+ this.proxyReq?.removeListener('close', this.release)
+ }
+
+ private expire(): void {
+ this.release()
+ logger.warn(`Attach handshake exceeded ${ATTACH_HANDSHAKE_TIMEOUT_MS / 1000} s`)
+ // With an error so the audit session completes its record, and before the client
+ // closes: that close also makes the audit session destroy this request.
+ this.proxyReq?.destroy(new Error('attach handshake timed out'))
+ respondAndClose(this.socket, 504, 'Gateway Timeout')
+ }
+}
diff --git a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.spec.ts b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.spec.ts
index e3dadef36..474b63282 100644
--- a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.spec.ts
@@ -1,3 +1,4 @@
+/// <reference lib="es2024.promise" />
/*
* Copyright 2025 Daytona Platforms Inc.
* Modified by BoxLite AI, 2025-2026
@@ -6,7 +7,9 @@
import { createProxyMiddleware } from 'http-proxy-middleware'
import type { IncomingMessage } from 'http'
-import { EventEmitter } from 'node:events'
+import { EventEmitter, once } from 'node:events'
+import { createServer, request } from 'node:http'
+import { connect, createServer as createTcpServer, type AddressInfo, type Socket } from 'node:net'
import { BoxliteWsProxyService } from './boxlite-ws-proxy.service'
import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'
import { AttachTicketService } from '../box/services/attach-ticket.service'
@@ -34,6 +37,22 @@ function fakeRedis() {
}
}
+/** The socket surface `upgrade()` uses; `destroy()` marks it gone as Node does. */
+function fakeSocket() {
+ const socket = new EventEmitter() as EventEmitter & {
+ destroyed: boolean
+ write: jest.Mock
+ destroy: jest.Mock
+ }
+ socket.destroyed = false
+ socket.write = jest.fn()
+ socket.destroy = jest.fn(() => {
+ socket.destroyed = true
+ socket.emit('close')
+ })
+ return socket
+}
+
describe('BoxliteWsProxyService', () => {
beforeEach(() => {
jest.clearAllMocks()
@@ -140,7 +159,7 @@ describe('BoxliteWsProxyService', () => {
const harness = buildAuthHarness()
const req = authRequest('blk_live_test')
req.headers['idempotency-key'] = key
- const socket = { write: jest.fn(), destroy: jest.fn() }
+ const socket = fakeSocket()
const proxyHandler = jest.mocked(createProxyMiddleware).mock.results.at(-1)?.value
const consume = jest.spyOn(harness.attachTickets, 'consume')
@@ -173,7 +192,7 @@ describe('BoxliteWsProxyService', () => {
autoResume: true,
})
autoResume.ensureReady.mockRejectedValue(new Error('start failed'))
- const socket = { write: jest.fn(), destroy: jest.fn() }
+ const socket = fakeSocket()
const proxyHandler = jest.mocked(createProxyMiddleware).mock.results.at(-1)?.value
await (service as unknown as BoxliteWsProxyService).upgrade(
@@ -345,12 +364,274 @@ describe('BoxliteWsProxyService', () => {
expect(organizationUserService.findOne).not.toHaveBeenCalled()
})
+ describe('the client socket', () => {
+ const proxyHandlerOf = () => jest.mocked(createProxyMiddleware).mock.results.at(-1)?.value
+
+ const admitWriteKey = (harness: ReturnType<typeof buildAuthHarness>) => {
+ harness.apiKeyService.getApiKeyByValue.mockResolvedValue({
+ organizationId: 'org-1',
+ userId: 'user-1',
+ expiresAt: null,
+ permissions: [OrganizationResourcePermission.WRITE_BOXES],
+ })
+ harness.organizationUserService.findOne.mockResolvedValue({ organizationId: 'org-1', userId: 'user-1' })
+ }
+
+ /** A Box whose resume stays pending until `resolve()`; `ensureReady` is its 30 s budget. */
+ const resumingBox = (harness: ReturnType<typeof buildAuthHarness>) => {
+ harness.boxService.findOneByIdOrName.mockResolvedValue({
+ id: 'box-uuid',
+ runnerId: 'runner-1',
+ autoResume: true,
+ })
+ const resume = Promise.withResolvers<void>()
+ harness.autoResume.ensureReady.mockImplementation(() => resume.promise)
+ return resume
+ }
+
+ /** The API's side of a real attach upgrade, routed as `main.ts` routes it. */
+ async function openUpgrade(harness: ReturnType<typeof buildAuthHarness>) {
+ const server = createServer()
+ const upgrades: Promise<void>[] = []
+ server.on('upgrade', (req: IncomingMessage, socket: Socket, head: Buffer) => {
+ upgrades.push((harness.service as unknown as BoxliteWsProxyService).upgrade(req, socket, head))
+ })
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const client = connect((server.address() as AddressInfo).port, '127.0.0.1')
+ await once(client, 'connect')
+ const upgraded = once(server, 'upgrade') as Promise<[IncomingMessage, Socket, Buffer]>
+ client.write(
+ 'GET /api/v1/org-1/boxes/public-box/executions/exec-1/attach HTTP/1.1\r\n' +
+ 'Host: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n' +
+ 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n' +
+ 'Authorization: Bearer blk_live_test\r\n\r\n',
+ )
+ const [, socket] = await upgraded
+ return {
+ socket,
+ upgrades,
+ reset: () => client.resetAndDestroy(),
+ close: () => {
+ client.destroy()
+ server.close()
+ },
+ }
+ }
+
+ // `events.once` adds an `error` listener of its own; this waits for the production
+ // handler's effect alone, so an unhandled `error` still fails the test.
+ const whenClosed = (socket: Socket) => {
+ const { promise, resolve } = Promise.withResolvers<void>()
+ socket.once('close', resolve)
+ return promise
+ }
+
+ it('survives a client reset while authentication is pending', async () => {
+ const harness = buildAuthHarness()
+ const key = Promise.withResolvers<null>()
+ harness.apiKeyService.getApiKeyByValue.mockImplementation(() => key.promise)
+ const proxyHandler = proxyHandlerOf()
+ const { socket, upgrades, reset, close } = await openUpgrade(harness)
+ try {
+ reset()
+ await whenClosed(socket)
+ key.resolve(null)
+ await upgrades[0]
+
+ expect(proxyHandler.upgrade).not.toHaveBeenCalled()
+ expect(harness.audit.createLog).not.toHaveBeenCalled()
+ } finally {
+ close()
+ }
+ })
+
+ it('survives a client reset while the Box resumes', async () => {
+ const harness = buildAuthHarness()
+ admitWriteKey(harness)
+ const resume = resumingBox(harness)
+ const proxyHandler = proxyHandlerOf()
+ const { socket, upgrades, reset, close } = await openUpgrade(harness)
+ try {
+ await new Promise<void>((resolve) => setImmediate(resolve))
+ reset()
+ await whenClosed(socket)
+ resume.resolve()
+ await upgrades[0]
+
+ expect(harness.autoResume.ensureReady).toHaveBeenCalledTimes(1)
+ expect(harness.runnerService.findOne).not.toHaveBeenCalled()
+ expect(harness.audit.createLog).not.toHaveBeenCalled()
+ expect(proxyHandler.upgrade).not.toHaveBeenCalled()
+ } finally {
+ close()
+ }
+ })
+
+ it('answers 504 when the handshake reaches 120 s before the runner request', async () => {
+ jest.useFakeTimers()
+ try {
+ const harness = buildAuthHarness()
+ admitWriteKey(harness)
+ const resume = resumingBox(harness)
+ const socket = fakeSocket()
+ const proxyHandler = proxyHandlerOf()
+
+ const pending = (harness.service as unknown as BoxliteWsProxyService).upgrade(
+ authRequest('blk_live_test'),
+ socket as never,
+ Buffer.alloc(0),
+ )
+ await jest.advanceTimersByTimeAsync(119_999)
+ expect(socket.write).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(1)
+ expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('HTTP/1.1 504 Gateway Timeout'))
+ expect(socket.destroy).toHaveBeenCalled()
+ resume.resolve()
+ await pending
+ expect(proxyHandler.upgrade).not.toHaveBeenCalled()
+ expect(harness.audit.createLog).not.toHaveBeenCalled()
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ describe('once the runner request is sent', () => {
+ const fakeProxyReq = () => {
+ const proxyReq = new EventEmitter() as EventEmitter & { destroy: jest.Mock; setHeader: jest.Mock }
+ proxyReq.destroy = jest.fn()
+ proxyReq.setHeader = jest.fn()
+ return proxyReq
+ }
+
+ /** What httpxy does once it installed its socket handler: emit `proxyReqWs`. */
+ async function handOff(harness: ReturnType<typeof buildAuthHarness>) {
+ admitWriteKey(harness)
+ const socket = fakeSocket()
+ const req = authRequest('blk_live_test')
+ const proxyReqWs = jest.mocked(createProxyMiddleware).mock.calls[0][0].on?.proxyReqWs
+ if (!proxyReqWs) throw new Error('the proxy has no proxyReqWs hook')
+ await (harness.service as unknown as BoxliteWsProxyService).upgrade(req, socket as never, Buffer.alloc(0))
+ return { socket, req, proxyReqWs }
+ }
+
+ // Only the deadline is faked; Node's networking keeps its own scheduling.
+ const fakeSetTimeoutOnly = () =>
+ jest.useFakeTimers({
+ doNotFake: ['nextTick', 'queueMicrotask', 'setImmediate', 'hrtime', 'performance', 'Date'],
+ })
+
+ /**
+ * A real runner leg: the `ClientRequest` httpxy would open toward `port`, with
+ * httpxy's persistent `error` handler, which outlives the handshake's own.
+ */
+ async function requestRunner(harness: ReturnType<typeof buildAuthHarness>, port: number) {
+ const { socket, req, proxyReqWs } = await handOff(harness)
+ const proxyReq = request({
+ host: '127.0.0.1',
+ port,
+ path: '/v1/boxes/box-uuid/executions/exec-1/attach',
+ headers: { connection: 'Upgrade', upgrade: 'websocket' },
+ })
+ const errors: Error[] = []
+ proxyReq.on('error', (error) => errors.push(error))
+ proxyReqWs(proxyReq, req, socket as never, {} as never, Buffer.alloc(0))
+ proxyReq.end()
+ return { socket, proxyReq, errors }
+ }
+
+ it('answers 504 and destroys the runner request when the runner never answers', async () => {
+ jest.useFakeTimers()
+ try {
+ const { socket, req, proxyReqWs } = await handOff(buildAuthHarness())
+ const proxyReq = fakeProxyReq()
+ proxyReqWs(proxyReq as never, req, socket as never, {} as never, Buffer.alloc(0))
+ await jest.advanceTimersByTimeAsync(120_000)
+
+ expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('504 Gateway Timeout'))
+ expect(socket.destroy).toHaveBeenCalled()
+ expect(proxyReq.destroy).toHaveBeenCalledWith(expect.any(Error))
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('drops the deadline once the runner answers 101', async () => {
+ jest.useFakeTimers()
+ try {
+ const { socket, req, proxyReqWs } = await handOff(buildAuthHarness())
+ const proxyReq = fakeProxyReq()
+ proxyReqWs(proxyReq as never, req, socket as never, {} as never, Buffer.alloc(0))
+ proxyReq.emit('upgrade', undefined, fakeSocket(), Buffer.alloc(0))
+ await jest.advanceTimersByTimeAsync(120_000)
+
+ expect(socket.write).not.toHaveBeenCalled()
+ expect(socket.destroy).not.toHaveBeenCalled()
+ expect(proxyReq.destroy).not.toHaveBeenCalled()
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('closes a real runner connection and completes the audit when the runner stalls', async () => {
+ fakeSetTimeoutOnly()
+ const runner = createTcpServer()
+ runner.listen(0, '127.0.0.1')
+ await once(runner, 'listening')
+ try {
+ const harness = buildAuthHarness()
+ const { socket, errors } = await requestRunner(harness, (runner.address() as AddressInfo).port)
+ const [runnerSocket] = await once(runner, 'connection')
+ runnerSocket.resume()
+ const runnerClosed = whenClosed(runnerSocket)
+
+ await jest.advanceTimersByTimeAsync(120_000)
+ await runnerClosed
+
+ expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('504 Gateway Timeout'))
+ expect(errors.map((error) => error.message)).toEqual(['attach handshake timed out'])
+ expect(harness.audit.updateLog).toHaveBeenCalledWith('audit-1', { statusCode: 0 }, 5000)
+ } finally {
+ runner.close()
+ jest.useRealTimers()
+ }
+ })
+
+ it('keeps a real runner connection past the deadline once the runner answers 101', async () => {
+ fakeSetTimeoutOnly()
+ const runner = createTcpServer()
+ runner.listen(0, '127.0.0.1')
+ await once(runner, 'listening')
+ // After the upgrade Node marks the request destroyed, so only its two sockets end the connection.
+ const sockets: Socket[] = []
+ try {
+ const { socket, proxyReq } = await requestRunner(buildAuthHarness(), (runner.address() as AddressInfo).port)
+ const [runnerSocket] = await once(runner, 'connection')
+ sockets.push(runnerSocket)
+ runnerSocket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n')
+ const [, connection] = await once(proxyReq, 'upgrade')
+ sockets.push(connection)
+
+ await jest.advanceTimersByTimeAsync(120_000)
+
+ expect(socket.write).not.toHaveBeenCalled()
+ expect(connection.destroyed).toBe(false)
+ } finally {
+ sockets.forEach((socket) => socket.destroy())
+ runner.close()
+ jest.useRealTimers()
+ }
+ })
+ })
+ })
+
describe('one-time attach tickets', () => {
const attachUrl = (ticket: string, execId = 'exec-1') =>
`/api/v1/org-1/boxes/public-box/executions/${execId}/attach?ticket=${ticket}&stdin=1`
async function upgradeWithTicket(harness: ReturnType<typeof buildAuthHarness>, url: string) {
- const socket = Object.assign(new EventEmitter(), { write: jest.fn(), destroy: jest.fn() })
+ const socket = fakeSocket()
const req = { url, headers: {} } as IncomingMessage
await (harness.service as unknown as BoxliteWsProxyService).upgrade(req, socket as never, Buffer.alloc(0))
return { req, socket }
diff --git a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts
index c6ee80df9..fb6822095 100644
--- a/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts
+++ b/apps/api/src/boxlite-rest/boxlite-ws-proxy.service.ts
@@ -23,6 +23,7 @@ import { BoxAutoResumeService } from '../box/services/box-auto-resume.service'
import { hasOrganizationResourcePermissions } from '../organization/guards/organization-resource-action.guard'
import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'
import { AttachTicketService } from '../box/services/attach-ticket.service'
+import { AttachHandshake, respondAndClose } from './attach-handshake'
import { AuditService } from '../audit/services/audit.service'
import { AttachAuditSession } from './attach-audit-session'
import { requestTiming } from '../common/utils/request-timing.util'
@@ -31,6 +32,7 @@ type RunnerUpgradeRequest = IncomingMessage & {
__boxliteRunner?: Runner
__boxliteRunnerBoxId?: string
__boxliteAttachAudit?: AttachAuditSession
+ __boxliteAttachHandshake?: AttachHandshake
}
// Matches /api/v1/boxes/<id>/executions/<id>/attach and the
@@ -103,6 +105,7 @@ export class BoxliteWsProxyService {
proxyReq.setHeader('Authorization', `Bearer ${runner.apiKey}`)
}
;(req as RunnerUpgradeRequest).__boxliteAttachAudit?.bind(proxyReq)
+ ;(req as RunnerUpgradeRequest).__boxliteAttachHandshake?.bind(proxyReq)
},
},
})
@@ -122,7 +125,8 @@ export class BoxliteWsProxyService {
/**
* Resolve auth + box + runner, then hand the upgrade to the shared
- * proxy middleware. Closes the socket cleanly on any failure.
+ * proxy middleware. Closes the socket cleanly on any failure, and stops
+ * once the client is gone.
*/
async upgrade(req: IncomingMessage, socket: Socket, head: Buffer): Promise<void> {
const timing = requestTiming(req)
@@ -133,16 +137,20 @@ export class BoxliteWsProxyService {
}
if (req.headers['idempotency-key'] !== undefined) {
- this.respondAndClose(socket, 400, 'Bad Request')
+ respondAndClose(socket, 400, 'Bad Request')
return
}
+ // Node removes the HTTP server's socket `error` listener before emitting `upgrade`,
+ // and the proxy installs its own only once the runner request starts.
+ const handshake = new AttachHandshake(socket)
// Browsers cannot set `Authorization` on a WebSocket; they send a ticket.
const auth = req.headers['authorization']
? await this.authenticate(req, match.tenant)
: await this.authenticateTicket(req, match)
+ if (socket.destroyed) return
if (!auth) {
- this.respondAndClose(socket, 401, 'Unauthorized')
+ respondAndClose(socket, 401, 'Unauthorized')
return
}
// The runner authenticates the proxy, not the ticket. Drop it before
@@ -151,17 +159,19 @@ export class BoxliteWsProxyService {
try {
const box = await this.boxService.findOneByIdOrName(match.boxId, auth.organization.id)
+ if (socket.destroyed) return
if (!box?.runnerId) {
- this.respondAndClose(socket, 404, 'Not Found')
+ respondAndClose(socket, 404, 'Not Found')
return
}
// A ticket names the box it was issued for, by id; the URL may use a name.
if (auth.ticketBoxId !== undefined && auth.ticketBoxId !== box.id) {
- this.respondAndClose(socket, 401, 'Unauthorized')
+ respondAndClose(socket, 401, 'Unauthorized')
return
}
if (box.autoResume) {
await this.autoResume.ensureReady(box, auth.organization, undefined, timing)
+ if (socket.destroyed) return
}
// Opening a WS attach is user activity,
// so the autostop cron does not reap a session that's still connected.
@@ -170,12 +180,14 @@ export class BoxliteWsProxyService {
.updateLastActivityAt(box.id, new Date())
.catch((err) => this.logger.warn(`updateLastActivityAt failed for ${box.id}: ${err}`))
const runner = await this.runnerService.findOne(box.runnerId)
+ if (socket.destroyed) return
if (!runner) {
- this.respondAndClose(socket, 404, 'Not Found')
+ respondAndClose(socket, 404, 'Not Found')
return
}
- ;(req as RunnerUpgradeRequest).__boxliteRunner = runner
- ;(req as RunnerUpgradeRequest).__boxliteRunnerBoxId = box.id
+ const upgradeReq = req as RunnerUpgradeRequest
+ upgradeReq.__boxliteRunner = runner
+ upgradeReq.__boxliteRunnerBoxId = box.id
let session: AttachAuditSession | undefined
try {
session = await AttachAuditSession.start(
@@ -191,11 +203,12 @@ export class BoxliteWsProxyService {
)
} catch {
this.logger.warn('Failed to create attach audit')
- this.respondAndClose(socket, 500, 'Internal Server Error')
+ respondAndClose(socket, 500, 'Internal Server Error')
return
}
if (!session) return
- ;(req as RunnerUpgradeRequest).__boxliteAttachAudit = session
+ upgradeReq.__boxliteAttachAudit = session
+ upgradeReq.__boxliteAttachHandshake = handshake
;(
this.proxy as unknown as {
upgrade: (req: IncomingMessage, socket: Socket, head: Buffer) => void
@@ -203,7 +216,7 @@ export class BoxliteWsProxyService {
).upgrade(req, socket, head)
} catch (err) {
this.logger.warn(`upgrade failed for ${req.url}: ${(err as Error).message}`)
- this.respondAndClose(socket, 404, 'Not Found')
+ respondAndClose(socket, 404, 'Not Found')
}
}
@@ -329,15 +342,6 @@ export class BoxliteWsProxyService {
return null
}
}
-
- private respondAndClose(socket: Socket, status: number, reason: string): void {
- try {
- socket.write(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
- } catch {
- // Socket may already be torn down — ignore.
- }
- socket.destroy()
- }
}
function withoutTicket(url: string): string {
diff --git a/apps/api/src/notification/gateways/notification.gateway.ts b/apps/api/src/notification/gateways/notification.gateway.ts
index e93ad3a00..7f86c5c92 100644
--- a/apps/api/src/notification/gateways/notification.gateway.ts
+++ b/apps/api/src/notification/gateways/notification.gateway.ts
@@ -27,9 +27,14 @@ import { RunnerEvents } from '../../box/constants/runner-events'
import { NotificationEmitter } from './notification-emitter.abstract'
import { UserService } from '../../user/user.service'
+// The API's HTTP server also carries the exec attach upgrade, whose handshake
+// waits for the Box and the runner. engine.io ends any upgrade outside its own
+// path that has written nothing after one second, so that cleanup stays off;
+// `main.ts` closes upgrades nobody handles.
@WebSocketGateway({
path: '/api/socket.io/',
transports: ['websocket'],
+ destroyUpgrade: false,
})
export class NotificationGateway extends NotificationEmitter implements OnGatewayInit, OnModuleInit {
private readonly logger = new Logger(NotificationGateway.name)
diff --git a/apps/api/src/notification/gateways/notification.gateway.upgrade.spec.ts b/apps/api/src/notification/gateways/notification.gateway.upgrade.spec.ts
new file mode 100644
index 000000000..9b6c73dfb
--- /dev/null
+++ b/apps/api/src/notification/gateways/notification.gateway.upgrade.spec.ts
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import 'reflect-metadata'
+import { once } from 'node:events'
+import { createServer, type Server as HttpServer } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { IoAdapter } from '@nestjs/platform-socket.io'
+// The package root does not re-export the decorator's metadata key.
+import { GATEWAY_OPTIONS } from '@nestjs/websockets/constants'
+import type { Server as SocketIOServer } from 'socket.io'
+import { WebSocket, WebSocketServer } from 'ws'
+import { NotificationGateway } from './notification.gateway'
+
+// `main.ts` routes exec attach upgrades on the API's HTTP server to the ws
+// proxy, which writes nothing until the Box is ready and the runner answers.
+describe('NotificationGateway on the shared HTTP server', () => {
+ let http: HttpServer
+ let io: SocketIOServer | undefined
+ let attach: WebSocketServer | undefined
+ let client: WebSocket | undefined
+
+ afterEach(async () => {
+ const closed = once(http, 'close')
+ client?.terminate()
+ attach?.close()
+ io?.close()
+ await closed
+ })
+
+ it('leaves a slow upgrade on another path to its handler', async () => {
+ http = createServer()
+ io = new IoAdapter(http).create(0, Reflect.getMetadata(GATEWAY_OPTIONS, NotificationGateway))
+ attach = new WebSocketServer({ noServer: true })
+ http.on('upgrade', (req, socket, head) => {
+ setTimeout(() => {
+ if (!socket.destroyed) attach?.handleUpgrade(req, socket, head, () => undefined)
+ }, 1500)
+ })
+ http.listen(0, '127.0.0.1')
+ await once(http, 'listening')
+
+ client = new WebSocket(
+ `ws://127.0.0.1:${(http.address() as AddressInfo).port}/api/v1/org-1/boxes/box-1/executions/exec-1/attach`,
+ { handshakeTimeout: 4000 },
+ )
+ await expect(once(client, 'open')).resolves.toEqual([])
+ })
+})