@stagepass/cli 2.2.6 → 2.3.0-beta.1
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.
- package/README.md +61 -13
- package/TESTING-macos.md +35 -8
- package/bin/index.js +4 -1
- package/package.json +9 -8
- package/src/cli.js +62 -7
- package/src/commands/certs.js +375 -19
- package/src/commands/daemon.js +75 -7
- package/src/commands/dev.js +419 -0
- package/src/commands/link.js +66 -25
- package/src/commands/new.js +397 -41
- package/src/commands/npm-run.js +8 -0
- package/src/commands/reload.js +2 -2
- package/src/commands/setup.js +5 -5
- package/src/commands/start.js +386 -83
- package/src/commands/stop.js +50 -31
- package/src/commands/unlink.js +8 -6
- package/src/commands/upgrade.js +51 -12
- package/src/lib/apply-site-block.js +48 -0
- package/src/lib/autostart.js +300 -3
- package/src/lib/caddyfile.js +72 -13
- package/src/lib/cdn-snippets.js +145 -3
- package/src/lib/certs.js +334 -47
- package/src/lib/dev-port.js +45 -0
- package/src/lib/doctor-site.js +61 -5
- package/src/lib/doctor.js +48 -4
- package/src/lib/ensure-running.js +89 -0
- package/src/lib/exec.js +72 -24
- package/src/lib/live-server.js +484 -0
- package/src/lib/node-engine.js +55 -0
- package/src/lib/notify.js +62 -0
- package/src/lib/origins.js +27 -5
- package/src/lib/package-versions.js +9 -0
- package/src/lib/paths.js +18 -0
- package/src/lib/php-fpm.js +33 -0
- package/src/lib/project-sync.js +165 -20
- package/src/lib/projects.js +137 -7
- package/src/lib/prompts.js +19 -0
- package/src/lib/registry.js +27 -6
- package/src/lib/scaffold.js +288 -11
- package/src/lib/site-detect.js +78 -25
- package/src/lib/snippets.js +14 -11
- package/src/lib/spinner.js +60 -0
- package/src/lib/versions.js +20 -8
- package/templates/project/AGENTS.md.tmpl +4 -3
- package/templates/project/README.md.tmpl +35 -6
- package/templates/project/api/README.md.tmpl +7 -0
- package/templates/project/examples/php/README.md.tmpl +18 -0
- package/templates/project/examples/php/form.php +105 -0
- package/templates/project/examples/php/proxy.php +171 -0
- package/templates/project/scripts/build.mjs +200 -37
package/src/lib/cdn-snippets.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
1
4
|
/**
|
|
2
5
|
* Canonical CDN embed snippets recommended by Stagepass docs.
|
|
3
6
|
* Doctor checks these so generated / documented snippets never drift to @latest.
|
|
4
|
-
* Do not scan user sites.
|
|
5
7
|
*/
|
|
6
8
|
export const RECOMMENDED_CDN_SNIPPETS = Object.freeze([
|
|
7
9
|
'https://cdn.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js',
|
|
@@ -11,14 +13,154 @@ export const RECOMMENDED_CDN_SNIPPETS = Object.freeze([
|
|
|
11
13
|
'https://cdn.jsdelivr.net/npm/@stagepass/modules@2/dist/all.min.js',
|
|
12
14
|
]);
|
|
13
15
|
|
|
14
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Unpinned / legacy CDN pins for @stagepass/loader and @stagepass/modules:
|
|
18
|
+
* - `@latest`
|
|
19
|
+
* - bare major `@1` (not `@1.2.0` exact pins)
|
|
20
|
+
* - package URL with no `@version` at all
|
|
21
|
+
*
|
|
22
|
+
* Matches jsDelivr and unpkg-style paths.
|
|
23
|
+
*/
|
|
24
|
+
export const UNPINNED_CDN_RE =
|
|
25
|
+
/(?:cdn\.jsdelivr\.net\/npm|unpkg\.com)\/@stagepass\/(?:loader|modules)(?:@latest|@1(?![0-9.])|(?!@))(?=[/"'?\s]|$)/gi;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Test whether a single URL/snippet string is an unpinned Stagepass CDN reference.
|
|
29
|
+
* @param {string} snippet
|
|
30
|
+
* @returns {boolean}
|
|
31
|
+
*/
|
|
32
|
+
export function isUnpinnedCdnSnippet(snippet) {
|
|
33
|
+
const text = String(snippet || '');
|
|
34
|
+
UNPINNED_CDN_RE.lastIndex = 0;
|
|
35
|
+
return UNPINNED_CDN_RE.test(text);
|
|
36
|
+
}
|
|
15
37
|
|
|
16
38
|
/**
|
|
17
39
|
* @param {string[]} [snippets]
|
|
18
40
|
* @returns {{ ok: boolean, offenders: string[] }}
|
|
19
41
|
*/
|
|
20
42
|
export function findUnpinnedCdnSnippets(snippets = RECOMMENDED_CDN_SNIPPETS) {
|
|
21
|
-
const offenders = snippets.filter((s) =>
|
|
43
|
+
const offenders = snippets.filter((s) => isUnpinnedCdnSnippet(s));
|
|
44
|
+
return { ok: offenders.length === 0, offenders };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Extract offending substring matches from free-form file content.
|
|
49
|
+
* @param {string} content
|
|
50
|
+
* @returns {string[]}
|
|
51
|
+
*/
|
|
52
|
+
export function findUnpinnedCdnMatchesInText(content) {
|
|
53
|
+
const text = String(content || '');
|
|
54
|
+
const candidateRe =
|
|
55
|
+
/(?:https?:\/\/)?(?:cdn\.jsdelivr\.net\/npm|unpkg\.com)\/@stagepass\/(?:loader|modules)[^"'<\s]*/gi;
|
|
56
|
+
const matches = text.match(candidateRe);
|
|
57
|
+
if (!matches) return [];
|
|
58
|
+
const seen = new Set();
|
|
59
|
+
const out = [];
|
|
60
|
+
for (const m of matches) {
|
|
61
|
+
if (!isUnpinnedCdnSnippet(m)) continue;
|
|
62
|
+
if (seen.has(m)) continue;
|
|
63
|
+
seen.add(m);
|
|
64
|
+
out.push(m);
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Default project files that may contain Webflow / CDN snippets. */
|
|
70
|
+
export const PROJECT_CDN_SCAN_FILES = Object.freeze([
|
|
71
|
+
'README.md',
|
|
72
|
+
'stagepass.json',
|
|
73
|
+
'webflow-head.html',
|
|
74
|
+
'webflow-footer.html',
|
|
75
|
+
'snippets.html',
|
|
76
|
+
'stagepass-snippets.html',
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
/** Skip HTML / allowlisted files larger than this when scanning for unpinned CDN URLs. */
|
|
80
|
+
export const PROJECT_CDN_SCAN_MAX_BYTES = 1024 * 1024;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Non-recursive `*.html` in project root and `snippets/` (regular files only).
|
|
84
|
+
* @param {string} cwd
|
|
85
|
+
* @param {typeof fs} [fse]
|
|
86
|
+
* @returns {Promise<string[]>}
|
|
87
|
+
*/
|
|
88
|
+
export async function listProjectHtmlCdnScanFiles(cwd, fse = fs) {
|
|
89
|
+
/** @type {string[]} */
|
|
90
|
+
const out = [];
|
|
91
|
+
for (const dirRel of ['', 'snippets']) {
|
|
92
|
+
const dir = dirRel ? path.join(cwd, dirRel) : cwd;
|
|
93
|
+
let names;
|
|
94
|
+
try {
|
|
95
|
+
names = await fse.readdir(dir);
|
|
96
|
+
} catch {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
for (const name of names) {
|
|
100
|
+
if (!name.endsWith('.html')) continue;
|
|
101
|
+
const rel = dirRel ? path.join(dirRel, name) : name;
|
|
102
|
+
const full = path.join(cwd, rel);
|
|
103
|
+
try {
|
|
104
|
+
const st = await fse.lstat(full);
|
|
105
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > PROJECT_CDN_SCAN_MAX_BYTES) continue;
|
|
106
|
+
out.push(rel);
|
|
107
|
+
} catch {
|
|
108
|
+
/* skip */
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Read-only scan of the current project's snippet-bearing files for unpinned CDN URLs.
|
|
117
|
+
* Scans allowlisted files plus `*.html` in the project root and `snippets/`
|
|
118
|
+
* (non-recursive; regular files ≤ 1 MB; symlinks skipped).
|
|
119
|
+
*
|
|
120
|
+
* @param {object} [opts]
|
|
121
|
+
* @param {string} [opts.cwd]
|
|
122
|
+
* @param {string[]} [opts.files]
|
|
123
|
+
* @param {boolean} [opts.skipHtmlDiscover]
|
|
124
|
+
* @param {typeof fs} [opts.fs]
|
|
125
|
+
* @param {(p: string) => Promise<boolean>} [opts.pathExists]
|
|
126
|
+
* @param {(p: string, enc: string) => Promise<string>} [opts.readFile]
|
|
127
|
+
* @returns {Promise<{ ok: boolean, offenders: { file: string, match: string }[] }>}
|
|
128
|
+
*/
|
|
129
|
+
export async function scanProjectUnpinnedCdn(opts = {}) {
|
|
130
|
+
const cwd = opts.cwd || process.cwd();
|
|
131
|
+
const fse = opts.fs || fs;
|
|
132
|
+
const fixed = opts.files || PROJECT_CDN_SCAN_FILES;
|
|
133
|
+
const html =
|
|
134
|
+
opts.skipHtmlDiscover === true ? [] : await listProjectHtmlCdnScanFiles(cwd, fse);
|
|
135
|
+
const files = [...new Set([...fixed, ...html])];
|
|
136
|
+
const pathExists = opts.pathExists || ((p) => fse.pathExists(p));
|
|
137
|
+
const readFile = opts.readFile || ((p, enc) => fse.readFile(p, enc));
|
|
138
|
+
/** @type {{ file: string, match: string }[]} */
|
|
139
|
+
const offenders = [];
|
|
140
|
+
|
|
141
|
+
for (const rel of files) {
|
|
142
|
+
if (typeof rel !== 'string' || rel.includes('..') || path.isAbsolute(rel)) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const full = path.join(cwd, rel);
|
|
146
|
+
if (!(await pathExists(full))) continue;
|
|
147
|
+
try {
|
|
148
|
+
const st = await fse.lstat(full);
|
|
149
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > PROJECT_CDN_SCAN_MAX_BYTES) continue;
|
|
150
|
+
} catch {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
let content = '';
|
|
154
|
+
try {
|
|
155
|
+
content = await readFile(full, 'utf8');
|
|
156
|
+
} catch {
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
for (const match of findUnpinnedCdnMatchesInText(content)) {
|
|
160
|
+
offenders.push({ file: rel, match });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
22
164
|
return { ok: offenders.length === 0, offenders };
|
|
23
165
|
}
|
|
24
166
|
|
package/src/lib/certs.js
CHANGED
|
@@ -2,8 +2,13 @@ import fs from 'fs-extra';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { X509Certificate } from 'node:crypto';
|
|
4
4
|
import tls from 'node:tls';
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
getCaddyRootCaPath,
|
|
7
|
+
getCaddyCertificatesLocalDir,
|
|
8
|
+
getCaddyPkiAuthoritiesLocalDir,
|
|
9
|
+
} from './paths.js';
|
|
6
10
|
import { defaultExec } from './exec.js';
|
|
11
|
+
import { validateDomain } from './domain.js';
|
|
7
12
|
|
|
8
13
|
/** Warn when the root CA expires within this many days. */
|
|
9
14
|
export const ROOT_EXPIRY_WARN_DAYS = 90;
|
|
@@ -142,16 +147,7 @@ export function parseSecurityFindCertificateOutput(output) {
|
|
|
142
147
|
return results;
|
|
143
148
|
}
|
|
144
149
|
|
|
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
|
-
*/
|
|
150
|
+
/** Compare local root fingerprint to System keychain (report only). */
|
|
155
151
|
export async function inspectKeychainTrust(opts) {
|
|
156
152
|
const exec = opts.exec || defaultExec;
|
|
157
153
|
const keychainPath =
|
|
@@ -191,14 +187,7 @@ export async function inspectKeychainTrust(opts) {
|
|
|
191
187
|
};
|
|
192
188
|
}
|
|
193
189
|
|
|
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
|
-
*/
|
|
190
|
+
/** Assess on-disk Caddy local root CA. */
|
|
202
191
|
export async function checkLocalRootCa(opts = {}) {
|
|
203
192
|
const rootPath = opts.rootPath || getCaddyRootCaPath();
|
|
204
193
|
const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
|
|
@@ -254,16 +243,31 @@ export async function checkLocalRootCa(opts = {}) {
|
|
|
254
243
|
};
|
|
255
244
|
}
|
|
256
245
|
|
|
246
|
+
/** True when lsof shows caddy on TCP 443. */
|
|
247
|
+
export async function isCaddyServing443(opts = {}) {
|
|
248
|
+
const exec = opts.exec || defaultExec;
|
|
249
|
+
try {
|
|
250
|
+
const { stdout } = await exec('lsof', ['-nP', '-iTCP:443', '-sTCP:LISTEN']);
|
|
251
|
+
return String(stdout || '').split('\n').some((line) => {
|
|
252
|
+
const cmd = line.trim().split(/\s+/)[0] || '';
|
|
253
|
+
return cmd && cmd !== 'COMMAND' && /caddy/i.test(cmd);
|
|
254
|
+
});
|
|
255
|
+
} catch {
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** @param {object} opts */
|
|
261
|
+
async function resolveCaddyServing443(opts) {
|
|
262
|
+
return typeof opts.caddyServing443 === 'boolean'
|
|
263
|
+
? opts.caddyServing443
|
|
264
|
+
: isCaddyServing443({ exec: opts.exec });
|
|
265
|
+
}
|
|
266
|
+
|
|
257
267
|
/**
|
|
258
|
-
*
|
|
259
|
-
* rejectUnauthorized is false; validity dates and SAN are checked manually.
|
|
260
|
-
*
|
|
268
|
+
* TLS handshake to 127.0.0.1:443 with SNI (rejectUnauthorized false).
|
|
261
269
|
* @param {object} opts
|
|
262
270
|
* @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
271
|
* @param {typeof tls.connect} [opts.connect]
|
|
268
272
|
*/
|
|
269
273
|
export function handshakeLocalDomain(opts) {
|
|
@@ -312,7 +316,7 @@ export function handshakeLocalDomain(opts) {
|
|
|
312
316
|
});
|
|
313
317
|
return;
|
|
314
318
|
}
|
|
315
|
-
const validity = assessCertificateValidity(peer, { now });
|
|
319
|
+
const validity = assessCertificateValidity(peer, { now, warnDays: 0 });
|
|
316
320
|
if (validity.status === 'fail') {
|
|
317
321
|
finish({
|
|
318
322
|
status: 'fail',
|
|
@@ -376,10 +380,7 @@ export function handshakeLocalDomain(opts) {
|
|
|
376
380
|
});
|
|
377
381
|
}
|
|
378
382
|
|
|
379
|
-
/**
|
|
380
|
-
* Full read-only certificate report for doctor / certs check.
|
|
381
|
-
* @param {object} [opts]
|
|
382
|
-
*/
|
|
383
|
+
/** Read-only cert report for doctor / certs check / start. */
|
|
383
384
|
export async function runCertsCheck(opts = {}) {
|
|
384
385
|
const root = await checkLocalRootCa({
|
|
385
386
|
rootPath: opts.rootPath,
|
|
@@ -416,6 +417,7 @@ export async function runCertsCheck(opts = {}) {
|
|
|
416
417
|
}
|
|
417
418
|
|
|
418
419
|
// Report-only: Homebrew service data dir may hold a second CA.
|
|
420
|
+
// Exclude its fingerprint from orphans so --remove-orphans never deletes a still-valid brew root.
|
|
419
421
|
if (opts.brewPrefix) {
|
|
420
422
|
const secondary = path.join(
|
|
421
423
|
opts.brewPrefix,
|
|
@@ -428,49 +430,334 @@ export async function runCertsCheck(opts = {}) {
|
|
|
428
430
|
'root.crt'
|
|
429
431
|
);
|
|
430
432
|
const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
|
|
433
|
+
const readFile = opts.readFile || ((p, enc) => fs.readFile(p, enc));
|
|
431
434
|
if (await pathExists(secondary)) {
|
|
435
|
+
let fingerprint256 = null;
|
|
436
|
+
try {
|
|
437
|
+
const pem = await readFile(secondary, 'utf8');
|
|
438
|
+
const cert = loadCertificate(pem);
|
|
439
|
+
fingerprint256 = normalizeFingerprint(cert.fingerprint256);
|
|
440
|
+
} catch {
|
|
441
|
+
// Still report the path; exclusion only when the fingerprint is readable.
|
|
442
|
+
}
|
|
432
443
|
report.secondaryRoots.push({
|
|
433
444
|
path: secondary,
|
|
445
|
+
fingerprint256,
|
|
434
446
|
note: 'Additional Caddy root found (Homebrew service data dir). Report only; not deleted.',
|
|
435
447
|
});
|
|
448
|
+
if (fingerprint256) {
|
|
449
|
+
const filterOrphans = (list) =>
|
|
450
|
+
(list || []).filter((o) => o.sha256 !== fingerprint256);
|
|
451
|
+
report.orphans = filterOrphans(report.orphans);
|
|
452
|
+
if (report.trust) {
|
|
453
|
+
report.trust.orphans = filterOrphans(report.trust.orphans);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
436
456
|
}
|
|
437
457
|
}
|
|
438
458
|
|
|
439
459
|
const domains = Array.isArray(opts.domains) ? opts.domains : [];
|
|
440
460
|
if (opts.skipHandshake !== true && domains.length > 0) {
|
|
441
|
-
|
|
442
|
-
const
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
461
|
+
if (!(await resolveCaddyServing443(opts))) {
|
|
462
|
+
for (const domain of domains) {
|
|
463
|
+
report.handshakes.push({
|
|
464
|
+
status: 'skip',
|
|
465
|
+
servername: domain,
|
|
466
|
+
reason: 'Caddy is not serving :443; TLS not checkable.',
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
} else {
|
|
470
|
+
for (const domain of domains) {
|
|
471
|
+
report.handshakes.push(
|
|
472
|
+
await handshakeLocalDomain({
|
|
473
|
+
servername: domain,
|
|
474
|
+
host: opts.handshakeHost,
|
|
475
|
+
port: opts.handshakePort,
|
|
476
|
+
timeoutMs: opts.handshakeTimeoutMs,
|
|
477
|
+
now: opts.now,
|
|
478
|
+
connect: opts.connect,
|
|
479
|
+
})
|
|
480
|
+
);
|
|
481
|
+
}
|
|
451
482
|
}
|
|
452
483
|
}
|
|
453
484
|
|
|
454
485
|
return report;
|
|
455
486
|
}
|
|
456
487
|
|
|
457
|
-
/**
|
|
458
|
-
* Guard: this module never deletes files or keychain items.
|
|
459
|
-
* Exported for unit tests.
|
|
460
|
-
*/
|
|
488
|
+
/** Gated renew ops only; permanent root/CN deletes stay off. */
|
|
461
489
|
export const DESTRUCTIVE_CERT_OPS = Object.freeze({
|
|
462
490
|
deleteRoot: false,
|
|
491
|
+
deleteKeychainItemByCn: false,
|
|
492
|
+
/** @deprecated same as deleteKeychainItemByCn */
|
|
463
493
|
deleteKeychainItem: false,
|
|
494
|
+
/** @deprecated use renewRootMoveBackup */
|
|
464
495
|
renewRoot: false,
|
|
496
|
+
renewRootMoveBackup: true,
|
|
497
|
+
renewSiteCertDir: true,
|
|
498
|
+
deleteKeychainItemBySha1: true,
|
|
465
499
|
});
|
|
466
500
|
|
|
467
|
-
|
|
501
|
+
/** @returns {true} */
|
|
502
|
+
export function assertReadOnlyCertOps() {
|
|
468
503
|
if (
|
|
469
504
|
DESTRUCTIVE_CERT_OPS.deleteRoot ||
|
|
505
|
+
DESTRUCTIVE_CERT_OPS.deleteKeychainItemByCn ||
|
|
470
506
|
DESTRUCTIVE_CERT_OPS.deleteKeychainItem ||
|
|
471
507
|
DESTRUCTIVE_CERT_OPS.renewRoot
|
|
472
508
|
) {
|
|
473
|
-
throw new Error(
|
|
509
|
+
throw new Error(
|
|
510
|
+
'Permanent root delete and CN-wildcard keychain delete must stay disabled.'
|
|
511
|
+
);
|
|
474
512
|
}
|
|
475
513
|
return true;
|
|
476
514
|
}
|
|
515
|
+
|
|
516
|
+
/** @deprecated use assertReadOnlyCertOps */
|
|
517
|
+
export function assertNoDestructiveCertOps() {
|
|
518
|
+
return assertReadOnlyCertOps();
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* @param {'renewRootMoveBackup'|'renewSiteCertDir'|'deleteKeychainItemBySha1'} op
|
|
523
|
+
*/
|
|
524
|
+
export function assertDestructiveCertOpAllowed(op) {
|
|
525
|
+
if (!DESTRUCTIVE_CERT_OPS[op]) {
|
|
526
|
+
throw new Error(`Destructive certificate operation is disabled: ${op}`);
|
|
527
|
+
}
|
|
528
|
+
return true;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** SHA-1 fingerprint: 40 hex chars, uppercase, no separators. */
|
|
532
|
+
export function normalizeSha1Fingerprint(value) {
|
|
533
|
+
const sha1 = normalizeFingerprint(value);
|
|
534
|
+
if (!/^[0-9A-F]{40}$/.test(sha1)) {
|
|
535
|
+
return {
|
|
536
|
+
ok: false,
|
|
537
|
+
error: 'SHA-1 fingerprint must be exactly 40 hex characters.',
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
return { ok: true, sha1 };
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** Argv for `security delete-certificate -Z` (never by CN). */
|
|
544
|
+
export function buildSecurityDeleteCertificateArgs(
|
|
545
|
+
sha1,
|
|
546
|
+
keychainPath = '/Library/Keychains/System.keychain'
|
|
547
|
+
) {
|
|
548
|
+
const normalized = normalizeSha1Fingerprint(sha1);
|
|
549
|
+
if (!normalized.ok) return normalized;
|
|
550
|
+
if (typeof keychainPath !== 'string' || !keychainPath.trim()) {
|
|
551
|
+
return { ok: false, error: 'Keychain path is required.' };
|
|
552
|
+
}
|
|
553
|
+
return {
|
|
554
|
+
ok: true,
|
|
555
|
+
args: ['delete-certificate', '-Z', normalized.sha1, keychainPath],
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** Linked `.sp` site cert dir under certificates/local (no traversal/symlinks). */
|
|
560
|
+
export async function resolveSafeSiteCertDir(opts) {
|
|
561
|
+
assertDestructiveCertOpAllowed('renewSiteCertDir');
|
|
562
|
+
|
|
563
|
+
const validated = validateDomain(opts.domain);
|
|
564
|
+
if (!validated.ok) {
|
|
565
|
+
return { ok: false, error: validated.error };
|
|
566
|
+
}
|
|
567
|
+
const domain = validated.domain;
|
|
568
|
+
const linked = new Set(
|
|
569
|
+
[...(opts.linkedDomains || [])].map((d) => String(d).toLowerCase())
|
|
570
|
+
);
|
|
571
|
+
if (!linked.has(domain)) {
|
|
572
|
+
return {
|
|
573
|
+
ok: false,
|
|
574
|
+
error: `Domain ${domain} is not a linked Stagepass project.`,
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
const base = path.resolve(
|
|
579
|
+
opts.certificatesLocalDir || getCaddyCertificatesLocalDir()
|
|
580
|
+
);
|
|
581
|
+
const candidate = path.resolve(base, domain);
|
|
582
|
+
|
|
583
|
+
if (!candidate.startsWith(`${base}${path.sep}`)) {
|
|
584
|
+
return { ok: false, error: 'Resolved certificate path escapes the local store.' };
|
|
585
|
+
}
|
|
586
|
+
if (candidate.includes('..')) {
|
|
587
|
+
return { ok: false, error: 'Certificate path must not contain .. segments.' };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
|
|
591
|
+
if (!(await pathExists(candidate))) {
|
|
592
|
+
return { ok: false, error: `Certificate directory does not exist: ${candidate}` };
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const lstat = opts.lstat || ((p) => fs.lstat(p));
|
|
596
|
+
let stats;
|
|
597
|
+
try {
|
|
598
|
+
stats = await lstat(candidate);
|
|
599
|
+
} catch (error) {
|
|
600
|
+
return {
|
|
601
|
+
ok: false,
|
|
602
|
+
error: `Could not lstat certificate directory: ${
|
|
603
|
+
error instanceof Error ? error.message : String(error)
|
|
604
|
+
}`,
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (stats.isSymbolicLink()) {
|
|
609
|
+
return { ok: false, error: 'Refusing to touch a symlinked certificate path.' };
|
|
610
|
+
}
|
|
611
|
+
if (!stats.isDirectory()) {
|
|
612
|
+
return { ok: false, error: 'Certificate path is not a directory.' };
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
return { ok: true, dir: candidate };
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Delete failing site cert dirs then reload Caddy (or defer if Caddy is down).
|
|
620
|
+
* @param {object} opts
|
|
621
|
+
*/
|
|
622
|
+
export async function renewSiteCertificates(opts) {
|
|
623
|
+
assertDestructiveCertOpAllowed('renewSiteCertDir');
|
|
624
|
+
const exec = opts.exec || defaultExec;
|
|
625
|
+
const remove = opts.remove || ((p) => fs.remove(p));
|
|
626
|
+
const domains = Array.isArray(opts.domains) ? opts.domains : [];
|
|
627
|
+
/** @type {{ domain: string, dir: string }[]} */
|
|
628
|
+
const deleted = [];
|
|
629
|
+
/** @type {{ domain: string, error: string }[]} */
|
|
630
|
+
const errors = [];
|
|
631
|
+
|
|
632
|
+
for (const domain of domains) {
|
|
633
|
+
const resolved = await resolveSafeSiteCertDir({
|
|
634
|
+
domain,
|
|
635
|
+
linkedDomains: opts.linkedDomains,
|
|
636
|
+
certificatesLocalDir: opts.certificatesLocalDir,
|
|
637
|
+
lstat: opts.lstat,
|
|
638
|
+
pathExists: opts.pathExists,
|
|
639
|
+
});
|
|
640
|
+
if (!resolved.ok) {
|
|
641
|
+
errors.push({ domain: String(domain), error: resolved.error });
|
|
642
|
+
continue;
|
|
643
|
+
}
|
|
644
|
+
const normalized = validateDomain(domain);
|
|
645
|
+
const domainLabel = normalized.ok ? normalized.domain : String(domain);
|
|
646
|
+
try {
|
|
647
|
+
await remove(resolved.dir);
|
|
648
|
+
deleted.push({ domain: domainLabel, dir: resolved.dir });
|
|
649
|
+
} catch (error) {
|
|
650
|
+
errors.push({
|
|
651
|
+
domain: domainLabel,
|
|
652
|
+
error: error instanceof Error ? error.message : String(error),
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
let reloaded = false;
|
|
658
|
+
let reloadError = null;
|
|
659
|
+
let reloadDeferred = false;
|
|
660
|
+
if (deleted.length > 0) {
|
|
661
|
+
if (!(await resolveCaddyServing443({ ...opts, exec }))) {
|
|
662
|
+
reloadDeferred = true;
|
|
663
|
+
} else {
|
|
664
|
+
try {
|
|
665
|
+
const reloadArgs = ['reload'];
|
|
666
|
+
if (opts.caddyfilePath) {
|
|
667
|
+
reloadArgs.push('--config', opts.caddyfilePath);
|
|
668
|
+
}
|
|
669
|
+
await exec('caddy', reloadArgs);
|
|
670
|
+
reloaded = true;
|
|
671
|
+
} catch (error) {
|
|
672
|
+
reloadError = error instanceof Error ? error.message : String(error);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
return { deleted, errors, reloaded, reloadError, reloadDeferred };
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** Move local CA authority folder to a timestamped backup (never delete). */
|
|
681
|
+
export async function moveLocalCaAuthorityToBackup(opts = {}) {
|
|
682
|
+
assertDestructiveCertOpAllowed('renewRootMoveBackup');
|
|
683
|
+
|
|
684
|
+
const authorityDir = path.resolve(
|
|
685
|
+
opts.authorityDir || getCaddyPkiAuthoritiesLocalDir()
|
|
686
|
+
);
|
|
687
|
+
const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
|
|
688
|
+
if (!(await pathExists(authorityDir))) {
|
|
689
|
+
return {
|
|
690
|
+
ok: false,
|
|
691
|
+
error: `CA authority directory not found: ${authorityDir}`,
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
const lstat = opts.lstat || ((p) => fs.lstat(p));
|
|
696
|
+
try {
|
|
697
|
+
const stats = await lstat(authorityDir);
|
|
698
|
+
if (stats.isSymbolicLink()) {
|
|
699
|
+
return { ok: false, error: 'Refusing to move a symlinked CA authority path.' };
|
|
700
|
+
}
|
|
701
|
+
if (!stats.isDirectory()) {
|
|
702
|
+
return { ok: false, error: 'CA authority path is not a directory.' };
|
|
703
|
+
}
|
|
704
|
+
} catch (error) {
|
|
705
|
+
return {
|
|
706
|
+
ok: false,
|
|
707
|
+
error: `Could not lstat CA authority path: ${
|
|
708
|
+
error instanceof Error ? error.message : String(error)
|
|
709
|
+
}`,
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const now = opts.now || new Date();
|
|
714
|
+
const stamp = now
|
|
715
|
+
.toISOString()
|
|
716
|
+
.replace(/[:.]/g, '-')
|
|
717
|
+
.replace(/Z$/, 'Z');
|
|
718
|
+
const backupDir = `${authorityDir}.backup.${stamp}`;
|
|
719
|
+
if (await pathExists(backupDir)) {
|
|
720
|
+
return { ok: false, error: `Backup path already exists: ${backupDir}` };
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
const move = opts.move || ((src, dest) => fs.move(src, dest));
|
|
724
|
+
try {
|
|
725
|
+
await move(authorityDir, backupDir);
|
|
726
|
+
} catch (error) {
|
|
727
|
+
return {
|
|
728
|
+
ok: false,
|
|
729
|
+
error: error instanceof Error ? error.message : String(error),
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
return { ok: true, authorityDir, backupDir };
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** Delete one orphaned keychain cert by SHA-1. */
|
|
737
|
+
export async function deleteKeychainCertificateBySha1(opts) {
|
|
738
|
+
assertDestructiveCertOpAllowed('deleteKeychainItemBySha1');
|
|
739
|
+
const built = buildSecurityDeleteCertificateArgs(
|
|
740
|
+
opts.sha1,
|
|
741
|
+
opts.keychainPath
|
|
742
|
+
);
|
|
743
|
+
if (!built.ok) return built;
|
|
744
|
+
|
|
745
|
+
const exec = opts.exec || defaultExec;
|
|
746
|
+
try {
|
|
747
|
+
await exec('security', built.args);
|
|
748
|
+
return { ok: true, args: built.args };
|
|
749
|
+
} catch (error) {
|
|
750
|
+
return {
|
|
751
|
+
ok: false,
|
|
752
|
+
error: error instanceof Error ? error.message : String(error),
|
|
753
|
+
args: built.args,
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/** Server names with handshake status fail (ignores skip/ok/warn). */
|
|
759
|
+
export function domainsNeedingSiteCertRenewal(handshakes = []) {
|
|
760
|
+
return handshakes
|
|
761
|
+
.filter((hs) => hs && hs.status === 'fail' && hs.servername)
|
|
762
|
+
.map((hs) => hs.servername);
|
|
763
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validate and normalize the Stagepass live-reload event-server port.
|
|
3
|
+
* Only integers in 1024..65535 may be written into a Caddyfile.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @param {unknown} port
|
|
8
|
+
* @returns {port is number}
|
|
9
|
+
*/
|
|
10
|
+
export function isValidDevPort(port) {
|
|
11
|
+
return (
|
|
12
|
+
typeof port === 'number' &&
|
|
13
|
+
Number.isInteger(port) &&
|
|
14
|
+
port >= 1024 &&
|
|
15
|
+
port <= 65535
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Coerce a stored/unknown value to a valid port, or null.
|
|
21
|
+
* @param {unknown} value
|
|
22
|
+
* @returns {number|null}
|
|
23
|
+
*/
|
|
24
|
+
export function normalizeDevPort(value) {
|
|
25
|
+
if (typeof value === 'string' && /^\d+$/.test(value)) {
|
|
26
|
+
value = Number(value);
|
|
27
|
+
}
|
|
28
|
+
return isValidDevPort(value) ? value : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Whether a PID looks alive (best-effort; signal 0).
|
|
33
|
+
* @param {unknown} pid
|
|
34
|
+
* @returns {boolean}
|
|
35
|
+
*/
|
|
36
|
+
export function isPidAlive(pid) {
|
|
37
|
+
const n = typeof pid === 'string' && /^\d+$/.test(pid) ? Number(pid) : pid;
|
|
38
|
+
if (typeof n !== 'number' || !Number.isInteger(n) || n <= 0) return false;
|
|
39
|
+
try {
|
|
40
|
+
process.kill(n, 0);
|
|
41
|
+
return true;
|
|
42
|
+
} catch {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
}
|