decklight 0.1.0 → 0.3.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.
Files changed (139) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +105 -183
  3. package/SPEC.md +861 -74
  4. package/cli/agents.mjs +206 -0
  5. package/cli/associate.mjs +279 -0
  6. package/cli/audit.mjs +424 -0
  7. package/cli/bundle.mjs +210 -45
  8. package/cli/deckfile.mjs +233 -0
  9. package/cli/decklight.mjs +216 -5
  10. package/cli/dev.mjs +455 -0
  11. package/cli/edit.mjs +733 -63
  12. package/cli/extension.mjs +108 -0
  13. package/cli/git.mjs +141 -0
  14. package/cli/import.mjs +398 -0
  15. package/cli/init.mjs +465 -121
  16. package/cli/loader.mjs +263 -0
  17. package/cli/marketplace.mjs +730 -0
  18. package/cli/pdf.mjs +156 -0
  19. package/cli/pkg.mjs +69 -0
  20. package/cli/plugin.mjs +646 -0
  21. package/cli/port-conflict.mjs +94 -0
  22. package/cli/present.mjs +560 -0
  23. package/cli/publish.mjs +342 -0
  24. package/cli/qr.mjs +334 -0
  25. package/cli/rec.mjs +12 -8
  26. package/cli/remote.mjs +149 -0
  27. package/cli/report-bug.mjs +97 -0
  28. package/cli/restore.mjs +174 -0
  29. package/cli/serve.mjs +247 -0
  30. package/cli/sign.mjs +216 -0
  31. package/cli/skill-content.mjs +222 -0
  32. package/cli/skills.mjs +338 -0
  33. package/cli/supervise.mjs +57 -0
  34. package/cli/theme.mjs +201 -0
  35. package/cli/units.mjs +488 -0
  36. package/cli/upgrade.mjs +250 -0
  37. package/cli/util.mjs +90 -0
  38. package/cli/wizard.mjs +432 -0
  39. package/cli/zip.mjs +121 -0
  40. package/dist/decklight.css +949 -72
  41. package/dist/decklight.js +220 -103
  42. package/dist/decklight.js.map +4 -4
  43. package/docs/architecture.svg +1 -1
  44. package/package.json +9 -6
  45. package/themes/README.md +6 -4
  46. package/themes/aurora.css +4 -1
  47. package/themes/berry.css +4 -1
  48. package/themes/carbon.css +4 -1
  49. package/themes/citrus.css +4 -1
  50. package/themes/coastal.css +4 -1
  51. package/themes/cosmos.css +4 -1
  52. package/themes/dune.css +4 -1
  53. package/themes/eclipse.css +4 -1
  54. package/themes/ember.css +4 -1
  55. package/themes/fjord.css +4 -1
  56. package/themes/gallery.html +3 -11
  57. package/themes/glacier.css +4 -1
  58. package/themes/graphite.css +4 -1
  59. package/themes/harvest.css +4 -1
  60. package/themes/ibm-modern.css +4 -1
  61. package/themes/ink.css +4 -1
  62. package/themes/latte.css +4 -1
  63. package/themes/linen.css +4 -1
  64. package/themes/meadow.css +4 -1
  65. package/themes/metropolis.css +4 -1
  66. package/themes/midnight.css +4 -1
  67. package/themes/mint.css +4 -1
  68. package/themes/moss.css +4 -1
  69. package/themes/obsidian.css +4 -1
  70. package/themes/orchid.css +4 -1
  71. package/themes/packs.json +4 -31
  72. package/themes/paper.css +4 -1
  73. package/themes/peony.css +4 -1
  74. package/themes/porcelain.css +4 -1
  75. package/themes/reveal-beige.css +4 -1
  76. package/themes/reveal-black.css +4 -1
  77. package/themes/reveal-blood.css +4 -1
  78. package/themes/reveal-dracula.css +4 -1
  79. package/themes/reveal-league.css +4 -1
  80. package/themes/reveal-moon.css +4 -1
  81. package/themes/reveal-night.css +4 -1
  82. package/themes/reveal-serif.css +4 -1
  83. package/themes/reveal-simple.css +4 -1
  84. package/themes/reveal-sky.css +4 -1
  85. package/themes/reveal-solarized.css +4 -1
  86. package/themes/reveal-white.css +4 -1
  87. package/themes/sepia.css +4 -1
  88. package/themes/seriph.css +4 -1
  89. package/themes/slate.css +4 -1
  90. package/themes/storm.css +4 -1
  91. package/themes/synthwave.css +4 -1
  92. package/themes/velvet.css +4 -1
  93. package/themes/yamabuki.css +120 -0
  94. package/tools/args.mjs +32 -0
  95. package/tools/bridge.mjs +30 -0
  96. package/tools/chrome.mjs +52 -0
  97. package/tools/color.mjs +110 -0
  98. package/tools/deck-html.mjs +138 -0
  99. package/tools/elevenlabs-tts.mjs +248 -0
  100. package/tools/escape.mjs +40 -0
  101. package/tools/extension-check-runner.mjs +41 -0
  102. package/tools/extension-check.mjs +266 -0
  103. package/tools/gemini-tts.mjs +44 -4
  104. package/tools/lipsync-engines.mjs +81 -0
  105. package/tools/lipsync-server.mjs +290 -0
  106. package/tools/lipsync.mjs +181 -0
  107. package/tools/local-voice.mjs +209 -0
  108. package/tools/ooxml.mjs +151 -0
  109. package/tools/pptx.mjs +320 -0
  110. package/tools/publish-site-voices.mjs +5 -1
  111. package/tools/publish-targets.mjs +143 -0
  112. package/tools/publish-voices.mjs +230 -0
  113. package/tools/shot.mjs +129 -0
  114. package/tools/theme-check.mjs +139 -0
  115. package/tools/tts-engines.mjs +455 -0
  116. package/tools/tts-setup.mjs +257 -0
  117. package/tools/veo.mjs +204 -0
  118. package/tools/video.mjs +316 -0
  119. package/tools/visemes.mjs +26 -0
  120. package/tools/voiceover-server.mjs +0 -0
  121. package/tools/voiceover.mjs +73 -39
  122. package/tools/zip.mjs +143 -0
  123. package/docs/demo.svg +0 -124
  124. package/themes/aliens.css +0 -84
  125. package/themes/apple2.css +0 -126
  126. package/themes/blade-runner.css +0 -83
  127. package/themes/c64.css +0 -85
  128. package/themes/friends.css +0 -82
  129. package/themes/gameboy.css +0 -118
  130. package/themes/genesis.css +0 -84
  131. package/themes/godfather.css +0 -82
  132. package/themes/ibm-oldschool.css +0 -84
  133. package/themes/miami-vice.css +0 -84
  134. package/themes/pulp-fiction.css +0 -84
  135. package/themes/severance.css +0 -82
  136. package/themes/snes.css +0 -82
  137. package/themes/star-wars.css +0 -85
  138. package/themes/stranger-things.css +0 -84
  139. package/themes/terminator.css +0 -84
