2026-03-28 01:40:18 +08:00
|
|
|
import crypto from 'crypto';
|
|
|
|
|
import fs from 'fs';
|
|
|
|
|
import path from 'path';
|
2026-03-19 06:58:08 +08:00
|
|
|
|
2026-04-01 12:38:38 +08:00
|
|
|
const dataDir = path.resolve(__dirname, '../data');
|
2026-03-19 06:58:08 +08:00
|
|
|
|
2026-04-01 12:38:38 +08:00
|
|
|
// JWT_SECRET is always managed by the server — auto-generated on first start and
|
|
|
|
|
// persisted to data/.jwt_secret. Use the admin panel to rotate it; do not set it
|
|
|
|
|
// via environment variable (env var would override a rotation on next restart).
|
|
|
|
|
const jwtSecretFile = path.join(dataDir, '.jwt_secret');
|
|
|
|
|
let _jwtSecret: string;
|
v2.1.0 — Real-time collaboration, performance & security overhaul
Real-Time Collaboration (WebSocket):
- WebSocket server with JWT auth and trip-based rooms
- Live sync for all CRUD operations (places, assignments, days, notes, budget, packing, reservations, files)
- Socket-based exclusion to prevent duplicate updates
- Auto-reconnect with exponential backoff
- Assignment move sync between days
Performance:
- 16 database indexes on all foreign key columns
- N+1 query fix in places, assignments and days endpoints
- Marker clustering (react-leaflet-cluster) with configurable radius
- List virtualization (react-window) for places sidebar
- useMemo for filtered places
- SQLite WAL mode + busy_timeout for concurrent writes
- Weather API: server-side cache (1h forecast, 15min current) + client sessionStorage
- Google Places photos: persisted to DB after first fetch
- Google Details: 3-tier cache (memory → sessionStorage → API)
Security:
- CORS auto-configuration (production: same-origin, dev: open)
- API keys removed from /auth/me response
- Admin-only endpoint for reading API keys
- Path traversal prevention in cover image deletion
- JWT secret persisted to file (survives restarts)
- Avatar upload file extension whitelist
- API key fallback: normal users use admin's key without exposure
- Case-insensitive email login
Dark Mode:
- Fixed hardcoded colors across PackingList, Budget, ReservationModal, ReservationsPanel
- Mobile map buttons and sidebar sheets respect dark mode
- Cluster markers always dark
UI/UX:
- Redesigned login page with animated planes, stars and feature cards
- Admin: create user functionality with CustomSelect
- Mobile: day-picker popup for assigning places to days
- Mobile: touch-friendly reorder buttons (32px targets)
- Mobile: responsive text (shorter labels on small screens)
- Packing list: index-based category colors
- i18n: translated date picker placeholder, fixed German labels
- Default map tile: CartoDB Light
2026-03-19 19:44:22 +08:00
|
|
|
|
2026-04-01 12:38:38 +08:00
|
|
|
try {
|
|
|
|
|
_jwtSecret = fs.readFileSync(jwtSecretFile, 'utf8').trim();
|
|
|
|
|
} catch {
|
|
|
|
|
_jwtSecret = crypto.randomBytes(32).toString('hex');
|
v2.1.0 — Real-time collaboration, performance & security overhaul
Real-Time Collaboration (WebSocket):
- WebSocket server with JWT auth and trip-based rooms
- Live sync for all CRUD operations (places, assignments, days, notes, budget, packing, reservations, files)
- Socket-based exclusion to prevent duplicate updates
- Auto-reconnect with exponential backoff
- Assignment move sync between days
Performance:
- 16 database indexes on all foreign key columns
- N+1 query fix in places, assignments and days endpoints
- Marker clustering (react-leaflet-cluster) with configurable radius
- List virtualization (react-window) for places sidebar
- useMemo for filtered places
- SQLite WAL mode + busy_timeout for concurrent writes
- Weather API: server-side cache (1h forecast, 15min current) + client sessionStorage
- Google Places photos: persisted to DB after first fetch
- Google Details: 3-tier cache (memory → sessionStorage → API)
Security:
- CORS auto-configuration (production: same-origin, dev: open)
- API keys removed from /auth/me response
- Admin-only endpoint for reading API keys
- Path traversal prevention in cover image deletion
- JWT secret persisted to file (survives restarts)
- Avatar upload file extension whitelist
- API key fallback: normal users use admin's key without exposure
- Case-insensitive email login
Dark Mode:
- Fixed hardcoded colors across PackingList, Budget, ReservationModal, ReservationsPanel
- Mobile map buttons and sidebar sheets respect dark mode
- Cluster markers always dark
UI/UX:
- Redesigned login page with animated planes, stars and feature cards
- Admin: create user functionality with CustomSelect
- Mobile: day-picker popup for assigning places to days
- Mobile: touch-friendly reorder buttons (32px targets)
- Mobile: responsive text (shorter labels on small screens)
- Packing list: index-based category colors
- i18n: translated date picker placeholder, fixed German labels
- Default map tile: CartoDB Light
2026-03-19 19:44:22 +08:00
|
|
|
try {
|
2026-04-01 12:38:38 +08:00
|
|
|
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
|
|
|
|
|
fs.writeFileSync(jwtSecretFile, _jwtSecret, { mode: 0o600 });
|
|
|
|
|
console.log('Generated and saved JWT secret to', jwtSecretFile);
|
|
|
|
|
} catch (writeErr: unknown) {
|
|
|
|
|
console.warn('WARNING: Could not persist JWT secret to disk:', writeErr instanceof Error ? writeErr.message : writeErr);
|
|
|
|
|
console.warn('Sessions will reset on server restart.');
|
v2.1.0 — Real-time collaboration, performance & security overhaul
Real-Time Collaboration (WebSocket):
- WebSocket server with JWT auth and trip-based rooms
- Live sync for all CRUD operations (places, assignments, days, notes, budget, packing, reservations, files)
- Socket-based exclusion to prevent duplicate updates
- Auto-reconnect with exponential backoff
- Assignment move sync between days
Performance:
- 16 database indexes on all foreign key columns
- N+1 query fix in places, assignments and days endpoints
- Marker clustering (react-leaflet-cluster) with configurable radius
- List virtualization (react-window) for places sidebar
- useMemo for filtered places
- SQLite WAL mode + busy_timeout for concurrent writes
- Weather API: server-side cache (1h forecast, 15min current) + client sessionStorage
- Google Places photos: persisted to DB after first fetch
- Google Details: 3-tier cache (memory → sessionStorage → API)
Security:
- CORS auto-configuration (production: same-origin, dev: open)
- API keys removed from /auth/me response
- Admin-only endpoint for reading API keys
- Path traversal prevention in cover image deletion
- JWT secret persisted to file (survives restarts)
- Avatar upload file extension whitelist
- API key fallback: normal users use admin's key without exposure
- Case-insensitive email login
Dark Mode:
- Fixed hardcoded colors across PackingList, Budget, ReservationModal, ReservationsPanel
- Mobile map buttons and sidebar sheets respect dark mode
- Cluster markers always dark
UI/UX:
- Redesigned login page with animated planes, stars and feature cards
- Admin: create user functionality with CustomSelect
- Mobile: day-picker popup for assigning places to days
- Mobile: touch-friendly reorder buttons (32px targets)
- Mobile: responsive text (shorter labels on small screens)
- Packing list: index-based category colors
- i18n: translated date picker placeholder, fixed German labels
- Default map tile: CartoDB Light
2026-03-19 19:44:22 +08:00
|
|
|
}
|
2026-03-19 06:58:08 +08:00
|
|
|
}
|
|
|
|
|
|
fix: decouple at-rest encryption from JWT_SECRET, add JWT rotation
Introduces a dedicated ENCRYPTION_KEY for encrypting stored secrets
(API keys, MFA TOTP, SMTP password, OIDC client secret) so that
rotating the JWT signing secret no longer invalidates encrypted data,
and a compromised JWT_SECRET no longer exposes stored credentials.
- server/src/config.ts: add ENCRYPTION_KEY (auto-generated to
data/.encryption_key if not set, same pattern as JWT_SECRET);
switch JWT_SECRET to `export let` so updateJwtSecret() keeps the
CJS module binding live for all importers without restart
- apiKeyCrypto.ts, mfaCrypto.ts: derive encryption keys from
ENCRYPTION_KEY instead of JWT_SECRET
- admin POST /rotate-jwt-secret: generates a new 32-byte hex secret,
persists it to data/.jwt_secret, updates the live in-process binding
via updateJwtSecret(), and writes an audit log entry
- Admin panel (Settings → Danger Zone): "Rotate JWT Secret" button
with a confirmation modal warning that all sessions will be
invalidated; on success the acting admin is logged out immediately
- docker-compose.yml, .env.example, README, Helm chart (values.yaml,
secret.yaml, deployment.yaml, NOTES.txt, README): document
ENCRYPTION_KEY and its upgrade migration path
2026-04-01 12:31:45 +08:00
|
|
|
// export let so TypeScript's CJS output keeps exports.JWT_SECRET live
|
|
|
|
|
// (generates `exports.JWT_SECRET = JWT_SECRET = newVal` inside updateJwtSecret)
|
|
|
|
|
export let JWT_SECRET = _jwtSecret;
|
|
|
|
|
|
|
|
|
|
// Called by the admin rotate-jwt-secret endpoint to update the in-process
|
|
|
|
|
// binding that all middleware and route files reference.
|
|
|
|
|
export function updateJwtSecret(newSecret: string): void {
|
|
|
|
|
JWT_SECRET = newSecret;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ENCRYPTION_KEY is used to derive at-rest encryption keys for stored secrets
|
|
|
|
|
// (API keys, MFA TOTP secrets, SMTP password, OIDC client secret, etc.).
|
|
|
|
|
// Keeping it separate from JWT_SECRET means you can rotate session tokens without
|
|
|
|
|
// invalidating all stored encrypted data, and vice-versa.
|
|
|
|
|
//
|
2026-04-01 15:47:31 +08:00
|
|
|
// Resolution order:
|
|
|
|
|
// 1. ENCRYPTION_KEY env var — explicit, always takes priority.
|
2026-04-01 16:03:11 +08:00
|
|
|
// 2. data/.encryption_key file — present on any install that has started at
|
|
|
|
|
// least once (written automatically by cases 1b and 3 below).
|
|
|
|
|
// 3. data/.jwt_secret — one-time fallback for existing installs upgrading
|
|
|
|
|
// without a pre-set ENCRYPTION_KEY. The value is immediately persisted to
|
|
|
|
|
// data/.encryption_key so JWT rotation can never break decryption later.
|
|
|
|
|
// 4. Auto-generated — fresh install with none of the above; persisted to
|
|
|
|
|
// data/.encryption_key.
|
|
|
|
|
const encKeyFile = path.join(dataDir, '.encryption_key');
|
2026-04-01 15:47:31 +08:00
|
|
|
let _encryptionKey: string = process.env.ENCRYPTION_KEY || '';
|
|
|
|
|
|
2026-04-01 16:03:11 +08:00
|
|
|
if (_encryptionKey) {
|
|
|
|
|
// Env var is set explicitly — persist it to file so the value survives
|
|
|
|
|
// container restarts even if the env var is later removed.
|
2026-04-01 15:47:31 +08:00
|
|
|
try {
|
2026-04-01 16:03:11 +08:00
|
|
|
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
|
|
|
|
|
fs.writeFileSync(encKeyFile, _encryptionKey, { mode: 0o600 });
|
2026-04-01 15:47:31 +08:00
|
|
|
} catch {
|
2026-04-01 16:03:11 +08:00
|
|
|
// Non-fatal: env var is the source of truth when set.
|
2026-04-01 15:47:31 +08:00
|
|
|
}
|
2026-04-01 16:03:11 +08:00
|
|
|
} else {
|
|
|
|
|
// Try the dedicated key file first (covers all installs after first start).
|
2026-04-01 15:47:31 +08:00
|
|
|
try {
|
|
|
|
|
_encryptionKey = fs.readFileSync(encKeyFile, 'utf8').trim();
|
|
|
|
|
} catch {
|
2026-04-01 16:03:11 +08:00
|
|
|
// File not found — first start on an existing or fresh install.
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!_encryptionKey) {
|
|
|
|
|
// One-time migration: existing install upgrading for the first time.
|
|
|
|
|
// Use the JWT secret as the encryption key and immediately write it to
|
|
|
|
|
// .encryption_key so future JWT rotations cannot break decryption.
|
2026-04-01 15:47:31 +08:00
|
|
|
try {
|
2026-04-01 16:03:11 +08:00
|
|
|
_encryptionKey = fs.readFileSync(jwtSecretFile, 'utf8').trim();
|
|
|
|
|
console.warn('WARNING: ENCRYPTION_KEY is not set. Falling back to JWT secret for at-rest encryption.');
|
|
|
|
|
console.warn('The value has been persisted to data/.encryption_key — JWT rotation is now safe.');
|
|
|
|
|
} catch {
|
|
|
|
|
// JWT secret not found — must be a fresh install.
|
2026-04-01 15:47:31 +08:00
|
|
|
}
|
|
|
|
|
}
|
2026-04-01 16:03:11 +08:00
|
|
|
|
|
|
|
|
if (!_encryptionKey) {
|
|
|
|
|
// Fresh install — auto-generate a dedicated key.
|
|
|
|
|
_encryptionKey = crypto.randomBytes(32).toString('hex');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Persist whatever key was resolved so subsequent starts skip the fallback chain.
|
|
|
|
|
try {
|
|
|
|
|
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
|
|
|
|
|
fs.writeFileSync(encKeyFile, _encryptionKey, { mode: 0o600 });
|
|
|
|
|
console.log('Encryption key persisted to', encKeyFile);
|
|
|
|
|
} catch (writeErr: unknown) {
|
|
|
|
|
console.warn('WARNING: Could not persist encryption key to disk:', writeErr instanceof Error ? writeErr.message : writeErr);
|
|
|
|
|
console.warn('Set ENCRYPTION_KEY env var to avoid losing access to encrypted secrets on restart.');
|
|
|
|
|
}
|
fix: decouple at-rest encryption from JWT_SECRET, add JWT rotation
Introduces a dedicated ENCRYPTION_KEY for encrypting stored secrets
(API keys, MFA TOTP, SMTP password, OIDC client secret) so that
rotating the JWT signing secret no longer invalidates encrypted data,
and a compromised JWT_SECRET no longer exposes stored credentials.
- server/src/config.ts: add ENCRYPTION_KEY (auto-generated to
data/.encryption_key if not set, same pattern as JWT_SECRET);
switch JWT_SECRET to `export let` so updateJwtSecret() keeps the
CJS module binding live for all importers without restart
- apiKeyCrypto.ts, mfaCrypto.ts: derive encryption keys from
ENCRYPTION_KEY instead of JWT_SECRET
- admin POST /rotate-jwt-secret: generates a new 32-byte hex secret,
persists it to data/.jwt_secret, updates the live in-process binding
via updateJwtSecret(), and writes an audit log entry
- Admin panel (Settings → Danger Zone): "Rotate JWT Secret" button
with a confirmation modal warning that all sessions will be
invalidated; on success the acting admin is logged out immediately
- docker-compose.yml, .env.example, README, Helm chart (values.yaml,
secret.yaml, deployment.yaml, NOTES.txt, README): document
ENCRYPTION_KEY and its upgrade migration path
2026-04-01 12:31:45 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-01 15:47:31 +08:00
|
|
|
export const ENCRYPTION_KEY = _encryptionKey;
|