Skip to content

Commit

Permalink
fix: (again) login with http not working after having already logged …
Browse files Browse the repository at this point in the history
…in with https #398
  • Loading branch information
rejetto committed Dec 18, 2023
1 parent 1968e2b commit 9142310
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
6 changes: 4 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,17 @@ import { selfCheckMiddleware } from './selfCheck'
import { acmeMiddleware } from './acme'
import './geo'
import { geoFilter } from './geo'
import events from './events'

ok(_.intersection(Object.keys(frontEndApis), Object.keys(adminApis)).length === 0) // they share same endpoints, don't clash

process.title = 'HFS ' + VERSION
const keys = process.env.COOKIE_SIGN_KEYS?.split(',')
|| [randomId(30)] // randomness at start gives some extra security, btu also invalidates existing sessions
export const app = new Koa({ keys })
app.use(someSecurity)
app.use(sessionMiddleware)
.use(someSecurity)
.use(acmeMiddleware)
.use(sessionMiddleware)
.use(prepareState)
.use(geoFilter)
.use(selfCheckMiddleware)
Expand All @@ -45,6 +46,7 @@ app.use(someSecurity)
.use(mount(API_URI, apiMiddleware({ ...frontEndApis, ...adminApis })))
.use(serveGuiAndSharedFiles)
.on('error', errorHandler)
events.emit('app', app)

function errorHandler(err:Error & { code:string, path:string }) {
const { code } = err
Expand Down
18 changes: 11 additions & 7 deletions src/middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { defineConfig } from './config'
import { sendErrorPage } from './errorPages'
import session from 'koa-session'
import { app } from './index'
import events from './events'

const forceHttps = defineConfig('force_https', true)
const ignoreProxies = defineConfig('ignore_proxies', false)
Expand Down Expand Up @@ -251,10 +252,13 @@ export const paramsDecoder: Koa.Middleware = async (ctx, next) => {
await next()
}

export const sessionMiddleware: Koa.Middleware = (ctx, next) =>
session({
key: 'hfs_$id' + (ctx.secure ? '' : '_http'), // once https cookie is created, http cannot
signed: true,
rolling: true,
sameSite: 'lax'
}, app)(ctx, next)
// once https cookie is created, http cannot do the same. The solution is to use 2 different cookies.
// But koa-session doesn't support 2 cookies, so I made this hacky solution: keep track of the options object, to modify the key at run-time.
let internalSessionMw: any
let options: any
events.on('app', () => // wait for app to be defined
internalSessionMw = session(options = { signed: true, rolling: true, sameSite: 'lax' } as const, app) )
export const sessionMiddleware: Koa.Middleware = (ctx, next) => {
options.key = 'hfs_' + ctx.protocol
return internalSessionMw(ctx, next)
}

0 comments on commit 9142310

Please sign in to comment.