@stagepass/cli 1.0.1 → 2.1.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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +216 -0
  3. package/TESTING-macos.md +58 -0
  4. package/bin/index.js +2 -76
  5. package/package.json +10 -4
  6. package/src/cli.js +320 -0
  7. package/src/commands/autostart.js +85 -0
  8. package/src/commands/certs.js +185 -0
  9. package/src/commands/daemon.js +126 -0
  10. package/src/commands/doctor.js +56 -0
  11. package/src/commands/link.js +145 -57
  12. package/src/commands/new.js +368 -0
  13. package/src/commands/npm-run.js +84 -0
  14. package/src/commands/reload.js +14 -11
  15. package/src/commands/start.js +21 -4
  16. package/src/commands/stop.js +15 -0
  17. package/src/commands/unlink.js +17 -30
  18. package/src/commands/upgrade.js +198 -0
  19. package/src/lib/autostart.js +360 -0
  20. package/src/lib/caddyfile.js +338 -0
  21. package/src/lib/cdn-snippets.js +27 -0
  22. package/src/lib/certs.js +476 -0
  23. package/src/lib/doctor.js +503 -0
  24. package/src/lib/domain.js +125 -0
  25. package/src/lib/exec.js +71 -0
  26. package/src/lib/migrate.js +96 -0
  27. package/src/lib/origins.js +160 -0
  28. package/src/lib/paths.js +132 -0
  29. package/src/lib/platform.js +47 -0
  30. package/src/lib/project-name.js +47 -0
  31. package/src/lib/projects.js +181 -0
  32. package/src/lib/remote-url.js +63 -0
  33. package/src/lib/scaffold.js +186 -0
  34. package/src/lib/snippets.js +83 -0
  35. package/src/lib/spawn.js +30 -0
  36. package/templates/project/AGENTS.md.tmpl +37 -0
  37. package/templates/project/README.md.tmpl +44 -0
  38. package/templates/project/jsconfig.json.tmpl +14 -0
  39. package/templates/project/scripts/build.mjs +110 -0
  40. package/templates/project/src/main.js.tmpl +29 -0
  41. package/templates/project/src/main.ts.tmpl +29 -0
  42. package/templates/project/src/styles.css.tmpl +8 -0
  43. package/templates/project/src/styles.scss.tmpl +8 -0
  44. package/templates/project/stagepass.json.tmpl +8 -0
  45. package/templates/project/tsconfig.json.tmpl +13 -0
  46. package/src/commands/__tests__/link.test.js +0 -113
  47. package/src/commands/__tests__/reload.test.js +0 -72
  48. package/src/commands/__tests__/unlink.test.js +0 -90
