decklight 0.4.0 → 0.5.0

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.
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * "A newer decklight exists" — the one line that reaches a user npx has pinned.
7
+ *
8
+ * `npx decklight` with no version reuses whatever tree npm already unpacked
9
+ * into `~/.npm/_npx/<hash>/`; it does not re-resolve the `latest` dist-tag. So
10
+ * the first version someone runs is the version they keep, and 0.4.0 could be
11
+ * on the registry within minutes of the publish while their terminal still
12
+ * printed 0.3.0 (#314). Teaching `npx decklight@latest` in the README fixes it
13
+ * for people who come back and read the README. This is for everyone else.
14
+ *
15
+ * THE CHECK IS NEVER ON THE CRITICAL PATH. A command reads a cache file it
16
+ * already has and prints from that; the refresh happens in a DETACHED child
17
+ * that the parent does not wait for and does not read. So the notice a run
18
+ * shows is the previous run's answer, which is the point — nothing about this
19
+ * feature can make `decklight bundle` slower, or hang it on a registry that is
20
+ * down, or leave a network call deciding when the process may exit.
21
+ *
22
+ * Everything here is pure over an injected env/clock/home, because the whole
23
+ * feature is a set of conditions under which decklight must stay SILENT — and a
24
+ * condition nothing can reach is a condition nobody can check.
25
+ */
26
+
27
+ import { spawn } from 'node:child_process';
28
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
29
+ import { join } from 'node:path';
30
+ import { fileURLToPath } from 'node:url';
31
+ import { configHome } from './marketplace.mjs';
32
+ import { isMain } from '../tools/args.mjs';
33
+
34
+ /** How long an answer stays good. A day: this is a courtesy, not telemetry. */
35
+ export const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
36
+
37
+ /** The dist-tag this asks about, and where. No dependency, just one GET. */
38
+ export const REGISTRY_URL = 'https://registry.npmjs.org/decklight/latest';
39
+
40
+ export const cachePath = (home = configHome()) => join(home, 'update-check.json');
41
+
42
+ /**
43
+ * Why this run must say nothing — a string, or false to speak.
44
+ *
45
+ * Returning the REASON rather than a boolean is deliberate: it is what makes
46
+ * the test read like the rule ("suppressed under CI") instead of like its
47
+ * implementation, and what lets `decklight report-bug` say why nobody has been
48
+ * told about a new version.
49
+ */
50
+ export function suppressed({ env = process.env, isTty = process.stderr.isTTY } = {}) {
51
+ if (env.DECKLIGHT_NO_UPDATE_CHECK) return 'DECKLIGHT_NO_UPDATE_CHECK is set';
52
+ // The ecosystem's own opt-out, honoured because someone who set it once meant
53
+ // it for every CLI on the machine, not for whichever ones knew the name.
54
+ if (env.NO_UPDATE_NOTIFIER) return 'NO_UPDATE_NOTIFIER is set';
55
+ if (env.CI) return 'CI';
56
+ if (!isTty) return 'stderr is not a terminal';
57
+ return false;
58
+ }
59
+
60
+ /**
61
+ * `latest` if it is genuinely newer than `current`, else null.
62
+ *
63
+ * Numeric compare on the three parts, and any prerelease on either side is
64
+ * ignored outright: nobody running a stable build should be nudged onto a
65
+ * `-rc.1`, and a machine on a prerelease already knows what it is doing.
66
+ */
67
+ export function newerVersion(current, latest) {
68
+ const parse = (v) => {
69
+ const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(v ?? '').trim());
70
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
71
+ };
72
+ const a = parse(current); const b = parse(latest);
73
+ if (!a || !b) return null;
74
+ for (let i = 0; i < 3; i++) {
75
+ if (b[i] > a[i]) return latest;
76
+ if (b[i] < a[i]) return null;
77
+ }
78
+ return null;
79
+ }
80
+
81
+ /** The cached answer, or null when there isn't a usable one. */
82
+ export function readCache(home = configHome()) {
83
+ try {
84
+ const c = JSON.parse(readFileSync(cachePath(home), 'utf8'));
85
+ return typeof c?.latest === 'string' && Number.isFinite(c?.checkedAt) ? c : null;
86
+ } catch { return null; }
87
+ }
88
+
89
+ export function writeCache(latest, home = configHome(), now = Date.now()) {
90
+ mkdirSync(home, { recursive: true });
91
+ writeFileSync(cachePath(home), `${JSON.stringify({ latest, checkedAt: now }, null, 2)}\n`);
92
+ }
93
+
94
+ export const stale = (cache, now = Date.now()) => !cache || (now - cache.checkedAt) > CACHE_TTL_MS;
95
+
96
+ /** What the user reads. One line, and it says what to type. */
97
+ export const noticeLine = (current, latest) =>
98
+ ` update: decklight ${latest} is out (you have ${current}) — npx decklight@latest …`;
99
+
100
+ /**
101
+ * The notice for this run, or null.
102
+ *
103
+ * Reads only what is already on disk. A machine that has never refreshed sees
104
+ * nothing, which is correct: the first run of a new install has nothing to be
105
+ * behind on, and the answer arrives for the next one.
106
+ */
107
+ export function updateNotice(current, { home = configHome(), env = process.env, isTty = process.stderr.isTTY, now = Date.now() } = {}) {
108
+ if (suppressed({ env, isTty })) return null;
109
+ const cache = readCache(home);
110
+ if (!cache) return null;
111
+ const newer = newerVersion(current, cache.latest);
112
+ return newer ? noticeLine(current, newer) : null;
113
+ }
114
+
115
+ /**
116
+ * Refresh the cache without the caller waiting, or caring.
117
+ *
118
+ * A detached child with no stdio: the parent's exit is unaffected, and a
119
+ * registry that hangs holds nothing open in the process that matters. Fully
120
+ * silent on failure — an offline machine gets no notice, no delay and no stack
121
+ * trace, which is the whole contract.
122
+ */
123
+ export function refreshInBackground({ home = configHome(), env = process.env, isTty = process.stderr.isTTY, now = Date.now() } = {}) {
124
+ if (suppressed({ env, isTty })) return false;
125
+ if (!stale(readCache(home), now)) return false;
126
+ try {
127
+ spawn(process.execPath, [fileURLToPath(import.meta.url), '--refresh'], {
128
+ detached: true, stdio: 'ignore', env: { ...env, DECKLIGHT_HOME: home },
129
+ }).unref();
130
+ return true;
131
+ } catch { return false; }
132
+ }
133
+
134
+ /** The child: ask the registry, write the answer, say nothing either way. */
135
+ export async function refreshMain({ home = configHome(), fetchImpl = fetch, timeoutMs = 4000 } = {}) {
136
+ try {
137
+ const r = await fetchImpl(REGISTRY_URL, { signal: AbortSignal.timeout(timeoutMs) });
138
+ if (!r.ok) return false;
139
+ const { version } = await r.json();
140
+ if (!/^\d+\.\d+\.\d+/.test(String(version ?? ''))) return false;
141
+ writeCache(version, home);
142
+ return true;
143
+ } catch { return false; }
144
+ }
145
+
146
+ if (isMain(import.meta.url)) {
147
+ // Never a non-zero exit and never a word on either stream: nothing is
148
+ // watching, and a background process that complains is a background process
149
+ // that shows up in somebody's logs for no reason.
150
+ await refreshMain();
151
+ process.exit(0);
152
+ }
153
+
154
+ // `existsSync` is imported for the cache-dir check callers may want; keep the
155
+ // surface honest if it stops being used.
156
+ export const cacheExists = (home = configHome()) => existsSync(cachePath(home));
package/cli/wizard.mjs CHANGED
@@ -23,8 +23,15 @@
23
23
  *
