Skip to content
Merged
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
20 changes: 19 additions & 1 deletion src/docs/swagger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,20 @@ const getForwardedHeaderValue = (
return value.split(",")[0]?.trim() || undefined;
};

const isLocalHost = (host: string): boolean => {
const normalizedHost = host.toLowerCase();

return (
normalizedHost.startsWith("localhost") ||
normalizedHost.startsWith("127.0.0.1") ||
normalizedHost.startsWith("[::1]")
);
};

export const resolveSwaggerBaseUrl = (
request: SwaggerRequestLike,
): string => {
const protocol =
const requestedProtocol =
getForwardedHeaderValue(request, "x-forwarded-proto") ?? request.protocol;
const host =
getForwardedHeaderValue(request, "x-forwarded-host") ?? request.get("host");
Expand All @@ -37,6 +47,14 @@ export const resolveSwaggerBaseUrl = (
return LOCAL_SWAGGER_SERVER.url;
}

// Public proxy platforms can forward traffic to the container over plain HTTP
// even when the external URL is HTTPS. Prefer HTTPS for non-local hosts so
// Swagger "Try it out" targets the public origin instead of an internal hop.
const protocol =
requestedProtocol === "http" && !isLocalHost(host)
? "https"
: requestedProtocol;

return `${protocol}://${host}`;
};

Expand Down
13 changes: 13 additions & 0 deletions tests/contracts/swagger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,19 @@ describe("swagger spec", () => {
expect(baseUrl).toBe("https://auth-api-production-a97b.up.railway.app");
});

it("prefers https for non-local public hosts when the proxy reports http", () => {
const baseUrl = resolveSwaggerBaseUrl({
protocol: "http",
get(header: string) {
return header === "host"
? "auth-api-production-a97b.up.railway.app"
: undefined;
},
});

expect(baseUrl).toBe("https://auth-api-production-a97b.up.railway.app");
});

it("falls back to the local server when the host header is unavailable", () => {
const baseUrl = resolveSwaggerBaseUrl({
protocol: "https",
Expand Down
Loading