decklight 0.5.0 → 0.6.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.
@@ -13,7 +13,7 @@
13
13
  // EADDRINUSE, and proactively, by author BEFORE it spawns the edit child —
14
14
  // that child's stdin is closed (piped, not a TTY), so it could never ask.
15
15
 
16
- import { createConnection } from 'node:net';
16
+ import { createConnection, createServer } from 'node:net';
17
17
 
18
18
  /** Is something listening on `port`? Port 0 ("OS picks one") never conflicts. */
19
19
  export function isPortOpen(port, host = '127.0.0.1', timeout = 400) {
@@ -49,11 +49,46 @@ export async function shutdownEditServer(port, host = '127.0.0.1') {
49
49
  return !(await isPortOpen(port, host));
50
50
  }
51
51
 
52
- /** The next port at or after `port` that nothing is listening on. */
53
- export async function nextFreePort(port, host = '127.0.0.1') {
54
- let p = port;
55
- while (await isPortOpen(p, host)) p++;
56
- return p;
52
+ /**
53
+ * Can we actually LISTEN on this port?
54
+ *
55
+ * `isPortOpen` asks a different question — it connects, so it answers "is
56
+ * somebody there". For "may I have this port" that is the wrong question, and
57
+ * on Windows it is wrong in a way that fails: Hyper-V and WinNAT reserve blocks
58
+ * of ephemeral ports (`netsh int ipv4 show excludedportrange`), and a reserved
59
+ * port has NOTHING LISTENING on it. Connect is refused, `isPortOpen` says
60
+ * "free", and the bind that follows gets `EACCES` — a permission error, not
61
+ * `EADDRINUSE`, which is why it read as a crash rather than a busy port (#334).
62
+ *
63
+ * Binding is the only probe that answers the question being asked. It costs one
64
+ * listen/close per candidate, which is cheaper than the connect it replaces.
65
+ */
66
+ export function canBind(port, host = '127.0.0.1') {
67
+ return new Promise((done) => {
68
+ const server = createServer();
69
+ // Every reason a bind can fail is a reason to try the next port: taken
70
+ // (EADDRINUSE), reserved or privileged (EACCES), or an address this host
71
+ // does not have (EADDRNOTAVAIL). None of them become usable by waiting.
72
+ server.once('error', () => done(false));
73
+ server.once('listening', () => server.close(() => done(true)));
74
+ try { server.listen(port, host); } catch { done(false); }
75
+ });
76
+ }
77
+
78
+ /**
79
+ * The next port at or after `port` this process can actually bind.
80
+ *
81
+ * Bounded, because the failure it now catches can repeat: a Hyper-V reservation
82
+ * is a BLOCK of ports, often 16 or more, and an unbounded walk through one is
83
+ * indistinguishable from a hang. Giving up returns the original port so the
84
+ * caller fails with the real bind error rather than on a number this function
85
+ * invented.
86
+ */
87
+ export async function nextFreePort(port, host = '127.0.0.1', tries = 64) {
88
+ for (let p = port; p < port + tries && p <= 65535; p++) {
89
+ if (await canBind(p, host)) return p;
90
+ }
91
+ return port;
57
92
  }
58
93
 
59
94
  /**
package/cli/present.mjs CHANGED
@@ -32,7 +32,7 @@ import { existsSync, readFileSync } from 'node:fs';
32
32
  import { resolve, sep, basename, dirname } from 'node:path';
33
33
  import { randomBytes } from 'node:crypto';
34
34
  import { argReader, isMain } from '../tools/args.mjs';
35
- import { allowRemote, lanAddress, staticFiles, sseChannel, listenTakingOverIfNeeded, withHeaders } from './serve.mjs';
35
+ import { allowRemote, lanAddress, staticFiles, sseChannel, listenTakingOverIfNeeded, withHeaders, isOwnOrigin } from './serve.mjs';
36
36
  import { createRemoteRelay } from './remote.mjs';
37
37
  import { corsHeaders } from '../tools/bridge.mjs';
38
38
 
@@ -43,6 +43,10 @@ const CORS = corsHeaders();
43
43
  import { auditDeck, formatLabel, stripUnaccounted } from './audit.mjs';
44
44
  import { loadLibrary, injectChrome } from './plugin.mjs';
45
45
  import { verifyFile, verifyBytes, formatSignature, isVerified, UNSIGNED, TAMPERED, VERIFIED } from './sign.mjs';
46
+ import {
47
+ SAFE_CONFIG, canPull, checkUpstream, resolveInterval, resolveUpstream, runGit, upstreamSuppressed,
48
+ } from './upstream.mjs';
49
+ import { oneline } from './git.mjs';
46
50
  import { isContainer, readContainer, formatManifest } from './deckfile.mjs';
47
51
 
48
52
  /**
@@ -122,6 +126,81 @@ export const CSP = [
122
126
  */
123
127
  export async function serveForRender(root, { html = null } = {}) {
124
128
  const files = staticFiles(root, { html });
129
+
130
+ /**
131
+ * Fast-forward, then re-read, re-audit and RE-PRINT.
132
+ *
133
+ * SPEC's condition on live reload under `present` is exactly this: never new
134
+ * bytes under the old verdict. So the label the presenter can see always
135
+ * describes the bytes being served, and the two move together.
136
+ */
137
+ async function doPull() {
138
+ // Re-checked against a FRESH fetch rather than trusted from the cached
139
+ // status: what was true ten minutes ago is not a licence to check out now.
140
+ const fresh = await refreshUpstream();
141
+ const allowed = canPull(fresh, { offered: pullArmed });
142
+ if (!allowed.ok) return { ok: false, ...allowed, http: allowed.state === 'dirty' ? 409 : 409 };
143
+
144
+ const from = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: upstream.repoRoot })).stdout;
145
+ console.log(` upstream: PULL requested by the deck — fast-forward only, onto ${upstream.upstream}`);
146
+ const merged = await runGit([...SAFE_CONFIG, '-c', `core.hooksPath=${upstream.repoRoot}/.git/decklight-no-hooks`,
147
+ 'merge', '--ff-only', '--no-verify', '@{upstream}'], { cwd: upstream.repoRoot, timeoutMs: 20000 });
148
+ if (!merged.ok) {
149
+ const why = oneline(merged.stderr || merged.err);
150
+ console.log(` upstream: the fast-forward was refused — ${why}`);
151
+ return { ok: false, state: 'not-fast-forward', message: why };
152
+ }
153
+ const to = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: upstream.repoRoot })).stdout;
154
+
155
+ // An upstream commit must never blank somebody's talk.
156
+ if (!existsSync(deckPath)) {
157
+ console.log(` upstream: fast-forwarded ${from} → ${to}, but the deck is gone from that commit`);
158
+ console.log(' still serving the bytes the label above describes');
159
+ return { ok: false, state: 'deck-gone', to, message: 'the deck is not in that commit — still serving the old bytes' };
160
+ }
161
+
162
+ const before = deck.payload;
163
+ const next = readAndAudit();
164
+ if (next.payload.equals(before)) {
165
+ console.log(` upstream: fast-forwarded ${from} → ${to} — the deck itself is unchanged`);
166
+ await refreshUpstream();
167
+ return { ok: true, state: 'pulled', from, to, deck: 'unchanged', reload: false, message: `fast-forwarded to ${to} — the deck is unchanged` };
168
+ }
169
+
170
+ // STRICT RATCHETS: a pull may turn it on and can never turn it off. A deck
171
+ // that could clear its own strict flag by pulling could disarm the one
172
+ // mitigation present applies without being asked.
173
+ const wasStrict = deck.strict;
174
+ deck = { ...next, strict: next.strict || wasStrict };
175
+ const degraded = (next.report.counts.unaccounted > 0 || next.report.counts.handlers > 0)
176
+ && !(report.counts.unaccounted > 0 || report.counts.handlers > 0);
177
+
178
+ console.log(` upstream: fast-forwarded ${from} → ${to}`);
179
+ console.log(' the deck file changed — re-read and re-audited; the label below replaces the one above');
180
+ for (const line of formatLabel(deck.report)) console.log(line);
181
+ console.log(formatSignature(deck.signature));
182
+ if (deck.strict) {
183
+ console.log(wasStrict && !next.strict
184
+ ? ' still serving strict — a pull cannot turn it off'
185
+ : ' serving strict — what could not be accounted for is stripped');
186
+ }
187
+ console.log(' the label above describes what the audience gets when the deck is reloaded');
188
+ await refreshUpstream();
189
+ return {
190
+ ok: true, state: 'pulled', from, to, deck: 'changed',
191
+ strict: deck.strict, degraded,
192
+ findings: { unaccounted: deck.report.counts.unaccounted, handlers: deck.report.counts.handlers },
193
+ // A degraded deck does NOT reload itself: the swap executes nothing (the
194
+ // browser is still showing the old DOM), so the reload can wait for a
195
+ // second confirmation that names what was found.
196
+ reload: !degraded,
197
+ message: degraded
198
+ ? `the updated deck runs ${deck.report.counts.unaccounted} unaccounted script block(s) and `
199
+ + `${deck.report.counts.handlers} inline handler(s) — they are stripped. Reload to show it`
200
+ : `fast-forwarded to ${to}`,
201
+ };
202
+ }
203
+
125
204
  const server = createServer(withHeaders({ 'content-security-policy': CSP }, (req, res) => {
126
205
  let url;
127
206
  try { url = new URL(req.url, 'http://127.0.0.1'); }
@@ -176,6 +255,11 @@ const USAGE = `usage: decklight present <deck.html|deck.decklight> [--port 8790]
176
255
  an executable attribute — so CI can gate on a deck before it is
177
256
  forwarded or published.
178
257
  --no-plugins present without your own chrome, whatever is installed.
258
+ --upstream-every N minutes between upstream checks; 0 turns the check off [10]
259
+ --no-upstream never look at the upstream — no git, no network
260
+ --upstream-pull register the update control the deck's H overlay drives.
261
+ OFF by default: with it on, any script in the deck can
262
+ fast-forward the clone the deck was served from.
179
263
 
180
264
  Your presenter plugins (decklight plugin) are layered on at serve time from
181
265
  ~/.decklight/plugins/ — a timer, a teleprompter, a confidence monitor. They
@@ -357,8 +441,34 @@ export async function presentMain(args, { client } = {}) {
357
441
  // no third state where a bad signature means something else — one degrade is
358
442
  // one thing to understand at the moment you have no time to understand two.
359
443
  const unverified = signature.state !== UNSIGNED && !isVerified(signature);
360
- const strict = args.includes('--strict') || report.counts.unaccounted > 0
361
- || report.counts.handlers > 0 || unverified;
444
+ // MUTABLE from here, because a pull may replace all of it (PRESENT#UPSTREAM).
445
+ // SPEC's condition on live reload is that the audit re-runs and the verdict is
446
+ // re-printed — never new bytes under the old label — so the bytes, the label,
447
+ // the signature and `strict` move together or not at all.
448
+ /** Read the deck, audit it, and decide strict — the startup block, reusable. */
449
+ function readAndAudit() {
450
+ const bytes = isContainer(deckPath) ? readContainer(deckPath).payload : readFileSync(deckPath);
451
+ const rep = auditDeck(bytes.toString('utf8'));
452
+ // The signature is NOT re-verified here: it is a sidecar for the file as
453
+ // published, verifying it costs the network, and a pull that changed the
454
+ // deck has already invalidated whatever the old one attested. The state is
455
+ // carried forward and the label says what it says.
456
+ return {
457
+ payload: bytes,
458
+ report: rep,
459
+ signature,
460
+ strict: args.includes('--strict') || rep.counts.unaccounted > 0 || rep.counts.handlers > 0,
461
+ };
462
+ }
463
+
464
+ let deck = {
465
+ payload,
466
+ report,
467
+ signature,
468
+ strict: args.includes('--strict') || report.counts.unaccounted > 0
469
+ || report.counts.handlers > 0 || unverified,
470
+ };
471
+ const strict = deck.strict;
362
472
 
363
473
  // The rewrite covers every html response, not only the deck: strict that
364
474
  // stopped at one file would be walked around by a second page under the same
@@ -379,7 +489,10 @@ export async function presentMain(args, { client } = {}) {
379
489
  // With an empty library `injectChrome` returns its input, so this whole
380
490
  // paragraph is a no-op and `present` is byte-for-byte the command it was.
381
491
  const chrome = args.includes('--no-plugins') ? { plugins: [], refused: [] } : loadLibrary();
382
- const strip = strict ? (text) => stripUnaccounted(text).html : null;
492
+ // Consulted per request rather than decided once: after a pull, `strict` may
493
+ // have RATCHETED ON, and the bytes served have to follow the verdict printed
494
+ // for them.
495
+ const strip = (text) => (deck.strict ? stripUnaccounted(text).html : text);
383
496
 
384
497
  // Only the deck gets chrome. Every OTHER html file under the root still gets
385
498
  // the strict rewrite — strict that stopped at one file would be walked
@@ -388,12 +501,12 @@ export async function presentMain(args, { client } = {}) {
388
501
  // documents into same-origin iframes). Those same iframes are why the chrome
389
502
  // is deck-only: presenter chrome belongs to the document the presenter is
390
503
  // looking at, and the shim removes itself if it finds it is framed anyway.
391
- const rewrite = (strip || chrome.plugins.length)
392
- ? (text, file) => {
393
- const out = strip ? strip(text) : text;
394
- return file === deckPath ? injectChrome(out, chrome.plugins) : out;
395
- }
396
- : null;
504
+ // Always a function now: `strip` is decided per call, so a pull that turns
505
+ // strict ON must not find the rewrite path was compiled away at startup.
506
+ const rewrite = (text, file) => {
507
+ const out = strip(text);
508
+ return file === deckPath ? injectChrome(out, chrome.plugins) : out;
509
+ };
397
510
  // No `index` here: "/" is the deck, and the deck is answered from memory
398
511
  // before this handler is consulted — a fallthrough should 404, not reopen
399
512
  // the disk read this route exists to avoid.
@@ -414,8 +527,8 @@ export async function presentMain(args, { client } = {}) {
414
527
  const servePayload = (req, res) => {
415
528
  if (req.method !== 'GET') return false;
416
529
  const body = rewrite
417
- ? Buffer.from(rewrite(payload.toString('utf8'), deckPath), 'utf8')
418
- : payload;
530
+ ? Buffer.from(rewrite(deck.payload.toString('utf8'), deckPath), 'utf8')
531
+ : deck.payload;
419
532
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' });
420
533
  res.end(body);
421
534
  return true;
@@ -453,6 +566,114 @@ export async function presentMain(args, { client } = {}) {
453
566
  // fixed string or first-party content, so no uncovered response was
454
567
  // exploitable — but "every response carries the header" is only worth
455
568
  // stating if it holds by construction, not by each writeHead remembering.
569
+
570
+ /**
571
+ * Fast-forward, then re-read, re-audit and RE-PRINT.
572
+ *
573
+ * SPEC's condition on live reload under `present` is exactly this: never new
574
+ * bytes under the old verdict. So the label the presenter can see always
575
+ * describes the bytes being served, and the two move together.
576
+ */
577
+ async function doPull() {
578
+ // Re-checked against a FRESH fetch rather than trusted from the cached
579
+ // status: what was true ten minutes ago is not a licence to check out now.
580
+ const fresh = await refreshUpstream();
581
+ const allowed = canPull(fresh, { offered: pullArmed });
582
+ if (!allowed.ok) return { ok: false, ...allowed, http: allowed.state === 'dirty' ? 409 : 409 };
583
+
584
+ const from = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: upstream.repoRoot })).stdout;
585
+ console.log(` upstream: PULL requested by the deck — fast-forward only, onto ${upstream.upstream}`);
586
+ const merged = await runGit([...SAFE_CONFIG, '-c', `core.hooksPath=${upstream.repoRoot}/.git/decklight-no-hooks`,
587
+ 'merge', '--ff-only', '--no-verify', '@{upstream}'], { cwd: upstream.repoRoot, timeoutMs: 20000 });
588
+ if (!merged.ok) {
589
+ const why = oneline(merged.stderr || merged.err);
590
+ console.log(` upstream: the fast-forward was refused — ${why}`);
591
+ return { ok: false, state: 'not-fast-forward', message: why };
592
+ }
593
+ const to = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: upstream.repoRoot })).stdout;
594
+
595
+ // An upstream commit must never blank somebody's talk.
596
+ if (!existsSync(deckPath)) {
597
+ console.log(` upstream: fast-forwarded ${from} → ${to}, but the deck is gone from that commit`);
598
+ console.log(' still serving the bytes the label above describes');
599
+ return { ok: false, state: 'deck-gone', to, message: 'the deck is not in that commit — still serving the old bytes' };
600
+ }
601
+
602
+ const before = deck.payload;
603
+ const next = readAndAudit();
604
+ if (next.payload.equals(before)) {
605
+ console.log(` upstream: fast-forwarded ${from} → ${to} — the deck itself is unchanged`);
606
+ await refreshUpstream();
607
+ return { ok: true, state: 'pulled', from, to, deck: 'unchanged', reload: false, message: `fast-forwarded to ${to} — the deck is unchanged` };
608
+ }
609
+
610
+ // STRICT RATCHETS: a pull may turn it on and can never turn it off. A deck
611
+ // that could clear its own strict flag by pulling could disarm the one
612
+ // mitigation present applies without being asked.
613
+ const wasStrict = deck.strict;
614
+ deck = { ...next, strict: next.strict || wasStrict };
615
+ const degraded = (next.report.counts.unaccounted > 0 || next.report.counts.handlers > 0)
616
+ && !(report.counts.unaccounted > 0 || report.counts.handlers > 0);
617
+
618
+ console.log(` upstream: fast-forwarded ${from} → ${to}`);
619
+ console.log(' the deck file changed — re-read and re-audited; the label below replaces the one above');
620
+ for (const line of formatLabel(deck.report)) console.log(line);
621
+ console.log(formatSignature(deck.signature));
622
+ if (deck.strict) {
623
+ console.log(wasStrict && !next.strict
624
+ ? ' still serving strict — a pull cannot turn it off'
625
+ : ' serving strict — what could not be accounted for is stripped');
626
+ }
627
+ console.log(' the label above describes what the audience gets when the deck is reloaded');
628
+ await refreshUpstream();
629
+ return {
630
+ ok: true, state: 'pulled', from, to, deck: 'changed',
631
+ strict: deck.strict, degraded,
632
+ findings: { unaccounted: deck.report.counts.unaccounted, handlers: deck.report.counts.handlers },
633
+ // A degraded deck does NOT reload itself: the swap executes nothing (the
634
+ // browser is still showing the old DOM), so the reload can wait for a
635
+ // second confirmation that names what was found.
636
+ reload: !degraded,
637
+ message: degraded
638
+ ? `the updated deck runs ${deck.report.counts.unaccounted} unaccounted script block(s) and `
639
+ + `${deck.report.counts.handlers} inline handler(s) — they are stripped. Reload to show it`
640
+ : `fast-forwarded to ${to}`,
641
+ };
642
+ }
643
+
644
+ // ── the upstream check (PRESENT#UPSTREAM) ─────────────────────────────────
645
+ const suppressed = upstreamSuppressed({ args, env: process.env });
646
+ const upstreamCtx = suppressed ? { state: 'disabled' } : await resolveUpstream(deckPath);
647
+ // Absent unless the deck is a tracked file in a clone with an upstream. This
648
+ // is the whole safety argument: a deck you were emailed is a single file and
649
+ // never reaches any of it.
650
+ const upstream = upstreamCtx.state === 'ok' ? upstreamCtx : null;
651
+ // The PULL is a second, explicit opt-in. Server-side there is no way to tell
652
+ // "the presenter clicked" from "a script in the deck called fetch()" — a
653
+ // page's own script is indistinguishable from its user — so the capability is
654
+ // "a deck served from a clone can update itself from that clone's upstream",
655
+ // which is a thing someone should have typed rather than something the cwd
656
+ // decided. And never with --remote: a phone must not move somebody's repo.
657
+ const pullArmed = Boolean(upstream) && args.includes('--upstream-pull') && !token;
658
+ let upstreamStatus = upstream
659
+ ? { state: 'unchecked', branch: upstream.branch, upstream: upstream.upstream, message: 'not checked yet' }
660
+ : { state: upstreamCtx.state, message: suppressed || null };
661
+ let checking = null;
662
+ const intervalMs = resolveInterval(args);
663
+ let lastReported = null;
664
+ const pullOffer = () => (pullArmed
665
+ ? { offered: true }
666
+ : { offered: false, reason: !upstream ? upstreamCtx.state : token ? '--remote is on' : 'start with --upstream-pull' });
667
+
668
+ async function refreshUpstream() {
669
+ if (!upstream) return upstreamStatus;
670
+ // Single-flight: a script in a loop must not spawn a hundred fetches.
671
+ if (!checking) {
672
+ checking = checkUpstream(upstream).then((s) => { upstreamStatus = s; checking = null; return s; });
673
+ }
674
+ return checking;
675
+ }
676
+
456
677
  const server = createServer(withHeaders({ 'content-security-policy': CSP }, (req, res) => {
457
678
  // Loopback always; off-loopback only /remote/* carrying the per-run token,
458
679
  // and only when --remote asked for a listener at all. Every other path is
@@ -487,6 +708,42 @@ export async function presentMain(args, { client } = {}) {
487
708
  return;
488
709
  }
489
710
  if (req.method === 'GET' && url.pathname === '/present/events') { decks.add(req, res, CORS); return; }
711
+ // ── the upstream (PRESENT#UPSTREAM) ─────────────────────────────────
712
+ // REGISTERED ONLY when the deck is a tracked file in a clone whose branch
713
+ // tracks something. On a deck you were emailed these are not refused, they
714
+ // do not exist — a POST lands on the same 405 as a POST to anything else,
715
+ // which is the argument the module header already makes about /edit/*.
716
+ //
717
+ // No CORS on either: /present/ping and /present/events carry it because the
718
+ // phone's origin differs, and the phone has no business here in either
719
+ // direction.
720
+ if (upstream && req.method === 'GET' && url.pathname === '/present/upstream') {
721
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-cache' });
722
+ res.end(JSON.stringify({ ok: true, ...upstreamStatus, pull: pullOffer() }));
723
+ return;
724
+ }
725
+ if (upstream && req.method === 'POST' && url.pathname === '/present/upstream/check') {
726
+ if (!isOwnOrigin(req, actualPort)) { res.writeHead(403); res.end('forbidden'); return; }
727
+ refreshUpstream().then(() => {
728
+ res.writeHead(200, { 'content-type': 'application/json' });
729
+ res.end(JSON.stringify({ ok: true, ...upstreamStatus, pull: pullOffer() }));
730
+ });
731
+ return;
732
+ }
733
+ if (pullArmed && req.method === 'POST' && url.pathname === '/present/upstream/pull') {
734
+ // The strict gate, not allowEditRequest: `null` is a sandboxed plugin
735
+ // frame's origin, and presenter chrome must not be able to fast-forward
736
+ // the presenter's repository.
737
+ if (!isOwnOrigin(req, actualPort)) { res.writeHead(403); res.end('forbidden'); return; }
738
+ // The body is never read. Not validated — READ. No field of the request
739
+ // reaches git or the filesystem; the repository, the branch and
740
+ // `@{upstream}` are all constants resolved before the server existed.
741
+ doPull().then((out) => {
742
+ res.writeHead(out.ok ? 200 : (out.http ?? 409), { 'content-type': 'application/json' });
743
+ res.end(JSON.stringify(out));
744
+ });
745
+ return;
746
+ }
490
747
  // The phone remote: controller, QR, readout channel. These are the only
491
748
  // paths allowRemote let through from off this machine, and not one of them
492
749
  // writes anything — the phone asks the deck to move, it never edits.
@@ -526,6 +783,34 @@ export async function presentMain(args, { client } = {}) {
526
783
  for (const line of formatLabel(report)) console.log(line);
527
784
  if (container) console.log(formatManifest(container.manifest));
528
785
  console.log(formatSignature(signature));
786
+ // The upstream, said once at startup and then only when it CHANGES. `up to
787
+ // date` every ten minutes for an hour is noise that trains people to stop
788
+ // reading the terminal — which is where the ingredients label lives.
789
+ if (upstream) {
790
+ console.log(` upstream: tracking ${upstream.upstream} — ${intervalMs ? `checking every ${intervalMs / 60000} min` : 'checked when asked'}`
791
+ + (pullArmed ? ', update control ON (--upstream-pull)' : ''));
792
+ if (!pullArmed && args.includes('--upstream-pull') && token) {
793
+ console.log(' upstream: --remote is on — the update control is off; pull from your own terminal');
794
+ }
795
+ } else if (suppressed) {
796
+ console.log(` upstream: not checked — ${suppressed}`);
797
+ }
798
+
799
+ // Kicked AFTER the last startup line and never awaited: nothing about this
800
+ // can delay the server coming up or hang a talk on a registry that is down —
801
+ // the cli/update-check.mjs contract, applied to a different remote.
802
+ if (upstream) {
803
+ const tick = () => refreshUpstream().then((st) => {
804
+ if (st.state !== lastReported) {
805
+ lastReported = st.state;
806
+ console.log(` upstream: ${st.message}`);
807
+ }
808
+ }).catch(() => {});
809
+ tick();
810
+ // unref'd so a Ctrl-C exits now rather than after an in-flight fetch.
811
+ // `--upstream-every 0` keeps the manual check and drops only the timer.
812
+ if (intervalMs > 0) setInterval(tick, intervalMs).unref();
813
+ }
529
814
  // Reported UNDER the label and never inside it. The label is an inventory of
530
815
  // the file; a plugin is not in the file, and folding one into those counts
531
816
  // would make the label start describing things the deck does not contain —
package/cli/restore.mjs CHANGED
@@ -34,20 +34,136 @@ import { git, inGitRepo, isIdentityError, oneline } from './git.mjs';
34
34
  const SEP = '\x01';
35
35
 
36
36
  /**
37
- * The commits that touched this deck, newest first: `{ hash, when, subject }`.
37
+ * The commits that touched this deck, newest first:
38
+ * `{ hash, when, subject, full }`.
39
+ *
40
+ * `full` is the unabbreviated hash, and it is here for one reason: marking a
41
+ * commit as unpushed means comparing it against `rev-list`'s output, and
42
+ * `%h`'s abbreviation length is a repository setting that can differ between
43
+ * the two commands. Comparing abbreviations is a bug that only appears in big
44
+ * repositories, which is the worst kind.
45
+ *
38
46
  * `run` is the git invoker, injected so this is testable without a repo.
39
47
  * Returns [] for a file git has never seen.
40
48
  */
41
49
  export function deckHistory(deckPath, cwd, run = git) {
42
50
  const rel = relative(cwd, deckPath) || basename(deckPath);
43
- const out = run(['log', `--format=%h${SEP}%ar${SEP}%s`, '--', rel], cwd);
51
+ const out = run(['log', `--format=%h${SEP}%ar${SEP}%s${SEP}%H`, '--', rel], cwd);
44
52
  if (!out) return [];
45
53
  return out.split('\n').filter(Boolean).map((line) => {
46
- const [hash, when, subject] = line.split(SEP);
47
- return { hash, when, subject };
54
+ const [hash, when, subject, full] = line.split(SEP);
55
+ return { hash, when, subject, full };
48
56
  });
49
57
  }
50
58
 
59
+ /**
60
+ * How many commits deep the per-version stats go.
61
+ *
62
+ * Every stat below is CHEAP except one: the slide count, which can only be had
63
+ * by reading the whole deck at that revision, and a bundled deck is most of a
64
+ * megabyte. Thirty of those is ~20 MB through one pipe — fine — and three
65
+ * hundred is not. Rows past the limit simply carry no badge, which is the
66
+ * right failure: a number missing from row 40 costs nothing, and a two-second
67
+ * stall every time somebody presses H costs the feature.
68
+ */
69
+ export const STAT_DEPTH = 30;
70
+
71
+ /** Slides in a deck's source. `<section\b` is the same measure `decklight pdf` uses. */
72
+ export const countSlides = (html) => (String(html).match(/<section\b/gi) ?? []).length;
73
+
74
+ /**
75
+ * `git log --numstat`'s output, as `full hash → { add, del }`. Pure.
76
+ *
77
+ * The shape is a hash line, a blank line, then one tab-separated numstat row
78
+ * per path. No separator is needed to tell them apart: a numstat row always
79
+ * contains tabs and a hash line never does, so the hash is recognised by being
80
+ * a hash. `-` where a count should be is git saying "binary" — that is a null,
81
+ * not a zero, and a deck that someone checked in with a `binary` gitattribute
82
+ * must not be reported as having changed nothing.
83
+ */
84
+ export function parseNumstat(out) {
85
+ const stats = new Map();
86
+ let full = null;
87
+ for (const line of String(out ?? '').split('\n')) {
88
+ if (/^[0-9a-f]{40,64}$/.test(line)) { full = line; continue; }
89
+ if (!full || !line.includes('\t')) continue;
90
+ const [add, del] = line.split('\t');
91
+ stats.set(full, {
92
+ add: add === '-' ? null : Number(add),
93
+ del: del === '-' ? null : Number(del),
94
+ });
95
+ }
96
+ return stats;
97
+ }
98
+
99
+ /**
100
+ * `git cat-file --batch`'s output, as `hash → slide count`. Pure.
101
+ *
102
+ * The format is a header line (`<oid> <type> <size>`), exactly `size` BYTES of
103
+ * content, then a newline — so the walk is by byte offset and never by
104
+ * splitting on newlines, which would desynchronise on the first deck
105
+ * containing one. A revision git cannot resolve answers `<name> missing`, with
106
+ * no content at all; that row just gets no count.
107
+ *
108
+ * `hashes` is the request order, which is also the reply order — that is the
109
+ * contract of `--batch`, and it is why the answers need no keys of their own.
110
+ */
111
+ export function parseCatFileBatch(buf, hashes) {
112
+ const out = new Map();
113
+ let at = 0;
114
+ for (const hash of hashes) {
115
+ const nl = buf.indexOf(10, at);
116
+ if (nl < 0) break;
117
+ const head = buf.toString('utf8', at, nl);
118
+ at = nl + 1;
119
+ if (/\b(missing|ambiguous)$/.test(head)) continue;
120
+ const size = Number(head.split(' ')[2]);
121
+ if (!Number.isFinite(size)) break;
122
+ out.set(hash, countSlides(buf.toString('utf8', at, at + size)));
123
+ at += size + 1; // the trailing newline --batch adds
124
+ }
125
+ return out;
126
+ }
127
+
128
+ /**
129
+ * Decorate history entries with what each version WAS and what it CHANGED:
130
+ * `slides`, `add`, `del`. Mutates and returns `entries`.
131
+ *
132
+ * Two git invocations for the whole list, not two per row — a history overlay
133
+ * that spawned sixty processes to draw sixty rows would be slower than the
134
+ * thing it is showing you. Everything here is a local object read: no network,
135
+ * no working tree, nothing written.
136
+ *
137
+ * Best-effort by construction. A repository that cannot answer leaves the
138
+ * fields undefined and the overlay draws the row without badges, because the
139
+ * hash and the subject are the part you actually navigate by.
140
+ */
141
+ export function decorateHistory(entries, deckPath, cwd, {
142
+ depth = STAT_DEPTH, run = git, exec = execFileSync,
143
+ } = {}) {
144
+ if (!entries.length) return entries;
145
+ const rel = relative(cwd, deckPath) || basename(deckPath);
146
+ try {
147
+ const stats = parseNumstat(run(['log', '--format=%H', '--numstat', '--', rel], cwd));
148
+ for (const e of entries) {
149
+ const s = stats.get(e.full);
150
+ if (s) { e.add = s.add; e.del = s.del; }
151
+ }
152
+ } catch { /* counts are a nicety; the list is the feature */ }
153
+ try {
154
+ const heads = entries.slice(0, depth).map((e) => e.full);
155
+ const buf = exec('git', ['cat-file', '--batch'], {
156
+ cwd,
157
+ input: heads.map((h) => `${h}:${rel}\n`).join(''),
158
+ maxBuffer: 128 * 1024 * 1024,
159
+ stdio: ['pipe', 'pipe', 'ignore'],
160
+ });
161
+ const slides = parseCatFileBatch(buf, heads);
162
+ for (const e of entries) if (slides.has(e.full)) e.slides = slides.get(e.full);
163
+ } catch { /* ditto */ }
164
+ return entries;
165
+ }
166
+
51
167
  /** One list row, aligned enough to scan: `a1b2c3d · 2 hours ago · subject`. */
52
168
  export function formatEntry({ hash, when, subject }, pad = 14) {
53
169
  return `${hash} ${String(when).padEnd(pad)} ${subject}`;
package/cli/serve.mjs CHANGED
@@ -80,6 +80,30 @@ export function allowEditRequest(req) {
80
80
  return isLoopbackOrigin(origin);
81
81
  }
82
82
 
83
+ /**
84
+ * A STRICTER gate: this exact origin, and nothing else.
85
+ *
86
+ * `allowEditRequest` above admits an absent Origin (curl, a probe) and the
87
+ * literal `null` — and `null` is what a SANDBOXED IFRAME sends. That is exactly
88
+ * what presenter chrome runs in (`injectChrome` mounts every plugin in one), so
89
+ * a gate that admits it would let a plugin reach an action the presenter never
90
+ * asked for. Pinning the port refuses another loopback dev server's page too,
91
+ * which the edit gate admits by design.
92
+ *
93
+ * Used by the one route in `present` that ACTS. The looser gate is right for
94
+ * `/edit/*`, where the server exists to be written to and a curl from the
95
+ * author's own machine is a feature; it is wrong here.
96
+ */
97
+ export function isOwnOrigin(req, port) {
98
+ const origin = req.headers?.origin;
99
+ if (typeof origin !== 'string' || !origin) return false;
100
+ return [
101
+ `http://127.0.0.1:${port}`,
102
+ `http://localhost:${port}`,
103
+ `http://[::1]:${port}`,
104
+ ].includes(origin);
105
+ }
106
+
83
107
  /**
84
108
  * Pure request classifier: may this request be answered at all?
85
109
  * Loopback: always. Off-loopback: only /remote/* paths carrying the per-run
@@ -126,6 +126,15 @@ nothing changed, so an extra call is harmless. If the port is not listening
126
126
  there is no authoring server: skip it silently and carry on, never start one
127
127
  yourself. This is what makes a history someone can read afterwards, instead
128
128
  of a wall of identical timer commits.
129
+
130
+ **That history is readable, and it is how a bad edit is undone.** \`decklight
131
+ history deck.html\` lists every commit that touched the deck and marks the ones
132
+ that exist only on this machine; \`decklight restore deck.html <hash>\` puts the
133
+ deck back — written as a NEW commit, never a rewrite, so restoring is always
134
+ safe to try. In the deck itself the same history is \`H\` (a live preview of
135
+ every version; \`⏎\` restores after asking). Prefer restore over hand-reverting
136
+ your own edits: it is exact, and it keeps the record honest about what
137
+ happened.
129
138
  `;
130
139
  }
131
140