@stagepass/cli 2.0.0 → 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.
@@ -0,0 +1,503 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'node:path';
3
+ import { defaultExec, resolveCommand } from './exec.js';
4
+ import {
5
+ getCaddyfilePath,
6
+ getProjectsPath,
7
+ getCaddyRootCaPath,
8
+ } from './paths.js';
9
+ import { parseBlocks } from './caddyfile.js';
10
+ import { loadProjects } from './projects.js';
11
+ import { runCertsCheck } from './certs.js';
12
+ import { getAutostartStatus } from './autostart.js';
13
+ import {
14
+ CHROME_LNA_HINT,
15
+ findUnpinnedCdnSnippets,
16
+ RECOMMENDED_CDN_SNIPPETS,
17
+ } from './cdn-snippets.js';
18
+
19
+ /**
20
+ * @typedef {'ok'|'warn'|'fail'|'info'} CheckStatus
21
+ * @typedef {{ id: string, status: CheckStatus, message: string, detail?: string }} DoctorCheck
22
+ */
23
+
24
+ /**
25
+ * @param {string} id
26
+ * @param {CheckStatus} status
27
+ * @param {string} message
28
+ * @param {string} [detail]
29
+ * @returns {DoctorCheck}
30
+ */
31
+ function check(id, status, message, detail) {
32
+ return detail ? { id, status, message, detail } : { id, status, message };
33
+ }
34
+
35
+ /**
36
+ * Parse `lsof -nP -iTCP:443 -sTCP:LISTEN` output.
37
+ * @param {string} stdout
38
+ * @returns {{ command: string, pid: string, name: string }[]}
39
+ */
40
+ export function parseLsofListenOutput(stdout) {
41
+ const lines = String(stdout || '')
42
+ .split('\n')
43
+ .map((l) => l.trim())
44
+ .filter(Boolean);
45
+ const results = [];
46
+ for (const line of lines) {
47
+ if (line.startsWith('COMMAND')) continue;
48
+ const parts = line.split(/\s+/);
49
+ if (parts.length < 2) continue;
50
+ results.push({
51
+ command: parts[0],
52
+ pid: parts[1],
53
+ name: path.basename(parts[0]),
54
+ });
55
+ }
56
+ return results;
57
+ }
58
+
59
+ /**
60
+ * @param {string} content
61
+ */
62
+ export function assessResolverContent(content) {
63
+ const text = String(content || '');
64
+ if (!/nameserver\s+127\.0\.0\.1\b/m.test(text)) {
65
+ return {
66
+ status: /** @type {CheckStatus} */ ('fail'),
67
+ message: '/etc/resolver/sp exists but does not point to 127.0.0.1',
68
+ };
69
+ }
70
+ return {
71
+ status: /** @type {CheckStatus} */ ('ok'),
72
+ message: '/etc/resolver/sp points to 127.0.0.1',
73
+ };
74
+ }
75
+
76
+ /**
77
+ * Structural checks for the Stagepass Caddyfile (not a full Caddy validate).
78
+ * @param {string} content
79
+ */
80
+ export function assessCaddyfileStructure(content) {
81
+ const text = String(content || '').trim();
82
+ if (!text) {
83
+ return {
84
+ status: /** @type {CheckStatus} */ ('warn'),
85
+ message: 'Caddyfile is empty (no linked projects yet)',
86
+ };
87
+ }
88
+
89
+ const blocks = parseBlocks(text);
90
+ if (blocks.length === 0) {
91
+ return {
92
+ status: /** @type {CheckStatus} */ ('warn'),
93
+ message: 'Caddyfile present but no Stagepass START/END site blocks found',
94
+ };
95
+ }
96
+
97
+ const legacy = blocks.filter((b) => b.isLegacy);
98
+ const missingRoot = blocks.filter((b) => !b.root);
99
+ if (missingRoot.length > 0) {
100
+ return {
101
+ status: /** @type {CheckStatus} */ ('fail'),
102
+ message: `Caddyfile has ${missingRoot.length} block(s) without a parseable root path`,
103
+ detail: missingRoot.map((b) => b.domain).join(', '),
104
+ };
105
+ }
106
+
107
+ if (legacy.length > 0) {
108
+ return {
109
+ status: /** @type {CheckStatus} */ ('warn'),
110
+ message: `Caddyfile has ${legacy.length} legacy block(s); run stagepass start or reload to migrate`,
111
+ detail: legacy.map((b) => b.domain).join(', '),
112
+ };
113
+ }
114
+
115
+ return {
116
+ status: /** @type {CheckStatus} */ ('ok'),
117
+ message: `Caddyfile structure OK (${blocks.length} site block(s))`,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Run all doctor checks (read-only). Never uses sudo. Never changes anything.
123
+ *
124
+ * @param {object} [opts]
125
+ * @returns {Promise<{ checks: DoctorCheck[], summary: { ok: number, warn: number, fail: number, info: number }, exitCode: number, hints: string[] }>}
126
+ */
127
+ export async function runDoctor(opts = {}) {
128
+ const exec = opts.exec || defaultExec;
129
+ const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
130
+ const readFile = opts.readFile || ((p, enc) => fs.readFile(p, enc));
131
+ const checks = /** @type {DoctorCheck[]} */ ([]);
132
+ const hints = /** @type {string[]} */ ([]);
133
+
134
+ // Homebrew
135
+ const brewPath = await resolveCommand('brew', exec);
136
+ if (!brewPath) {
137
+ checks.push(check('homebrew', 'fail', 'Homebrew not found on PATH'));
138
+ } else {
139
+ checks.push(check('homebrew', 'ok', `Homebrew found (${brewPath})`));
140
+ }
141
+
142
+ let brewPrefix = null;
143
+ if (brewPath) {
144
+ try {
145
+ const { stdout } = await exec('brew', ['--prefix']);
146
+ brewPrefix = stdout.trim() || null;
147
+ } catch {
148
+ brewPrefix = null;
149
+ }
150
+ }
151
+
152
+ // Caddy
153
+ const caddyPath = await resolveCommand('caddy', exec);
154
+ if (!caddyPath) {
155
+ checks.push(check('caddy', 'fail', 'Caddy not found on PATH'));
156
+ } else {
157
+ checks.push(check('caddy', 'ok', `Caddy found (${caddyPath})`));
158
+ }
159
+
160
+ // PHP / php-fpm
161
+ const phpPath = await resolveCommand('php', exec);
162
+ let phpFpmPath = await resolveCommand('php-fpm', exec);
163
+ if (!phpFpmPath && brewPrefix) {
164
+ const candidate = path.join(brewPrefix, 'sbin', 'php-fpm');
165
+ if (await pathExists(candidate)) phpFpmPath = candidate;
166
+ }
167
+ if (!phpPath && !phpFpmPath) {
168
+ checks.push(check('php', 'fail', 'PHP / php-fpm not found'));
169
+ } else if (!phpFpmPath) {
170
+ checks.push(
171
+ check(
172
+ 'php',
173
+ 'warn',
174
+ `PHP found (${phpPath}) but php-fpm binary not found`,
175
+ 'Stagepass Caddy blocks use php_fastcgi 127.0.0.1:9000'
176
+ )
177
+ );
178
+ } else {
179
+ checks.push(
180
+ check(
181
+ 'php',
182
+ 'ok',
183
+ `PHP/php-fpm found (${phpFpmPath}${phpPath ? `; php=${phpPath}` : ''})`
184
+ )
185
+ );
186
+ }
187
+
188
+ // dnsmasq
189
+ let dnsmasqPath = await resolveCommand('dnsmasq', exec);
190
+ if (!dnsmasqPath && brewPrefix) {
191
+ const candidate = path.join(brewPrefix, 'sbin', 'dnsmasq');
192
+ if (await pathExists(candidate)) dnsmasqPath = candidate;
193
+ }
194
+ if (!dnsmasqPath) {
195
+ checks.push(check('dnsmasq', 'fail', 'dnsmasq not found'));
196
+ } else {
197
+ checks.push(check('dnsmasq', 'ok', `dnsmasq found (${dnsmasqPath})`));
198
+ }
199
+
200
+ // /etc/resolver/sp
201
+ const resolverPath = opts.resolverPath || '/etc/resolver/sp';
202
+ if (!(await pathExists(resolverPath))) {
203
+ checks.push(
204
+ check(
205
+ 'resolver',
206
+ 'fail',
207
+ `${resolverPath} missing`,
208
+ 'Run stagepass setup to create the .sp resolver'
209
+ )
210
+ );
211
+ } else {
212
+ try {
213
+ const content = await readFile(resolverPath, 'utf8');
214
+ const assessed = assessResolverContent(content);
215
+ checks.push(check('resolver', assessed.status, assessed.message));
216
+ } catch (error) {
217
+ checks.push(
218
+ check(
219
+ 'resolver',
220
+ 'fail',
221
+ `Could not read ${resolverPath}`,
222
+ error instanceof Error ? error.message : String(error)
223
+ )
224
+ );
225
+ }
226
+ }
227
+
228
+ // Port 443 listener (no sudo)
229
+ try {
230
+ const { stdout } = await exec('lsof', [
231
+ '-nP',
232
+ '-iTCP:443',
233
+ '-sTCP:LISTEN',
234
+ ]);
235
+ const listeners = parseLsofListenOutput(stdout);
236
+ if (listeners.length === 0) {
237
+ checks.push(
238
+ check('port443', 'warn', 'Nothing listening on TCP 443', 'Run stagepass start')
239
+ );
240
+ } else {
241
+ const summary = listeners
242
+ .map((l) => `${l.command}(pid ${l.pid})`)
243
+ .join(', ');
244
+ const hasCaddy = listeners.some((l) =>
245
+ /caddy/i.test(l.command) || /caddy/i.test(l.name)
246
+ );
247
+ checks.push(
248
+ check(
249
+ 'port443',
250
+ hasCaddy ? 'ok' : 'warn',
251
+ hasCaddy
252
+ ? `Port 443 listener: ${summary}`
253
+ : `Port 443 occupied (no caddy seen): ${summary}`
254
+ )
255
+ );
256
+ }
257
+ } catch (error) {
258
+ const err = /** @type {{ code?: string|number, message?: string }} */ (error);
259
+ const msg = err.message || String(error);
260
+ if (
261
+ err.code === 'EPERM' ||
262
+ err.code === 'EACCES' ||
263
+ /permission denied/i.test(msg)
264
+ ) {
265
+ checks.push(
266
+ check(
267
+ 'port443',
268
+ 'warn',
269
+ 'Could not inspect port 443 (permission denied)',
270
+ 'Doctor never uses sudo; try manually: lsof -nP -iTCP:443 -sTCP:LISTEN'
271
+ )
272
+ );
273
+ } else if (err.code === 1 || err.code === '1') {
274
+ // lsof exits 1 when no matches
275
+ checks.push(
276
+ check('port443', 'warn', 'Nothing listening on TCP 443', 'Run stagepass start')
277
+ );
278
+ } else {
279
+ checks.push(check('port443', 'warn', `Could not inspect port 443: ${msg}`));
280
+ }
281
+ }
282
+
283
+ // Caddyfile
284
+ const caddyfilePath = opts.caddyfilePath || getCaddyfilePath();
285
+ if (!(await pathExists(caddyfilePath))) {
286
+ checks.push(
287
+ check(
288
+ 'caddyfile',
289
+ 'fail',
290
+ `Stagepass Caddyfile missing (${caddyfilePath})`,
291
+ 'Run stagepass setup / link'
292
+ )
293
+ );
294
+ } else {
295
+ try {
296
+ const content = await readFile(caddyfilePath, 'utf8');
297
+ const assessed = assessCaddyfileStructure(content);
298
+ checks.push(
299
+ check('caddyfile', assessed.status, assessed.message, assessed.detail)
300
+ );
301
+ } catch (error) {
302
+ checks.push(
303
+ check(
304
+ 'caddyfile',
305
+ 'fail',
306
+ 'Could not read Caddyfile',
307
+ error instanceof Error ? error.message : String(error)
308
+ )
309
+ );
310
+ }
311
+ }
312
+
313
+ // Linked projects whose folders no longer exist
314
+ const projectsPath = opts.projectsPath || getProjectsPath();
315
+ try {
316
+ const doc = await loadProjects(projectsPath);
317
+ const domains = Object.keys(doc.projects || {});
318
+ const missing = [];
319
+ for (const domain of domains) {
320
+ const root = doc.projects[domain]?.root;
321
+ if (!root || !(await pathExists(root))) {
322
+ missing.push(`${domain} -> ${root || '(no root)'}`);
323
+ }
324
+ }
325
+ if (domains.length === 0) {
326
+ checks.push(check('projects', 'warn', 'No linked projects in projects.json'));
327
+ } else if (missing.length > 0) {
328
+ checks.push(
329
+ check(
330
+ 'projects',
331
+ 'fail',
332
+ `${missing.length} linked project folder(s) missing`,
333
+ missing.join('; ')
334
+ )
335
+ );
336
+ } else {
337
+ checks.push(
338
+ check('projects', 'ok', `${domains.length} linked project(s) exist on disk`)
339
+ );
340
+ }
341
+ } catch (error) {
342
+ checks.push(
343
+ check(
344
+ 'projects',
345
+ 'warn',
346
+ 'Could not read projects.json',
347
+ error instanceof Error ? error.message : String(error)
348
+ )
349
+ );
350
+ }
351
+
352
+ // Certificates (check only)
353
+ const projectsDoc = await loadProjects(projectsPath);
354
+ const linkedDomains = Object.keys(projectsDoc.projects || {});
355
+ const certReport = await runCertsCheck({
356
+ exec,
357
+ rootPath: opts.rootCaPath || getCaddyRootCaPath(),
358
+ brewPrefix,
359
+ domains: opts.skipHandshake ? [] : linkedDomains,
360
+ skipHandshake: opts.skipHandshake === true,
361
+ now: opts.now,
362
+ pathExists,
363
+ readFile,
364
+ connect: opts.connect,
365
+ handshakeTimeoutMs: opts.handshakeTimeoutMs,
366
+ });
367
+
368
+ if (certReport.root.status === 'fail') {
369
+ checks.push(
370
+ check('certs.root', 'fail', certReport.root.reason, certReport.root.path)
371
+ );
372
+ } else if (certReport.root.status === 'warn') {
373
+ checks.push(
374
+ check('certs.root', 'warn', certReport.root.reason, certReport.root.path)
375
+ );
376
+ } else {
377
+ checks.push(
378
+ check('certs.root', 'ok', certReport.root.reason, certReport.root.path)
379
+ );
380
+ }
381
+
382
+ if (!certReport.trust?.trusted) {
383
+ checks.push(
384
+ check(
385
+ 'certs.trust',
386
+ 'fail',
387
+ 'Caddy local root is not trusted in the System keychain',
388
+ certReport.trust?.error || 'Run: stagepass certs trust'
389
+ )
390
+ );
391
+ } else {
392
+ checks.push(
393
+ check('certs.trust', 'ok', 'Caddy local root is trusted in the System keychain')
394
+ );
395
+ }
396
+
397
+ if (certReport.orphans?.length > 0) {
398
+ const detail = certReport.orphans
399
+ .map((o) => `SHA-1=${o.sha1 || 'unknown'} SHA-256=${o.sha256}`)
400
+ .join('; ');
401
+ checks.push(
402
+ check(
403
+ 'certs.orphans',
404
+ 'warn',
405
+ `${certReport.orphans.length} orphaned Caddy root(s) in keychain (report only; not deleted)`,
406
+ detail
407
+ )
408
+ );
409
+ } else {
410
+ checks.push(check('certs.orphans', 'ok', 'No orphaned Caddy roots in keychain'));
411
+ }
412
+
413
+ for (const secondary of certReport.secondaryRoots || []) {
414
+ checks.push(check('certs.secondary', 'warn', secondary.note, secondary.path));
415
+ }
416
+
417
+ for (const hs of certReport.handshakes || []) {
418
+ checks.push(
419
+ check(
420
+ `certs.tls.${hs.servername}`,
421
+ hs.status,
422
+ hs.reason || `TLS check for ${hs.servername}`
423
+ )
424
+ );
425
+ }
426
+
427
+ // LaunchAgent
428
+ const autostart = await getAutostartStatus({
429
+ exec,
430
+ pathExists,
431
+ uid: opts.uid,
432
+ plistPath: opts.plistPath,
433
+ });
434
+ if (!autostart.plistExists && !autostart.loaded) {
435
+ checks.push(
436
+ check(
437
+ 'autostart',
438
+ 'warn',
439
+ 'LaunchAgent not installed',
440
+ 'Optional: stagepass autostart on'
441
+ )
442
+ );
443
+ } else if (autostart.plistExists && !autostart.loaded) {
444
+ checks.push(
445
+ check(
446
+ 'autostart',
447
+ 'warn',
448
+ `LaunchAgent plist present but not loaded (${autostart.label})`,
449
+ autostart.plistPath
450
+ )
451
+ );
452
+ } else {
453
+ checks.push(
454
+ check(
455
+ 'autostart',
456
+ 'ok',
457
+ `LaunchAgent loaded (${autostart.label})`,
458
+ autostart.plistPath
459
+ )
460
+ );
461
+ }
462
+
463
+ // CDN snippets (Stagepass-recommended; do not scan user sites)
464
+ const snippets = opts.cdnSnippets || RECOMMENDED_CDN_SNIPPETS;
465
+ const unpinned = findUnpinnedCdnSnippets(snippets);
466
+ if (!unpinned.ok) {
467
+ checks.push(
468
+ check(
469
+ 'cdn',
470
+ 'warn',
471
+ 'Recommended CDN snippets include @latest (prefer major pin @2)',
472
+ unpinned.offenders.join(', ')
473
+ )
474
+ );
475
+ } else {
476
+ checks.push(
477
+ check(
478
+ 'cdn',
479
+ 'ok',
480
+ 'Recommended CDN snippets use a pinned major (@2), not @latest'
481
+ )
482
+ );
483
+ }
484
+
485
+ hints.push(CHROME_LNA_HINT);
486
+
487
+ const summary = { ok: 0, warn: 0, fail: 0, info: 0 };
488
+ for (const c of checks) {
489
+ if (c.status === 'ok') summary.ok += 1;
490
+ else if (c.status === 'warn') summary.warn += 1;
491
+ else if (c.status === 'fail') summary.fail += 1;
492
+ else summary.info += 1;
493
+ }
494
+
495
+ return {
496
+ checks,
497
+ summary,
498
+ exitCode: summary.fail > 0 ? 1 : 0,
499
+ hints,
500
+ certReport,
501
+ autostart,
502
+ };
503
+ }
@@ -0,0 +1,71 @@
1
+ import { execFile as nodeExecFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ const execFileAsync = promisify(nodeExecFile);
5
+
6
+ /**
7
+ * @typedef {object} ExecResult
8
+ * @property {string} stdout
9
+ * @property {string} stderr
10
+ * @property {number|null} [code]
11
+ */
12
+
13
+ /**
14
+ * @typedef {(file: string, args?: string[], options?: object) => Promise<ExecResult>} ExecFn
15
+ */
16
+
17
+ /**
18
+ * Default execFile wrapper. Always uses argument arrays (never a shell string).
19
+ * @type {ExecFn}
20
+ */
21
+ export async function defaultExec(file, args = [], options = {}) {
22
+ const inheritStdio = options.stdio === 'inherit';
23
+ // Always force shell:false after spreading options so callers cannot enable a shell.
24
+ const opts = inheritStdio
25
+ ? { ...options, shell: false }
26
+ : {
27
+ encoding: 'utf8',
28
+ maxBuffer: 4 * 1024 * 1024,
29
+ ...options,
30
+ shell: false,
31
+ };
32
+ try {
33
+ const result = await execFileAsync(file, args, opts);
34
+ return {
35
+ stdout: result?.stdout != null ? String(result.stdout) : '',
36
+ stderr: result?.stderr != null ? String(result.stderr) : '',
37
+ code: 0,
38
+ };
39
+ } catch (error) {
40
+ const err = /** @type {NodeJS.ErrnoException & { stdout?: string, stderr?: string, code?: number|string }} */ (
41
+ error
42
+ );
43
+ const wrapped = new Error(err.message || String(error));
44
+ Object.assign(wrapped, {
45
+ code: err.code,
46
+ errno: err.errno,
47
+ stdout: err.stdout != null ? String(err.stdout) : '',
48
+ stderr: err.stderr != null ? String(err.stderr) : '',
49
+ killed: /** @type {{ killed?: boolean }} */ (err).killed,
50
+ signal: /** @type {{ signal?: string }} */ (err).signal,
51
+ });
52
+ throw wrapped;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Resolve which executable exists via `command -v` style lookup without a shell.
58
+ * Uses `which` on PATH via execFile.
59
+ * @param {string} name
60
+ * @param {ExecFn} [exec]
61
+ * @returns {Promise<string|null>}
62
+ */
63
+ export async function resolveCommand(name, exec = defaultExec) {
64
+ try {
65
+ const { stdout } = await exec('/usr/bin/env', ['which', name]);
66
+ const path = stdout.trim().split('\n')[0];
67
+ return path || null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
package/src/lib/paths.js CHANGED
@@ -18,6 +18,64 @@ export function getServerLogPath() {
18
18
  return path.join(getStagepassDir(), 'server.log');
19
19
  }
20
20
 
21
+ /** Daemon / autostart log directory (~/.stagepass/logs). */
22
+ export function getLogsDir() {
23
+ return path.join(getStagepassDir(), 'logs');
24
+ }
25
+
26
+ export function getDaemonStdoutLogPath() {
27
+ return path.join(getLogsDir(), 'daemon.stdout.log');
28
+ }
29
+
30
+ export function getDaemonStderrLogPath() {
31
+ return path.join(getLogsDir(), 'daemon.stderr.log');
32
+ }
33
+
34
+ /** LaunchAgent label (owned GitHub-io reverse DNS; not a third-party domain). */
35
+ export const LAUNCH_AGENT_LABEL = 'io.github.arobertherz.stagepass';
36
+
37
+ export function getLaunchAgentsDir() {
38
+ return path.join(os.homedir(), 'Library', 'LaunchAgents');
39
+ }
40
+
41
+ export function getLaunchAgentPlistPath() {
42
+ return path.join(getLaunchAgentsDir(), `${LAUNCH_AGENT_LABEL}.plist`);
43
+ }
44
+
45
+ /**
46
+ * Caddy default data directory on macOS (user instance).
47
+ * Honours XDG_DATA_HOME when set (same rules as Caddy itself).
48
+ * @param {{ home?: string, env?: NodeJS.ProcessEnv }} [opts]
49
+ */
50
+ export function getCaddyDataDir(opts = {}) {
51
+ const env = opts.env || process.env;
52
+ const home = opts.home || os.homedir();
53
+ if (env.XDG_DATA_HOME) {
54
+ return path.join(env.XDG_DATA_HOME, 'caddy');
55
+ }
56
+ return path.join(home, 'Library', 'Application Support', 'Caddy');
57
+ }
58
+
59
+ /**
60
+ * Path to Caddy's local root CA certificate.
61
+ * @param {{ home?: string, env?: NodeJS.ProcessEnv, dataDir?: string }} [opts]
62
+ */
63
+ export function getCaddyRootCaPath(opts = {}) {
64
+ const dataDir = opts.dataDir || getCaddyDataDir(opts);
65
+ return path.join(dataDir, 'pki', 'authorities', 'local', 'root.crt');
66
+ }
67
+
68
+ /**
69
+ * Common secondary data dir when Homebrew's Caddy service sets XDG_DATA_HOME.
70
+ * Report-only helper for doctor/certs (never delete).
71
+ * @param {{ brewPrefix?: string|null }} [opts]
72
+ */
73
+ export function getBrewCaddyDataDir(opts = {}) {
74
+ const prefix = opts.brewPrefix;
75
+ if (!prefix) return null;
76
+ return path.join(prefix, 'var', 'lib', 'caddy');
77
+ }
78
+
21
79
  /** System / dangerous roots that must never be linked as site roots. */
22
80
  export const FORBIDDEN_ROOTS = Object.freeze([
23
81
  '/',
@@ -0,0 +1,47 @@
1
+ /** Env var that skips the macOS-only guard (tests/CI only). */
2
+ export const SKIP_PLATFORM_CHECK_ENV = 'STAGEPASS_SKIP_PLATFORM_CHECK';
3
+
4
+ /**
5
+ * @param {string} [platform=process.platform]
6
+ * @returns {boolean}
7
+ */
8
+ export function isMacOS(platform = process.platform) {
9
+ return platform === 'darwin';
10
+ }
11
+
12
+ /**
13
+ * Build the user-facing unsupported-platform message.
14
+ * @param {string} platform
15
+ * @returns {string}
16
+ */
17
+ export function unsupportedPlatformMessage(platform) {
18
+ return `Stagepass CLI supports macOS only (detected: ${platform}).`;
19
+ }
20
+
21
+ /**
22
+ * Exit with a clear error when running system commands off macOS.
23
+ * No-op when `STAGEPASS_SKIP_PLATFORM_CHECK=1` (tests/CI only) or on darwin.
24
+ *
25
+ * @param {object} [options]
26
+ * @param {string} [options.platform]
27
+ * @param {NodeJS.ProcessEnv} [options.env]
28
+ * @param {(code: number) => void} [options.exit]
29
+ * @param {(msg: string) => void} [options.write]
30
+ */
31
+ export function assertSupportedPlatform(options = {}) {
32
+ const platform = options.platform ?? process.platform;
33
+ const env = options.env ?? process.env;
34
+ const exit = options.exit ?? ((code) => process.exit(code));
35
+ const write = options.write ?? ((msg) => console.error(msg));
36
+
37
+ if (env[SKIP_PLATFORM_CHECK_ENV] === '1') {
38
+ return;
39
+ }
40
+
41
+ if (isMacOS(platform)) {
42
+ return;
43
+ }
44
+
45
+ write(unsupportedPlatformMessage(platform));
46
+ exit(1);
47
+ }