Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

3.3 KB
Raw Blame
import { readEnv } from '../../app-config';
import { SESSION_DURATION_MS, SESSION_DURATION_REMEMBER_MS } from '../../config';

import { Request, Response } from 'express';

const COOKIE_NAME = 'trek_session';

/**
 * Controls the cookie lifetime for a login:
 *  - `undefined` → persistent `maxAge: SESSION_DURATION_MS` (the historical
 *    default, used by register/demo and anything that doesn't opt in).
 *  - `true`  → persistent `maxAge: SESSION_DURATION_REMEMBER_MS` ("Remember me").
 *  - `false` → no `maxAge` — a browser-session cookie cleared on browser close.
 */
export type RememberOption = boolean | undefined;

/**
 * Decide whether the session cookie should carry the `Secure` flag.
 *
 * We previously only derived this from `NODE_ENV=production` or
 * `FORCE_HTTPS=true`. That left behind a common self-host setup:
 * TREK running behind Traefik / Caddy / Cloudflare Tunnel with
 * `NODE_ENV=development` locally and no `FORCE_HTTPS` — the cookie
 * went out without `Secure`, even though the public leg was https.
 *
 * Now we also honour `req.secure`, which Express derives from
 * `X-Forwarded-Proto` once `trust proxy` is set (TREK sets it to `1`
 * in production automatically). If Express sees the request was TLS
 * on the outermost hop, the cookie is `Secure`. `COOKIE_SECURE=false`
 * remains the explicit escape hatch for plain-HTTP LAN testing.
 */
export function cookieOptions(clear = false, req?: Request, remember?: RememberOption) {
  if (readEnv().http.cookieSecureDisabled) {
    return buildOptions(clear, false, remember);
  }
  const envSecure = readEnv().app.isProduction || readEnv().http.forceHttps;
  const requestSecure = req?.secure === true;
  return buildOptions(clear, envSecure || requestSecure, remember);
}

function resolveMaxAge(remember: RememberOption): { maxAge: number } | Record<string, never> {
  // false → session cookie (omit maxAge); true → the longer "remember me"
  // window; undefined → the historical default. Each maxAge matches the JWT exp.
  if (remember === false) return {};
  if (remember === true) return { maxAge: SESSION_DURATION_REMEMBER_MS };
  return { maxAge: SESSION_DURATION_MS };
}

function buildOptions(clear: boolean, secure: boolean, remember?: RememberOption) {
  return {
    httpOnly: true,
    secure,
    sameSite: 'lax' as const,
    path: '/',
    ...(clear ? {} : resolveMaxAge(remember)),
  };
}

/**
 * True when we are about to set a `Secure` session cookie but the request did
 * NOT arrive over HTTPS — the browser silently drops the cookie, so the next
 * request has no session and the server answers "Access token required". This is
 * the classic plain-HTTP install gotcha; callers surface it to the user with a
 * concrete fix (use HTTPS or set COOKIE_SECURE=false) instead of a bare 401.
 */
export function willDropSecureCookie(req?: Request): boolean {
  if (readEnv().http.cookieSecureDisabled) return false;
  if (req?.secure === true) return false;
  return readEnv().app.isProduction || readEnv().http.forceHttps;
}

export function setAuthCookie(res: Response, token: string, req?: Request, remember?: RememberOption): void {
  res.cookie(COOKIE_NAME, token, cookieOptions(false, req, remember));
}

export function clearAuthCookie(res: Response, req?: Request): void {
  res.clearCookie(COOKIE_NAME, cookieOptions(true, req));
}