From b5a750795044a9824bd6264d471421484ee3df9b Mon Sep 17 00:00:00 2001 From: Wan <495709+wa0x6e@users.noreply.github.com> Date: Thu, 7 Sep 2023 11:14:21 +0900 Subject: [PATCH] fix: IPFS gateway should return only json (#174) --- src/proxy.ts | 15 +++++++++++++-- test/e2e/proxy.test.ts | 10 +++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/proxy.ts b/src/proxy.ts index bb6dc28..1f7f231 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -32,9 +32,20 @@ router.get('/ipfs/*', async (req, res) => { if (!response.ok) { return Promise.reject(response.status); } - status = 1; - return { gateway, json: await response.json() }; + if (!['text/plain', 'application/json'].includes(response.headers.get('content-type'))) { + return Promise.reject(''); + } + + let json; + try { + json = await response.json(); + } catch { + return Promise.reject(''); + } + + status = 1; + return { gateway, json }; } finally { end({ status }); countOpenGatewaysRequest.dec({ name: gateway }); diff --git a/test/e2e/proxy.test.ts b/test/e2e/proxy.test.ts index 897dc1d..4da6964 100644 --- a/test/e2e/proxy.test.ts +++ b/test/e2e/proxy.test.ts @@ -4,7 +4,7 @@ const HOST = `http://localhost:${process.env.PORT || 3003}`; describe('GET /ipfs/*', () => { describe('when the IPFS cid exists', () => { - it('returns the JSON file', async () => { + it('returns a JSON file', async () => { const response = await request(HOST).get( '/ipfs/bafkreib5epjzumf3omr7rth5mtcsz4ugcoh3ut4d46hx5xhwm4b3pqr2vi' ); @@ -12,6 +12,14 @@ describe('GET /ipfs/*', () => { expect(response.statusCode).toBe(200); expect(response.body).toEqual({ status: 'OK' }); }); + + it('returns a 400 error when not a JSON file', async () => { + const response = await request(HOST).get( + '/ipfs/bafybeie2x4ptheqskiauhfz4w4pbq7o6742oupitganczhjanvffp2spti' + ); + + expect(response.statusCode).toBe(400); + }); }); describe('when the IPFS cid does not exist', () => {