adds USE_INSECURE_COOKIES for hosts without SSL support

This commit is contained in:
nai-degen 2023-11-03 15:24:53 -05:00
parent 51dd0c71ba
commit 5a8fb3aff6
4 changed files with 23 additions and 4 deletions

View File

@ -48,6 +48,9 @@
# The port to listen on.
# PORT=7860
# Whether cookies should be set without the Secure flag, for hosts that don't support SSL.
# USE_INSECURE_COOKIES=false
# Detail level of logging. (trace | debug | info | warn | error)
# LOG_LEVEL=info

View File

@ -152,6 +152,11 @@ type Config = {
quotaRefreshPeriod?: "hourly" | "daily" | string;
/** Whether to allow users to change their own nicknames via the UI. */
allowNicknameChanges: boolean;
/**
* If true, cookies will be set without the `Secure` attribute, allowing
* the admin UI to used over HTTP.
*/
useInsecureCookies: boolean;
};
// To change configs, create a file called .env in the root directory.
@ -223,6 +228,7 @@ export const config: Config = {
},
quotaRefreshPeriod: getEnvWithDefault("QUOTA_REFRESH_PERIOD", undefined),
allowNicknameChanges: getEnvWithDefault("ALLOW_NICKNAME_CHANGES", true),
useInsecureCookies: getEnvWithDefault("USE_INSECURE_COOKIES", false),
} as const;
function generateCookieSecret() {
@ -326,6 +332,7 @@ export const OMITTED_KEYS: (keyof Config)[] = [
"blockMessage",
"blockRedirect",
"allowNicknameChanges",
"useInsecureCookies",
];
const getKeys = Object.keys as <T extends object>(obj: T) => Array<keyof T>;

View File

@ -1,11 +1,15 @@
import { doubleCsrf } from "csrf-csrf";
import express from "express";
import { COOKIE_SECRET } from "../config";
import { config, COOKIE_SECRET } from "../config";
const { generateToken, doubleCsrfProtection } = doubleCsrf({
getSecret: () => COOKIE_SECRET,
cookieName: "csrf",
cookieOptions: { sameSite: "strict", path: "/" },
cookieOptions: {
sameSite: "strict",
path: "/",
secure: !config.useInsecureCookies,
},
getTokenFromRequest: (req) => {
const val = req.body["_csrf"] || req.query["_csrf"];
delete req.body["_csrf"];

View File

@ -1,7 +1,7 @@
import cookieParser from "cookie-parser";
import expressSession from "express-session";
import MemoryStore from "memorystore";
import { COOKIE_SECRET } from "../config";
import { config, COOKIE_SECRET } from "../config";
const ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
@ -12,7 +12,12 @@ const sessionMiddleware = expressSession({
resave: false,
saveUninitialized: false,
store: new (MemoryStore(expressSession))({ checkPeriod: ONE_WEEK }),
cookie: { sameSite: "strict", maxAge: ONE_WEEK, signed: true },
cookie: {
sameSite: "strict",
maxAge: ONE_WEEK,
signed: true,
secure: !config.useInsecureCookies,
},
});
const withSession = [cookieParserMiddleware, sessionMiddleware];