Skip to content

Commit

Permalink
Support comma-delimited x-forwarded-proto (#227)
Browse files Browse the repository at this point in the history
* Support comma-delimited x-forwarded-proto

* Changeset
  • Loading branch information
typeofweb authored Apr 11, 2023
1 parent ab24968 commit 5057d34
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/cool-knives-punch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@saleor/app-sdk": patch
---

Support comma-delimited x-forwarded-proto
10 changes: 9 additions & 1 deletion src/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ export const getSaleorHeaders = (headers: { [name: string]: string | string[] |
});

export const getBaseUrl = (headers: { [name: string]: string | string[] | undefined }): string => {
const { host, "x-forwarded-proto": protocol = "http" } = headers;
const { host, "x-forwarded-proto": xForwardedProto = "http" } = headers;

const xForwardedProtos = Array.isArray(xForwardedProto)
? xForwardedProto.join(",")
: xForwardedProto;
const protocols = xForwardedProtos.split(",");
// prefer https over other protocols
const protocol = protocols.find((el) => el === "https") || protocols[0];

return `${protocol}://${host}`;
};
30 changes: 30 additions & 0 deletions src/middleware/with-base-url.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,35 @@ describe("middleware", () => {
expect(mockRequest.context.baseURL).toBe("https://my-saleor-env.saleor.cloud");
expect(mockHandlerFn).toHaveBeenCalledOnce();
});

it("supports multiple comma-delimited values in x-forwarded-proto", async () => {
const mockRequest = {
context: {},
headers: {
host: "my-saleor-env.saleor.cloud",
"x-forwarded-proto": "https,http",
},
} as unknown as Request;

await withBaseURL(mockHandlerFn)(mockRequest);

expect(mockRequest.context.baseURL).toBe("https://my-saleor-env.saleor.cloud");
expect(mockHandlerFn).toHaveBeenCalledOnce();
});

it("supports multiple x-forwarded-proto headers", async () => {
const mockRequest = {
context: {},
headers: {
host: "my-saleor-env.saleor.cloud",
"x-forwarded-proto": ["http", "ftp,https"],
},
} as unknown as Request;

await withBaseURL(mockHandlerFn)(mockRequest);

expect(mockRequest.context.baseURL).toBe("https://my-saleor-env.saleor.cloud");
expect(mockHandlerFn).toHaveBeenCalledOnce();
});
});
});

0 comments on commit 5057d34

Please sign in to comment.