@stagepass/cli 1.0.0 → 2.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Robert Herz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,169 @@
1
+ # `@stagepass/cli`
2
+
3
+ Local development orchestrator for Webflow projects.
4
+
5
+ The CLI sets up and manages the local Stagepass infrastructure (`.sp` domains, Caddy, DNS, PHP) so your live Webflow site can load local assets through the Stagepass loader.
6
+
7
+ ## Install
8
+
9
+ Requires Node.js **18+** (`engines.node`: `>=18.0.0`) on **macOS** with Homebrew.
10
+
11
+ ```bash
12
+ npm install -g @stagepass/cli@2.0.0
13
+ ```
14
+
15
+ Or without a global install:
16
+
17
+ ```bash
18
+ npx @stagepass/cli@2.0.0 setup
19
+ ```
20
+
21
+ ## Requirements
22
+
23
+ - macOS
24
+ - Node.js 18+
25
+ - Homebrew
26
+
27
+ ## Quick Start
28
+
29
+ Recommended order:
30
+
31
+ ```bash
32
+ stagepass setup
33
+ stagepass start
34
+
35
+ # inside your project folder
36
+ stagepass link my-project --origin www.example.com --origin my-project.webflow.io
37
+ ```
38
+
39
+ Your project is then available at `https://my-project.sp`. Success output:
40
+
41
+ ```text
42
+ Linked: https://my-project.sp -> /absolute/path/to/project
43
+ ```
44
+
45
+ ## Commands
46
+
47
+ | Command | Description |
48
+ | :--- | :--- |
49
+ | `stagepass setup` | Install Caddy, PHP, Dnsmasq via Homebrew and configure the local `.sp` resolver (`address=/.sp/127.0.0.1` + `/etc/resolver/sp`). |
50
+ | `stagepass start` | Start background Caddy & PHP services. Migrates legacy Caddyfile blocks if needed. |
51
+ | `stagepass link [domain]` | Link the current directory to a `.sp` domain, write/update the Caddyfile + `~/.stagepass/projects.json`, reload Caddy. |
52
+ | `stagepass unlink [domain]` | Remove the site block and `projects.json` entry, reload Caddy. |
53
+ | `stagepass reload` | Reload Caddy configuration. Migrates legacy Caddyfile blocks if needed. |
54
+ | `stagepass stop` | Stop background services. |
55
+
56
+ All commands support `-v, --verbose`.
57
+
58
+ ### Domain argument (`link` / `unlink`)
59
+
60
+ - Optional. When omitted, defaults to the **current folder name**.
61
+ - Values are lowercased; accidental `https://` and trailing `/` are stripped.
62
+ - The `.sp` suffix is **always** applied (pass `my-project` or `my-project.sp`).
63
+ - Labels must be DNS-safe (`[a-z0-9]`, inner hyphens). When derived from a folder and invalid, the CLI slugifies and prints a dim notice.
64
+ - Explicit invalid domains are rejected (nothing is written).
65
+
66
+ ### `link` options
67
+
68
+ | Option | Behaviour |
69
+ | :--- | :--- |
70
+ | `--origin <host>` | Allow CORS from this live hostname (**repeatable**). Merges into the stored list (deduped). |
71
+ | `--remove-origin <host>` | Remove a previously stored CORS hostname (**repeatable**). |
72
+ | `--allow-all-origins` | Enable `Access-Control-Allow-Origin: *` (prints a security warning). Prefer `--origin`. |
73
+ | `--no-allow-all-origins` | Disable allow-all mode and use the origin allowlist. |
74
+ | `-v, --verbose` | Show Caddy reload output / errors. |
75
+
76
+ **`--origin` / `--remove-origin` format:** `example.com`, `www.example.com`, `*.example.com`, or `https://example.com`. Hostnames only (optional leading `*.`); no path, port, or `http://` for live origins.
77
+
78
+ If Caddy reload fails after a successful write, the CLI warns and suggests `stagepass start`.
79
+
80
+ Examples:
81
+
82
+ ```bash
83
+ stagepass link my-project --origin www.example.com --origin example.com
84
+ stagepass link my-project --origin my-project.webflow.io
85
+ stagepass link my-project --remove-origin old.example.com
86
+ stagepass link my-project --no-allow-all-origins
87
+ stagepass link my-project --allow-all-origins # emergency / legacy compatibility only
88
+ ```
89
+
90
+ Re-running `stagepass link` keeps stored origins / allow-all setting unless you change them with flags. Omitting both `--allow-all-origins` and `--no-allow-all-origins` leaves the stored value unchanged. New projects default to `allowAllOrigins: false`.
91
+
92
+ If `projects.json` is missing an entry but a v2 Caddyfile block exists, CORS options are restored from the `# stagepass-options:` marker instead of being reset.
93
+
94
+ ## Security
95
+
96
+ Linked sites are hardened automatically:
97
+
98
+ ### Blocked paths (always)
99
+
100
+ These always return **404** (including `OPTIONS`), including with `--allow-all-origins`, and never reach PHP or `file_server`:
101
+
102
+ - Any path segment starting with `.` (covers `.git`, `.env`, `.env.local`, `.DS_Store`, `.ssh`, `.npmrc`, …)
103
+ - `node_modules/`
104
+ - Extensions: `.pem`, `.key`, `.p12`, `.pfx`, `.crt`, `.cer`, `.sqlite`, `.db`, `.log`
105
+
106
+ ### CORS (cross-origin embedding)
107
+
108
+ Stagepass reflects `Access-Control-Allow-Origin` for **allowed** browser `Origin` values (no credentials):
109
+
110
+ **Default allowlist (always on):**
111
+
112
+ - `https://*.sp`
113
+ - `http(s)://localhost[:port]` and `http(s)://127.0.0.1[:port]`
114
+ - Per-project live domains from `--origin` / `~/.stagepass/projects.json`
115
+
116
+ Webflow staging/live hosts are **not** included by default. Add them per project, e.g. `--origin my-project.webflow.io`. An explicit `--origin *.webflow.io` (or `*.webflow.com`) is accepted but prints a warning (any Webflow user's site would then be allowed).
117
+
118
+ Matching responses also send `Vary: Origin`. Preflight (`OPTIONS`) for allowed origins returns `204` with reflected ACAO, `Access-Control-Allow-Methods: GET, HEAD, POST, OPTIONS`, reflected `Access-Control-Allow-Headers`, `Access-Control-Max-Age: 86400`, and `Access-Control-Allow-Private-Network: true` (Chrome Private Network Access from public HTTPS → loopback).
119
+
120
+ Non-matching origins get **no** ACAO. Non-allowlisted `OPTIONS` still get `204` without CORS headers.
121
+
122
+ ### Domain & path validation
123
+
124
+ - Domains are lowercased, must be DNS-safe labels, and always end with `.sp`. Invalid folder names are slugified when the domain is omitted.
125
+ - Project roots refuse `/`, your home directory, and common system roots (`/Users`, `/System`, `/Library`, …). Paths are escaped for the Caddyfile.
126
+
127
+ ### Project config
128
+
129
+ Per-domain settings live in `~/.stagepass/projects.json`:
130
+
131
+ ```json
132
+ {
133
+ "version": 1,
134
+ "projects": {
135
+ "my-project.sp": {
136
+ "root": "/Users/you/Sites/my-project",
137
+ "origins": ["www.example.com"],
138
+ "allowAllOrigins": false
139
+ }
140
+ }
141
+ }
142
+ ```
143
+
144
+ ## Migration from older CLI versions
145
+
146
+ On `stagepass link`, `reload`, and `start`, legacy Caddyfile blocks (no `# stagepass-block: v2` marker) are upgraded automatically:
147
+
148
+ 1. A timestamped backup is written once: `~/.stagepass/Caddyfile.bak-YYYYMMDD-HHMMSS`
149
+ 2. Blocks are rewritten with path blocking + the version marker
150
+ 3. **`allowAllOrigins` is enabled** for migrated blocks so existing Webflow / live-domain embedding keeps working
151
+ 4. A short notice recommends tightening CORS
152
+
153
+ Recommended after migration:
154
+
155
+ ```bash
156
+ stagepass link --origin www.example.com
157
+ stagepass link --no-allow-all-origins
158
+ ```
159
+
160
+ Hand-written content outside `# START:` / `# END:` markers is left untouched. Unparsable legacy blocks are left unchanged with a warning. Migration is idempotent (second run does nothing and creates no new backup).
161
+
162
+ ## Related Packages
163
+
164
+ - `@stagepass/loader`: browser runtime for swapping production assets.
165
+ - `@stagepass/modules`: optional runtime modules (`inject`, `cookies`).
166
+
167
+ ## Repository
168
+
169
+ - Docs and full setup: [stagepass repository](https://github.com/arobertherz/stagepass)
package/bin/index.js CHANGED
@@ -1,79 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { program } from 'commander';
4
- import chalk from 'chalk';
5
- import { setup } from '../src/commands/setup.js';
6
- import { link } from '../src/commands/link.js';
7
- import { unlink } from '../src/commands/unlink.js';
8
- import { start } from '../src/commands/start.js';
9
- import { stop } from '../src/commands/stop.js';
10
- import { reload } from '../src/commands/reload.js';
3
+ import { createProgram } from '../src/cli.js';
11
4
 
12
- program
13
- .name('stagepass')
14
- .description('The missing link between Webflow and local dev.')
15
- .version('1.0.0');
16
-
17
- // Command: SETUP
18
- program
19
- .command('setup')
20
- .description('Install dependencies (Caddy, PHP, Dnsmasq) and configure .sp domain')
21
- .option('-v, --verbose', 'Show detailed installation logs')
22
- .action(async (options) => {
23
- try {
24
- await setup(options);
25
- } catch (error) {
26
- console.error(chalk.red('\nSetup failed.'));
27
- if (options.verbose) console.error(error);
28
- else console.error(chalk.dim('Run with -v for details.'));
29
- }
30
- });
31
-
32
- // Command: LINK
33
- program
34
- .command('link')
35
- .description('Link current directory to a .sp domain')
36
- .argument('[domain]', 'Domain name (optional)')
37
- .option('-v, --verbose', 'Show Caddy reload output')
38
- .action(async (domain, options) => {
39
- await link(domain, options);
40
- });
41
-
42
- // Command: UNLINK
43
- program
44
- .command('unlink')
45
- .description('Unlink current directory from .sp domain')
46
- .argument('[domain]', 'Domain name (optional, defaults to current folder name)')
47
- .option('-v, --verbose', 'Show Caddy reload output')
48
- .action(async (domain, options) => {
49
- await unlink(domain, options);
50
- });
51
-
52
- // Command: RELOAD
53
- program
54
- .command('reload')
55
- .description('Reload Caddy configuration')
56
- .option('-v, --verbose', 'Show Caddy reload output')
57
- .action(async (options) => {
58
- await reload(options);
59
- });
60
-
61
- // Command: START
62
- program
63
- .command('start')
64
- .description('Start background services (Caddy & PHP)')
65
- .option('-v, --verbose', 'Show detailed Caddy server logs')
66
- .action(async (options) => {
67
- await start(options);
68
- });
69
-
70
- // Command: STOP
71
- program
72
- .command('stop')
73
- .description('Stop all background services')
74
- .option('-v, --verbose', 'Show detailed stop logs')
75
- .action(async (options) => {
76
- await stop(options);
77
- });
78
-
79
- program.parse(process.argv);
5
+ createProgram().parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/cli",
3
- "version": "1.0.0",
3
+ "version": "2.0.0",
4
4
  "description": "Local Development Orchestrator for Webflow",
5
5
  "type": "module",
6
6
  "main": "bin/index.js",
@@ -9,10 +9,17 @@
9
9
  },
10
10
  "files": [
11
11
  "bin",
12
- "src"
12
+ "src/cli.js",
13
+ "src/commands/*.js",
14
+ "src/lib/*.js",
15
+ "README.md",
16
+ "LICENSE"
13
17
  ],
14
18
  "scripts": {
15
- "start": "node bin/index.js"
19
+ "start": "node bin/index.js",
20
+ "build": "echo 'No build step required for CLI package'",
21
+ "test": "vitest run",
22
+ "test:watch": "vitest"
16
23
  },
17
24
  "keywords": [
18
25
  "webflow",
@@ -38,7 +45,10 @@
38
45
  "ora": "^7.0.1",
39
46
  "sudo-prompt": "^9.2.1"
40
47
  },
48
+ "devDependencies": {
49
+ "vitest": "^5.0.5"
50
+ },
41
51
  "engines": {
42
52
  "node": ">=18.0.0"
43
53
  }
44
- }
54
+ }
package/src/cli.js ADDED
@@ -0,0 +1,123 @@
1
+ import { createRequire } from 'module';
2
+ import { Command } from 'commander';
3
+ import chalk from 'chalk';
4
+ import { setup as defaultSetup } from './commands/setup.js';
5
+ import { link as defaultLink } from './commands/link.js';
6
+ import { unlink as defaultUnlink } from './commands/unlink.js';
7
+ import { start as defaultStart } from './commands/start.js';
8
+ import { stop as defaultStop } from './commands/stop.js';
9
+ import { reload as defaultReload } from './commands/reload.js';
10
+
11
+ const require = createRequire(import.meta.url);
12
+ const { version: packageVersion } = require('../package.json');
13
+
14
+ function collectRepeatable(value, previous) {
15
+ return previous.concat([value]);
16
+ }
17
+
18
+ /**
19
+ * Build the Commander program (no parse). Injectable handlers for unit tests.
20
+ *
21
+ * @param {object} [deps]
22
+ * @param {typeof defaultSetup} [deps.setup]
23
+ * @param {typeof defaultLink} [deps.link]
24
+ * @param {typeof defaultUnlink} [deps.unlink]
25
+ * @param {typeof defaultStart} [deps.start]
26
+ * @param {typeof defaultStop} [deps.stop]
27
+ * @param {typeof defaultReload} [deps.reload]
28
+ * @param {string} [deps.version]
29
+ */
30
+ export function createProgram(deps = {}) {
31
+ const setup = deps.setup || defaultSetup;
32
+ const link = deps.link || defaultLink;
33
+ const unlink = deps.unlink || defaultUnlink;
34
+ const start = deps.start || defaultStart;
35
+ const stop = deps.stop || defaultStop;
36
+ const reload = deps.reload || defaultReload;
37
+ const version = deps.version || packageVersion;
38
+
39
+ const program = new Command();
40
+
41
+ program
42
+ .name('stagepass')
43
+ .description('The missing link between Webflow and local dev.')
44
+ .version(version);
45
+
46
+ program
47
+ .command('setup')
48
+ .description('Install dependencies (Caddy, PHP, Dnsmasq) and configure .sp domain')
49
+ .option('-v, --verbose', 'Show detailed installation logs')
50
+ .action(async (options) => {
51
+ try {
52
+ await setup(options);
53
+ } catch (error) {
54
+ console.error(chalk.red('\nSetup failed.'));
55
+ if (options.verbose) console.error(error);
56
+ else console.error(chalk.dim('Run with -v for details.'));
57
+ }
58
+ });
59
+
60
+ program
61
+ .command('link')
62
+ .description('Link current directory to a .sp domain')
63
+ .argument('[domain]', 'Domain name (optional)')
64
+ .option('-v, --verbose', 'Show Caddy reload output')
65
+ .option(
66
+ '--origin <host>',
67
+ 'Allow CORS from this live hostname (repeatable; e.g. example.com or *.example.com)',
68
+ collectRepeatable,
69
+ []
70
+ )
71
+ .option(
72
+ '--remove-origin <host>',
73
+ 'Remove a previously stored CORS hostname (repeatable)',
74
+ collectRepeatable,
75
+ []
76
+ )
77
+ .option(
78
+ '--allow-all-origins',
79
+ 'Allow CORS from any Origin (Access-Control-Allow-Origin: *). Insecure; prefer --origin.'
80
+ )
81
+ .option(
82
+ '--no-allow-all-origins',
83
+ 'Disable allow-all CORS and use the origin allowlist'
84
+ )
85
+ .action(async (domain, options) => {
86
+ await link(domain, options);
87
+ });
88
+
89
+ program
90
+ .command('unlink')
91
+ .description('Unlink current directory from .sp domain')
92
+ .argument('[domain]', 'Domain name (optional, defaults to current folder name)')
93
+ .option('-v, --verbose', 'Show Caddy reload output')
94
+ .action(async (domain, options) => {
95
+ await unlink(domain, options);
96
+ });
97
+
98
+ program
99
+ .command('reload')
100
+ .description('Reload Caddy configuration')
101
+ .option('-v, --verbose', 'Show Caddy reload output')
102
+ .action(async (options) => {
103
+ await reload(options);
104
+ });
105
+
106
+ program
107
+ .command('start')
108
+ .description('Start background services (Caddy & PHP)')
109
+ .option('-v, --verbose', 'Show detailed Caddy server logs')
110
+ .action(async (options) => {
111
+ await start(options);
112
+ });
113
+
114
+ program
115
+ .command('stop')
116
+ .description('Stop all background services')
117
+ .option('-v, --verbose', 'Show detailed stop logs')
118
+ .action(async (options) => {
119
+ await stop(options);
120
+ });
121
+
122
+ return program;
123
+ }
@@ -1,79 +1,178 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'path';
3
- import os from 'os';
4
3
  import chalk from 'chalk';
