Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/server/signalling/handlers/fileShare.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { EventEmitter } from "node:events"
import type { IncomingMessage, ServerResponse } from "node:http"
import { describe, expect, it } from "vitest"
import {
handleFileBrowse,
handleFileDelete,
handleFileDownload,
} from "./fileShare.ts"

class FakeResponse extends EventEmitter {
statusCode = 0
body = ""

writeHead(status: number): this {
this.statusCode = status
return this
}

end(body?: string): this {
this.body = body ?? ""
this.emit("finish")
return this
}
}

function makeMalformedRequest(): IncomingMessage {
return Object.assign(new EventEmitter(), {
url: "http://[",
headers: { host: "[" },
socket: { remoteAddress: "127.0.0.1" },
}) as unknown as IncomingMessage
}

describe("file-share HTTP handlers", () => {
it.each([
["browse", handleFileBrowse],
["download", handleFileDownload],
["delete", handleFileDelete],
])("returns 400 for malformed request URLs in %s", async (_name, handler) => {
const response = new FakeResponse()

await expect(
Promise.resolve().then(() =>
handler(makeMalformedRequest(), response as unknown as ServerResponse),
),
).resolves.toBeUndefined()

expect(response.statusCode).toBe(400)
expect(JSON.parse(response.body)).toEqual({
error: "Invalid request URL",
})
})
})
20 changes: 16 additions & 4 deletions src/server/signalling/handlers/fileShare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { IncomingMessage, ServerResponse } from "node:http"
import { randomUUID } from "node:crypto"
import fs from "node:fs"
import path from "node:path"
import { json, requireAuth } from "../utils.ts"
import { json, parseRequestUrl, requireAuth } from "../utils.ts"
import logger from "../../../utils/logger.ts"
import { getUploadDir } from "../../../utils/configHelper.ts"