24
24
  * ## Credentials
25
25
  *
26
- * Pasted in the player, posted to the author server, written `0600` under the
27
- * config home. Loopback-only by construction rather than by check: the author
26
+ * Pasted in the player, posted to the author server, and stored under the
27
+ * config home RESTRICTED TO THE ACCOUNT THAT PASTED THEM — `0600` on POSIX,
28
+ * and on Windows an explicit ACL granting only that user, because `0600` there
29
+ * is a number with no meaning and inheriting whatever the profile hands out is
30
+ * not a decision decklight ever made deliberately (#308). Every sentence
31
+ * decklight prints about this comes from `protectionOf`, which READS THE FILE
32
+ * BACK rather than repeating what the write intended: the one thing worse than
33
+ * a key with weak permissions is a key with weak permissions and a CLI saying
34
+ * otherwise. Loopback-only by construction rather than by check: the author
28
35
  * server refuses every `/edit/*` mutation off-loopback unconditionally
29
36
  * (`allowRemote`), flag or no flag. Never logged, never written into the deck,
30
37
  * never picked up by `bundle` — a key that reached a deck would travel with it.
@@ -39,8 +46,9 @@
39
46
  */
40
47
 
41
48
  import { readFileSync, writeFileSync, mkdirSync, chmodSync, statSync, existsSync } from 'node:fs';
49
+ import { execFileSync } from 'node:child_process';
42
50
  import path, { delimiter } from 'node:path';
43
- import { homedir } from 'node:os';
51
+ import { homedir, userInfo } from 'node:os';
44
52
  import { configHome } from './marketplace.mjs';
45
53
 
46
54
  /** Where credentials live. Beside `marketplaces.json`, same config home. */
@@ -257,19 +265,30 @@ export const BRIDGE_ADDR = '127.0.0.1:8787';
257
265
  * One function so the wording exists once; the player prints both strings
258
266
  * verbatim (as text, never markup) and refuses a schema that lacks them.
259
267
  */
260
- export function provenance(schema, qualified) {
268
+ export function provenance(schema, qualified, { platform = process.platform } = {}) {
261
269
  if (typeof qualified !== 'string' || !/^[^@\s]+@[^@\s]+$/.test(qualified)) {
262
270
  throw new SchemaError('provenance needs the entry\'s qualified registry name, like "elevenlabs@voices"');
263
271
  }
264
272
  const endpoints = [...new Set([schema.validate, schema.install].filter(Boolean))];
273
+ // The protection, named in the terms of the machine reading it. `0600` is
274
+ // the whole of the promise on POSIX and means nothing at all on Windows, and
275
+ // printing it there was decklight claiming a protection it was not providing
276
+ // (#308). `restrictFile` is what makes the Windows half true.
277
+ const where = `~/.decklight/credentials.json (${STORAGE_NOTE[platform === 'win32' ? 'win32' : 'posix']})`;
265
278
  return {
266
279
  askedBy: `asked by ${qualified}`,
267
280
  sentTo: endpoints.length
268
- ? `answers go to its own bridge on this machine (${endpoints.map((p) => BRIDGE_ADDR + p).join(' and ')}), then ~/.decklight/credentials.json (0600)`
269
- : 'answers stay on this machine: ~/.decklight/credentials.json (0600)',
281
+ ? `answers go to its own bridge on this machine (${endpoints.map((p) => BRIDGE_ADDR + p).join(' and ')}), then ${where}`
282
+ : `answers stay on this machine: ${where}`,
270
283
  };
271
284
  }
272
285
 
286
+ /** How the credential file is protected, per platform, in one phrase. */
287
+ export const STORAGE_NOTE = {
288
+ posix: '0600',
289
+ win32: 'locked to your Windows account',
290
+ };
291
+
273
292
  /** Which of a schema's fields are secrets — the only ones that get hidden. */
274
293
  export const secretNames = (schema) =>
275
294
  new Set(schema.fields.filter((f) => f.type === 'secret').map((f) => f.name));
@@ -309,20 +328,166 @@ export function loadCredentials(home = configHome()) {
309
328
  }
310
329
 
311
330
  /**
312
- * Store one engine's answers, `0600`.
331
+ * Cut `file` down to the account that owns it, and say which way it was done.
332
+ *
333
+ * POSIX has `0600` and that IS the protection. Windows does not: `chmodSync`
334
+ * there only toggles the read-only attribute, so a file written with mode
335
+ * `0o600` carries whatever ACL the user profile hands it — usually adequate,
336
+ * and not something decklight did. `icacls /inheritance:r` drops the inherited
337
+ * entries and `/grant:r <user>:F` puts back exactly one, so afterwards the only
338
+ * principal on the file is the person who pasted the key.
339
+ *
340
+ * Returns HOW, never a boolean: the caller's next job is to print a true
341
+ * sentence, and "it worked" is not enough to write one with. A machine where
342
+ * icacls is unavailable or the filesystem has no ACLs (a FAT volume, a network
343
+ * share) is not an error — it is `inherited`, which is what the profile would
344
+ * have given anyway and is said out loud rather than papered over.
345
+ */
346
+ export function restrictFile(file, {
347
+ platform = process.platform, exec = execFileSync, chmod = chmodSync,
348
+ user = () => userInfo().username, env = process.env,
349
+ } = {}) {
350
+ if (platform !== 'win32') {
351
+ // Set on every write, not only on create: a file left world-readable by
352
+ // something else must not stay that way, and `writeFileSync`'s mode
353
+ // argument is ignored for a path that already exists.
354
+ chmod(file, 0o600);
355
+ return { how: 'posix', who: null };
356
+ }
357
+ // Three steps, because `/inheritance:r` is not the blunt instrument the usual
358
+ // one-line recipe assumes. It removes INHERITED entries only, and the Windows
359
+ // runner showed a freshly written file carrying SYSTEM and Administrators as
360
+ // EXPLICIT ones (no `(I)` marker): `/inheritance:r` then had nothing to do,
361
+ // `/grant:r` replaced only this account's own entry, both calls exited 0, and
362
+ // the file looked restricted while everyone it started with could still read
363
+ // it. An explicit entry has to be removed explicitly.
364
+ const run = (args) => exec('icacls', [file, ...args], { stdio: 'pipe' });
365
+ try {
366
+ run(['/inheritance:r']);
367
+ } catch (e) {
368
+ return { how: 'inherited', who: null, why: reason(e) };
369
+ }
370
+ // Two spellings of one account, because icacls fails the whole call on a
371
+ // principal it cannot look up and WHICH one resolves is a property of the
372
+ // machine: `MACHINE\\jo` is what Windows prints and what a domain-joined box
373
+ // wants, a bare `jo` is what a local account often wants.
374
+ let who = null;
375
+ let last = null;
376
+ for (const candidate of new Set([qualifiedUser(user, env), user()])) {
377
+ if (who) break;
378
+ try { run(['/grant:r', `${candidate}:F`]); who = candidate; } catch (e) { last = e; }
379
+ }
380
+ if (!who) {
381
+ // The grant is load-bearing: without it, an inheritance drop that DID
382
+ // remove something leaves a file nobody can read. Put the profile's own
383
+ // permissions back — a weak protection beats an unreadable credential file.
384
+ try { run(['/inheritance:e']); } catch { /* reported below anyway */ }
385
+ return { how: 'inherited', who: null, why: reason(last) };
386
+ }
387
+ // Then everyone else, by name, from the file's own DACL. SYSTEM and the
388
+ // Administrators group go too: an administrator can take ownership whatever
389
+ // this says, so leaving them on buys nothing, and "restricted to the account
390
+ // that pasted it" has to mean that or it is not worth printing. Best effort —
391
+ // an entry that will not come off is not an error here, because the caller
392
+ // reads the file back and reports what is actually on it.
393
+ try {
394
+ const me = bareName(who);
395
+ for (const g of aclGrantees(exec('icacls', [file], { encoding: 'utf8' }), file)) {
396
+ if (bareName(g) === me) continue;
397
+ try { run(['/remove:g', g]); } catch { /* named by the read-back */ }
398
+ }
399
+ } catch { /* likewise */ }
400
+ return { how: 'acl', who, why: null };
401
+ }
402
+
403
+ /**
404
+ * An account name without its domain, lowercased.
405
+ *
406
+ * icacls answers with the fully qualified `MACHINE\\jo` whatever spelling it was
407
+ * granted in, so comparing anything else compares a spelling, not an identity.
408
+ */
409
+ export const bareName = (s) => String(s).toLowerCase().split('\\').pop();
410
+
411
+ /** What icacls said, short enough for a log line. */
412
+ const reason = (e) => String(e?.stderr || e?.message || e).trim().split('\n')[0].slice(0, 200);
413
+
414
+ /**
415
+ * The account name to hand icacls.
416
+ *
417
+ * A bare username is what `os.userInfo()` gives and is usually enough, but it
418
+ * has to RESOLVE — icacls fails the whole call on a principal it cannot look
419
+ * up, and a machine where the bare name is ambiguous would silently keep the
420
+ * profile's permissions. `USERDOMAIN\USERNAME` is the form Windows itself uses
421
+ * and the one that resolves on a domain-joined machine, so it is preferred
422
+ * when the environment supplies it.
423
+ */
424
+ export function qualifiedUser(user = () => userInfo().username, env = process.env) {
425
+ const name = user();
426
+ const domain = env.USERDOMAIN;
427
+ return domain && !name.includes('\\') ? `${domain}\\${name}` : name;
428
+ }
429
+
430
+ /**
431
+ * What the file on disk is ACTUALLY protected by — read back, never assumed.
432
+ *
433
+ * This is the function every user-facing sentence about credential storage
434
+ * comes from, including `report-bug`'s, so that what decklight says and what is
435
+ * true cannot drift apart the way they did in #308.
436
+ */
437
+ export function protectionOf(file, {
438
+ platform = process.platform, exec = execFileSync, stat = statSync,
439
+ exists = existsSync, user = () => userInfo().username,
440
+ } = {}) {
441
+ if (!exists(file)) return { state: 'absent', label: 'nothing stored' };
442
+ if (platform !== 'win32') {
443
+ const mode = stat(file).mode & 0o777;
444
+ return mode === 0o600
445
+ ? { state: 'private', label: '0600' }
446
+ : { state: 'open', label: `0${mode.toString(8)} — readable by more than you` };
447
+ }
448
+ let grantees;
449
+ try {
450
+ grantees = aclGrantees(exec('icacls', [file], { encoding: 'utf8' }), file);
451
+ } catch {
452
+ return { state: 'unknown', label: 'Windows ACL (icacls could not read it)' };
453
+ }
454
+ const me = bareName(user());
455
+ const others = grantees.filter((g) => bareName(g) !== me);
456
+ return others.length
457
+ ? { state: 'open', label: `Windows ACL — also readable by ${others.join(', ')}` }
458
+ : { state: 'private', label: `Windows ACL — restricted to ${user()}` };
459
+ }
460
+
461
+ /**
462
+ * The principals `icacls <file>` lists, from its output.
463
+ *
464
+ * The file's own path is on the first line ahead of the first principal and may
465
+ * contain spaces (`C:\Users\Jo Bloggs\…`), so it is removed by name before
466
+ * anything is parsed rather than guessed at with whitespace.
467
+ */
468
+ export function aclGrantees(out, file) {
469
+ return String(out).replaceAll(file, '').split(/\r?\n/)
470
+ .map((line) => /^\s*(.+?):\(/.exec(line)?.[1]?.trim())
471
+ .filter(Boolean);
472
+ }
473
+
474
+ /**
475
+ * Store one engine's answers, restricted to this account.
313
476
  *
314
- * The mode is set on every write, not only on create: a file that was
315
- * world-readable before this call must not stay world-readable after it, and
316
- * `writeFileSync`'s mode argument is ignored for a path that already exists.
477
+ * Returns `{ file, protection }` — what was written and what it is really
478
+ * protected by, read back off the disk. A caller that wants to say where the
479
+ * key went has both halves and cannot accidentally say only the first.
317
480
  */
318
- export function saveCredentials(engine, answers, home = configHome()) {
481
+ export function saveCredentials(engine, answers, home = configHome(), opts = {}) {
319
482
  const file = credentialsPath(home);
320
483
  mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
321
484
  const all = loadCredentials(home);
322
485
  all[engine] = { ...answers };
323
486
  writeFileSync(file, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
324
- chmodSync(file, 0o600);
325
- return file;
487
+ // What was attempted, then what is actually true. The second is the answer;
488
+ // the first is why, on a machine where the answer is disappointing.
489
+ const attempted = restrictFile(file, opts);
490
+ return { file, protection: { ...protectionOf(file, opts), why: attempted.why ?? null } };
326
491
  }
327
492
 
328
493
  /** Forget an engine's answers. Returns whether there was anything to forget. */
@@ -332,7 +497,7 @@ export function forgetCredentials(engine, home = configHome()) {
332
497
  if (!(engine in all)) return false;
333
498
  delete all[engine];
334
499
  writeFileSync(credentialsPath(home), `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
335
- chmodSync(credentialsPath(home), 0o600);
500
+ restrictFile(credentialsPath(home));
336
501
  return true;
337
502
  }
338
503
 
@@ -427,6 +592,9 @@ export async function configureEngine(engine, answers, {
427
592
  if (!ok) return { state: REJECTED, schema, reason: `${schema.title} did not accept those answers` };
428
593
  }
429
594
 
430
- const file = save(engine, answers, home);
431
- return { state: CONFIGURED, schema, file, stored: redactAnswers(schema, answers) };
595
+ // Both halves: where the key went, and what is actually protecting it there.
596
+ // The second is read off the disk, so a caller reporting it cannot repeat an
597
+ // intention the filesystem did not honour (#308).
598
+ const { file, protection } = save(engine, answers, home);
599
+ return { state: CONFIGURED, schema, file, protection, stored: redactAnswers(schema, answers) };
432
600
  }