5
4
  import { execa } from 'execa';
6
5
  import ora from 'ora';
6
+ import { resolveLinkDomain } from '../lib/domain.js';
7
+ import { renderSiteBlock, upsertBlock, parseBlocks } from '../lib/caddyfile.js';
8
+ import {
9
+ validateRoot,
10
+ getCaddyfilePath,
11
+ getStagepassDir,
12
+ getProjectsPath,
13
+ } from '../lib/paths.js';
14
+ import { upsertProject, getProject } from '../lib/projects.js';
15
+ import {
16
+ validateOriginList,
17
+ isBroadWebflowWildcard,
18
+ } from '../lib/origins.js';
19
+ import { ensureCaddyfileMigrated } from '../lib/migrate.js';
7
20
 
21
+ /**
22
+ * @param {string|undefined} domain
23
+ * @param {object} options
24
+ * @param {boolean} [options.verbose]
25
+ * @param {string[]} [options.origin]
26
+ * @param {string[]} [options.removeOrigin]
27
+ * @param {boolean} [options.allowAllOrigins]
28
+ */
8
29
  export async function link(domain, options = {}) {
9
30
  const currentDir = process.cwd();
31
+ const folderName = path.basename(currentDir);
10
32
 
11
- // Domain logic
12
- let targetDomain = domain;
13
- if (!targetDomain) {
14
- targetDomain = path.basename(currentDir);
33
+ const resolved = resolveLinkDomain(domain, folderName);
34
+ if (!resolved.ok) {
35
+ console.log(chalk.red(`❌ ${resolved.error}`));
36
+ return;
15
37
  }
16
- targetDomain = targetDomain.replace(/\.sp$/, '') + '.sp';
17
38
 
18
- // Config paths
19
- const caddyDir = path.join(os.homedir(), '.stagepass');
20
- const caddyFilePath = path.join(caddyDir, 'Caddyfile');
39
+ const targetDomain = resolved.domain;
40
+ const rootCheck = validateRoot(currentDir);
41
+ if (!rootCheck.ok) {
42
+ console.log(chalk.red(`❌ ${rootCheck.error}`));
43
+ return;
44
+ }
45
+
46
+ const originsFromFlags = options.origin || [];
47
+ if (originsFromFlags.length > 0) {
48
+ const check = validateOriginList(originsFromFlags);
49
+ if (!check.ok) {
50
+ console.log(chalk.red(`❌ Invalid --origin: ${check.error}`));
51
+ return;
52
+ }
53
+ for (const entry of check.origins) {
54
+ if (isBroadWebflowWildcard(entry)) {
55
+ console.log(
56
+ chalk.yellow(
57
+ ` Warning: ${entry} allows any Webflow user's site to make cross-origin requests to this .sp domain.`
58
+ )
59
+ );
60
+ }
61
+ }
62
+ }
63
+
64
+ const originsToRemove = options.removeOrigin || [];
65
+ if (originsToRemove.length > 0) {
66
+ const check = validateOriginList(originsToRemove);
67
+ if (!check.ok) {
68
+ console.log(chalk.red(`❌ Invalid --remove-origin: ${check.error}`));
69
+ return;
70
+ }
71
+ }
72
+
73
+ let allowAllOriginsFlag;
74
+ if (options.allowAllOrigins === true) allowAllOriginsFlag = true;
75
+ else if (options.allowAllOrigins === false) allowAllOriginsFlag = false;
76
+ else allowAllOriginsFlag = undefined;
77
+
78
+ const caddyDir = getStagepassDir();
79
+ const caddyFilePath = getCaddyfilePath();
80
+ const projectsPath = getProjectsPath();
81
+
82
+ if (resolved.slugged) {
83
+ console.log(
84
+ chalk.dim(
85
+ `Folder name was not a valid domain; using ${chalk.bold(targetDomain)}`
86
+ )
87
+ );
88
+ }
21
89
 
22
90
  const spinner = ora(`Linking ${chalk.bold(targetDomain)}...`).start();
23
91
 
24
- // 1. Write config
25
92
  try {
26
- await fs.ensureDir(caddyDir);
27
-
28
- let content = '';
29
- if (await fs.pathExists(caddyFilePath)) {
30
- content = await fs.readFile(caddyFilePath, 'utf-8');
31
- }
93
+ await fs.ensureDir(caddyDir);
32
94
 
33
- const blockStart = `# START: ${targetDomain}`;
34
- const blockEnd = `# END: ${targetDomain}`;
35
-
36
- const newBlock = `
37
- ${blockStart}
38
- ${targetDomain} {
39
- root * "${currentDir}"
40
- php_fastcgi 127.0.0.1:9000
41
- file_server
42
- tls internal
43
- header Access-Control-Allow-Origin *
44
- }
45
- ${blockEnd}`;
95
+ spinner.stop();
96
+ await ensureCaddyfileMigrated({ caddyfilePath: caddyFilePath, projectsPath });
97
+ spinner.start(`Linking ${chalk.bold(targetDomain)}...`);
46
98
 
47
- const regex = new RegExp(`${escapeRegExp(blockStart)}[\\s\\S]*?${escapeRegExp(blockEnd)}`, 'g');
99
+ let content = '';
100
+ if (await fs.pathExists(caddyFilePath)) {
101
+ content = await fs.readFile(caddyFilePath, 'utf-8');
102
+ }
48
103
 
49
- if (regex.test(content)) {
50
- content = content.replace(regex, newBlock.trim());
51
- } else {
52
- content += `\n${newBlock.trim()}\n`;
53
- }
104
+ const existingBlocks = parseBlocks(content);
105
+ const existingBlock = existingBlocks.find((b) => b.domain === targetDomain);
106
+ const alreadyLinked = Boolean(existingBlock);
107
+ const existingProject = await getProject(targetDomain, projectsPath);
108
+ const isNew = !alreadyLinked && !existingProject;
109
+
110
+ // When projects.json is missing the domain but a v2 block exists, seed from
111
+ // the block marker so re-link does not silently reset CORS settings.
112
+ let seed = null;
113
+ if (!existingProject && existingBlock && !existingBlock.isLegacy) {
114
+ seed = {
115
+ origins: existingBlock.options.origins || [],
116
+ allowAllOrigins: existingBlock.options.allowAllOrigins === true,
117
+ };
118
+ }
54
119
 
55
- await fs.writeFile(caddyFilePath, content.trim());
120
+ const project = await upsertProject(
121
+ targetDomain,
122
+ {
123
+ root: rootCheck.path,
124
+ originsFromFlags,
125
+ originsToRemove,
126
+ allowAllOriginsFlag,
127
+ isNew,
128
+ seed,
129
+ },
130
+ projectsPath
131
+ );
132
+
133
+ const newBlock = renderSiteBlock(targetDomain, rootCheck.path, {
134
+ allowAllOrigins: project.allowAllOrigins,
135
+ origins: project.origins,
136
+ });
137
+
138
+ content = upsertBlock(content, targetDomain, newBlock);
139
+ await fs.writeFile(caddyFilePath, `${content.trim()}\n`, 'utf-8');
140
+
141
+ if (project.allowAllOrigins) {
142
+ spinner.stop();
143
+ console.log(
144
+ chalk.yellow(
145
+ ' Warning: allow-all-origins is enabled (Access-Control-Allow-Origin: *). Prefer --origin <live-domain> then --no-allow-all-origins.'
146
+ )
147
+ );
148
+ spinner.start(`Linking ${chalk.bold(targetDomain)}...`);
149
+ } else if (
150
+ !project.origins.some(
151
+ (o) => o.endsWith('.webflow.io') || o.endsWith('.webflow.com') || isBroadWebflowWildcard(o)
152
+ )
153
+ ) {
154
+ spinner.stop();
155
+ console.log(
156
+ chalk.dim(
157
+ ' Tip: Webflow is not in the default CORS allowlist. Add staging/live with `stagepass link --origin my-project.webflow.io` (or an explicit `*.webflow.io` with caution).'
158
+ )
159
+ );
160
+ spinner.start(`Linking ${chalk.bold(targetDomain)}...`);
161
+ }
56
162
  } catch (e) {
57
- spinner.fail('Failed to write config.');
58
- if (options.verbose) console.error(e);
59
- return;
163
+ spinner.fail('Failed to write config.');
164
+ if (options.verbose) console.error(e);
165
+ else if (e && e.message) console.log(chalk.dim(` ${e.message}`));
166
+ return;
60
167
  }
61
168
 
62
- // 2. Reload Caddy
63
169
  try {
64
- // If verbose is ON, show output. If OFF, ignore it (pipe).
65
170
  const stdioMode = options.verbose ? 'inherit' : 'ignore';
66
-
67
171
  await execa('caddy', ['reload', '--config', caddyFilePath], { stdio: stdioMode });
68
-
69
- spinner.succeed(`Linked: https://${targetDomain} -> ${currentDir}`);
172
+ spinner.succeed(`Linked: https://${targetDomain} -> ${rootCheck.path}`);
70
173
  } catch (error) {
71
174
  spinner.warn('Config written, but Caddy reload failed.');
72
175
  console.log(chalk.dim(' Is Stagepass running? Try: stagepass start'));
73
176
  if (options.verbose) console.error(error);
74
177
  }
75
178
  }
76
-
77
- function escapeRegExp(string) {
78
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
79
- }