Expand Down Expand Up @@ -248,9 +248,13 @@ export async function handleFileBrowse(
req: IncomingMessage,
res: ServerResponse,
): Promise<void> {
const url = parseRequestUrl(req)
if (!url) {
json(res, 400, { error: "Invalid request URL" })
return
}
if (!requireAuth(req, res)) return

const url = new URL(req.url ?? "", `http://${req.headers.host}`)
const reqPath = url.searchParams.get("path")
const defaultDir = getUploadDir()

Expand Down Expand Up @@ -333,8 +337,12 @@ export function handleFileDownload(
req: IncomingMessage,
res: ServerResponse,
): void {
const url = parseRequestUrl(req)
if (!url) {
json(res, 400, { error: "Invalid request URL" })
return
}
if (!requireAuth(req, res)) return
const url = new URL(req.url ?? "", `http://${req.headers.host}`)
const filePathParam = url.searchParams.get("path")
const fileId = url.searchParams.get("fileId")

Expand Down Expand Up @@ -397,8 +405,12 @@ export function handleFileDelete(
req: IncomingMessage,
res: ServerResponse,
): void {
const url = parseRequestUrl(req)
if (!url) {
json(res, 400, { error: "Invalid request URL" })
return
}
if (!requireAuth(req, res)) return
const url = new URL(req.url ?? "", `http://${req.headers.host}`)
const fileId = url.searchParams.get("fileId")
if (!fileId) {
json(res, 400, { error: "Missing fileId" })
Expand Down
59 changes: 59 additions & 0 deletions src/server/signalling/handlers/rtc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ function makeRequest(url: string, body?: string): IncomingMessage {
return request as unknown as IncomingMessage
}

function makeMalformedRequest(): IncomingMessage {
return Object.assign(new EventEmitter(), {
url: "http://[",
headers: { host: "[" },
socket: { remoteAddress: "192.0.2.10" },
}) as unknown as IncomingMessage
}

function managerStub() {
return {
handleOffer: vi.fn(),
Expand All @@ -70,6 +78,57 @@ async function readResponse(response: FakeResponse) {
}

describe("RTC signaling HTTP handlers", () => {
it("returns 400 for malformed request URLs across RTC handlers", async () => {
const manager = asManager(managerStub())
const cases = [
(response: FakeResponse) =>
handleOffer(
makeMalformedRequest(),
response as unknown as ServerResponse,
{
webrtcManager: manager,
},
),
(response: FakeResponse) =>
handleAnswer(
makeMalformedRequest(),
response as unknown as ServerResponse,
{
webrtcManager: manager,
},
),
(response: FakeResponse) =>
handleIce(
makeMalformedRequest(),
response as unknown as ServerResponse,
{
webrtcManager: manager,
},
),
(response: FakeResponse) =>
handleSessionSSE(
makeMalformedRequest(),
response as unknown as ServerResponse,
{ webrtcManager: manager },
),
(response: FakeResponse) =>
handleSessionDelete(
makeMalformedRequest(),
response as unknown as ServerResponse,
{ webrtcManager: manager },
),
]

for (const runHandler of cases) {
const response = new FakeResponse()
expect(() => runHandler(response)).not.toThrow()
expect(await readResponse(response)).toEqual({
status: 400,
body: { error: "Invalid request URL" },
})
}
})

it("returns 503 when the WebRTC engine is unavailable", async () => {
const response = new FakeResponse()

Expand Down
66 changes: 41 additions & 25 deletions src/server/signalling/handlers/rtc.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { IncomingMessage, ServerResponse } from "node:http"
import type { WebRTCManager } from "../webRTC.ts"
import logger from "../../../utils/logger.ts"
import { parseJsonBody, json } from "../utils.ts"
import { parseJsonBody, parseRequestUrl, json } from "../utils.ts"

export interface RtcHandlerDeps {
webrtcManager: WebRTCManager | null
Expand All @@ -12,14 +12,15 @@ export function handleOffer(
res: ServerResponse,
deps: RtcHandlerDeps,
): void {
const url = parseRequestUrl(req)
if (!url) {
json(res, 400, { error: "Invalid request URL" })
return
}
if (!deps.webrtcManager) {
json(res, 503, { error: "WebRTC engine not ready" })
return
}
const url = new URL(
req.url ?? "",
`http://${req.headers.host ?? "localhost"}`,
)
const remoteAddr = req.socket.remoteAddress
const authHeader = req.headers.authorization
const queryToken = url.searchParams.get("token")
Expand Down Expand Up @@ -47,14 +48,15 @@ export function handleAnswer(
res: ServerResponse,
deps: RtcHandlerDeps,
): void {
const url = parseRequestUrl(req)
if (!url) {
json(res, 400, { error: "Invalid request URL" })
return
}
if (!deps.webrtcManager) {
json(res, 503, { error: "WebRTC engine not ready" })
return
}
const url = new URL(
req.url ?? "",
`http://${req.headers.host ?? "localhost"}`,
)
const remoteAddr = req.socket.remoteAddress
const authHeader = req.headers.authorization
const queryToken = url.searchParams.get("token")
Expand Down Expand Up @@ -92,14 +94,15 @@ export function handleIce(
res: ServerResponse,
deps: RtcHandlerDeps,
): void {
const url = parseRequestUrl(req)
if (!url) {
json(res, 400, { error: "Invalid request URL" })
return
}
if (!deps.webrtcManager) {
json(res, 503, { error: "WebRTC engine not ready" })
return
}
const url = new URL(
req.url ?? "",
`http://${req.headers.host ?? "localhost"}`,
)
const remoteAddr = req.socket.remoteAddress
const authHeader = req.headers.authorization
const queryToken = url.searchParams.get("token")
Expand Down Expand Up @@ -137,12 +140,12 @@ export function handleSessionSSE(
res: ServerResponse,
deps: RtcHandlerDeps,
): void {
const url = parseAddress(req, res)
if (url === undefined) return
if (!deps.webrtcManager) {
json(res, 503, { error: "WebRTC engine not ready" })
return
}
const url = parseAddress(req, res)
if (url === undefined) return
const accepted = deps.webrtcManager.handleSessionSse(
url.remoteAddr,
url.authHeader,
Expand All @@ -161,12 +164,14 @@ export function handleSessionDelete(
res: ServerResponse,
deps: RtcHandlerDeps,
): void {
const requestMeta = parseRequestMeta(req, res)
if (requestMeta === undefined) return
if (!deps.webrtcManager) {
json(res, 503, { error: "WebRTC engine not ready" })
return
}
// sessionId comes from the request body, not the URL — parse auth fields inline
const { remoteAddr, authHeader, queryToken } = parseRequestMeta(req)
const { remoteAddr, authHeader, queryToken } = requestMeta
const wm = deps.webrtcManager

parseJsonBody<{ sessionId?: string }>(req)
Expand Down Expand Up @@ -196,11 +201,21 @@ export function handleSessionDelete(
}

/** Extracts auth fields from a request — no sessionId guard (use parseAddress for SSE). */
function parseRequestMeta(req: IncomingMessage) {
const url = new URL(
req.url ?? "",
`http://${req.headers.host ?? "localhost"}`,
)
function parseRequestMeta(
req: IncomingMessage,
res: ServerResponse,
):
| {
remoteAddr: string | undefined
authHeader: string | undefined
queryToken: string | null
}
| undefined {
const url = parseRequestUrl(req)
if (!url) {
json(res, 400, { error: "Invalid request URL" })
return undefined
}
return {
remoteAddr: req.socket.remoteAddress,
authHeader: req.headers.authorization,
Expand All @@ -223,10 +238,11 @@ function parseAddress(
sessionId: string
}
| undefined {
const url = new URL(
req.url ?? "",
`http://${req.headers.host ?? "localhost"}`,
)
const url = parseRequestUrl(req)
if (!url) {
json(res, 400, { error: "Invalid request URL" })
return undefined
}
const sessionId = url.searchParams.get("sessionId")
if (!sessionId) {
json(res, 400, { error: "Missing sessionId" })
Expand Down
11 changes: 6 additions & 5 deletions src/server/signalling/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from "../InputHandler.ts"
import type { InputConfig } from "../types.ts"
import { getLanIp, isLoopbackAddress } from "../../utils/net.ts"
import { requireAuth, parseJsonBody, json } from "./utils.ts"
import { requireAuth, parseJsonBody, parseRequestUrl, json } from "./utils.ts"
import {
loadServerConfig,
saveServerConfig,
Expand Down Expand Up @@ -174,10 +174,11 @@ export function attachSignalingRoutes(server: any): void {
res: ServerResponse,
next?: () => void,
) => {
const url = new URL(
req.url ?? "",
`http://${req.headers.host ?? "localhost"}`,
)
const url = parseRequestUrl(req)
if (!url) {
json(res, 400, { error: "Invalid request URL" })
return
}
const { pathname } = url

if (!pathname.startsWith("/api/")) {
Expand Down
25 changes: 24 additions & 1 deletion src/server/signalling/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { IncomingMessage } from "node:http"
import { PassThrough } from "node:stream"
import { describe, expect, it } from "vitest"
import { parseJsonBody } from "./utils.ts"
import { parseJsonBody, parseRequestUrl } from "./utils.ts"

function mockRequest(chunks: Buffer[]): IncomingMessage {
const stream = new PassThrough()
Expand Down Expand Up @@ -34,3 +34,26 @@ describe("parseJsonBody", () => {
await expect(parseJsonBody(req)).rejects.toThrow("Payload too large")
})
})

describe("parseRequestUrl", () => {
it.each([
["malformed Host header", "[", "/api/host/status"],
["missing Host header", undefined, "/api/host/status"],
])("parses requests with a %s", (_description, host, reqUrl) => {
const req = {
url: reqUrl,
headers: host === undefined ? {} : { host },
} as IncomingMessage

expect(parseRequestUrl(req)?.pathname).toBe("/api/host/status")
})

it("returns null for a malformed request URL", () => {
const req = {
url: "http://[",
headers: { host: "[" },
} as IncomingMessage

expect(parseRequestUrl(req)).toBeNull()
})
})
8 changes: 8 additions & 0 deletions src/server/signalling/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ export function json(res: ServerResponse, status: number, body: unknown): void {
res.end(payload)
}

export function parseRequestUrl(req: IncomingMessage): URL | null {
try {
return new URL(req.url ?? "", "http://localhost")
} catch {
return null
}
}

/** Returns true when the caller is authorized (local or valid bearer token). */
export function requireAuth(
req: IncomingMessage,
Expand Down
Loading