1 | import randomString from "crypto-random-string";
|
2 | import cookieSession from "cookie-session";
|
3 | import log from "./log";
|
4 |
|
5 | function secret(
|
6 | opts: CookieSessionInterfaces.CookieSessionOptions = {}
|
7 | ): Pick<CookieSessionInterfaces.CookieSessionOptions, "signed" | "secret"> {
|
8 | if (opts.secret) {
|
9 |
|
10 | return { secret: opts.secret, signed: true };
|
11 | }
|
12 |
|
13 |
|
14 |
|
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 |
|
45 |
|
46 | export default (opts?: CookieSessionInterfaces.CookieSessionOptions) => {
|
47 | return cookieSession({
|
48 | name: "session",
|
49 | maxAge: 24 * 60 * 60 * 1000,
|
50 | ...opts,
|
51 | ...secret(opts)
|
52 | });
|
53 | };
|