Skip to content

fix: ctx.request.origin should respect proxy flag via X-Forwarded-Proto#1940

Open
guoyangzhen wants to merge 1 commit intokoajs:masterfrom
guoyangzhen:master
Open

fix: ctx.request.origin should respect proxy flag via X-Forwarded-Proto#1940
guoyangzhen wants to merge 1 commit intokoajs:masterfrom
guoyangzhen:master

Conversation

@guoyangzhen
Copy link
Copy Markdown

Fixes #1746

Problem

With app.proxy = true, ctx.request.origin ignores X-Forwarded-Proto and always returns http://. This is because the getter returns this.req.headers.origin (the CORS Origin header) instead of constructing the origin from the request URL.

Meanwhile ctx.protocol correctly returns https from X-Forwarded-Proto, and ctx.host correctly reads X-Forwarded-Host.

Fix

Change origin getter to construct ${protocol}://${host} using the existing getters that already respect the proxy flag. Returns null when host is empty (maintaining backward compatibility for cases where no host header is present).

Test

With nginx proxy passing X-Forwarded-Proto: https and X-Forwarded-Host: mywebsite.com:

  • Before: ctx.request.origin = http://mywebsite.com (from raw Origin header)
  • After: ctx.request.origin = https://mywebsite.com (from proxy headers)

Fixes koajs#1746

The origin getter returned this.req.headers.origin (the CORS Origin header)
which ignores the proxy flag. Changed to construct origin from protocol and
host getters, which already respect X-Forwarded-Proto and X-Forwarded-Host
when app.proxy is true.
Copy link
Copy Markdown
Author

@guoyangzhen guoyangzhen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The CI failure is because this PR changes the semantics of ctx.origin:

Before: Returns the Origin HTTP request header (used for CORS)
After: Constructs protocol://host from the request URL

The test sets headers.origin = 'http://example.com' and headers.host = 'localhost'.

  • Old behavior: returns http://example.com (the Origin header)
  • New behavior: returns http://localhost (constructed from host)

These serve different purposes. The Origin header is used for CORS, while protocol://host is the request's actual URL origin. If the intent is to provide the request URL origin, consider adding a separate getter (e.g., request.urlOrigin) instead of changing the existing ctx.origin behavior, which would be a breaking change for CORS middleware.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[fix] ctx.request.origin ignores proxy flag (X-Forwarded-Proto)

1 participant