{"record":{"id":"c02c13c4477f5347","repo":"coder/code-server","slug":"invalid-port","errorCode":null,"errorMessage":"Invalid port","messagePattern":"Invalid port","errorType":"http","errorClass":"HttpError","httpStatus":400,"severity":"error","filePath":"src/node/routes/pathProxy.ts","lineNumber":19,"sourceCode":"import { Request, Response } from \"express\"\nimport * as path from \"path\"\nimport { HttpCode, HttpError } from \"../../common/http\"\nimport { ensureProxyEnabled, authenticated, ensureAuthenticated, ensureOrigin, redirect, self } from \"../http\"\nimport { proxy as _proxy } from \"../proxy\"\nimport type { WebsocketRequest } from \"../wsRouter\"\n\nconst getProxyTarget = (\n  req: Request,\n  opts?: {\n    proxyBasePath?: string\n  },\n): string => {\n  // If there is a base path, strip it out.\n  const base = (req as any).base || \"\"\n  // Cast since we only have one port param.\n  const port = parseInt(req.params.port as string, 10)\n  if (isNaN(port)) {\n    throw new HttpError(\"Invalid port\", HttpCode.BadRequest)\n  }\n  return `http://0.0.0.0:${port}${opts?.proxyBasePath || \"\"}/${req.originalUrl.slice(base.length)}`\n}\n\nexport async function proxy(\n  req: Request,\n  res: Response,\n  opts?: {\n    passthroughPath?: boolean\n    proxyBasePath?: string\n  },\n): Promise<void> {\n  ensureProxyEnabled(req)\n\n  if (req.method === \"OPTIONS\" && req.args[\"skip-auth-preflight\"]) {\n    // Allow preflight requests with `skip-auth-preflight` flag\n  } else if (!(await authenticated(req))) {\n    // If visiting the root (/:port only) redirect to the login page.","sourceCodeStart":1,"sourceCodeEnd":37,"githubUrl":"https://github.com/coder/code-server/blob/51f90a376b42e217b38937410fe2855e0c1db87e/src/node/routes/pathProxy.ts#L1-L37","documentation":"Thrown by getProxyTarget() in the path proxy route when req.params.port cannot be parsed into a valid number via parseInt(..., 10). It is raised as an HttpError with status 400 (HttpCode.BadRequest), meaning Express's error handler converts it into a proper HTTP 400 response rather than a 500. The proxy is the /:port/... route that forwards requests to a local port.","triggerScenarios":"A request to the port-proxy route whose :port route parameter is missing, empty, or non-numeric (e.g. /proxy/abc/ or a misrouted URL where the port segment is a word). parseInt returns NaN for these, triggering the guard before the http://0.0.0.0:${port} target is constructed.","commonSituations":"A bad link or bookmark pointing to /proxy/<garbage>/; a route misconfiguration that lets a non-numeric segment reach the proxy handler; a client building the proxy URL from an unvalidated variable; a port passed as a string with whitespace or a leading slash.","solutions":["Correct the URL so the :port segment is a positive integer (1-65535), e.g. /proxy/3000/.","If generating proxy links programmatically, coerce and validate the port with Number.isInteger before constructing the URL.","Ensure your routing prefix is not consuming the port segment (check req.params and the base-path config).","If 400s appear unexpectedly, inspect the request URL logged upstream to find the malformed segment."],"exampleFix":"// before\nconst url = `/proxy/${maybePort}/`  // maybePort could be 'abc'\n// after\nconst n = Number(maybePort)\nif (!Number.isInteger(n) || n < 1 || n > 65535) throw new RangeError('bad port')\nconst url = `/proxy/${n}/`","handlingStrategy":"type-guard","validationCode":"// Validate the port before constructing a proxy URL\nfunction validPort(p: unknown): p is number {\n  const n = Number(p)\n  return Number.isInteger(n) && n > 0 && n <= 65535\n}\nif (!validPort(portParam)) throw new RangeError('port must be 1-65535')","typeGuard":"function isPort(v: unknown): v is number {\n  return typeof v === 'number' ? Number.isInteger(v) && v > 0 && v <= 65535\n    : typeof v === 'string' && /^\\d+$/.test(v) && +v > 0 && +v <= 65535\n}","tryCatchPattern":"// Express converts the thrown HttpError to a 400 via errorHandler. In a client:\ntry {\n  const res = await fetch(`/proxy/${port}/`)\n  if (res.status === 400) throw new Error('Server rejected the port')\n} catch (e) { /* log and surface */ }","preventionTips":["Always type-check and bound the port (1-65535) before building the proxy URL.","Route only numeric segments to the proxy handler.","URL-encode dynamic path components.","Log the raw request URL when 400s spike to catch malformed links."],"tags":["proxy","validation","http","bad-request"],"backgroundTag":null,"analyzedSha":"51f90a376b42e217b38937410fe2855e0c1db87e","analyzedAt":"2026-08-12T11:27:34.273Z","schemaVersion":2},"datasetVersion":"2026-08-12T13:17:24.610Z"}