(req: express.Request)
| 374 | * Authenticate the request origin against the host. Throw if invalid. |
| 375 | */ |
| 376 | export function authenticateOrigin(req: express.Request): void { |
| 377 | // A missing origin probably means the source is non-browser. Not sure we |
| 378 | // have a use case for this but let it through. |
| 379 | const originRaw = getFirstHeader(req, "origin") |
| 380 | if (!originRaw) { |
| 381 | return |
| 382 | } |
| 383 | |
| 384 | let origin: string |
| 385 | try { |
| 386 | origin = new URL(originRaw).host.trim().toLowerCase() |
| 387 | } catch (error) { |
| 388 | throw new Error(`unable to parse malformed origin "${originRaw}"`) |
| 389 | } |
| 390 | |
| 391 | const trustedOrigins = req.args["trusted-origins"] || [] |
| 392 | if (isTrustedOrigin(origin, trustedOrigins)) { |
| 393 | return |
| 394 | } |
| 395 | |
| 396 | const host = getHost(req) |
| 397 | if (typeof host === "undefined") { |
| 398 | // A missing host likely means the reverse proxy has not been configured to |
| 399 | // forward the host which means we cannot perform the check. Emit an error |
| 400 | // so an admin can fix the issue. |
| 401 | logger.error("No host headers found") |
| 402 | logger.error("Are you behind a reverse proxy that does not forward the host?") |
| 403 | throw new Error("no host headers found") |
| 404 | } |
| 405 | |
| 406 | if (host !== origin) { |
| 407 | throw new Error(`host "${host}" does not match origin "${origin}"`) |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | /** |
| 412 | * Get the host from headers. It will be trimmed and lowercased. |
no test coverage detected