Skip to content

Commit eddba8c

Browse files
lsr911claude
andcommitted
fix(matrix): guard JSON.parse against malformed homeserver response bodies
Wrap JSON.parse(text) in MatrixAuthedHttpClient.requestJson with try/catch to prevent a malformed Matrix homeserver response from throwing an unhandled SyntaxError. On parse failure, throw an Error with statusCode attached (matching the buildHttpError convention) so callers can handle it like any other Matrix API error. Co-Authored-By: Claude <[email protected]> Signed-off-by: lsr911 <[email protected]>
1 parent be94853 commit eddba8c

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

extensions/matrix/src/matrix/sdk/http-client.test.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,4 +140,33 @@ describe("MatrixAuthedHttpClient", () => {
140140
expect(httpError.message).toBe("forbidden");
141141
expect(httpError.statusCode).toBe(403);
142142
});
143+
144+
it("throws descriptive error on malformed JSON success response", async () => {
145+
performMatrixRequestMock.mockResolvedValue({
146+
response: new Response("NOT JSON {{{", {
147+
status: 200,
148+
headers: { "content-type": "application/json" },
149+
}),
150+
text: "NOT JSON {{{",
151+
buffer: Buffer.from("NOT JSON {{{", "utf8"),
152+
});
153+
154+
const client = new MatrixAuthedHttpClient({
155+
homeserver: "https://matrix.example.org",
156+
accessToken: "token",
157+
});
158+
let rejection: unknown;
159+
try {
160+
await client.requestJson({
161+
method: "GET",
162+
endpoint: "/_matrix/client/v3/sync",
163+
timeoutMs: 5000,
164+
});
165+
} catch (error) {
166+
rejection = error;
167+
}
168+
169+
expect(rejection).toBeInstanceOf(Error);
170+
expect((rejection as Error).message).toContain("malformed JSON");
171+
});
143172
});

extensions/matrix/src/matrix/sdk/http-client.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,14 @@ export class MatrixAuthedHttpClient {
5252
if (!text.trim()) {
5353
return {};
5454
}
55-
return JSON.parse(text);
55+
try {
56+
return JSON.parse(text);
57+
} catch {
58+
throw Object.assign(
59+
new Error("Matrix homeserver returned malformed JSON"),
60+
{ statusCode: response.status },
61+
);
62+
}
5663
}
5764
return text;
5865
}

0 commit comments

Comments
 (0)