@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,338 @@
1
+ import { escapeRegExp } from './domain.js';
2
+ import { escapeCaddyQuotedString, validateRoot } from './paths.js';
3
+ import { buildOriginAllowlistRegex, validateOriginList } from './origins.js';
4
+
5
+ /** Marker written inside every Stagepass-managed site block. */
6
+ export const BLOCK_VERSION = 'v2';
7
+
8
+ /**
9
+ * Sensitive path / extension blocking (always on).
10
+ * Hidden segments: any path component starting with "." (.git, .env, .DS_Store, …).
11
+ * Also: node_modules trees and private key / cert / db / log file extensions.
12
+ */
13
+ export const BLOCKED_PATH_REGEXP =
14
+ '(?i)((^|/)\\.|((^|/)node_modules(/|$))|\\.(pem|key|p12|pfx|crt|cer|sqlite|db|log)$)';
15
+
16
+ export const SENSITIVE_BLOCK_DOCS = Object.freeze({
17
+ hiddenSegments: 'Any URL path segment starting with "." (e.g. /.git, /.env, /.npmrc)',
18
+ directories: ['node_modules'],
19
+ extensions: ['.pem', '.key', '.p12', '.pfx', '.crt', '.cer', '.sqlite', '.db', '.log'],
20
+ });
21
+
22
+ /**
23
+ * @typedef {object} SiteBlockOptions
24
+ * @property {boolean} [allowAllOrigins]
25
+ * @property {string[]} [origins]
26
+ */
27
+
28
+ /**
29
+ * @param {string} domain - normalized foo.sp
30
+ * @param {string} root - absolute project path
31
+ * @param {SiteBlockOptions} [options]
32
+ * @returns {string} full block including START/END markers
33
+ */
34
+ export function renderSiteBlock(domain, root, options = {}) {
35
+ const rootResult = validateRoot(root);
36
+ if (!rootResult.ok) {
37
+ throw new Error(rootResult.error);
38
+ }
39
+
40
+ const allowAllOrigins = options.allowAllOrigins === true;
41
+ const originsResult = validateOriginList(options.origins || []);
42
+ if (!originsResult.ok) {
43
+ throw new Error(originsResult.error);
44
+ }
45
+ const origins = originsResult.origins;
46
+
47
+ const quotedRoot = `"${escapeCaddyQuotedString(rootResult.path)}"`;
48
+ const optionsComment = formatOptionsComment({ allowAllOrigins, origins });
49
+
50
+ const lines = [
51
+ `# START: ${domain}`,
52
+ `# stagepass-block: ${BLOCK_VERSION}`,
53
+ optionsComment,
54
+ `${domain} {`,
55
+ // tls must stay at site level (not inside handle) — Caddy rejects it as an HTTP handler
56
+ ' tls internal',
57
+ '',
58
+ ` @blocked path_regexp blocked ${BLOCKED_PATH_REGEXP}`,
59
+ ' handle @blocked {',
60
+ ' respond 404',
61
+ ' }',
62
+ '',
63
+ ];
64
+
65
+ if (allowAllOrigins) {
66
+ lines.push(...allowAllCorsLines());
67
+ } else {
68
+ lines.push(...allowlistCorsLines(origins));
69
+ }
70
+
71
+ lines.push(
72
+ '',
73
+ ' handle {',
74
+ ` root * ${quotedRoot}`,
75
+ ' php_fastcgi 127.0.0.1:9000',
76
+ ' file_server'
77
+ );
78
+
79
+ if (allowAllOrigins) {
80
+ lines.push(' header Access-Control-Allow-Origin *');
81
+ } else {
82
+ lines.push(
83
+ ' header @cors_origin Access-Control-Allow-Origin "{http.request.header.Origin}"',
84
+ ' header @cors_origin Vary Origin'
85
+ );
86
+ }
87
+
88
+ lines.push(' }', '}', `# END: ${domain}`);
89
+
90
+ return lines.join('\n');
91
+ }
92
+
93
+ function formatOptionsComment({ allowAllOrigins, origins }) {
94
+ const parts = [`allowAllOrigins=${allowAllOrigins ? 'true' : 'false'}`];
95
+ if (origins.length > 0) {
96
+ parts.push(`origins=${origins.join(',')}`);
97
+ }
98
+ return `# stagepass-options: ${parts.join(' ')}`;
99
+ }
100
+
101
+ function allowAllCorsLines() {
102
+ return [
103
+ ' @options method OPTIONS',
104
+ ' handle @options {',
105
+ ' header Access-Control-Allow-Origin *',
106
+ ' header Access-Control-Allow-Methods "GET, HEAD, POST, OPTIONS"',
107
+ ' header Access-Control-Allow-Headers "{http.request.header.Access-Control-Request-Headers}"',
108
+ ' header Access-Control-Max-Age 86400',
109
+ ' header Access-Control-Allow-Private-Network true',
110
+ ' respond 204',
111
+ ' }',
112
+ ];
113
+ }
114
+
115
+ function allowlistCorsLines(origins) {
116
+ const originRe = buildOriginAllowlistRegex(origins);
117
+ return [
118
+ ` @cors_origin header_regexp Origin ${originRe}`,
119
+ ' @cors_preflight {',
120
+ ' method OPTIONS',
121
+ ` header_regexp Origin ${originRe}`,
122
+ ' }',
123
+ ' handle @cors_preflight {',
124
+ ' header Access-Control-Allow-Origin "{http.request.header.Origin}"',
125
+ ' header Vary Origin',
126
+ ' header Access-Control-Allow-Methods "GET, HEAD, POST, OPTIONS"',
127
+ ' header Access-Control-Allow-Headers "{http.request.header.Access-Control-Request-Headers}"',
128
+ ' header Access-Control-Max-Age 86400',
129
+ ' header Access-Control-Allow-Private-Network true',
130
+ ' respond 204',
131
+ ' }',
132
+ ' @options method OPTIONS',
133
+ ' handle @options {',
134
+ ' respond 204',
135
+ ' }',
136
+ ];
137
+ }
138
+
139
+ /**
140
+ * Parse Stagepass START/END blocks from a Caddyfile.
141
+ * @param {string} content
142
+ */
143
+ export function parseBlocks(content) {
144
+ const re = /# START: ([^\n]+)\n([\s\S]*?)# END: \1/g;
145
+ const blocks = [];
146
+ let match;
147
+ while ((match = re.exec(content)) !== null) {
148
+ const domain = match[1].trim();
149
+ const inner = match[2];
150
+ const full = match[0];
151
+ const isLegacy = !/# stagepass-block:\s*v\d+/m.test(full);
152
+ const options = parseOptionsFromBlock(full);
153
+ const root = extractRootFromBlock(inner);
154
+ blocks.push({
155
+ domain,
156
+ full,
157
+ inner,
158
+ isLegacy,
159
+ options,
160
+ root,
161
+ index: match.index,
162
+ length: full.length,
163
+ });
164
+ }
165
+ return blocks;
166
+ }
167
+
168
+ /**
169
+ * @param {string} blockText
170
+ */
171
+ export function parseOptionsFromBlock(blockText) {
172
+ const defaults = { allowAllOrigins: false, origins: [] };
173
+ const line = blockText.match(/^# stagepass-options:\s*(.+)$/m);
174
+ if (!line) {
175
+ if (!/# stagepass-block:/m.test(blockText)) {
176
+ return { allowAllOrigins: true, origins: [] };
177
+ }
178
+ return defaults;
179
+ }
180
+
181
+ const text = line[1];
182
+ const allowMatch = text.match(/allowAllOrigins=(true|false)/);
183
+ const allowAllOrigins = allowMatch ? allowMatch[1] === 'true' : false;
184
+ const originsMatch = text.match(/origins=([^\s]+)/);
185
+ let origins = [];
186
+ if (originsMatch) {
187
+ const list = validateOriginList(originsMatch[1].split(',').filter(Boolean));
188
+ origins = list.ok ? list.origins : [];
189
+ }
190
+ return { allowAllOrigins, origins };
191
+ }
192
+
193
+ /**
194
+ * Extract root path from `root * "..."` inside a site block body.
195
+ * @param {string} inner
196
+ * @returns {string|null}
197
+ */
198
+ export function extractRootFromBlock(inner) {
199
+ const m = inner.match(/root\s+\*\s+"((?:\\.|[^"\\])*)"/);
200
+ if (!m) return null;
201
+ return m[1].replace(/\\"/g, '"').replace(/\\\\/g, '\\');
202
+ }
203
+
204
+ /**
205
+ * Replace or append a site block for domain. Preserves foreign content.
206
+ * @param {string} content
207
+ * @param {string} domain
208
+ * @param {string} newBlock
209
+ */
210
+ export function upsertBlock(content, domain, newBlock) {
211
+ const start = `# START: ${domain}`;
212
+ const end = `# END: ${domain}`;
213
+ const regex = new RegExp(
214
+ `${escapeRegExp(start)}[\\s\\S]*?${escapeRegExp(end)}`,
215
+ 'g'
216
+ );
217
+ const trimmed = newBlock.trim();
218
+ if (regex.test(content)) {
219
+ return content.replace(regex, trimmed);
220
+ }
221
+ const base = content.trim();
222
+ return base ? `${base}\n\n${trimmed}\n` : `${trimmed}\n`;
223
+ }
224
+
225
+ /**
226
+ * Remove a site block for domain.
227
+ * @param {string} content
228
+ * @param {string} domain
229
+ */
230
+ export function removeBlock(content, domain) {
231
+ const start = `# START: ${domain}`;
232
+ const end = `# END: ${domain}`;
233
+ const regex = new RegExp(
234
+ `${escapeRegExp(start)}[\\s\\S]*?${escapeRegExp(end)}`,
235
+ 'g'
236
+ );
237
+ if (!regex.test(content)) {
238
+ return { content, removed: false };
239
+ }
240
+ let next = content.replace(regex, '').trim();
241
+ next = next.replace(/\n{3,}/g, '\n\n');
242
+ return { content: next, removed: true };
243
+ }
244
+
245
+ /**
246
+ * Migrate legacy (pre-v2) Stagepass blocks to the current renderer.
247
+ *
248
+ * Legacy blocks get allowAllOrigins=true so existing Webflow embedding keeps working.
249
+ *
250
+ * @param {string} content
251
+ * @param {object} [opts]
252
+ * @param {(msg: string) => void} [opts.warn]
253
+ */
254
+ export function migrateLegacyContent(content, opts = {}) {
255
+ const warn = opts.warn || (() => {});
256
+ const blocks = parseBlocks(content);
257
+ const legacy = blocks.filter((b) => b.isLegacy);
258
+
259
+ if (legacy.length === 0) {
260
+ return { content, changed: false, migrated: [], skipped: [], warnings: [] };
261
+ }
262
+
263
+ let next = content;
264
+ const migrated = [];
265
+ const skipped = [];
266
+ const warnings = [];
267
+
268
+ const ordered = [...legacy].sort((a, b) => b.index - a.index);
269
+
270
+ for (const block of ordered) {
271
+ if (!block.root) {
272
+ const reason = 'could not parse root path';
273
+ skipped.push({ domain: block.domain, reason });
274
+ const msg = `Left legacy block ${block.domain} unchanged (${reason}).`;
275
+ warnings.push(msg);
276
+ warn(msg);
277
+ continue;
278
+ }
279
+
280
+ const rootCheck = validateRoot(block.root);
281
+ if (!rootCheck.ok) {
282
+ const reason = rootCheck.error;
283
+ skipped.push({ domain: block.domain, reason });
284
+ const msg = `Left legacy block ${block.domain} unchanged (${reason}).`;
285
+ warnings.push(msg);
286
+ warn(msg);
287
+ continue;
288
+ }
289
+
290
+ let newBlock;
291
+ try {
292
+ newBlock = renderSiteBlock(block.domain, rootCheck.path, {
293
+ allowAllOrigins: true,
294
+ origins: [],
295
+ });
296
+ } catch (e) {
297
+ const reason = e.message || String(e);
298
+ skipped.push({ domain: block.domain, reason });
299
+ const msg = `Left legacy block ${block.domain} unchanged (${reason}).`;
300
+ warnings.push(msg);
301
+ warn(msg);
302
+ continue;
303
+ }
304
+
305
+ next =
306
+ next.slice(0, block.index) +
307
+ newBlock.trim() +
308
+ next.slice(block.index + block.length);
309
+ migrated.push({ domain: block.domain, root: rootCheck.path });
310
+ }
311
+
312
+ next = next.replace(/\n{3,}/g, '\n\n');
313
+ if (next.trim()) {
314
+ next = `${next.trim()}\n`;
315
+ } else {
316
+ next = '';
317
+ }
318
+
319
+ return {
320
+ content: next,
321
+ changed: migrated.length > 0,
322
+ migrated,
323
+ skipped,
324
+ warnings,
325
+ };
326
+ }
327
+
328
+ /**
329
+ * Format a timestamp for Caddyfile.bak-YYYYMMDD-HHMMSS
330
+ * @param {Date} [date]
331
+ */
332
+ export function formatBackupStamp(date = new Date()) {
333
+ const pad = (n) => String(n).padStart(2, '0');
334
+ return (
335
+ `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}` +
336
+ `-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`
337
+ );
338
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Canonical CDN embed snippets recommended by Stagepass docs.
3
+ * Doctor checks these so generated / documented snippets never drift to @latest.
4
+ * Do not scan user sites.
5
+ */
6
+ export const RECOMMENDED_CDN_SNIPPETS = Object.freeze([
7
+ 'https://cdn.jsdelivr.net/npm/@stagepass/loader@2/dist/loader.min.js',
8
+ 'https://cdn.jsdelivr.net/npm/@stagepass/modules@2/dist/inject.min.js',
9
+ 'https://cdn.jsdelivr.net/npm/@stagepass/modules@2/dist/cookies.min.js',
10
+ 'https://cdn.jsdelivr.net/npm/@stagepass/modules@2/dist/maintenance.min.js',
11
+ 'https://cdn.jsdelivr.net/npm/@stagepass/modules@2/dist/all.min.js',
12
+ ]);
13
+
14
+ const UNPINNED_RE = /@(?:latest)(?=[/"'?]|$)/i;
15
+
16
+ /**
17
+ * @param {string[]} [snippets]
18
+ * @returns {{ ok: boolean, offenders: string[] }}
19
+ */
20
+ export function findUnpinnedCdnSnippets(snippets = RECOMMENDED_CDN_SNIPPETS) {
21
+ const offenders = snippets.filter((s) => UNPINNED_RE.test(s));
22
+ return { ok: offenders.length === 0, offenders };
23
+ }
24
+
25
+ /** Chrome Local Network Access hint (public HTTPS → loopback). */
26
+ export const CHROME_LNA_HINT =
27
+ 'Chrome may block public HTTPS pages from reaching local .sp hosts until Local Network Access is allowed for the site (site settings → Local network access).';