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
15 changes: 11 additions & 4 deletions packages/core/src/authFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,18 @@ export async function authFetch(
return makeJsonTolerant(response);
}

// Upstream responses aren't always JSON: a rate-limited request comes back as plain
// text ("Too many requests…") and a 204 has no body. Native Response.json() throws on
// both, which would crash callers that parse the body before checking the status. Make
// json() tolerant so callers always get a value: parsed JSON, { message: text } for a
// Upstream responses aren't always JSON, and native Response.json() throws on the ones
// that aren't, which would crash the 24 call sites that parse a body before checking
// the status. Make json() tolerant instead: parsed JSON, { message: text } for a
// non-JSON body, or undefined for an empty one.
//
// Two things still reach this. A 204 carries no body, which is what GET
// /magic-link/check answers while a link is unconfirmed. And the auth API sits behind a
// load balancer, so a 502 or a gateway timeout arrives as that proxy's HTML error page
// without the API being involved at all, which no change upstream can prevent.
//
// The rate-limited case this used to name is fixed: a 429 has answered the JSON error
// shape since seamless-auth-api#241. That removed a reason for this shim, not the shim.
function makeJsonTolerant(response: Response): Response {
if (typeof response.text !== "function") {
return response;
Expand Down
8 changes: 4 additions & 4 deletions packages/core/tests/authFetch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ describe("authFetch", () => {
);
});

it("does not throw when the response body is non-JSON (e.g. a 429)", async () => {
it("does not throw when the response body is non-JSON (e.g. a proxy error page)", async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: false,
status: 429,
text: async () => "Too many requests, please try again later.",
status: 502,
text: async () => "<html><body>502 Bad Gateway</body></html>",
});

const { authFetch } = await import("../dist/authFetch.js");
Expand All @@ -63,7 +63,7 @@ describe("authFetch", () => {
});

await expect(res.json()).resolves.toEqual({
message: "Too many requests, please try again later.",
message: "<html><body>502 Bad Gateway</body></html>",
});
});

Expand Down
Loading