From 91423106e3fb16c28d56b1aa8b99c696905ffbe3 Mon Sep 17 00:00:00 2001 From: Massimo Melina Date: Sat, 16 Dec 2023 23:58:15 +0100 Subject: [PATCH] fix: (again) login with http not working after having already logged in with https #398 --- src/index.ts | 6 ++++-- src/middlewares.ts | 18 +++++++++++------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/index.ts b/src/index.ts index b6fd93458..1b785c50b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,6 +23,7 @@ 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 @@ -30,9 +31,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) @@ -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 diff --git a/src/middlewares.ts b/src/middlewares.ts index c2854866b..7db0605b0 100644 --- a/src/middlewares.ts +++ b/src/middlewares.ts @@ -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) @@ -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) \ No newline at end of file +// 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) +} \ No newline at end of file