Changeset 09ee2bd in Klonkt for src/server.js


Ignore:
Timestamp:
06/23/2026 09:25:42 PM (3 months ago)
Author:
Robin Genis <roboburr@…>
Branches:
main
Children:
f99bbe8
Parents:
45271b7
Message:

feat: auto-generate SESSION_SECRET if not set (zero-config Docker/manual)

If SESSION_SECRET is missing, generate a strong one on first boot and persist it
to <dataDir>/.session-secret (stable across restarts/updates). Env var still wins.
PUBLIC_BASE_URL already falls back to the request host. So Docker (B) and manual
(C) installs now run with no required .env editing. Docs + .env.example updated;
docker-compose comment translated to English.

Co-Authored-By: Claude <noreply@…>

File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/server.js

    r45271b7 r09ee2bd  
    1313import path from 'path';
    1414import fs from 'fs';
     15import crypto from 'crypto';
    1516import { fileURLToPath } from 'url';
    1617import http from 'http';
     
    6364import changelogRoutes from './routes/changelog.js';
    6465
     66// SESSION_SECRET: use the env var if set. Otherwise auto-generate a strong one
     67// and persist it next to the database, so it stays stable across restarts and
     68// updates. This lets Docker / bare-Node installs run with zero manual config.
    6569if (!process.env.SESSION_SECRET) {
    66   console.error('❌ FATAL: SESSION_SECRET is required');
    67   process.exit(1);
     70  const dataDir = path.dirname(process.env.DATABASE_PATH || './storage/database.sqlite');
     71  const secretFile = path.join(dataDir, '.session-secret');
     72  try { process.env.SESSION_SECRET = fs.readFileSync(secretFile, 'utf8').trim(); } catch { /* not yet generated */ }
     73  if (!process.env.SESSION_SECRET) {
     74    fs.mkdirSync(dataDir, { recursive: true });
     75    process.env.SESSION_SECRET = crypto.randomBytes(32).toString('hex');
     76    fs.writeFileSync(secretFile, process.env.SESSION_SECRET, { mode: 0o600 });
     77    console.log(`🔑 Generated a SESSION_SECRET (stored in ${secretFile})`);
     78  }
    6879}
    6980
     81// A SESSION_SECRET that was explicitly set in the env must still be strong in prod.
    7082if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
    71   console.error('❌ FATAL: SESSION_SECRET too weak for production');
     83  console.error('❌ FATAL: SESSION_SECRET is too weak for production (set a longer, random one in .env)');
    7284  process.exit(1);
    7385}
Note: See TracChangeset for help on using the changeset viewer.