@@ -0,0 +1,476 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'node:path';
3
+ import { X509Certificate } from 'node:crypto';
4
+ import tls from 'node:tls';
5
+ import { getCaddyRootCaPath } from './paths.js';
6
+ import { defaultExec } from './exec.js';
7
+
8
+ /** Warn when the root CA expires within this many days. */
9
+ export const ROOT_EXPIRY_WARN_DAYS = 90;
10
+
11
+ export const CADDY_LOCAL_AUTHORITY_CN = 'Caddy Local Authority';
12
+
13
+ /**
14
+ * Normalize a SHA-256 fingerprint to uppercase hex without separators.
15
+ * @param {string} value
16
+ */
17
+ export function normalizeFingerprint(value) {
18
+ return String(value || '')
19
+ .replace(/[^0-9a-fA-F]/g, '')
20
+ .toUpperCase();
21
+ }
22
+
23
+ /**
24
+ * @param {string|Buffer} pem
25
+ * @returns {X509Certificate}
26
+ */
27
+ export function loadCertificate(pem) {
28
+ return new X509Certificate(pem);
29
+ }
30
+
31
+ /**
32
+ * @param {X509Certificate} cert
33
+ * @param {{ now?: Date, warnDays?: number }} [opts]
34
+ */
35
+ export function assessCertificateValidity(cert, opts = {}) {
36
+ const now = opts.now || new Date();
37
+ const warnDays = opts.warnDays ?? ROOT_EXPIRY_WARN_DAYS;
38
+ const validFrom = new Date(cert.validFrom);
39
+ const validTo = new Date(cert.validTo);
40
+
41
+ if (Number.isNaN(validFrom.getTime()) || Number.isNaN(validTo.getTime())) {
42
+ return {
43
+ status: 'fail',
44
+ reason: 'Could not parse certificate validity dates.',
45
+ validFrom,
46
+ validTo,
47
+ daysRemaining: null,
48
+ };
49
+ }
50
+
51
+ if (now < validFrom) {
52
+ return {
53
+ status: 'fail',
54
+ reason: 'Certificate is not valid yet.',
55
+ validFrom,
56
+ validTo,
57
+ daysRemaining: null,
58
+ };
59
+ }
60
+
61
+ if (now > validTo) {
62
+ return {
63
+ status: 'fail',
64
+ reason: 'Certificate has expired.',
65
+ validFrom,
66
+ validTo,
67
+ daysRemaining: 0,
68
+ };
69
+ }
70
+
71
+ const msRemaining = validTo.getTime() - now.getTime();
72
+ const daysRemaining = Math.floor(msRemaining / (24 * 60 * 60 * 1000));
73
+ if (daysRemaining < warnDays) {
74
+ return {
75
+ status: 'warn',
76
+ reason: `Certificate expires in ${daysRemaining} day(s) (below ${warnDays}-day threshold).`,
77
+ validFrom,
78
+ validTo,
79
+ daysRemaining,
80
+ };
81
+ }
82
+
83
+ return {
84
+ status: 'ok',
85
+ reason: `Valid until ${validTo.toISOString()} (${daysRemaining} day(s) remaining).`,
86
+ validFrom,
87
+ validTo,
88
+ daysRemaining,
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Check whether a peer certificate covers the expected hostname (SAN or CN).
94
+ * @param {X509Certificate} cert
95
+ * @param {string} hostname
96
+ */
97
+ export function certificateCoversHostname(cert, hostname) {
98
+ const host = String(hostname || '').toLowerCase();
99
+ if (!host) return false;
100
+
101
+ try {
102
+ if (typeof cert.checkHost === 'function') {
103
+ return Boolean(cert.checkHost(host));
104
+ }
105
+ } catch {
106
+ // fall through to manual SAN/CN check
107
+ }
108
+
109
+ const san = cert.subjectAltName || '';
110
+ const dnsNames = [...san.matchAll(/DNS:([^,\s]+)/gi)].map((m) =>
111
+ m[1].toLowerCase()
112
+ );
113
+ if (dnsNames.includes(host)) return true;
114
+
115
+ const cnMatch = /(?:^|\n)CN\s*=\s*([^\n]+)/i.exec(cert.subject || '');
116
+ if (cnMatch && cnMatch[1].trim().toLowerCase() === host) return true;
117
+
118
+ return false;
119
+ }
120
+
121
+ /**
122
+ * Parse `security find-certificate -a -Z -c ...` output into certificate records.
123
+ * @param {string} output
124
+ * @returns {{ sha256: string, sha1: string, label: string }[]}
125
+ */
126
+ export function parseSecurityFindCertificateOutput(output) {
127
+ const blocks = String(output || '').split(/(?=SHA-256 hash:)/i);
128
+ const results = [];
129
+
130
+ for (const block of blocks) {
131
+ const sha256Match = block.match(/SHA-256 hash:\s*([0-9A-Fa-f:]+)/i);
132
+ if (!sha256Match) continue;
133
+ const sha1Match = block.match(/SHA-1 hash:\s*([0-9A-Fa-f:]+)/i);
134
+ const labelMatch = block.match(/"alis"<blob>="([^"]+)"/);
135
+ results.push({
136
+ sha256: normalizeFingerprint(sha256Match[1]),
137
+ sha1: sha1Match ? normalizeFingerprint(sha1Match[1]) : '',
138
+ label: labelMatch ? labelMatch[1] : '',
139
+ });
140
+ }
141
+
142
+ return results;
143
+ }
144
+
145
+ /**
146
+ * Compare local root against System keychain trust store (report only).
147
+ * Never deletes keychain items.
148
+ *
149
+ * @param {object} opts
150
+ * @param {string} opts.rootFingerprintSha256
151
+ * @param {import('./exec.js').ExecFn} [opts.exec]
152
+ * @param {string} [opts.keychainPath]
153
+ * @param {string} [opts.searchName]
154
+ */
155
+ export async function inspectKeychainTrust(opts) {
156
+ const exec = opts.exec || defaultExec;
157
+ const keychainPath =
158
+ opts.keychainPath || '/Library/Keychains/System.keychain';
159
+ const searchName = opts.searchName || CADDY_LOCAL_AUTHORITY_CN;
160
+ const expected = normalizeFingerprint(opts.rootFingerprintSha256);
161
+
162
+ let stdout = '';
163
+ try {
164
+ const result = await exec('security', [
165
+ 'find-certificate',
166
+ '-a',
167
+ '-Z',
168
+ '-c',
169
+ searchName,
170
+ keychainPath,
171
+ ]);
172
+ stdout = result.stdout || '';
173
+ } catch (error) {
174
+ return {
175
+ trusted: false,
176
+ entries: [],
177
+ orphans: [],
178
+ error: error instanceof Error ? error.message : String(error),
179
+ };
180
+ }
181
+
182
+ const entries = parseSecurityFindCertificateOutput(stdout);
183
+ const match = entries.find((e) => e.sha256 === expected);
184
+ const orphans = entries.filter((e) => e.sha256 && e.sha256 !== expected);
185
+
186
+ return {
187
+ trusted: Boolean(match),
188
+ entries,
189
+ orphans,
190
+ error: null,
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Read and assess the on-disk Caddy local root CA.
196
+ * @param {object} [opts]
197
+ * @param {string} [opts.rootPath]
198
+ * @param {Date} [opts.now]
199
+ * @param {(p: string) => Promise<boolean>} [opts.pathExists]
200
+ * @param {(p: string, enc: string) => Promise<string>} [opts.readFile]
201
+ */
202
+ export async function checkLocalRootCa(opts = {}) {
203
+ const rootPath = opts.rootPath || getCaddyRootCaPath();
204
+ const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
205
+ const readFile = opts.readFile || ((p, enc) => fs.readFile(p, enc));
206
+
207
+ if (!(await pathExists(rootPath))) {
208
+ return {
209
+ status: 'fail',
210
+ path: rootPath,
211
+ reason: 'Caddy local root CA not found.',
212
+ cert: null,
213
+ validity: null,
214
+ fingerprint256: null,
215
+ };
216
+ }
217
+
218
+ let pem;
219
+ try {
220
+ pem = await readFile(rootPath, 'utf8');
221
+ } catch (error) {
222
+ return {
223
+ status: 'fail',
224
+ path: rootPath,
225
+ reason: `Could not read root CA: ${error instanceof Error ? error.message : String(error)}`,
226
+ cert: null,
227
+ validity: null,
228
+ fingerprint256: null,
229
+ };
230
+ }
231
+
232
+ let cert;
233
+ try {
234
+ cert = loadCertificate(pem);
235
+ } catch (error) {
236
+ return {
237
+ status: 'fail',
238
+ path: rootPath,
239
+ reason: `Invalid root CA PEM: ${error instanceof Error ? error.message : String(error)}`,
240
+ cert: null,
241
+ validity: null,
242
+ fingerprint256: null,
243
+ };
244
+ }
245
+
246
+ const validity = assessCertificateValidity(cert, { now: opts.now });
247
+ return {
248
+ status: validity.status,
249
+ path: rootPath,
250
+ reason: validity.reason,
251
+ cert,
252
+ validity,
253
+ fingerprint256: normalizeFingerprint(cert.fingerprint256),
254
+ };
255
+ }
256
+
257
+ /**
258
+ * Optional TLS handshake against 127.0.0.1:443 with SNI.
259
+ * rejectUnauthorized is false; validity dates and SAN are checked manually.
260
+ *
261
+ * @param {object} opts
262
+ * @param {string} opts.servername
263
+ * @param {string} [opts.host]
264
+ * @param {number} [opts.port]
265
+ * @param {number} [opts.timeoutMs]
266
+ * @param {Date} [opts.now]
267
+ * @param {typeof tls.connect} [opts.connect]
268
+ */
269
+ export function handshakeLocalDomain(opts) {
270
+ const host = opts.host || '127.0.0.1';
271
+ const port = opts.port ?? 443;
272
+ const timeoutMs = opts.timeoutMs ?? 2500;
273
+ const servername = opts.servername;
274
+ const connect = opts.connect || tls.connect;
275
+ const now = opts.now || new Date();
276
+
277
+ return new Promise((resolve) => {
278
+ /** @type {import('node:tls').TLSSocket | null} */
279
+ let socket = null;
280
+ let settled = false;
281
+
282
+ const finish = (result) => {
283
+ if (settled) return;
284
+ settled = true;
285
+ try {
286
+ if (socket) socket.destroy();
287
+ } catch {
288
+ // ignore
289
+ }
290
+ resolve(result);
291
+ };
292
+
293
+ try {
294
+ socket = connect(
295
+ {
296
+ host,
297
+ port,
298
+ servername,
299
+ rejectUnauthorized: false,
300
+ timeout: timeoutMs,
301
+ },
302
+ () => {
303
+ try {
304
+ const peer = socket.getPeerX509Certificate
305
+ ? socket.getPeerX509Certificate()
306
+ : null;
307
+ if (!peer) {
308
+ finish({
309
+ status: 'fail',
310
+ servername,
311
+ reason: 'No peer certificate returned.',
312
+ });
313
+ return;
314
+ }
315
+ const validity = assessCertificateValidity(peer, { now });
316
+ if (validity.status === 'fail') {
317
+ finish({
318
+ status: 'fail',
319
+ servername,
320
+ reason: validity.reason,
321
+ validity,
322
+ });
323
+ return;
324
+ }
325
+ if (!certificateCoversHostname(peer, servername)) {
326
+ finish({
327
+ status: 'fail',
328
+ servername,
329
+ reason: `Certificate SAN/CN does not cover ${servername}.`,
330
+ validity,
331
+ });
332
+ return;
333
+ }
334
+ finish({
335
+ status: validity.status === 'warn' ? 'warn' : 'ok',
336
+ servername,
337
+ reason:
338
+ validity.status === 'warn'
339
+ ? validity.reason
340
+ : `TLS OK for ${servername}.`,
341
+ validity,
342
+ });
343
+ } catch (error) {
344
+ finish({
345
+ status: 'fail',
346
+ servername,
347
+ reason: error instanceof Error ? error.message : String(error),
348
+ });
349
+ }
350
+ }
351
+ );
352
+ } catch (error) {
353
+ finish({
354
+ status: 'fail',
355
+ servername,
356
+ reason: error instanceof Error ? error.message : String(error),
357
+ });
358
+ return;
359
+ }
360
+
361
+ socket.on('error', (error) => {
362
+ finish({
363
+ status: 'fail',
364
+ servername,
365
+ reason: error instanceof Error ? error.message : String(error),
366
+ });
367
+ });
368
+
369
+ socket.on('timeout', () => {
370
+ finish({
371
+ status: 'fail',
372
+ servername,
373
+ reason: `TLS handshake timed out after ${timeoutMs}ms.`,
374
+ });
375
+ });
376
+ });
377
+ }
378
+
379
+ /**
380
+ * Full read-only certificate report for doctor / certs check.
381
+ * @param {object} [opts]
382
+ */
383
+ export async function runCertsCheck(opts = {}) {
384
+ const root = await checkLocalRootCa({
385
+ rootPath: opts.rootPath,
386
+ now: opts.now,
387
+ pathExists: opts.pathExists,
388
+ readFile: opts.readFile,
389
+ });
390
+
391
+ /** @type {object} */
392
+ const report = {
393
+ root,
394
+ trust: null,
395
+ orphans: [],
396
+ secondaryRoots: [],
397
+ handshakes: [],
398
+ };
399
+
400
+ if (root.fingerprint256) {
401
+ const trust = await inspectKeychainTrust({
402
+ rootFingerprintSha256: root.fingerprint256,
403
+ exec: opts.exec,
404
+ keychainPath: opts.keychainPath,
405
+ searchName: opts.searchName,
406
+ });
407
+ report.trust = trust;
408
+ report.orphans = trust.orphans || [];
409
+ } else {
410
+ report.trust = {
411
+ trusted: false,
412
+ entries: [],
413
+ orphans: [],
414
+ error: 'No local root fingerprint to compare.',
415
+ };
416
+ }
417
+
418
+ // Report-only: Homebrew service data dir may hold a second CA.
419
+ if (opts.brewPrefix) {
420
+ const secondary = path.join(
421
+ opts.brewPrefix,
422
+ 'var',
423
+ 'lib',
424
+ 'caddy',
425
+ 'pki',
426
+ 'authorities',
427
+ 'local',
428
+ 'root.crt'
429
+ );
430
+ const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
431
+ if (await pathExists(secondary)) {
432
+ report.secondaryRoots.push({
433
+ path: secondary,
434
+ note: 'Additional Caddy root found (Homebrew service data dir). Report only; not deleted.',
435
+ });
436
+ }
437
+ }
438
+
439
+ const domains = Array.isArray(opts.domains) ? opts.domains : [];
440
+ if (opts.skipHandshake !== true && domains.length > 0) {
441
+ for (const domain of domains) {
442
+ const result = await handshakeLocalDomain({
443
+ servername: domain,
444
+ host: opts.handshakeHost,
445
+ port: opts.handshakePort,
446
+ timeoutMs: opts.handshakeTimeoutMs,
447
+ now: opts.now,
448
+ connect: opts.connect,
449
+ });
450
+ report.handshakes.push(result);
451
+ }
452
+ }
453
+
454
+ return report;
455
+ }
456
+
457
+ /**
458
+ * Guard: this module never deletes files or keychain items.
459
+ * Exported for unit tests.
460
+ */
461
+ export const DESTRUCTIVE_CERT_OPS = Object.freeze({
462
+ deleteRoot: false,
463
+ deleteKeychainItem: false,
464
+ renewRoot: false,
465
+ });
466
+
467
+ export function assertNoDestructiveCertOps() {
468
+ if (
469
+ DESTRUCTIVE_CERT_OPS.deleteRoot ||
470
+ DESTRUCTIVE_CERT_OPS.deleteKeychainItem ||
471
+ DESTRUCTIVE_CERT_OPS.renewRoot
472
+ ) {
473
+ throw new Error('Destructive certificate operations must stay disabled.');
474
+ }
475
+ return true;
476
+ }