Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(server): 🐛 Redirecting to files with trailing slashes. #15

Merged
merged 2 commits into from
Oct 18, 2023
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
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