@selvajs/cli 4.20.1-beta.2 → 4.20.1-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selvajs/cli",
3
- "version": "4.20.1-beta.2",
3
+ "version": "4.20.1-beta.3",
4
4
  "description": "Scaffold and operate a Selva white-label deployment. `npx @selvajs/cli <dir>` to bootstrap, `selva <cmd>` to manage.",
5
5
  "license": "MIT",
6
6
  "author": "VektorNode",
@@ -12,10 +12,10 @@
12
12
 
13
13
  import { RENAMED_ENV_VARS, RETIRED_ENV_VARS } from '../env.js';
14
14
  import { keyRotationStatus } from '../generated/config.js';
15
+ import { KEY_PLACEHOLDER } from '../secrets.js';
15
16
  import { green, red, yellow } from './result.js';
16
17
 
17
18
  const HEX_64 = /^[0-9a-f]{64}$/i;
18
- const PLACEHOLDER = 'replace-this-with-a-random-32-byte-hex-key';
19
19
 
20
20
  const VALID_AUTH = ['local', 'supabase', 'header'];
21
21
  // Header-auth is an auth provider only — it has no data or storage layer.
@@ -28,7 +28,7 @@ const VALID_DATA = ['local', 'supabase'];
28
28
  */
29
29
  export function checkSecret(value, label) {
30
30
  if (!value) return red(`${label} — unset`);
31
- if (value === PLACEHOLDER) return red(`${label} — still the placeholder`);
31
+ if (value === KEY_PLACEHOLDER) return red(`${label} — still the placeholder`);
32
32
  if (!HEX_64.test(value) && !isBase64Of32Bytes(value)) {
33
33
  return red(`${label} — not 32 bytes as 64 hex chars or base64`);
34
34
  }
@@ -42,7 +42,7 @@ export function checkSecret(value, label) {
42
42
  export function checkHmacKey(value) {
43
43
  const label = 'SELVA_HMAC_KEY is at least 32 characters';
44
44
  if (!value) return red(`${label} — unset`);
45
- if (value === PLACEHOLDER) return red(`${label} — still the placeholder`);
45
+ if (value === KEY_PLACEHOLDER) return red(`${label} — still the placeholder`);
46
46
  if (value.length < 32) return red(`${label} — only ${value.length}`);
47
47
  return green(label);
48
48
  }
@@ -1,7 +1,7 @@
1
1
  // `selva config show|set|unset`: what this deployment's .env sets, checked
2
2
  // against the manifest the runtime declares.
3
3
 
4
- import { copyFileSync, existsSync, readFileSync } from 'node:fs';
4
+ import { existsSync, readFileSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import pc from 'picocolors';
7
7
  import { parseEnv, setEnvValues, writeEnvText } from '../env.js';
@@ -145,8 +145,7 @@ function runShow(argv) {
145
145
  function backUp(envPath) {
146
146
  if (!existsSync(envPath)) return null;
147
147
  const bak = backupPathFor(envPath, backupStamp());
148
- copyFileSync(envPath, bak);
149
- writeEnvText(bak, readFileSync(bak, 'utf8'));
148
+ writeEnvText(bak, readFileSync(envPath, 'utf8'));
150
149
  return bak;
151
150
  }
152
151
 
@@ -8,7 +8,6 @@
8
8
  import {
9
9
  existsSync,
10
10
  readFileSync,
11
- copyFileSync,
12
11
  readdirSync,
13
12
  accessSync,
14
13
  constants,
@@ -397,7 +396,7 @@ function checkEnvDocs(dir) {
397
396
  const drift = diffEnvKeys(before, after);
398
397
  if (drift) return red(`refused to strip .env — ${drift}`);
399
398
 
400
- copyFileSync(envPath, envPath + '.bak');
399
+ writeEnvText(envPath + '.bak', current);
401
400
  writeEnvText(envPath, strippedText);
402
401
  return green(`stripped ${removed} comment lines from .env (backup: .env.bak)`);
403
402
  } catch (err) {
@@ -8,9 +8,29 @@ import * as p from '@clack/prompts';
8
8
  import pc from 'picocolors';
9
9
  import { collectConfig } from '../prompts.js';
10
10
  import { parseEnv, seededTemplateDefaults, setEnvValues, writeEnvText } from '../env.js';
11
- import { generateKey } from '../secrets.js';
11
+ import { KEY_PLACEHOLDER, generateKey } from '../secrets.js';
12
12
  import { readEnvTemplate, requireDeploymentDir, resolveDeploymentDir } from '../paths.js';
13
13
 
14
+ /**
15
+ * The root keys init writes back. An existing key is never replaced: rotating
16
+ * SELVA_HMAC_KEY or SELVA_AT_REST_KEY invalidates sessions and at-rest
17
+ * encryption, which is `selva keys rotate`'s job. A missing key (a scaffold
18
+ * that bailed mid-flight) or the template placeholder is safe to generate.
19
+ */
20
+ export function rootKeysFor(current, generate = generateKey) {
21
+ const keys = {};
22
+ const generated = [];
23
+ for (const name of ['SELVA_HMAC_KEY', 'SELVA_AT_REST_KEY']) {
24
+ if (current[name] && current[name] !== KEY_PLACEHOLDER) {
25
+ keys[name] = current[name];
26
+ } else {
27
+ keys[name] = generate();
28
+ generated.push(name);
29
+ }
30
+ }
31
+ return { keys, generated };
32
+ }
33
+
14
34
  export async function runInit() {
15
35
  const dir = resolveDeploymentDir();
16
36
  requireDeploymentDir(dir);
@@ -20,29 +40,9 @@ export async function runInit() {
20
40
  const current = parseEnv(text);
21
41
  const values = await collectConfig({ defaults: current, mode: 'init' });
22
42
 
23
- // Never regenerate an existing key: rotating SELVA_HMAC_KEY or
24
- // SELVA_AT_REST_KEY invalidates sessions and at-rest encryption — that's
25
- // `selva keys rotate`'s job, not init's. Missing keys (a scaffold that
26
- // bailed mid-flight) are the one case it's safe to generate here.
27
- if (
28
- current.SELVA_HMAC_KEY &&
29
- current.SELVA_HMAC_KEY !== 'replace-this-with-a-random-32-byte-hex-key'
30
- ) {
31
- values.SELVA_HMAC_KEY = current.SELVA_HMAC_KEY;
32
- } else {
33
- values.SELVA_HMAC_KEY = generateKey();
34
- p.log.warn('SELVA_HMAC_KEY was missing — generated a fresh one.');
35
- }
36
-
37
- if (
38
- current.SELVA_AT_REST_KEY &&
39
- current.SELVA_AT_REST_KEY !== 'replace-this-with-a-random-32-byte-hex-key'
40
- ) {
41
- values.SELVA_AT_REST_KEY = current.SELVA_AT_REST_KEY;
42
- } else {
43
- values.SELVA_AT_REST_KEY = generateKey();
44
- p.log.warn('SELVA_AT_REST_KEY was missing — generated a fresh one.');
45
- }
43
+ const { keys, generated } = rootKeysFor(current);
44
+ Object.assign(values, keys);
45
+ for (const name of generated) p.log.warn(`${name} was missing — generated a fresh one.`);
46
46
 
47
47
  // Line-level: keys the prompts don't cover, and the operator's comments, stay as they are.
48
48
  // A prompt answered blank means unset, as it did when the file was re-rendered.
@@ -206,8 +206,7 @@ export async function runMigrate(
206
206
  return;
207
207
  }
208
208
  const bak = backupPathFor(envPath, backupStamp());
209
- copyFileSync(envPath, bak);
210
- writeEnvText(bak, readFileSync(bak, 'utf8'));
209
+ writeEnvText(bak, readFileSync(envPath, 'utf8'));
211
210
  writeEnvText(envPath, envPlan.text);
212
211
  p.outro(
213
212
  pc.green('.env migrated. ') +
@@ -263,8 +262,7 @@ export async function runMigrate(
263
262
  writeFileSync(pkgPath, JSON.stringify(target, null, 2) + '\n', 'utf8');
264
263
 
265
264
  if (envChanged) {
266
- copyFileSync(envPath, envBak);
267
- writeEnvText(envBak, readFileSync(envBak, 'utf8'));
265
+ writeEnvText(envBak, readFileSync(envPath, 'utf8'));
268
266
  writeEnvText(envPath, envPlan.text);
269
267
  }
270
268
 
@@ -292,7 +290,7 @@ export async function runMigrate(
292
290
  s.stop(pc.red('npm install failed — rolling back'));
293
291
  copyFileSync(bakPath, pkgPath);
294
292
  if (envChanged && existsSync(envBak)) {
295
- copyFileSync(envBak, envPath);
293
+ writeEnvText(envPath, readFileSync(envBak, 'utf8'));
296
294
  }
297
295
 
298
296
  // A half-installed node_modules from the failed attempt is worse than the old
package/src/env.js CHANGED
@@ -2,7 +2,17 @@
2
2
  // `node --env-file` boots the app with, so the CLI never sees a value the app
3
3
  // doesn't.
4
4
 
5
- import { readFileSync, writeFileSync, existsSync, chmodSync } from 'node:fs';
5
+ import { randomBytes } from 'node:crypto';
6
+ import {
7
+ chownSync,
8
+ existsSync,
9
+ readFileSync,
10
+ realpathSync,
11
+ renameSync,
12
+ rmSync,
13
+ statSync,
14
+ writeFileSync
15
+ } from 'node:fs';
6
16
  import { parseEnv as nodeParseEnv } from 'node:util';
7
17
  import { ALL_SETTINGS, RETIRED_KEYS } from './generated/config.js';
8
18
 
@@ -244,11 +254,28 @@ export function writeEnvFile(path, template, values) {
244
254
  writeEnvText(path, renderEnvValues(template, values));
245
255
  }
246
256
 
247
- /** `.env` holds both root keys, so it is the owner's alone. */
257
+ /**
258
+ * `.env` holds both root keys, so it is the owner's alone. The text goes into a
259
+ * new 0600 file renamed over the old one: `mode` applies only when a file is
260
+ * created, so writing into an existing 0644 `.env` exposes the keys until a
261
+ * later chmod.
262
+ */
248
263
  export function writeEnvText(path, text) {
249
- writeFileSync(path, text, { encoding: 'utf8', mode: 0o600 });
250
- // `mode` applies only when the file is created; an existing file keeps its own.
251
- if (process.platform !== 'win32') chmodSync(path, 0o600);
264
+ // Through a symlinked .env to the file it points at, so the link survives.
265
+ const target = existsSync(path) ? realpathSync(path) : path;
266
+ const tmp = `${target}.${randomBytes(6).toString('hex')}.tmp`;
267
+ writeFileSync(tmp, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
268
+ try {
269
+ // Run as root, the new file would otherwise be root's and unreadable by the app's user.
270
+ if (process.getuid?.() === 0 && existsSync(target)) {
271
+ const { uid, gid } = statSync(target);
272
+ chownSync(tmp, uid, gid);
273
+ }
274
+ renameSync(tmp, target);
275
+ } catch (err) {
276
+ rmSync(tmp, { force: true });
277
+ throw err;
278
+ }
252
279
  }
253
280
 
254
281
  /**
package/src/secrets.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
 
3
+ // What the shipped .env template holds until a real key replaces it.
4
+ export const KEY_PLACEHOLDER = 'replace-this-with-a-random-32-byte-hex-key';
5
+
3
6
  // 32 bytes hex = 64-character string. Matches the runtime's expectation
4
7
  // (HMAC-SHA256 key + AES-256-GCM key, both 32 bytes).
5
8
  export function generateKey() {