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
package/cli/serve.mjs ADDED
@@ -0,0 +1,247 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The deck-server core — everything a localhost deck server needs that is not
5
+ // an editing endpoint: the loopback/token security classifier, static file
6
+ // serving with a traversal guard, SSE fan-out, and port binding with takeover.
7
+ //
8
+ // Extracted from edit.mjs so `decklight present` (MARKETPLACE.md,
9
+ // PRESENT_SERVER) can serve a deck read-only by reusing this core with the
10
+ // /edit/* routes ABSENT — not merely refused. Nothing in this module writes a
11
+ // file.
12
+
13
+ import { readFileSync, existsSync, statSync } from 'node:fs';
14
+ import { resolve, extname, sep } from 'node:path';
15
+ import { timingSafeEqual } from 'node:crypto';
16
+ import { networkInterfaces } from 'node:os';
17
+ import { createInterface } from 'node:readline/promises';
18
+ import { resolvePortConflict } from './port-conflict.mjs';
19
+
20
+ // ── remote access: the security seam for the phone remote (#39) ────────────
21
+ // --remote widens the LISTENER, never the editing surface: off-loopback,
22
+ // only /remote/* answers, and only with the per-run token; every /edit/*
23
+ // mutation (and the static files) refuses non-loopback callers
24
+ // unconditionally, flag or no flag.
25
+
26
+ /** Loopback caller? IPv4-mapped IPv6 (::ffff:127.0.0.1) counts too. */
27
+ export function isLoopback(addr) {
28
+ const a = String(addr ?? '').replace(/^::ffff:/i, '');
29
+ return a === '::1' || /^127\./.test(a);
30
+ }
31
+
32
+ /**
33
+ * Is this `Origin` a loopback WEB origin — a page a localhost server handed
34
+ * out (`http://127.0.0.1:8788`, `http://localhost:5173`, `http://[::1]:…`)? A
35
+ * hostname, not a socket address: this reads the string the browser stamped on
36
+ * the request, which is a different question from `isLoopback` (who is dialing
37
+ * the socket) and the one a CSRF gate has to ask.
38
+ */
39
+ export function isLoopbackOrigin(origin) {
40
+ let u;
41
+ try { u = new URL(String(origin)); } catch { return false; }
42
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return false;
43
+ const host = u.hostname.replace(/^\[|\]$/g, '');
44
+ if (host === 'localhost' || host === '::1') return true;
45
+ // 127.0.0.0/8, and ONLY as a dotted quad. `isLoopback` above is deliberately
46
+ // loose (`/^127\./`) because it reads SOCKET addresses, which are numeric. A
47
+ // hostname is not: `127.0.0.1.evil.example` is a domain an attacker can
48
+ // register and would sail through that prefix test, so the origin check
49
+ // pins all four octets.
50
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
51
+ return !!m && m[1] === '127' && m.slice(1).every((o) => Number(o) <= 255);
52
+ }
53
+
54
+ /**
55
+ * The CSRF gate for the author server's `/edit/*` surface (#222). The attacker
56
+ * is the user's OWN browser: while `decklight author` runs, any page in any tab
57
+ * can `fetch()` loopback, and a permissive `access-control-allow-origin` is no
58
+ * defense — a "simple" `text/plain` POST is sent with NO preflight, so the
59
+ * agent has already run by the time the browser consults CORS on the way back.
60
+ * The gate therefore runs BEFORE the handler, on the one field a page cannot
61
+ * forge: the `Origin` the browser attaches.
62
+ *
63
+ * Answered YES for:
64
+ * - a request with no `Origin` at all — the CLI, `curl`, the port-conflict
65
+ * probe, the test suite: not a browser cross-origin call.
66
+ * - a loopback web origin — the deck this very server serves (same-origin),
67
+ * and any other same-machine dev server the author is running.
68
+ * - `null` — a `file://`-opened deck, the SPEC'd double-click path.
69
+ *
70
+ * Answered NO for every other origin, which is exactly the `https://evil.example`
71
+ * tab the ticket is about. Residual: `null` is also the origin of a sandboxed
72
+ * iframe, so a page that embeds one can still reach here; closing that would
73
+ * cost the `file://` path a token it has no way to receive, and the SPEC keeps
74
+ * the double-click affordance. It is called out in PRESENTING.
75
+ */
76
+ export function allowEditRequest(req) {
77
+ const origin = req.headers?.origin;
78
+ if (origin === undefined) return true;
79
+ if (origin === 'null') return true;
80
+ return isLoopbackOrigin(origin);
81
+ }
82
+
83
+ /**
84
+ * Pure request classifier: may this request be answered at all?
85
+ * Loopback: always. Off-loopback: only /remote/* paths carrying the per-run
86
+ * token (?t= query or x-decklight-token header) — everything else, all
87
+ * /edit/* mutations included, is refused regardless of any token. `token`
88
+ * is null when --remote is off, which refuses every off-loopback request
89
+ * (defense in depth behind the 127.0.0.1 binding).
90
+ */
91
+ export function allowRemote(req, token) {
92
+ if (isLoopback(req.socket?.remoteAddress)) return true;
93
+ if (!token) return false;
94
+ let url;
95
+ try { url = new URL(req.url, 'http://x'); } catch { return false; }
96
+ // new URL() normalizes dot segments, so /remote/../edit/notes is /edit/notes
97
+ if (url.pathname !== '/remote' && !url.pathname.startsWith('/remote/')) return false;
98
+ const sent = Buffer.from(String(url.searchParams.get('t') ?? req.headers?.['x-decklight-token'] ?? ''));
99
+ const want = Buffer.from(token);
100
+ return sent.length === want.length && timingSafeEqual(sent, want);
101
+ }
102
+
103
+ /** The machine's LAN address — what the printed /remote?t= URL should carry. */
104
+ export function lanAddress(interfaces = networkInterfaces()) {
105
+ for (const addrs of Object.values(interfaces)) {
106
+ for (const a of addrs ?? []) {
107
+ if (!a.internal && a.family === 'IPv4') return a.address;
108
+ }
109
+ }
110
+ return null;
111
+ }
112
+
113
+ export const MIME = {
114
+ '.html': 'text/html; charset=utf-8',
115
+ '.js': 'text/javascript', '.mjs': 'text/javascript',
116
+ '.css': 'text/css', '.json': 'application/json',
117
+ '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg',
118
+ '.gif': 'image/gif', '.ico': 'image/x-icon', '.webp': 'image/webp',
119
+ '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.mp3': 'audio/mpeg',
120
+ '.mp4': 'video/mp4', '.webm': 'video/webm',
121
+ '.woff': 'font/woff', '.woff2': 'font/woff2', '.map': 'application/json',
122
+ };
123
+
124
+ // Re-exported so the server's callers keep one import: the escape itself is
125
+ // tools/escape.mjs's, which also covers quotes — this one did not, under a
126
+ // name that reads like it covers everything.
127
+ export { escapeHtml } from '../tools/escape.mjs';
128
+
129
+ /**
130
+ * Wrap a request handler so EVERY response it writes carries `headers` —
131
+ * the deck, its assets, error pages, JSON, SSE, all of it. They are set
132
+ * before the handler runs, and writeHead merges them under any headers a
133
+ * route names itself, so a route can sharpen one but can never lose one by
134
+ * not mentioning it. This is the seam the present server's
135
+ * Content-Security-Policy arrives through (PRESENT): "every response
136
+ * carries the header" holds by construction here, instead of by every
137
+ * writeHead in every route remembering.
138
+ */
139
+ export function withHeaders(headers, handler) {
140
+ return (req, res) => {
141
+ for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
142
+ return handler(req, res);
143
+ };
144
+ }
145
+
146
+ /**
147
+ * Static files under `root`, GET only: traversal-guarded, MIME-typed,
148
+ * no-cache. `index` is the path "/" serves (the deck). Returns whether the
149
+ * request was handled.
150
+ *
151
+ * `html` rewrites the text of every text/html response on its way out and
152
+ * leaves every other type alone. It is how `present --strict` (PRESENT#STRICT)
153
+ * serves a deck with the unaccounted blocks removed while the file on disk
154
+ * stays exactly as it arrived: the transform sits between the read and the
155
+ * write, so there is no point in this path where the modified bytes could be
156
+ * mistaken for the deck.
157
+ *
158
+ * Dotfiles are refused unconditionally — no path segment may start with `.`,
159
+ * decoded or not. A deck has no business fetching `.env` or `.git/config`,
160
+ * and with `connect-src https:` open (PRESENT), anything a hostile deck can
161
+ * read same-origin it can also send anywhere.
162
+ *
163
+ * `knownTypesOnly` additionally refuses every extension the MIME table does
164
+ * not name. `present` passes it: the table is the set of types a deck can
165
+ * actually use, and a file beside a travelled deck that is none of them —
166
+ * `id_rsa`, a `.pem`, a database — is only ever fetched to be exfiltrated.
167
+ * The author server does not, so an author's exotic asset still serves as
168
+ * octet-stream from their own machine.
169
+ */
170
+ export function staticFiles(root, { index = '/index.html', html: rewriteHtml = null, knownTypesOnly = false } = {}) {
171
+ return (req, res, url) => {
172
+ if (req.method !== 'GET') return false;
173
+ const rel = url.pathname === '/' ? index : decodeURIComponent(url.pathname);
174
+ const file = resolve(root, '.' + rel);
175
+ if (!file.startsWith(root + sep) && file !== root) { res.writeHead(403); res.end('forbidden'); return true; }
176
+ if (!existsSync(file) || !statSync(file).isFile()) { res.writeHead(404); res.end('not found'); return true; }
177
+ // Policy refusals come AFTER the existence check on purpose: a path that
178
+ // is not there stays a plain 404, indistinguishable from any other unknown
179
+ // path — a probe for /edit/ping must not learn anything from the answer.
180
+ const type = MIME[extname(file).toLowerCase()];
181
+ if (rel.split('/').some((s) => s.startsWith('.')) || (knownTypesOnly && !type)) {
182
+ res.writeHead(403); res.end('forbidden'); return true;
183
+ }
184
+ let body = readFileSync(file);
185
+ if (rewriteHtml && type === MIME['.html']) body = Buffer.from(rewriteHtml(body.toString('utf8'), file), 'utf8');
186
+ res.writeHead(200, { 'content-type': type ?? 'application/octet-stream', 'cache-control': 'no-cache' });
187
+ res.end(body);
188
+ return true;
189
+ };
190
+ }
191
+
192
+ /**
193
+ * One SSE fan-out. add() takes a response over (headers, greeting comment,
194
+ * cleanup on close) and returns it; broadcast() sends a named event to every
195
+ * subscriber; raw() sends bytes as-is (the deck's unnamed `data: reload`
196
+ * message predates named events and stays byte-identical).
197
+ */
198
+ export function sseChannel() {
199
+ const clients = new Set();
200
+ return {
201
+ get size() { return clients.size; },
202
+ add(req, res, headers = {}) {
203
+ res.writeHead(200, { ...headers, 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
204
+ res.write(': connected\n\n');
205
+ clients.add(res);
206
+ req.on('close', () => clients.delete(res));
207
+ return res;
208
+ },
209
+ broadcast(event, data) {
210
+ for (const res of clients) res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
211
+ },
212
+ raw(chunk) {
213
+ for (const res of clients) res.write(chunk);
214
+ },
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Bind `server` to `port` on `host`. On EADDRINUSE, work out who's there
220
+ * (resolvePortConflict) — on a TTY that's an interactive choice, otherwise
221
+ * the port silently bumps — and retry until something binds. Returns the
222
+ * port actually bound (server.address().port, so :0 still reports its
223
+ * OS-assigned port).
224
+ */
225
+ export async function listenTakingOverIfNeeded(server, port, host = '127.0.0.1') {
226
+ const tty = process.stdin.isTTY && process.stdout.isTTY;
227
+ let rl;
228
+ const ask = tty ? (q) => (rl ??= createInterface({ input: process.stdin, output: process.stdout })).question(q) : undefined;
229
+ try {
230
+ for (;;) {
231
+ try {
232
+ return await new Promise((res, rej) => {
233
+ const onError = (e) => { server.off('listening', onListening); rej(e); };
234
+ const onListening = () => { server.off('error', onError); res(server.address().port); };
235
+ server.once('error', onError);
236
+ server.once('listening', onListening);
237
+ server.listen(port, host);
238
+ });
239
+ } catch (e) {
240
+ if (e.code !== 'EADDRINUSE') throw e;
241
+ port = await resolvePortConflict(port, { ask, log: console.log });
242
+ }
243
+ }
244
+ } finally {
245
+ rl?.close();
246
+ }
247
+ }
package/cli/sign.mjs ADDED
@@ -0,0 +1,216 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Sigstore signing and verification for decks (MARKETPLACE.md INTEGRITY).
6
+ *
7
+ * The premise the whole wave rests on: **a file cannot vouch for itself.** An
8
+ * attacker who can edit the payload edits any checker embedded beside it in the
9
+ * same pass, and `file://` HTML gets no OS signature UI at all. So verification
10
+ * has to come from outside the file — which is what a detached signature is.
11
+ *
12
+ * **There are no keys.** Not "the keys are managed elsewhere" — there is no key
13
+ * file anywhere in this design, ever. Sigstore keyless mints a short-lived
14
+ * certificate bound to an OIDC identity, uses it for one signature, and lets it
15
+ * expire minutes later; the transparency log is what makes the signature
16
+ * checkable after that certificate is long dead. It is the same trust root the
17
+ * npm release's provenance already uses, so this adds a use, not a posture.
18
+ *
19
+ * Where that identity comes from is worth stating exactly, because the obvious
20
+ * assumption is wrong: `sigstore@5` has **no interactive browser flow**. It
21
+ * takes the ambient OIDC token in CI (GitHub Actions with `id-token: write`,
22
+ * which is what `release.yml` already grants npm) or an identity token handed
23
+ * to it explicitly — `SIGSTORE_ID_TOKEN`, the variable cosign uses. On a
24
+ * workstation with neither, signing fails in a fraction of a second saying so.
25
+ * Describing a sign-in this client cannot perform would send someone looking
26
+ * for a browser window that is never going to open.
27
+ *
28
+ * **The sidecar is the authority.** `talk.html` is signed; `talk.html.sig`
29
+ * carries the Sigstore bundle. Nothing is embedded in the deck: a copy inside
30
+ * the payload cannot cover the payload that contains it, so it could only ever
31
+ * be a convenience — and a convenience that looks like a signature is worse
32
+ * than no signature at all.
33
+ *
34
+ * The client is an OPTIONAL dependency, loaded lazily and never at import time.
35
+ * The runtime keeps zero dependencies (CLAUDE.md) and CI installs with
36
+ * `--omit=optional`, so every path here has to behave sensibly when `sigstore`
37
+ * is simply not there — and "sensibly" means saying so, never quietly deciding
38
+ * an unverified deck is fine.
39
+ */
40
+
41
+ import { readFileSync, existsSync, writeFileSync } from 'node:fs';
42
+
43
+ /** Where a file's signature lives. Detached, adjacent, and boringly named. */
44
+ export const sidecarFor = (file) => `${file}.sig`;
45
+
46
+ /** How to get the client, said once, so every caller says it the same way. */
47
+ export const INSTALL_HINT = 'run: npm install sigstore';
48
+
49
+ /**
50
+ * The sigstore client, or null when it is not installed.
51
+ *
52
+ * Lazy on purpose: an import at module load would make `present` — which needs
53
+ * this only when a sidecar exists — pay for it on every start, and would make
54
+ * the whole CLI unloadable on an install that skipped optional dependencies.
55
+ */
56
+ export async function loadClient() {
57
+ try { return await import('sigstore'); } catch { return null; }
58
+ }
59
+
60
+ /**
61
+ * Sign bytes; return the Sigstore bundle to write as a sidecar.
62
+ *
63
+ * Throws rather than returning a failure, and the caller is expected to have
64
+ * written NOTHING yet: `bundle --sign` signs the deck it is about to write, so
65
+ * a signing failure leaves no unsigned artifact behind to be picked up later
66
+ * and mistaken for a finished one. That ordering is the whole reason this takes
67
+ * bytes instead of a path.
68
+ */
69
+ export async function signBytes(bytes, { client, token = process.env.SIGSTORE_ID_TOKEN } = {}) {
70
+ // `undefined` means "go find one"; an explicit null means "there isn't one",
71
+ // which is how a caller (and a test) says so without hiding node_modules.
72
+ const sigstore = client === undefined ? await loadClient() : client;
73
+ if (!sigstore) {
74
+ throw new Error(`signing needs the sigstore client, which is not installed — ${INSTALL_HINT}`);
75
+ }
76
+ try {
77
+ return await sigstore.sign(Buffer.from(bytes), token ? { identityToken: token } : {});
78
+ } catch (e) {
79
+ // Two different things fail here and both deserve naming. Fulcio issues the
80
+ // certificate and Rekor records the entry, so keyless signing cannot happen
81
+ // offline — and before either, something has to say who you are. Reporting
82
+ // a bare socket error or "error retrieving identity token" would leave
83
+ // someone auditing their deck for a fault that is not in it.
84
+ throw new Error(`signing failed: ${e.message}\n`
85
+ + ' Sigstore keyless needs two things: an OIDC identity to sign as — the\n'
86
+ + ' ambient token in CI (GitHub Actions needs `permissions: id-token: write`),\n'
87
+ + ' or SIGSTORE_ID_TOKEN set explicitly; this client has no browser sign-in —\n'
88
+ + ' and the network, for Fulcio to issue the certificate and Rekor to record\n'
89
+ + ' it. Nothing was written.');
90
+ }
91
+ }
92
+
93
+ /**
94
+ * The states a deck's signature can be in, and what each one means.
95
+ *
96
+ * `unsigned` is NOT a failure — most decks are unsigned, and treating "nobody
97
+ * attested to this" as an alarm would train people to ignore the one case that
98
+ * matters. `unchecked` is not a pass either: a sidecar we could not evaluate
99
+ * tells us nothing, and calling that "fine" would be the manufactured
100
+ * confidence the ingredients label refuses everywhere else. Both `tampered` and
101
+ * `unchecked` therefore mean "not verified", and callers that gate on
102
+ * verification gate on exactly that.
103
+ */
104
+ export const VERIFIED = 'verified';
105
+ export const TAMPERED = 'tampered';
106
+ export const UNCHECKED = 'unchecked';
107
+ export const UNSIGNED = 'unsigned';
108
+
109
+ /**
110
+ * Did verification actually establish who signed these bytes?
111
+ *
112
+ * Both halves are required. A result that verified but names nobody —
113
+ * "verified with unknown identity" — gates like `unchecked`: the design here
114
+ * is "print the name, the human judges it", and a nameless signer leaves
115
+ * nothing to judge. This is the single predicate every consequential decision
116
+ * routes through (`--check`'s exit code, the strict-mode degrade), so the
117
+ * tightening lives here and not at the call sites.
118
+ */
119
+ export const isVerified = (r) => r.state === VERIFIED && r.identity != null;
120
+
121
+ /**
122
+ * When the signature was recorded, read straight out of the bundle.
123
+ *
124
+ * From the transparency log entry rather than from anything self-reported: a
125
+ * timestamp a signer could choose is not evidence of when they signed.
126
+ */
127
+ function signedAt(bundle) {
128
+ const secs = bundle?.verificationMaterial?.tlogEntries?.[0]?.integratedTime;
129
+ return secs ? new Date(Number(secs) * 1000).toISOString().replace(/\.\d+Z$/, 'Z') : null;
130
+ }
131
+
132
+ /**
133
+ * Verify `bytes` against a sidecar bundle.
134
+ *
135
+ * The identity comes from what the verifier RETURNS, not from reading the
136
+ * bundle: the bundle is the attacker-supplied half of this exchange, and the
137
+ * subject printed on screen has to be the one the trust chain actually
138
+ * established, or the line is theatre.
139
+ */
140
+ export async function verifyBytes(bytes, bundle, { client } = {}) {
141
+ const sigstore = client === undefined ? await loadClient() : client;
142
+ if (!sigstore) {
143
+ return { state: UNCHECKED, reason: `the sigstore client is not installed — ${INSTALL_HINT}` };
144
+ }
145
+ try {
146
+ const signer = await sigstore.verify(bundle, Buffer.from(bytes));
147
+ return {
148
+ state: VERIFIED,
149
+ identity: signer?.identity?.subjectAlternativeName ?? null,
150
+ issuer: signer?.identity?.extensions?.issuer ?? null,
151
+ at: signedAt(bundle),
152
+ };
153
+ } catch (e) {
154
+ // A verification failure and an unreachable trust root are different facts
155
+ // and must not print the same line. The first says these bytes are not the
156
+ // bytes that were signed; the second says we could not find out.
157
+ const offline = /ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ETIMEDOUT|network|TUF/i.test(e.message ?? '');
158
+ return offline
159
+ ? { state: UNCHECKED, reason: `the trust root could not be reached (${e.message})` }
160
+ : { state: TAMPERED, reason: e.message };
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Verify a file against its sidecar, if it has one.
166
+ *
167
+ * Returns `unsigned` when there is no sidecar — the ordinary case, and not
168
+ * something to sound an alarm about.
169
+ */
170
+ export async function verifyFile(file, { client, sidecar = sidecarFor(file) } = {}) {
171
+ if (!existsSync(sidecar)) return { state: UNSIGNED, sidecar };
172
+ let bundle;
173
+ try {
174
+ bundle = JSON.parse(readFileSync(sidecar, 'utf8'));
175
+ } catch (e) {
176
+ // A sidecar that is not a bundle is a broken claim, not an absent one.
177
+ return { state: TAMPERED, sidecar, reason: `the sidecar is not a readable Sigstore bundle (${e.message})` };
178
+ }
179
+ return { ...await verifyBytes(readFileSync(file), bundle, { client }), sidecar };
180
+ }
181
+
182
+ /** Write a sidecar beside `file`. Pretty-printed — it is meant to be readable. */
183
+ export function writeSidecar(file, bundle) {
184
+ const sidecar = sidecarFor(file);
185
+ writeFileSync(sidecar, `${JSON.stringify(bundle, null, 2)}\n`);
186
+ return sidecar;
187
+ }
188
+
189
+ /**
190
+ * One line about the signature, for the terminal.
191
+ *
192
+ * Names WHO, not merely that a signature exists — "signed" on its own is the
193
+ * kind of reassurance that gets read as "safe", and an attacker can sign a deck
194
+ * too. The identity is the part a person can actually judge.
195
+ */
196
+ export function formatSignature(result, { indent = ' ' } = {}) {
197
+ switch (result.state) {
198
+ case VERIFIED:
199
+ // A signature can check out cryptographically while the certificate
200
+ // names nobody. Precision matters: the bytes did verify, the signer did
201
+ // not resolve to a name — and `isVerified` gates it as unverified,
202
+ // because a name nobody can judge is not an attestation.
203
+ if (result.identity == null) {
204
+ return `${indent}signature — verified with unknown identity: the certificate does not name`
205
+ + ` who signed these bytes${result.at ? ` (${result.at})` : ''}`;
206
+ }
207
+ return `${indent}signature — verified: signed by ${result.identity}`
208
+ + `${result.issuer ? ` via ${result.issuer}` : ''}${result.at ? `, ${result.at}` : ''}`;
209
+ case TAMPERED:
210
+ return `${indent}signature — DOES NOT VERIFY: these are not the bytes that were signed (${result.reason})`;
211
+ case UNCHECKED:
212
+ return `${indent}signature — present but NOT checked here: ${result.reason}`;
213
+ default:
214
+ return `${indent}signature — none; nothing attests to these bytes`;
215
+ }
216
+ }