From a981c12d1c97290a0622b86bf2f35960067ac821 Mon Sep 17 00:00:00 2001 From: Nishant Arora <1895906+whizzzkid@users.noreply.github.com> Date: Wed, 18 Oct 2023 10:01:29 -0600 Subject: [PATCH] =?UTF-8?q?fix(server):=20=F0=9F=90=9B=20Redirecting=20to?= =?UTF-8?q?=20files=20with=20trailing=20slashes.=20(#15)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nishant Arora <1895906+whizzzkid@users.noreply.github.com> --- src/heliaFetch.ts | 9 ++++++++- src/heliaServer.ts | 6 +++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/heliaFetch.ts b/src/heliaFetch.ts index 758a5e7..f36fa8f 100644 --- a/src/heliaFetch.ts +++ b/src/heliaFetch.ts @@ -87,6 +87,13 @@ export class HeliaFetch { return result.groups as { namespace: string, address: string, relativePath: string } } + /** + * Remove duplicate slashes and trailing slashes from a path. + */ + public sanitizeUrlPath (path: string): string { + return path.replace(/([^:]\/)\/+/g, '$1').replace(/\/$/, '') + } + /** * fetch a path from IPFS or IPNS */ @@ -163,7 +170,7 @@ export class HeliaFetch { const directoryPath = options?.path ?? '' return async (): Promise<{ name: string, cid: CID }> => { try { - const path = `${directoryPath}/${file}`.replace(/\/\//g, '/') + const path = this.sanitizeUrlPath(`${directoryPath}/${file}`) this.log('Trying to get root file:', { file, directoryPath }) const stats = await this.fs.stat(cid, { path }) this.log('Got root file:', { file, directoryPath, stats }) diff --git a/src/heliaServer.ts b/src/heliaServer.ts index d15bc46..3381014 100644 --- a/src/heliaServer.ts +++ b/src/heliaServer.ts @@ -74,7 +74,7 @@ export class HeliaServer { } // absolute redirect this.log('Redirecting to relative to referer:', referrerPath) - response.redirect(301, relativeRedirectPath) + response.redirect(relativeRedirectPath) } } catch (error) { this.log('Error redirecting to relative path:', error) @@ -125,9 +125,9 @@ export class HeliaServer { if (!request.originalUrl.startsWith(refererPath) && (refNamespace === 'ipns' || refNamespace === 'ipfs') ) { - const finalUrl = `${request.headers.referer}/${reqDomain}/${relativePath}`.replace(/([^:]\/)\/+/g, '$1') + const finalUrl = this.heliaFetch.sanitizeUrlPath(`${request.headers.referer}/${reqDomain}/${relativePath}`) this.log('Redirecting to final URL:', finalUrl) - response.redirect(301, finalUrl) + response.redirect(finalUrl) } } }