@@ -0,0 +1,94 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Shared "the port's taken" resolution for `decklight author`'s edit server.
5
+ // The occupant is usually a PAST edit server (you started one
6
+ // yesterday, forgot, and now `init`/`author` wants the same default port) — so
7
+ // rather than guess at a PID, ask it directly: every edit server answers
8
+ // GET /edit/ping with the deck it's serving, and POST /edit/shutdown stops it
9
+ // as cleanly as its own Ctrl-C (final autocommit included). That makes "kill
10
+ // it and take over" a plain HTTP round trip, no lsof/ps, no platform split.
11
+ //
12
+ // Used two ways: reactively, when edit's own server.listen() hits
13
+ // EADDRINUSE, and proactively, by author BEFORE it spawns the edit child —
14
+ // that child's stdin is closed (piped, not a TTY), so it could never ask.
15
+
16
+ import { createConnection } from 'node:net';
17
+
18
+ /** Is something listening on `port`? Port 0 ("OS picks one") never conflicts. */
19
+ export function isPortOpen(port, host = '127.0.0.1', timeout = 400) {
20
+ if (!port) return Promise.resolve(false);
21
+ return new Promise((done) => {
22
+ const socket = createConnection({ host, port, timeout });
23
+ socket.once('connect', () => { socket.destroy(); done(true); });
24
+ socket.once('timeout', () => { socket.destroy(); done(false); });
25
+ socket.once('error', () => done(false));
26
+ });
27
+ }
28
+
29
+ /** Ask the occupant what it's editing — null if it isn't an edit server at all. */
30
+ export async function identifyEditServer(port, host = '127.0.0.1') {
31
+ try {
32
+ const res = await fetch(`http://${host}:${port}/edit/ping`, { signal: AbortSignal.timeout(800) });
33
+ if (!res.ok) return null;
34
+ const data = await res.json();
35
+ return data?.ok ? data : null;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ /** Ask it to stop — it auto-commits and exits, same as its own Ctrl-C. Resolves once the port is free. */
42
+ export async function shutdownEditServer(port, host = '127.0.0.1') {
43
+ try {
44
+ await fetch(`http://${host}:${port}/edit/shutdown`, { method: 'POST', signal: AbortSignal.timeout(800) });
45
+ } catch {
46
+ // it may hang up mid-response as it exits — that's the expected shape
47
+ }
48
+ for (let i = 0; i < 30 && (await isPortOpen(port, host)); i++) await new Promise((r) => setTimeout(r, 100));
49
+ return !(await isPortOpen(port, host));
50
+ }
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;
57
+ }
58
+
59
+ /**
60
+ * Pure: what to do about a taken port — testable without a socket or a
61
+ * terminal. Only offers to kill an occupant we can actually identify AND
62
+ * only when something can be asked; anything else just moves to a free port.
63
+ */
64
+ export function planPortConflict({ tty = false, identified = null } = {}) {
65
+ return tty && identified ? 'ask' : 'bump';
66
+ }
67
+
68
+ /**
69
+ * The port is already bound. Work out who's there and either take it over or
70
+ * move on. `ask` is `(prompt) => Promise<string>`; its absence means no TTY
71
+ * to ask, so the port just bumps. Returns the port actually free to use.
72
+ */
73
+ export async function resolvePortConflict(port, { host = '127.0.0.1', ask, log = () => {} } = {}) {
74
+ const identified = await identifyEditServer(port, host);
75
+ const action = planPortConflict({ tty: Boolean(ask), identified });
76
+
77
+ if (action === 'ask') {
78
+ log(` port ${port} is already in use — decklight is editing "${identified.name}" there`);
79
+ const answer = (await ask(' [k]ill that session and take it over, or use a [d]ifferent port? [k/D] ')).trim().toLowerCase();
80
+ if (answer.startsWith('k')) {
81
+ log(` stopping the session editing "${identified.name}"…`);
82
+ if (await shutdownEditServer(port, host)) return port;
83
+ log(" it didn't stop in time — using a different port instead");
84
+ }
85
+ } else {
86
+ log(identified
87
+ ? ` port ${port} is already in use — decklight is editing "${identified.name}" there; using a different port`
88
+ : ` port ${port} is already in use; using a different port`);
89
+ }
90
+
91
+ const next = await nextFreePort(port + 1, host);
92
+ log(` → using port ${next}`);
93
+ return next;
94
+ }
@@ -0,0 +1,560 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * `decklight present <deck>` — play a deck you did not author.
6
+ *
7
+ * The asymmetry this answers (MARKETPLACE.md WHY): a plugin runs on the
8
+ * machine of the person who chose to install it, but a DECK travels — emailed,
9
+ * published, presented — so anything inlined into one runs in front of an
10
+ * audience that installed nothing and consented to nothing. Opening someone
11
+ * else's deck straight off the filesystem gives that content `file://` origin
12
+ * and no policy at all.
13
+ *
14
+ * Serving it over localhost instead buys the one thing a file cannot have: a
15
+ * `Content-Security-Policy` **HTTP header**, which the document cannot
16
+ * override. A `<meta>` CSP inside the deck is worth nothing here — an attacker
17
+ * who can edit the payload edits the meta tag in the same pass.
18
+ *
19
+ * This module registers exactly one capability: GET a file under the deck's
20
+ * directory. There is no `/edit/*` route to refuse, because none is ever
21
+ * registered (#168 split `cli/serve.mjs` out of `cli/edit.mjs` for precisely
22
+ * this), and nothing here writes to disk.
23
+ *
24
+ * Three things now ride on that one capability, in the order they run: the
25
+ * ingredients label names what the file will execute (PRESENT#AUDIT), strict
26
+ * mode removes what it could not account for on the way out (PRESENT#STRICT),
27
+ * and the CSP header bounds whatever is left.
28
+ */
29
+
30
+ import { createServer } from 'node:http';
31
+ import { existsSync, readFileSync } from 'node:fs';
32
+ import { resolve, sep, basename, dirname } from 'node:path';
33
+ import { randomBytes } from 'node:crypto';
34
+ import { argReader, isMain } from '../tools/args.mjs';
35
+ import { allowRemote, lanAddress, staticFiles, sseChannel, listenTakingOverIfNeeded, withHeaders } from './serve.mjs';
36
+ import { createRemoteRelay } from './remote.mjs';
37
+ import { corsHeaders } from '../tools/bridge.mjs';
38
+
39
+ // The phone is a different origin from the deck (a LAN address, not localhost),
40
+ // so the remote's own endpoints need CORS. Nothing else here does — the deck is
41
+ // same-origin with the server that serves it.
42
+ const CORS = corsHeaders();
43
+ import { auditDeck, formatLabel, stripUnaccounted } from './audit.mjs';
44
+ import { loadLibrary, injectChrome } from './plugin.mjs';
45
+ import { verifyFile, verifyBytes, formatSignature, isVerified, UNSIGNED, TAMPERED, VERIFIED } from './sign.mjs';
46
+ import { isContainer, readContainer, formatManifest } from './deckfile.mjs';
47
+
48
+ /**
49
+ * The policy, and honestly what it is worth.
50
+ *
51
+ * `script-src` has to carry `'unsafe-inline'`: a bundled deck IS inline script
52
+ * (the runtime is inlined by `decklight bundle`) and even a source deck calls
53
+ * `Decklight.init()` from an inline block. So this header does NOT stop a deck
54
+ * from running script — that is what PRESENT#AUDIT names and PRESENT#STRICT
55
+ * strips, and claiming otherwise here would manufacture confidence the
56
+ * mechanism cannot back.
57
+ *
58
+ * What it does stop is what a hostile deck would want to DO with that script:
59
+ * `default-src 'none'` denies every fetch destination not listed below,
60
+ * `object-src` kills plugin embedding, `base-uri` stops relative-URL
61
+ * hijacking, and `form-action 'none'` means a credential form pasted into a
62
+ * deck has nowhere to post. Exfiltration is narrowed to `https:` rather than
63
+ * closed, because that is where SPEC'd narration lives (below).
64
+ *
65
+ * Each opening is a SPEC'd feature, not a convenience:
66
+ * - `media-src https:` — a recorded track's `dir` may be an absolute URL, and
67
+ * background video stays external by design (PRESENTING). `blob:` is the
68
+ * stitched/`createObjectURL` audio path.
69
+ * - `connect-src https:` — manifest tracks fetch `manifest.signed.json` from a
70
+ * bucket; a presigned URL's origin is not knowable ahead of time, so it
71
+ * cannot be pinned to an allowlist here.
72
+ * - `frame-src`/`frame-ancestors 'self'` — the theme picker, the slide finder
73
+ * and the speaker view all boot the deck into same-origin iframes. `'none'`
74
+ * would break the picker preview; `'self'` still refuses embedding by
75
+ * another site.
76
+ * - `style-src 'unsafe-inline'` — themes are inline `<style data-theme>`
77
+ * blocks and the engine writes inline custom properties (`--pin-y`).
78
+ *
79
+ * Deliberately absent: the local TTS/lipsync bridges (`127.0.0.1:8787/8789`).
80
+ * Live synthesis is an authoring-path engine, and MARKETPLACE.md ENGINES is
81
+ * explicit that engines never come up outside author mode — a deck you were
82
+ * emailed asking to reach a local service is the shape of a probe. Recorded
83
+ * narration needs no bridge and is unaffected.
84
+ */
85
+ export const CSP = [
86
+ "default-src 'none'",
87
+ "script-src 'self' 'unsafe-inline'",
88
+ "style-src 'self' 'unsafe-inline'",
89
+ "img-src 'self' data: blob: https:",
90
+ "media-src 'self' data: blob: https:",
91
+ "font-src 'self' data:",
92
+ "connect-src 'self' https:",
93
+ "frame-src 'self'",
94
+ "frame-ancestors 'self'",
95
+ "base-uri 'none'",
96
+ "form-action 'none'",
97
+ "object-src 'none'",
98
+ ].join('; ');
99
+
100
+ /**
101
+ * Serve files under `root` over http://127.0.0.1 with this module's CSP on
102
+ * EVERY response, for the render tools (`tools/shot.mjs`, `tools/video.mjs`).
103
+ *
104
+ * It is `present`'s serving core with the audit/strict/remote/edit surface
105
+ * stripped off: `withHeaders` for the policy, `staticFiles` for a
106
+ * traversal-guarded GET, an ephemeral loopback port. A deck screenshotted or
107
+ * filmed BEFORE anyone presents it therefore runs under the same policy
108
+ * `present` gives it — instead of over `file://` with
109
+ * `--allow-file-access-from-files`, the flag that let a deck's own JS read any
110
+ * local file it could name and ship it anywhere (#229). An http origin cannot
111
+ * read `file://` at all, and the CSP bounds where the rest can reach; a read is
112
+ * confined to what `staticFiles` will serve under `root`.
113
+ *
114
+ * `html` rewrites the text of every text/html response on its way out (shot
115
+ * injects its driver and `--theme` link there, in memory — no temp file). The
116
+ * server must be driven with an ASYNC Chrome (execFile, not execFileSync): a
117
+ * synchronous child blocks the event loop, and this in-process server would
118
+ * never answer the browser it launched.
119
+ *
120
+ * Returns `{ origin, close }` — `origin` is `http://127.0.0.1:<port>`, `close`
121
+ * resolves when the listener is shut.
122
+ */
123
+ export async function serveForRender(root, { html = null } = {}) {
124
+ const files = staticFiles(root, { html });
125
+ const server = createServer(withHeaders({ 'content-security-policy': CSP }, (req, res) => {
126
+ let url;
127
+ try { url = new URL(req.url, 'http://127.0.0.1'); }
128
+ catch { res.writeHead(400); res.end('bad request'); return; }
129
+ if (files(req, res, url)) return;
130
+ res.writeHead(405); res.end('method not allowed');
131
+ }));
132
+ const port = await listenTakingOverIfNeeded(server, 0, '127.0.0.1');
133
+ return {
134
+ origin: `http://127.0.0.1:${port}`,
135
+ close: () => new Promise((r) => server.close(r)),
136
+ };
137
+ }
138
+
139
+ const USAGE = `usage: decklight present <deck.html|deck.decklight> [--port 8790] [--strict]
140
+ [--root <dir>] [--remote] [--host <addr>] [--check]
141
+ [--no-plugins]
142
+
143
+ plays a deck read-only over localhost — the safe way to open one you did not
144
+ author. Serves ONLY GET, only under the deck's own directory — refusing
145
+ dotfiles and every file type a deck cannot use — and writes nothing.
146
+
147
+ A .decklight container (bundle --deck) is unwrapped in memory and treated
148
+ exactly like the deck it wraps: same audit, same policy, same strict rule. Its
149
+ signature is verified and its manifest is printed as what it is — the
150
+ container's own claim about itself, next to the one thing that was checked.
151
+ The manifest's origin (repo and commit) is never printed: the signature
152
+ covers the deck alone, so even on a verified container the origin is whatever
153
+ the packer wrote, and a provenance line nobody vouches for does not belong
154
+ one skim away from a verified identity. It stays in the manifest for tooling
155
+ to read.
156
+
157
+ --port N port to bind; a taken port offers to take over that session
158
+ (on a TTY) or moves on to the next free one [8790]
159
+ --strict serve with every script block that is not the runtime removed,
160
+ along with every inline on*= handler, javascript: URL and srcdoc
161
+ document. The removal happens on the way out — the file on disk
162
+ is never touched. Turns itself on when the label finds something.
163
+ --root D serve D instead of the deck's directory, for a SOURCE deck that
164
+ reaches up for its runtime (demo/talk.html loading
165
+ ../dist/decklight.js). The deck must live under D, and everything
166
+ under D that passes the dotfile and file-type rules becomes
167
+ fetchable by the deck's own script — which is why widening the
168
+ root is a flag you type, never something the cwd decides.
169
+ --remote also listen on the LAN for the phone remote. Off this machine ONLY
170
+ /remote/* answers, and only with the per-run token the printed URL
171
+ and its QR carry — the deck itself, and every file beside it, stay
172
+ unreachable from the LAN whether or not this flag is passed.
173
+ --host A the address --remote binds [0.0.0.0]
174
+ --check print the ingredients label and exit — no server. Exits non-zero
175
+ if the deck runs any script that is not the runtime — a block or
176
+ an executable attribute — so CI can gate on a deck before it is
177
+ forwarded or published.
178
+ --no-plugins present without your own chrome, whatever is installed.
179
+
180
+ Your presenter plugins (decklight plugin) are layered on at serve time from
181
+ ~/.decklight/plugins/ — a timer, a teleprompter, a confidence monitor. They
182
+ are YOURS: the deck on disk is untouched, nothing is written into it, and the
183
+ same file presented on a machine without them is identical slides and no
184
+ warning. Each one renders inside a sandboxed frame with an opaque origin, so
185
+ it draws chrome and cannot reach the slides — a plugin that asks for slide
186
+ content is refused by name, because a deck has to stay a deterministic
187
+ artifact or two people presenting the same file present different decks.
188
+
189
+ A plugin is never part of the ingredients label: the label counts what is in
190
+ the file, the chrome is listed under it as what it is. Loading one registers
191
+ no route and does not widen the policy below by a single source.
192
+
193
+ Every start prints the ingredients label: which runtime is embedded and
194
+ whether its bytes are the ones this install ships, how many inert data blocks
195
+ the runtime will read, and — named, with line numbers — every script block
196
+ that will execute and is NOT accounted for, plus every executable attribute
197
+ (an inline on*= handler, a javascript: or data:text/html URL, an inline
198
+ srcdoc document — the vectors 'unsafe-inline' below would otherwise let run
199
+ unnamed). It is an inventory, not a verdict:
200
+ there is no "safe" here, because the scan is a heuristic over a file someone
201
+ may have edited and a green check would promise more than it can keep.
202
+
203
+ A deck with a detached signature beside it (talk.html.sig) is verified BEFORE
204
+ it renders, and the terminal names who signed it — an identity you can judge,
205
+ not a check mark. Sigstore keyless, so there are no keys: the certificate was
206
+ minted for one signature against the signer's OIDC identity and expired
207
+ minutes later; the transparency log is what keeps it checkable. A deck with no
208
+ sidecar is not an alarm — most decks are unsigned, and treating that as a
209
+ finding would train you to ignore the one that matters. Verifying needs the
210
+ sigstore client and the network; when it cannot be done here, that is said as
211
+ its own state and never as a pass.
212
+
213
+ When the label finds an unaccounted block — or a signature does not verify,
214
+ or cannot be checked here — strict mode turns ITSELF on and says so in the
215
+ terminal. It does not ask, and there is no --force to turn it
216
+ back off: ten minutes before a talk is the worst possible moment for a
217
+ refusal, and an escape hatch would be reached for exactly then — so the deck
218
+ always plays, and the part nobody can account for is the part that doesn't.
219
+ Removed blocks are named in the terminal, never on the audience's screen.
220
+
221
+ What survives strict is what a deck needs to render itself: the runtime, the
222
+ Decklight.init call, JSON data blocks and templates. Builds, layouts, themes,
223
+ charts and background media are markup, CSS and attributes — never at risk. A
224
+ clean deck under --strict is byte-identical to the same deck without it.
225
+
226
+ There is no editing surface: the /edit/* routes are not registered at all, so
227
+ a POST to one is as unknown as a POST to anything else. That is also why the
228
+ phone remote lives here rather than on the author server — getting a clicker
229
+ should not mean running write endpoints against your deck while you are on
230
+ stage and not looking at it.
231
+
232
+ Every response carries this Content-Security-Policy as an HTTP header, which
233
+ the deck cannot override the way it could a <meta> tag:
234
+
235
+ ${CSP.replace(/; /g, ';\n ')}
236
+
237
+ Recorded narration from a bucket and external background video still play —
238
+ that is what the https: sources in media-src/connect-src are for. Live voice
239
+ does not: synthesis needs the local bridge, which is an authoring-mode engine
240
+ and is deliberately not reachable from here.
241
+
242
+ Read the policy honestly: script-src carries 'unsafe-inline' because a
243
+ bundled deck IS inline script, so this does not stop a deck from running
244
+ code. It stops that code from reaching anywhere it shouldn't.`;
245
+
246
+ // `client` is the sigstore client — injectable for the same reason as
247
+ // `bundleMain`'s: `undefined` means "go load the real one", an explicit stub
248
+ // lets a test drive the verification states without the network.
249
+ export async function presentMain(args, { client } = {}) {
250
+ const positional = args.filter((a) => !a.startsWith('-'));
251
+ if (args.includes('--help') || args.includes('-h') || !positional.length) {
252
+ console.log(USAGE);
253
+ return 0;
254
+ }
255
+ const { opt } = argReader(args);
256
+ const port = Number(opt('--port', 8790));
257
+
258
+ // --remote widens the LISTENER and nothing else (PRESENT#REMOTE). The point
259
+ // of moving the phone remote here is that getting a clicker should not mean
260
+ // running an editing server against your deck while you are on stage and not
261
+ // looking at it — so this server still registers no /edit/* route, and the
262
+ // only paths a caller off this machine can reach are /remote/*, with the
263
+ // per-run token. allowRemote is the same classifier the author server uses;
264
+ // one implementation, tested once.
265
+ const remote = args.includes('--remote') || opt('--host') !== undefined;
266
+ const host = remote ? opt('--host', '0.0.0.0') : '127.0.0.1';
267
+ const token = remote ? randomBytes(16).toString('base64url') : null;
268
+
269
+ const deckPath = resolve(process.cwd(), positional[0]);
270
+ if (!existsSync(deckPath)) {
271
+ console.error(`deck not found: ${deckPath}`);
272
+ return 1;
273
+ }
274
+ // A .decklight is the same deck with its signature and manifest stapled on
275
+ // (DECK_FILE), so it is unwrapped here and everything below treats it exactly
276
+ // like the HTML it wraps — same audit, same CSP, same strict rule. Nothing is
277
+ // written to unwrap it: the payload is a slice of the bytes already read.
278
+ let container = null;
279
+ if (isContainer(deckPath)) {
280
+ try { container = readContainer(deckPath); } catch (e) { console.error(e.message); return 1; }
281
+ }
282
+ const payload = container ? container.payload : readFileSync(deckPath);
283
+
284
+ // The audit runs because it is the only way in (PRESENT): a standalone
285
+ // `verify` is a step people skip, so folding it into the command you already
286
+ // use to present means it runs every time, at no extra effort.
287
+ const report = auditDeck(payload.toString('utf8'));
288
+
289
+ // The signature, if the deck came with one (INTEGRITY#SIGNING). Costs nothing
290
+ // when there is no sidecar — the common case returns without touching the
291
+ // network — and the audit above runs either way, because the two answer
292
+ // different questions: a signature says WHO vouched for these bytes, the label
293
+ // says what the bytes will do. A signed deck can still run something nobody
294
+ // should, and the label is what would name it.
295
+ let signature;
296
+ if (container) {
297
+ signature = container.signature
298
+ ? await verifyBytes(container.payload, container.signature, { client })
299
+ : { state: TAMPERED, reason: 'the container carries no signature' };
300
+ // The manifest is the container's own label. When it does not describe the
301
+ // deck it is stapled to, something rewrote one half — which is the same
302
+ // conclusion as a signature that does not verify, so it is the same state.
303
+ if (!container.digestOk && signature.state === VERIFIED) {
304
+ signature = { state: TAMPERED, reason: 'the manifest digest does not match the payload' };
305
+ }
306
+ } else {
307
+ signature = await verifyFile(deckPath, { client });
308
+ }
309
+
310
+ if (args.includes('--check')) {
311
+ for (const line of formatLabel(report, { indent: '' })) console.log(line);
312
+ if (container) console.log(formatManifest(container.manifest, { indent: '' }));
313
+ if (signature.state !== UNSIGNED) console.log(formatSignature(signature, { indent: '' }));
314
+ // Non-zero means "this deck executes something I could not account for", or
315
+ // "it carries a signature I could not stand behind" — not "this deck is
316
+ // malicious", which is a call no exit code should make. `unchecked` counts:
317
+ // a gate that passes when it could not evaluate the claim is not a gate.
318
+ return report.counts.unaccounted || report.counts.handlers
319
+ || (signature.state !== UNSIGNED && !isVerified(signature)) ? 1 : 0;
320
+ }
321
+
322
+ // The served root is the deck's OWN directory, never the cwd. Everything
323
+ // under the root is fetchable by the deck's own script same-origin, and with
324
+ // `connect-src https:` open below, fetchable means exfiltratable — so a root
325
+ // inherited from wherever the command happened to run (a project checkout,
326
+ // $HOME via file association) would hand a hostile deck whatever lived
327
+ // there. A deck handed to you is a bundled single file with no external refs
328
+ // at all; its directory is exactly the exposure you accepted by opening it.
329
+ //
330
+ // A SOURCE deck's assets are not always siblings — `demo/showcase.html`
331
+ // reaches up for `../dist/decklight.js` — and rooting at the deck's
332
+ // directory would 403 the engine and serve a page that never boots. That is
333
+ // what `--root` is for: the same wider exposure, but chosen by a flag you
334
+ // typed, and printed at startup so it is never silent.
335
+ const rootArg = opt('--root');
336
+ const root = rootArg ? resolve(process.cwd(), rootArg) : dirname(deckPath);
337
+ if (!deckPath.startsWith(root + sep)) {
338
+ console.error('deck must live under --root');
339
+ return 1;
340
+ }
341
+ const deckUrl = '/' + deckPath.slice(root.length + 1).split(sep).join('/');
342
+
343
+ // Strict is not a mode you opt into after reading the label — it is what the
344
+ // label DOES when it finds something (PRESENT#STRICT). The alternative
345
+ // designs both fail at the same moment: refusing to serve leaves someone with
346
+ // no talk ten minutes before they give it, and offering a --force turns the
347
+ // finding into a prompt that will be clicked through precisely then. Playing
348
+ // the deck without the part nobody could account for is the only option that
349
+ // is still the right one under time pressure, so it is the automatic one.
350
+ //
351
+ // A signature that does not verify feeds the SAME path (INTEGRITY#SIGNING):
352
+ // signing adds a source of failure, not a new behaviour. There is deliberately
353
+ // no third state where a bad signature means something else — one degrade is
354
+ // one thing to understand at the moment you have no time to understand two.
355
+ const unverified = signature.state !== UNSIGNED && !isVerified(signature);
356
+ const strict = args.includes('--strict') || report.counts.unaccounted > 0
357
+ || report.counts.handlers > 0 || unverified;
358
+
359
+ // The rewrite covers every html response, not only the deck: strict that
360
+ // stopped at one file would be walked around by a second page under the same
361
+ // root, and the deck can reach one — the theme picker, the slide finder and
362
+ // the speaker view all boot documents into same-origin iframes.
363
+ // The presenter's own chrome (PRESENT#PLUGINS) — a timer, a teleprompter,
364
+ // a confidence monitor. It is loaded from ~/.decklight/plugins/, which is
365
+ // the presenter's library and not the deck's: the installer is the
366
+ // risk-bearer and nothing here travels, which is the same trust model that
367
+ // makes a build-time transform defensible (MARKETPLACE.md EXTENSIONS).
368
+ //
369
+ // Two orderings below are load-bearing rather than incidental:
370
+ // - it loads AFTER `auditDeck` has read the bytes, so a plugin is never
371
+ // counted as an unaccounted script block in the ingredients label. The
372
+ // label describes the file; a plugin is not in the file.
373
+ // - it injects AFTER `stripUnaccounted`, so strict mode never strips the
374
+ // chrome as if the deck had smuggled it in.
375
+ // With an empty library `injectChrome` returns its input, so this whole
376
+ // paragraph is a no-op and `present` is byte-for-byte the command it was.
377
+ const chrome = args.includes('--no-plugins') ? { plugins: [], refused: [] } : loadLibrary();
378
+ const strip = strict ? (text) => stripUnaccounted(text).html : null;
379
+
380
+ // Only the deck gets chrome. Every OTHER html file under the root still gets
381
+ // the strict rewrite — strict that stopped at one file would be walked
382
+ // around by a second page under the same root, and the deck can reach one
383
+ // (the theme picker, the slide finder and the speaker view all boot
384
+ // documents into same-origin iframes). Those same iframes are why the chrome
385
+ // is deck-only: presenter chrome belongs to the document the presenter is
386
+ // looking at, and the shim removes itself if it finds it is framed anyway.
387
+ const rewrite = (strip || chrome.plugins.length)
388
+ ? (text, file) => {
389
+ const out = strip ? strip(text) : text;
390
+ return file === deckPath ? injectChrome(out, chrome.plugins) : out;
391
+ }
392
+ : null;
393
+ // No `index` here: "/" is the deck, and the deck is answered from memory
394
+ // before this handler is consulted — a fallthrough should 404, not reopen
395
+ // the disk read this route exists to avoid.
396
+ const files = staticFiles(root, { html: rewrite, knownTypesOnly: true });
397
+
398
+ // The deck itself is served from MEMORY — container and plain HTML alike —
399
+ // from the bytes the audit read and the signature covered. The label, the
400
+ // signature verdict and `strict` were all decided against those bytes at
401
+ // startup and printed as a verdict; re-reading the file per request would
402
+ // let a deck edited on disk AFTER that moment ride out under it (#235). For
403
+ // a container this also avoids the one write this command does not make —
404
+ // unpacking to a temp file that would sit somewhere after the talk, which is
405
+ // precisely the file nobody meant to keep. Everything else about the
406
+ // response is identical to any other file under the root: same strict
407
+ // rewrite, same policy header, same GET-only server around it. If live
408
+ // reload of the deck under `present` is ever wanted, it must re-run the
409
+ // audit and re-print the verdict — never silently serve new bytes.
410
+ const servePayload = (req, res) => {
411
+ if (req.method !== 'GET') return false;
412
+ const body = rewrite
413
+ ? Buffer.from(rewrite(payload.toString('utf8'), deckPath), 'utf8')
414
+ : payload;
415
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' });
416
+ res.end(body);
417
+ return true;
418
+ };
419
+
420
+ // Is this URL the deck? Matched on the RESOLVED path, exactly as staticFiles
421
+ // would resolve it, so a percent-encoded spelling of the same file cannot
422
+ // slip past this route into the per-request disk read below it.
423
+ const isDeck = (url) => {
424
+ if (url.pathname === '/') return true;
425
+ let rel;
426
+ try { rel = decodeURIComponent(url.pathname); } catch { return false; }
427
+ return resolve(root, '.' + rel) === deckPath;
428
+ };
429
+
430
+ // Two one-way channels, kept apart on purpose. `decks` is what a deck served
431
+ // by this server subscribes to, and the ONLY event it ever carries is
432
+ // `remote` — no `reload`, no `agent`, because neither exists here and a
433
+ // presenting server that could tell a deck to reload would be an editing
434
+ // server with the writes left out. The phone's own stream lives in the relay.
435
+ const decks = sseChannel();
436
+ let actualPort = null;
437
+ const relay = createRemoteRelay({
438
+ deckName: basename(deckPath),
439
+ token,
440
+ remoteUrl: () => `http://${lanAddress() ?? host}:${actualPort}/remote?t=${token}`,
441
+ relayToDeck: (event, data) => decks.broadcast(event, data),
442
+ deckCount: () => decks.size,
443
+ CORS,
444
+ });
445
+
446
+ // The CSP is set once, out here, for EVERY response this server writes —
447
+ // the deck and its assets, but also the 403/404/405 pages, the control-
448
+ // channel JSON and SSE, and the remote controller. Every body below is a
449
+ // fixed string or first-party content, so no uncovered response was
450
+ // exploitable — but "every response carries the header" is only worth
451
+ // stating if it holds by construction, not by each writeHead remembering.
452
+ const server = createServer(withHeaders({ 'content-security-policy': CSP }, (req, res) => {
453
+ // Loopback always; off-loopback only /remote/* carrying the per-run token,
454
+ // and only when --remote asked for a listener at all. Every other path is
455
+ // refused off this machine unconditionally — flag or no flag, token or no
456
+ // token — which is why the static files and the deck itself cannot be
457
+ // reached from the LAN even while the remote can.
458
+ if (!allowRemote(req, token)) {
459
+ res.writeHead(403);
460
+ res.end('forbidden: this deck is served to this machine only; off it, only /remote/* answers, with the session token');
461
+ return;
462
+ }
463
+ let url;
464
+ try { url = new URL(req.url, 'http://127.0.0.1'); } catch { res.writeHead(400); res.end('bad request'); return; }
465
+ // The deck's own path answers from the audited bytes (servePayload above).
466
+ // For a container that also means the URL a person sees is the file they
467
+ // double-clicked — serving the raw archive bytes there would hand a
468
+ // browser something it cannot render.
469
+ if (isDeck(url)) {
470
+ if (servePayload(req, res)) return;
471
+ res.writeHead(405); res.end('method not allowed'); return;
472
+ }
473
+ // staticFiles answers GET (200/403/404) and declines everything else. A
474
+ // POST to /edit/notes lands here exactly like a POST to /anything — there
475
+ // is no route to have refused it, which is the point of the ticket.
476
+ // The presenting control channel. `/present/ping` is how a deck discovers
477
+ // it is being presented rather than authored, and the answer deliberately
478
+ // carries no agent roster and no edit capability — there is nothing here to
479
+ // report about editing, because there is nothing here that edits.
480
+ if (req.method === 'GET' && url.pathname === '/present/ping') {
481
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json', 'cache-control': 'no-cache' });
482
+ res.end(JSON.stringify({ ok: true, name: basename(deckPath), remote: !!token, present: true }));
483
+ return;
484
+ }
485
+ if (req.method === 'GET' && url.pathname === '/present/events') { decks.add(req, res, CORS); return; }
486
+ // The phone remote: controller, QR, readout channel. These are the only
487
+ // paths allowRemote let through from off this machine, and not one of them
488
+ // writes anything — the phone asks the deck to move, it never edits.
489
+ let body = '';
490
+ if (req.method === 'POST') {
491
+ req.on('data', (c) => { body += c; if (body.length > 4096) req.destroy(); });
492
+ req.on('end', () => {
493
+ try {
494
+ if (relay.handle(req, res, url, body)) return;
495
+ } catch {
496
+ res.writeHead(400, { ...CORS, 'content-type': 'application/json' });
497
+ res.end(JSON.stringify({ ok: false, error: 'bad payload' }));
498
+ return;
499
+ }
500
+ res.writeHead(405);
501
+ res.end('method not allowed');
502
+ });
503
+ return;
504
+ }
505
+ if (relay.handle(req, res, url, '')) return;
506
+ if (files(req, res, url)) return;
507
+ res.writeHead(405);
508
+ res.end('method not allowed');
509
+ }));
510
+
511
+ const actual = await listenTakingOverIfNeeded(server, port, host);
512
+ actualPort = actual;
513
+ console.log(`decklight present on http://127.0.0.1:${actual}${deckUrl} — read-only, CSP enforced. Ctrl-C stops`);
514
+ console.log(` serving ${root} — ${rootArg ? '--root as given' : "the deck's own directory"};`
515
+ + ' dotfiles and non-deck file types refused; no /edit/* routes, nothing is written');
516
+ if (token) {
517
+ console.log(` remote: listening on ${host} — http://${lanAddress() ?? host}:${actual}/remote?t=${token}`);
518
+ console.log(' off this machine ONLY /remote/* answers, with that token — the deck itself does not');
519
+ }
520
+ // Before the first slide renders, not after — the point is to be able to
521
+ // decide not to open it.
522
+ for (const line of formatLabel(report)) console.log(line);
523
+ if (container) console.log(formatManifest(container.manifest));
524
+ console.log(formatSignature(signature));
525
+ // Reported UNDER the label and never inside it. The label is an inventory of
526
+ // the file; a plugin is not in the file, and folding one into those counts
527
+ // would make the label start describing things the deck does not contain —
528
+ // which is exactly the honesty the label exists for. Naming which plugins
529
+ // read the speaker notes is the other half of `needs: ["notes"]` being a
530
+ // declaration rather than a silent grant.
531
+ for (const p of chrome.plugins) {
532
+ console.log(` chrome: ${p.name} (${p.slot}) — yours, not in the deck`
533
+ + `${p.needs.includes('notes') ? '; reads your speaker notes' : ''}`);
534
+ }
535
+ for (const r of chrome.refused) {
536
+ console.log(` chrome: ${r.name} REFUSED — not loaded, the deck plays without it`);
537
+ console.log(` ${r.reason.replace(/\n/g, '\n ')}`);
538
+ }
539
+ // Here and nowhere else. The audience is looking at the deck; a banner on the
540
+ // page would tell them something they cannot act on, about a file they did
541
+ // not choose to open, in the middle of someone's talk.
542
+ if (strict) {
543
+ const n = report.counts.unaccounted, h = report.counts.handlers;
544
+ if (unverified) console.log(' the signature did not verify — serving strict');
545
+ const removed = [
546
+ n ? `${n} unaccounted script block${n === 1 ? '' : 's'}` : '',
547
+ h ? `${h} executable attribute${h === 1 ? '' : 's'}` : '',
548
+ ].filter(Boolean).join(' and ');
549
+ console.log(removed
550
+ ? ` ${removed} stripped — serving strict. The file on disk is untouched`
551
+ : ` nothing to strip — this deck is served exactly as ${container ? 'the container carries it' : 'it was read from disk'}`);
552
+ }
553
+
554
+ const stop = () => { server.close(); process.exit(0); };
555
+ process.on('SIGINT', stop);
556
+ process.on('SIGTERM', stop);
557
+ return 0;
558
+ }
559
+
560
+ if (isMain(import.meta.url)) process.exitCode = await presentMain(process.argv.slice(2));