Skip to content

Commit

Permalink
fix(server): 🐛 Redirecting to files with trailing slashes. (#15)
Browse files Browse the repository at this point in the history
Signed-off-by: Nishant Arora <[email protected]>
  • Loading branch information
whizzzkid authored Oct 18, 2023
1 parent 5224019 commit a981c12
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
9 changes: 8 additions & 1 deletion src/heliaFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down Expand Up @@ -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 })
Expand Down
6 changes: 3 additions & 3 deletions src/heliaServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}
}
}
Expand Down

0 comments on commit a981c12

Please sign in to comment.