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 19, 2023
1 parent d5f3dc6 commit cf5e9ae
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ 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 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 @@ -263,10 +264,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 cf5e9ae

Please sign in to comment.