UNPKG

1.42 kBPlain TextView Raw
1import randomString from "crypto-random-string";
2import cookieSession from "cookie-session";
3import log from "./log";
4
5function secret(
6 opts: CookieSessionInterfaces.CookieSessionOptions = {}
7): Pick<CookieSessionInterfaces.CookieSessionOptions, "signed" | "secret"> {
8 if (opts.secret) {
9 /* Assume user provided everything needed */
10 return { secret: opts.secret, signed: true };
11 }
12
13 // Don't sign session when testing as the http client in Node < 10 does not
14 // properly handle multiple set-cookie headers.
15 const signed = process.env.NODE_ENV !== "test";
16
17 if (!signed) {
18 return { signed: false, secret: undefined };
19 }
20
21 if (process.env.NODE_ENV === "development") {
22 log.info(
23 `SESSION_SECRET env not set - using default secret for development.`
24 );
25 return {
26 secret: "insecure",
27 signed: true
28 };
29 }
30
31 log.info(
32 `SESSION_SECRET env not set - generating a random secret for production.`
33 );
34 log.info(
35 `NOTE: Set a secret to keep sessions across server restarts and to allow horizontal scaling.`
36 );
37 return {
38 secret: randomString({ length: 20 }),
39 signed: true
40 };
41}
42
43/**
44 * Returns a middleware that does the session handling.
45 */
46export default (opts?: CookieSessionInterfaces.CookieSessionOptions) => {
47 return cookieSession({
48 name: "session",
49 maxAge: 24 * 60 * 60 * 1000, // 24 hours
50 ...opts,
51 ...secret(opts)
52 });
53};