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): 🩹 Using sessionID as a fallback to requests where referer is missing. #20

Merged
merged 2 commits into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
77 changes: 77 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"homepage": "https://github.com/whizzzkid/helia-docker#readme",
"devDependencies": {
"@types/express": "4.x",
"@types/express-session": "1.17.9",
"@types/mime-types": "2.x",
"@types/node": "20.x",
"aegir": "40.x",
Expand All @@ -48,6 +49,7 @@
"@helia/unixfs": "1.x",
"express": "4.x",
"express-prom-bundle": "6.x",
"express-session": "1.17.3",
"file-type": "18.x",
"helia": "2.x",
"lru-cache": "10.x",
Expand Down
52 changes: 38 additions & 14 deletions src/heliaServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,23 +59,36 @@ export class HeliaServer {
]
}

/**
* Computes referer path for the request.
*/
private fetchRefererPath ({ request }: IRouteHandler): string {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private fetchRefererPath ({ request }: IRouteHandler): string {
private getRefererFromRouteHandler ({ request }: IRouteHandler): string {

I don't think we should use the term fetch here.

Also, (joke) just because HTTP spec spells referrer wrong doesn't mean we need to? =P

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it was driving me crazy, sorry tired of seeing two different spellings.

let refererPath = new URL(request.headers.referer ?? 'http://ipfs.io').pathname
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

defaulting to 'ipfs.io' here seems wrong. why not default to ${currentUrl}?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not currentUrl (because pathname) but request.hostname should work.

if (refererPath === '/') {
refererPath = request.sessionID
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we use sessionId in scenarios other than when refererPath === '/'?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

referrer should be more reliable, in most cases, this is just a fallback.

}

if (refererPath !== undefined) {
return refererPath
}

throw new Error('Error calculating referer')
}

/**
* Handles redirecting to the relative path
*/
private async redirectRelative ({ request, response }: IRouteHandler): Promise<void> {
try {
const referrerPath = new URL(request.headers.referer ?? '').pathname
if (referrerPath !== undefined) {
this.log('Referer found:', referrerPath)
let relativeRedirectPath = `${referrerPath}${request.path}`
const { namespace, address } = this.heliaFetch.parsePath(referrerPath)
if (namespace === 'ipns') {
relativeRedirectPath = `/${namespace}/${address}${request.path}`
}
// absolute redirect
this.log('Redirecting to relative to referer:', referrerPath)
response.redirect(relativeRedirectPath)
const refererPath = this.fetchRefererPath({ request, response })
let relativeRedirectPath = `${refererPath}${request.path}`
const { namespace, address } = this.heliaFetch.parsePath(refererPath)
if (namespace === 'ipns') {
relativeRedirectPath = `/${namespace}/${address}${request.path}`
}
// absolute redirect
this.log('Redirecting to relative to referer:', refererPath)
response.redirect(relativeRedirectPath)
} catch (error) {
this.log('Error redirecting to relative path:', error)
response.status(500).end()
Expand Down Expand Up @@ -113,9 +126,8 @@ export class HeliaServer {
address: reqDomain
} = this.heliaFetch.parsePath(request.path)

if (request.headers.referer !== undefined) {
this.log('Referer found:', request.headers.referer)
const refererPath = new URL(request.headers.referer).pathname
try {
const refererPath = this.fetchRefererPath({ request, response })
const {
namespace: refNamespace,
address: refDomain
Expand All @@ -131,6 +143,8 @@ export class HeliaServer {
return true
}
}
} catch (error) {
this.log('Error checking for additional redirection:', error)
}
return false
}
Expand Down Expand Up @@ -190,4 +204,14 @@ export class HeliaServer {
await this.heliaFetch.node?.gc()
response.status(200).end()
}

/**
* Generates a session ID for the request.
* This is a very ghetto way of identifying what the root ipns path for a request is.
* Overloading the sessionID the first request allows us to use the same session for all subsequent requests. Mostly!
* In many cases it won't work, but the browser won't care for those either.
*/
public sessionId (request: Request): string {
return request.sessionID ?? request.path
}
}
13 changes: 9 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import debug from 'debug'
import express from 'express'
import promBundle from 'express-prom-bundle'
import session from 'express-session'
import { HeliaServer, type IRouteEntry } from './heliaServer.js'

const logger = debug('helia-server')
const app = express()
const promMetricsMiddleware = promBundle({ includeMethod: true })

const heliaServer = new HeliaServer(logger)
await heliaServer.isReady

// Constants
const PORT = (process?.env?.PORT ?? 8080) as number
const HOST = process?.env?.HOST ?? '0.0.0.0'

// Add the prometheus middleware
const app = express()
app.use(promMetricsMiddleware)

const heliaServer = new HeliaServer(logger)
await heliaServer.isReady
app.use(session({
genid: heliaServer.sessionId,
secret: 'very secret value'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: too secret of a value. please remove from commit history.

}))

// Add the routes
app.get('/', (req, res) => {
Expand Down