unplugin-https-reverse-proxy 4.1.0-beta.2 → 4.1.0-beta.4

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.
@@ -8,6 +8,10 @@ import {
8
8
  hmrSseBridgeClientScript,
9
9
  setupHmrSseBridge
10
10
  } from "./chunk-C5A7XLKL.js";
11
+ import {
12
+ isPrivilegeDenied,
13
+ markPrivilegeDenied
14
+ } from "./chunk-WOMR3ZLM.js";
11
15
  import {
12
16
  decodeMessage,
13
17
  serializeMessage,
@@ -15,458 +19,21 @@ import {
15
19
  } from "./chunk-RKHJN6KY.js";
16
20
 
17
21
  // src/index.ts
18
- import process8 from "node:process";
22
+ import process9 from "node:process";
19
23
  import { Table } from "console-table-printer";
20
24
  import c from "picocolors";
21
25
  import { createUnplugin } from "unplugin";
22
26
 
23
27
  // src/caddy/index.ts
24
28
  import { execFile } from "node:child_process";
25
- import { chmodSync, createWriteStream, existsSync as existsSync5, mkdirSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
26
- import { readFile as readFile3, unlink as unlink3, writeFile as writeFile2 } from "node:fs/promises";
29
+ import { chmodSync, createWriteStream, existsSync as existsSync5, mkdirSync, unlinkSync as unlinkSync2 } from "node:fs";
30
+ import { readFile as readFile3, unlink, writeFile as writeFile2 } from "node:fs/promises";
27
31
  import { platform as platform3 } from "node:os";
28
32
  import { join as join6 } from "node:path";
29
- import process7 from "node:process";
30
-
31
- // node_modules/.pnpm/alien-signals@2.0.7/node_modules/alien-signals/esm/system.mjs
32
- var ReactiveFlags;
33
- (function(ReactiveFlags2) {
34
- ReactiveFlags2[ReactiveFlags2["None"] = 0] = "None";
35
- ReactiveFlags2[ReactiveFlags2["Mutable"] = 1] = "Mutable";
36
- ReactiveFlags2[ReactiveFlags2["Watching"] = 2] = "Watching";
37
- ReactiveFlags2[ReactiveFlags2["RecursedCheck"] = 4] = "RecursedCheck";
38
- ReactiveFlags2[ReactiveFlags2["Recursed"] = 8] = "Recursed";
39
- ReactiveFlags2[ReactiveFlags2["Dirty"] = 16] = "Dirty";
40
- ReactiveFlags2[ReactiveFlags2["Pending"] = 32] = "Pending";
41
- })(ReactiveFlags || (ReactiveFlags = {}));
42
- function createReactiveSystem({ update, notify: notify2, unwatched }) {
43
- let currentVersion = 0;
44
- return {
45
- link: link2,
46
- unlink: unlink4,
47
- propagate: propagate2,
48
- checkDirty: checkDirty2,
49
- endTracking: endTracking2,
50
- startTracking: startTracking2,
51
- shallowPropagate: shallowPropagate2
52
- };
53
- function link2(dep, sub) {
54
- const prevDep = sub.depsTail;
55
- if (prevDep !== void 0 && prevDep.dep === dep) {
56
- return;
57
- }
58
- const nextDep = prevDep !== void 0 ? prevDep.nextDep : sub.deps;
59
- if (nextDep !== void 0 && nextDep.dep === dep) {
60
- nextDep.version = currentVersion;
61
- sub.depsTail = nextDep;
62
- return;
63
- }
64
- const prevSub = dep.subsTail;
65
- if (prevSub !== void 0 && prevSub.version === currentVersion && prevSub.sub === sub) {
66
- return;
67
- }
68
- const newLink = sub.depsTail = dep.subsTail = {
69
- version: currentVersion,
70
- dep,
71
- sub,
72
- prevDep,
73
- nextDep,
74
- prevSub,
75
- nextSub: void 0
76
- };
77
- if (nextDep !== void 0) {
78
- nextDep.prevDep = newLink;
79
- }
80
- if (prevDep !== void 0) {
81
- prevDep.nextDep = newLink;
82
- } else {
83
- sub.deps = newLink;
84
- }
85
- if (prevSub !== void 0) {
86
- prevSub.nextSub = newLink;
87
- } else {
88
- dep.subs = newLink;
89
- }
90
- }
91
- function unlink4(link3, sub = link3.sub) {
92
- const dep = link3.dep;
93
- const prevDep = link3.prevDep;
94
- const nextDep = link3.nextDep;
95
- const nextSub = link3.nextSub;
96
- const prevSub = link3.prevSub;
97
- if (nextDep !== void 0) {
98
- nextDep.prevDep = prevDep;
99
- } else {
100
- sub.depsTail = prevDep;
101
- }
102
- if (prevDep !== void 0) {
103
- prevDep.nextDep = nextDep;
104
- } else {
105
- sub.deps = nextDep;
106
- }
107
- if (nextSub !== void 0) {
108
- nextSub.prevSub = prevSub;
109
- } else {
110
- dep.subsTail = prevSub;
111
- }
112
- if (prevSub !== void 0) {
113
- prevSub.nextSub = nextSub;
114
- } else if ((dep.subs = nextSub) === void 0) {
115
- unwatched(dep);
116
- }
117
- return nextDep;
118
- }
119
- function propagate2(link3) {
120
- let next2 = link3.nextSub;
121
- let stack;
122
- top:
123
- do {
124
- const sub = link3.sub;
125
- let flags = sub.flags;
126
- if (!(flags & 60)) {
127
- sub.flags = flags | 32;
128
- } else if (!(flags & 12)) {
129
- flags = 0;
130
- } else if (!(flags & 4)) {
131
- sub.flags = flags & ~8 | 32;
132
- } else if (!(flags & 48) && isValidLink(link3, sub)) {
133
- sub.flags = flags | 40;
134
- flags &= 1;
135
- } else {
136
- flags = 0;
137
- }
138
- if (flags & 2) {
139
- notify2(sub);
140
- }
141
- if (flags & 1) {
142
- const subSubs = sub.subs;
143
- if (subSubs !== void 0) {
144
- const nextSub = (link3 = subSubs).nextSub;
145
- if (nextSub !== void 0) {
146
- stack = { value: next2, prev: stack };
147
- next2 = nextSub;
148
- }
149
- continue;
150
- }
151
- }
152
- if ((link3 = next2) !== void 0) {
153
- next2 = link3.nextSub;
154
- continue;
155
- }
156
- while (stack !== void 0) {
157
- link3 = stack.value;
158
- stack = stack.prev;
159
- if (link3 !== void 0) {
160
- next2 = link3.nextSub;
161
- continue top;
162
- }
163
- }
164
- break;
165
- } while (true);
166
- }
167
- function startTracking2(sub) {
168
- ++currentVersion;
169
- sub.depsTail = void 0;
170
- sub.flags = sub.flags & ~56 | 4;
171
- }
172
- function endTracking2(sub) {
173
- const depsTail = sub.depsTail;
174
- let toRemove = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
175
- while (toRemove !== void 0) {
176
- toRemove = unlink4(toRemove, sub);
177
- }
178
- sub.flags &= ~4;
179
- }
180
- function checkDirty2(link3, sub) {
181
- let stack;
182
- let checkDepth = 0;
183
- top:
184
- do {
185
- const dep = link3.dep;
186
- const flags = dep.flags;
187
- let dirty = false;
188
- if (sub.flags & 16) {
189
- dirty = true;
190
- } else if ((flags & 17) === 17) {
191
- if (update(dep)) {
192
- const subs = dep.subs;
193
- if (subs.nextSub !== void 0) {
194
- shallowPropagate2(subs);
195
- }
196
- dirty = true;
197
- }
198
- } else if ((flags & 33) === 33) {
199
- if (link3.nextSub !== void 0 || link3.prevSub !== void 0) {
200
- stack = { value: link3, prev: stack };
201
- }
202
- link3 = dep.deps;
203
- sub = dep;
204
- ++checkDepth;
205
- continue;
206
- }
207
- if (!dirty) {
208
- const nextDep = link3.nextDep;
209
- if (nextDep !== void 0) {
210
- link3 = nextDep;
211
- continue;
212
- }
213
- }
214
- while (checkDepth--) {
215
- const firstSub = sub.subs;
216
- const hasMultipleSubs = firstSub.nextSub !== void 0;
217
- if (hasMultipleSubs) {
218
- link3 = stack.value;
219
- stack = stack.prev;
220
- } else {
221
- link3 = firstSub;
222
- }
223
- if (dirty) {
224
- if (update(sub)) {
225
- if (hasMultipleSubs) {
226
- shallowPropagate2(firstSub);
227
- }
228
- sub = link3.sub;
229
- continue;
230
- }
231
- } else {
232
- sub.flags &= ~32;
233
- }
234
- sub = link3.sub;
235
- const nextDep = link3.nextDep;
236
- if (nextDep !== void 0) {
237
- link3 = nextDep;
238
- continue top;
239
- }
240
- dirty = false;
241
- }
242
- return dirty;
243
- } while (true);
244
- }
245
- function shallowPropagate2(link3) {
246
- do {
247
- const sub = link3.sub;
248
- const flags = sub.flags;
249
- if ((flags & 48) === 32) {
250
- sub.flags = flags | 16;
251
- if (flags & 2) {
252
- notify2(sub);
253
- }
254
- }
255
- } while ((link3 = link3.nextSub) !== void 0);
256
- }
257
- function isValidLink(checkLink, sub) {
258
- let link3 = sub.depsTail;
259
- while (link3 !== void 0) {
260
- if (link3 === checkLink) {
261
- return true;
262
- }
263
- link3 = link3.prevDep;
264
- }
265
- return false;
266
- }
267
- }
268
-
269
- // node_modules/.pnpm/alien-signals@2.0.7/node_modules/alien-signals/esm/index.mjs
270
- var queuedEffects = [];
271
- var { link, unlink, propagate, checkDirty, endTracking, startTracking, shallowPropagate } = createReactiveSystem({
272
- update(signal2) {
273
- if ("getter" in signal2) {
274
- return updateComputed(signal2);
275
- } else {
276
- return updateSignal(signal2, signal2.value);
277
- }
278
- },
279
- notify,
280
- unwatched(node2) {
281
- if ("getter" in node2) {
282
- let toRemove = node2.deps;
283
- if (toRemove !== void 0) {
284
- node2.flags = 17;
285
- do {
286
- toRemove = unlink(toRemove, node2);
287
- } while (toRemove !== void 0);
288
- }
289
- } else if (!("previousValue" in node2)) {
290
- effectOper.call(node2);
291
- }
292
- }
293
- });
294
- var batchDepth = 0;
295
- var notifyIndex = 0;
296
- var queuedEffectsLength = 0;
297
- var activeSub;
298
- var activeScope;
299
- function setCurrentSub(sub) {
300
- const prevSub = activeSub;
301
- activeSub = sub;
302
- return prevSub;
303
- }
304
- function signal(initialValue) {
305
- return signalOper.bind({
306
- previousValue: initialValue,
307
- value: initialValue,
308
- subs: void 0,
309
- subsTail: void 0,
310
- flags: 1
311
- });
312
- }
313
- function computed(getter) {
314
- return computedOper.bind({
315
- value: void 0,
316
- subs: void 0,
317
- subsTail: void 0,
318
- deps: void 0,
319
- depsTail: void 0,
320
- flags: 17,
321
- getter
322
- });
323
- }
324
- function effect(fn) {
325
- const e = {
326
- fn,
327
- subs: void 0,
328
- subsTail: void 0,
329
- deps: void 0,
330
- depsTail: void 0,
331
- flags: 2
332
- };
333
- if (activeSub !== void 0) {
334
- link(e, activeSub);
335
- } else if (activeScope !== void 0) {
336
- link(e, activeScope);
337
- }
338
- const prev = setCurrentSub(e);
339
- try {
340
- e.fn();
341
- } finally {
342
- setCurrentSub(prev);
343
- }
344
- return effectOper.bind(e);
345
- }
346
- function updateComputed(c2) {
347
- const prevSub = setCurrentSub(c2);
348
- startTracking(c2);
349
- try {
350
- const oldValue = c2.value;
351
- return oldValue !== (c2.value = c2.getter(oldValue));
352
- } finally {
353
- setCurrentSub(prevSub);
354
- endTracking(c2);
355
- }
356
- }
357
- function updateSignal(s, value2) {
358
- s.flags = 1;
359
- return s.previousValue !== (s.previousValue = value2);
360
- }
361
- function notify(e) {
362
- const flags = e.flags;
363
- if (!(flags & 64)) {
364
- e.flags = flags | 64;
365
- const subs = e.subs;
366
- if (subs !== void 0) {
367
- notify(subs.sub);
368
- } else {
369
- queuedEffects[queuedEffectsLength++] = e;
370
- }
371
- }
372
- }
373
- function run(e, flags) {
374
- if (flags & 16 || flags & 32 && checkDirty(e.deps, e)) {
375
- const prev = setCurrentSub(e);
376
- startTracking(e);
377
- try {
378
- e.fn();
379
- } finally {
380
- setCurrentSub(prev);
381
- endTracking(e);
382
- }
383
- return;
384
- } else if (flags & 32) {
385
- e.flags = flags & ~32;
386
- }
387
- let link2 = e.deps;
388
- while (link2 !== void 0) {
389
- const dep = link2.dep;
390
- const depFlags = dep.flags;
391
- if (depFlags & 64) {
392
- run(dep, dep.flags = depFlags & ~64);
393
- }
394
- link2 = link2.nextDep;
395
- }
396
- }
397
- function flush() {
398
- while (notifyIndex < queuedEffectsLength) {
399
- const effect2 = queuedEffects[notifyIndex];
400
- queuedEffects[notifyIndex++] = void 0;
401
- run(effect2, effect2.flags &= ~64);
402
- }
403
- notifyIndex = 0;
404
- queuedEffectsLength = 0;
405
- }
406
- function computedOper() {
407
- const flags = this.flags;
408
- if (flags & 16 || flags & 32 && checkDirty(this.deps, this)) {
409
- if (updateComputed(this)) {
410
- const subs = this.subs;
411
- if (subs !== void 0) {
412
- shallowPropagate(subs);
413
- }
414
- }
415
- } else if (flags & 32) {
416
- this.flags = flags & ~32;
417
- }
418
- if (activeSub !== void 0) {
419
- link(this, activeSub);
420
- } else if (activeScope !== void 0) {
421
- link(this, activeScope);
422
- }
423
- return this.value;
424
- }
425
- function signalOper(...value2) {
426
- if (value2.length) {
427
- if (this.value !== (this.value = value2[0])) {
428
- this.flags = 17;
429
- const subs = this.subs;
430
- if (subs !== void 0) {
431
- propagate(subs);
432
- if (!batchDepth) {
433
- flush();
434
- }
435
- }
436
- }
437
- } else {
438
- const value3 = this.value;
439
- if (this.flags & 16) {
440
- if (updateSignal(this, value3)) {
441
- const subs = this.subs;
442
- if (subs !== void 0) {
443
- shallowPropagate(subs);
444
- }
445
- }
446
- }
447
- if (activeSub !== void 0) {
448
- link(this, activeSub);
449
- }
450
- return value3;
451
- }
452
- }
453
- function effectOper() {
454
- let dep = this.deps;
455
- while (dep !== void 0) {
456
- dep = unlink(dep, this);
457
- }
458
- const sub = this.subs;
459
- if (sub !== void 0) {
460
- unlink(sub);
461
- }
462
- this.flags = 0;
463
- }
464
-
465
- // src/caddy/index.ts
33
+ import process8 from "node:process";
466
34
  import { got } from "got-cjs";
467
35
  import { HttpProxyAgent } from "http-proxy-agent";
468
36
  import { HttpsProxyAgent } from "https-proxy-agent";
469
- import * as lockfile from "proper-lockfile";
470
37
 
471
38
  // node_modules/.pnpm/@ark+util@0.46.0/node_modules/@ark/util/out/arrays.js
472
39
  var liftArray = (data) => Array.isArray(data) ? data : [data];
@@ -13416,8 +12983,9 @@ async function genCaddyfile(ctx) {
13416
12983
  }
13417
12984
 
13418
12985
  // src/caddy/config.ts
13419
- import { existsSync as existsSync2, readFileSync as readFileSync2, watch, writeFileSync } from "node:fs";
13420
- import { unlink as unlink2 } from "node:fs/promises";
12986
+ import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
12987
+ import process3 from "node:process";
12988
+ import * as lockfile from "proper-lockfile";
13421
12989
 
13422
12990
  // src/caddy/constants.ts
13423
12991
  import os from "node:os";
@@ -13549,56 +13117,108 @@ var supportList = [
13549
13117
  ];
13550
13118
 
13551
13119
  // src/caddy/config.ts
13552
- function useCaddyConfig() {
13553
- const configContentRef = signal("{}");
13554
- const configJsonRef = computed(() => {
13555
- try {
13556
- return JSON.parse(configContentRef());
13557
- } catch {
13558
- return void 0;
13559
- }
13560
- });
13561
- function setConfigContent() {
13562
- if (!existsSync2(caddyConfigPath)) {
13563
- writeFileSync(caddyConfigPath, "{}");
13564
- }
13565
- try {
13566
- configContentRef(readFileSync2(caddyConfigPath, "utf-8"));
13567
- } catch {
13568
- configContentRef("");
13569
- }
13120
+ function isAlive(pid) {
13121
+ if (pid === void 0)
13122
+ return true;
13123
+ try {
13124
+ process3.kill(pid, 0);
13125
+ return true;
13126
+ } catch {
13127
+ return false;
13570
13128
  }
13571
- if (!existsSync2(caddyConfigPath)) {
13572
- writeFileSync(caddyConfigPath, "{}");
13129
+ }
13130
+ function readConfig() {
13131
+ if (!existsSync2(caddyConfigPath))
13132
+ return {};
13133
+ let parsed2;
13134
+ try {
13135
+ parsed2 = JSON.parse(readFileSync2(caddyConfigPath, "utf-8"));
13136
+ } catch {
13137
+ return {};
13573
13138
  }
13574
- const watchCaddyConfig = watch(caddyConfigPath, () => {
13575
- setConfigContent();
13576
- });
13577
- function writeCaddyConfig(_proxies) {
13578
- const proxies = configJsonRef() || {};
13579
- _proxies.forEach((p) => {
13580
- let base = p.base || "/";
13581
- if (!base.startsWith("/"))
13582
- base = `/${base}`;
13583
- if (base !== "/" && !base.endsWith("/"))
13584
- base = `${base}/`;
13585
- const index = `${p.target}${p.portSuffix}${base}`;
13586
- proxies[index] = { ...p, base };
13587
- });
13588
- const content = JSON.stringify(proxies, null, 2);
13589
- configContentRef(content);
13590
- return writeFileSync(caddyConfigPath, content);
13139
+ const alive = {};
13140
+ for (const [key, entry] of Object.entries(parsed2)) {
13141
+ if (isAlive(entry == null ? void 0 : entry.ownerPid))
13142
+ alive[key] = entry;
13591
13143
  }
13592
- async function cleanUp() {
13593
- await unlink2(caddyConfigPath).catch(() => {
13594
- });
13595
- configContentRef("{}");
13596
- watchCaddyConfig.close();
13144
+ return alive;
13145
+ }
13146
+ function writeConfig(proxies) {
13147
+ const content = JSON.stringify(proxies, null, 2);
13148
+ const temp = `${caddyConfigPath}.${process3.pid}.tmp`;
13149
+ writeFileSync(temp, content);
13150
+ renameSync(temp, caddyConfigPath);
13151
+ }
13152
+ async function mutateConfig(lock3, mutate) {
13153
+ const release = await lock3.acquire();
13154
+ try {
13155
+ const proxies = readConfig();
13156
+ mutate(proxies);
13157
+ writeConfig(proxies);
13158
+ return proxies;
13159
+ } finally {
13160
+ release();
13597
13161
  }
13162
+ }
13163
+ function useCaddyConfig(options = {}) {
13164
+ const lock3 = options.lock ?? createFileLock();
13598
13165
  return {
13599
- configJsonRef,
13600
- writeCaddyConfig,
13601
- cleanUp
13166
+ configJsonRef: () => existsSync2(caddyConfigPath) ? readConfig() : void 0,
13167
+ async writeCaddyConfig(_proxies, key) {
13168
+ await mutateConfig(lock3, (proxies) => {
13169
+ for (const p of _proxies)
13170
+ proxies[routeKey(p, key)] = { ...p, base: normalizeBase(p.base), ownerPid: process3.pid };
13171
+ });
13172
+ },
13173
+ async removeProxy(key) {
13174
+ const proxies = await mutateConfig(lock3, (current) => {
13175
+ for (const route of Object.keys(current)) {
13176
+ if (route.endsWith(`#${key}`))
13177
+ delete current[route];
13178
+ }
13179
+ });
13180
+ if (Object.keys(proxies).length === 0)
13181
+ removeConfigFile();
13182
+ },
13183
+ readProxies: () => readConfig(),
13184
+ async cleanUp() {
13185
+ removeConfigFile();
13186
+ }
13187
+ };
13188
+ }
13189
+ function removeConfigFile() {
13190
+ try {
13191
+ if (existsSync2(caddyConfigPath))
13192
+ unlinkSync(caddyConfigPath);
13193
+ } catch {
13194
+ }
13195
+ }
13196
+ function normalizeBase(base) {
13197
+ let out = base || "/";
13198
+ if (!out.startsWith("/"))
13199
+ out = `/${out}`;
13200
+ if (out !== "/" && !out.endsWith("/"))
13201
+ out = `${out}/`;
13202
+ return out;
13203
+ }
13204
+ function routeKey(proxy, ownerKey) {
13205
+ return `${proxy.target}${proxy.portSuffix}${normalizeBase(proxy.base)}#${ownerKey}`;
13206
+ }
13207
+ function createFileLock() {
13208
+ return {
13209
+ async acquire() {
13210
+ if (!existsSync2(caddyConfigPath))
13211
+ writeFileSync(caddyConfigPath, "{}");
13212
+ const release = await lockfile.lock(caddyConfigPath, {
13213
+ realpath: false,
13214
+ stale: 1e4,
13215
+ retries: { retries: 20, minTimeout: 10, maxTimeout: 100 }
13216
+ });
13217
+ return () => {
13218
+ void release().catch(() => {
13219
+ });
13220
+ };
13221
+ }
13602
13222
  };
13603
13223
  }
13604
13224
 
@@ -13615,27 +13235,39 @@ function isCaddyReloadCancellation(line) {
13615
13235
  // src/caddy/privileged.ts
13616
13236
  import { Buffer as Buffer2 } from "node:buffer";
13617
13237
  import { EventEmitter } from "node:events";
13618
- import { dirname as dirname2, join as join5 } from "node:path";
13619
- import process6 from "node:process";
13238
+ import { dirname as dirname3, join as join5 } from "node:path";
13239
+ import process7 from "node:process";
13620
13240
  import { fileURLToPath } from "node:url";
13621
13241
 
13622
13242
  // src/privileged/entry.ts
13623
13243
  import { existsSync as existsSync3 } from "node:fs";
13624
- import { join as join3 } from "node:path";
13625
- import process3 from "node:process";
13244
+ import { dirname as dirname2, join as join3 } from "node:path";
13245
+ import process4 from "node:process";
13626
13246
  function resolveHelperEntry(options) {
13627
- const { moduleDir, nodeBin = process3.execPath, exists: exists2 = existsSync3 } = options;
13247
+ const { moduleDir, nodeBin = process4.execPath, exists: exists2 = existsSync3 } = options;
13628
13248
  for (const name of ["privileged-helper.js", "privileged-helper.cjs", "privileged-helper.mjs"]) {
13629
- const candidate = join3(moduleDir, name);
13630
- if (exists2(candidate))
13249
+ const candidate = findUp(moduleDir, name, exists2);
13250
+ if (candidate)
13631
13251
  return { entry: nodeBin, args: [candidate] };
13632
13252
  }
13633
- const source = join3(moduleDir, "privileged-helper.ts");
13634
- const tsxCli = join3(moduleDir, "../node_modules/tsx/dist/cli.mjs");
13635
- if (exists2(source) && exists2(tsxCli))
13253
+ const source = findUp(moduleDir, "privileged-helper.ts", exists2);
13254
+ const tsxCli = findUp(moduleDir, "node_modules/tsx/dist/cli.mjs", exists2);
13255
+ if (source && tsxCli)
13636
13256
  return { entry: nodeBin, args: [tsxCli, source] };
13637
13257
  throw new Error(`privileged helper entry not found in ${moduleDir}. Build the package first.`);
13638
13258
  }
13259
+ function findUp(from, relative, exists2) {
13260
+ let current = from;
13261
+ while (true) {
13262
+ const candidate = join3(current, relative);
13263
+ if (exists2(candidate))
13264
+ return candidate;
13265
+ const parent = dirname2(current);
13266
+ if (parent === current)
13267
+ return void 0;
13268
+ current = parent;
13269
+ }
13270
+ }
13639
13271
 
13640
13272
  // src/privileged/session.ts
13641
13273
  import { Buffer } from "node:buffer";
@@ -13643,16 +13275,17 @@ import { existsSync as existsSync4 } from "node:fs";
13643
13275
  import { readFile as readFile2, writeFile } from "node:fs/promises";
13644
13276
  import { platform as platform2 } from "node:os";
13645
13277
  import { join as join4 } from "node:path";
13278
+ import * as lockfile2 from "proper-lockfile";
13646
13279
 
13647
13280
  // src/privileged/launch.ts
13648
13281
  import { spawn as spawn2, spawnSync } from "node:child_process";
13649
13282
  import { randomBytes } from "node:crypto";
13650
13283
  import { platform } from "node:os";
13651
- import process5 from "node:process";
13284
+ import process6 from "node:process";
13652
13285
 
13653
13286
  // src/privileged/client.ts
13654
13287
  import { connect } from "node:net";
13655
- import process4 from "node:process";
13288
+ import process5 from "node:process";
13656
13289
  var FORWARDED_ENV_KEYS = [
13657
13290
  "HOME",
13658
13291
  "USER",
@@ -13665,7 +13298,7 @@ var FORWARDED_ENV_KEYS = [
13665
13298
  "NO_PROXY",
13666
13299
  "no_proxy"
13667
13300
  ];
13668
- function collectForwardedEnv(source = process4.env) {
13301
+ function collectForwardedEnv(source = process5.env) {
13669
13302
  const result = {};
13670
13303
  for (const key of FORWARDED_ENV_KEYS) {
13671
13304
  const value2 = source[key];
@@ -13883,18 +13516,42 @@ function spawnElevatedOnWindows(options) {
13883
13516
  function createHelperToken() {
13884
13517
  return randomBytes(24).toString("hex");
13885
13518
  }
13886
- function authenticateSudo(sudoCommand = "sudo") {
13519
+ function describePasswordReason(target, https) {
13520
+ const port = https ? "443" : "80";
13521
+ return [
13522
+ `reverse proxy needs administrator permission for ${target}`,
13523
+ ` \xB7 bind port ${port}${https ? ` for https://${target}` : ""}`,
13524
+ ` \xB7 add ${target} to the hosts file`,
13525
+ "",
13526
+ "This is the only prompt; the rest of the dev server keeps running as you.",
13527
+ "Press Ctrl+C at the prompt to skip the proxy and keep the dev server."
13528
+ ];
13529
+ }
13530
+ function authenticateSudo(sudoCommand = "sudo", options = {}) {
13887
13531
  if (platform() === "win32")
13888
13532
  return { ok: true };
13889
13533
  if (spawnSync(sudoCommand, ["-n", "true"], { stdio: "ignore" }).status === 0)
13890
13534
  return { ok: true };
13535
+ if (options.target) {
13536
+ for (const line of describePasswordReason(options.target, options.https ?? false))
13537
+ process6.stderr.write(`${line}
13538
+ `);
13539
+ process6.stderr.write("\n");
13540
+ }
13891
13541
  if (spawnSync(sudoCommand, ["-v"], { stdio: "inherit" }).status === 0)
13892
13542
  return { ok: true };
13893
13543
  return {
13894
13544
  ok: false,
13545
+ denied: true,
13895
13546
  message: "administrator permission is required to edit the hosts file and bind ports 80/443"
13896
13547
  };
13897
13548
  }
13549
+ var PrivilegeDeniedError = class extends Error {
13550
+ constructor(message) {
13551
+ super(message);
13552
+ this.name = "PrivilegeDeniedError";
13553
+ }
13554
+ };
13898
13555
  async function startPrivilegedHelper(options) {
13899
13556
  var _a4, _b3;
13900
13557
  const {
@@ -13905,14 +13562,16 @@ async function startPrivilegedHelper(options) {
13905
13562
  sudoCommand = "sudo",
13906
13563
  skipAuth = false,
13907
13564
  direct = false,
13908
- env: env2 = process5.env,
13565
+ env: env2 = process6.env,
13909
13566
  log,
13910
13567
  connectTimeoutMs = 12e4
13911
13568
  } = options;
13912
13569
  if (!skipAuth && !direct) {
13913
- const auth = authenticateSudo(sudoCommand);
13914
- if (!auth.ok)
13915
- throw new Error(auth.message);
13570
+ const auth = authenticateSudo(sudoCommand, options.reason);
13571
+ if (!auth.ok) {
13572
+ const message = auth.message ?? "administrator permission is required";
13573
+ throw auth.denied ? new PrivilegeDeniedError(message) : new Error(message);
13574
+ }
13916
13575
  }
13917
13576
  const forwarded = collectForwardedEnv(env2);
13918
13577
  const forwardedArgs = Object.entries(forwarded).map(([key, value2]) => `${key}=${value2}`);
@@ -13922,8 +13581,8 @@ async function startPrivilegedHelper(options) {
13922
13581
  socketPath,
13923
13582
  "--token",
13924
13583
  token,
13925
- ...typeof process5.getuid === "function" ? ["--owner-uid", String(process5.getuid())] : [],
13926
- ...typeof process5.getgid === "function" ? ["--owner-gid", String(process5.getgid())] : [],
13584
+ ...typeof process6.getuid === "function" ? ["--owner-uid", String(process6.getuid())] : [],
13585
+ ...typeof process6.getgid === "function" ? ["--owner-gid", String(process6.getgid())] : [],
13927
13586
  ...options.caddyStoragePath ? ["--caddy-storage", options.caddyStoragePath] : [],
13928
13587
  "--caddy",
13929
13588
  options.caddyBin,
@@ -13932,7 +13591,7 @@ async function startPrivilegedHelper(options) {
13932
13591
  ];
13933
13592
  let child;
13934
13593
  if (!direct && platform() === "win32") {
13935
- await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: process5.cwd() });
13594
+ await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: process6.cwd() });
13936
13595
  } else {
13937
13596
  const command = direct ? helperEntry : sudoCommand;
13938
13597
  const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
@@ -13989,21 +13648,34 @@ function sessionSocketPath(runtimeDir) {
13989
13648
  }
13990
13649
  async function openHelperSession(scope2) {
13991
13650
  const socketPath = sessionSocketPath(scope2.runtimeDir);
13992
- if (existsSync4(socketPath) || platform2() === "win32") {
13993
- const token2 = await readToken(scope2.runtimeDir);
13994
- if (token2) {
13995
- const reused = await connectExistingHelper(socketPath, token2);
13996
- if (reused) {
13997
- return {
13998
- client: reused,
13999
- reused: true,
14000
- close: async () => {
14001
- await reused.close();
14002
- }
14003
- };
14004
- }
14005
- }
13651
+ const release = await acquireStartLock(scope2.runtimeDir);
13652
+ try {
13653
+ const reused = await tryReuse(socketPath, scope2);
13654
+ if (reused)
13655
+ return reused;
13656
+ return await startNew(socketPath, scope2);
13657
+ } finally {
13658
+ release();
14006
13659
  }
13660
+ }
13661
+ async function tryReuse(socketPath, scope2) {
13662
+ if (!existsSync4(socketPath) && platform2() !== "win32")
13663
+ return void 0;
13664
+ const token = await readToken(scope2.runtimeDir);
13665
+ if (!token)
13666
+ return void 0;
13667
+ const reused = await connectExistingHelper(socketPath, token);
13668
+ if (!reused)
13669
+ return void 0;
13670
+ return {
13671
+ client: reused,
13672
+ reused: true,
13673
+ close: async () => {
13674
+ await reused.close();
13675
+ }
13676
+ };
13677
+ }
13678
+ async function startNew(socketPath, scope2) {
14007
13679
  const token = createHelperToken();
14008
13680
  const started = await startPrivilegedHelper({
14009
13681
  socketPath,
@@ -14017,6 +13689,7 @@ async function openHelperSession(scope2) {
14017
13689
  caddyStoragePath: scope2.caddyStoragePath,
14018
13690
  caddyBin: scope2.caddyBin,
14019
13691
  caddyConfigPath: scope2.caddyConfigPath,
13692
+ reason: scope2.reason,
14020
13693
  log: scope2.log
14021
13694
  });
14022
13695
  await writeToken(scope2.runtimeDir, token);
@@ -14028,6 +13701,22 @@ async function openHelperSession(scope2) {
14028
13701
  }
14029
13702
  };
14030
13703
  }
13704
+ async function acquireStartLock(runtimeDir) {
13705
+ const lockPath = join4(runtimeDir, "helper.start.lock");
13706
+ try {
13707
+ await writeFile(lockPath, "", { flag: "a" });
13708
+ } catch {
13709
+ }
13710
+ const release = await lockfile2.lock(lockPath, {
13711
+ realpath: false,
13712
+ stale: 3e4,
13713
+ retries: { retries: 100, minTimeout: 50, maxTimeout: 200 }
13714
+ });
13715
+ return () => {
13716
+ void release().catch(() => {
13717
+ });
13718
+ };
13719
+ }
14031
13720
  async function readToken(runtimeDir) {
14032
13721
  try {
14033
13722
  const content = await readFile2(tokenPath(runtimeDir), "utf8");
@@ -14046,7 +13735,7 @@ async function writeToken(runtimeDir, token) {
14046
13735
 
14047
13736
  // src/caddy/privileged.ts
14048
13737
  function resolvePrivilegedEnv() {
14049
- const moduleDir = typeof __dirname === "string" ? __dirname : dirname2(fileURLToPath(import.meta.url));
13738
+ const moduleDir = typeof __dirname === "string" ? __dirname : dirname3(fileURLToPath(import.meta.url));
14050
13739
  const resolved = resolveHelperEntry({ moduleDir });
14051
13740
  return { helperEntry: resolved.entry, helperArgs: resolved.args };
14052
13741
  }
@@ -14086,7 +13775,7 @@ var HelperCaddyProcess = class extends EventEmitter {
14086
13775
  }
14087
13776
  };
14088
13777
  function caddyStoragePath() {
14089
- return process6.platform === "win32" ? join5(process6.env.AppData ?? "", "Caddy") : join5(process6.env.HOME ?? "", "Library/Application Support/Caddy");
13778
+ return process7.platform === "win32" ? join5(process7.env.AppData ?? "", "Caddy") : join5(process7.env.HOME ?? "", "Library/Application Support/Caddy");
14090
13779
  }
14091
13780
  function openPrivilegedSession(runtimeDir, options) {
14092
13781
  const env2 = resolvePrivilegedEnv();
@@ -14102,6 +13791,7 @@ function openPrivilegedSession(runtimeDir, options) {
14102
13791
  // execute a path supplied over the socket.
14103
13792
  caddyBin: options.caddyBin,
14104
13793
  caddyConfigPath: options.caddyConfigPath,
13794
+ reason: options.reason,
14105
13795
  log: options.log
14106
13796
  });
14107
13797
  }
@@ -14235,15 +13925,15 @@ async function download() {
14235
13925
  const file = createWriteStream(caddyPath);
14236
13926
  let _platform = platform3().toString();
14237
13927
  _platform === "win32" && (_platform = "windows");
14238
- let _arch = process7.arch.toString();
13928
+ let _arch = process8.arch.toString();
14239
13929
  _arch === "x64" && (_arch = "amd64");
14240
13930
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
14241
13931
  if (!support)
14242
13932
  return reject2(new Error("not support"));
14243
13933
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
14244
- existsSync5(caddyPath) && unlinkSync(caddyPath);
14245
- const httpProxy = process7.env.HTTP_PROXY || process7.env.http_proxy;
14246
- const httpsProxy = process7.env.HTTPS_PROXY || process7.env.https_proxy;
13934
+ existsSync5(caddyPath) && unlinkSync2(caddyPath);
13935
+ const httpProxy = process8.env.HTTP_PROXY || process8.env.http_proxy;
13936
+ const httpsProxy = process8.env.HTTPS_PROXY || process8.env.https_proxy;
14247
13937
  const httpAgent = httpProxy ? new HttpProxyAgent(httpProxy) : void 0;
14248
13938
  const httpsAgent = httpsProxy ? new HttpsProxyAgent(httpsProxy) : void 0;
14249
13939
  const chmodCaddyOnce = once(() => {
@@ -14259,7 +13949,7 @@ async function download() {
14259
13949
  chmodCaddyOnce();
14260
13950
  }).pipe(file).on("finish", () => {
14261
13951
  logProgressOver();
14262
- if (process7.platform === "win32")
13952
+ if (process8.platform === "win32")
14263
13953
  return resolve2(caddyPath);
14264
13954
  chmodSync(caddyPath, 493);
14265
13955
  resolve2(caddyPath);
@@ -14302,43 +13992,35 @@ function splitHostPort(addr) {
14302
13992
  return { host: addr.slice(0, lastColon), port: addr.slice(lastColon + 1) };
14303
13993
  }
14304
13994
  var defaultDependencies = {
14305
- openSession: (runtimeDir) => openPrivilegedSession(runtimeDir, {
13995
+ openSession: (runtimeDir, reason) => openPrivilegedSession(runtimeDir, {
14306
13996
  log: (message) => consola.debug(message),
14307
13997
  // Both paths are fixed here, before any socket traffic: the privileged
14308
13998
  // helper must never execute something named in a request.
14309
13999
  caddyBin: caddyPath,
14310
- caddyConfigPath: caddyFilePath
14311
- })
14000
+ caddyConfigPath: caddyFilePath,
14001
+ reason
14002
+ }),
14003
+ config: () => getCaddyConfig()
14312
14004
  };
14313
14005
  var CaddyInstant = class {
14314
14006
  constructor(deps = {}) {
14315
14007
  this.inited = false;
14316
14008
  this.stoped = false;
14317
- /** has locked when start */
14318
- this.locked = false;
14319
14009
  this._stopEffects = [];
14010
+ /** Identifies this instance's routes in the shared config. */
14011
+ this.proxyKey = `${process8.pid}-${Math.random().toString(36).slice(2, 8)}`;
14320
14012
  this.deps = { ...defaultDependencies, ...deps };
14321
- this.locked = this.checkLock();
14322
- }
14323
- checkLock() {
14324
- if (!existsSync5(caddyLockFilePath))
14325
- writeFileSync2(caddyLockFilePath, "");
14326
- try {
14327
- return lockfile.checkSync(caddyLockFilePath);
14328
- } catch {
14329
- return false;
14330
- }
14331
14013
  }
14332
14014
  /**
14333
14015
  * Connects to the privileged helper, starting it once if needed. It is
14334
14016
  * reused across instances so a second dev server does not ask for a
14335
14017
  * password again.
14336
14018
  */
14337
- async session() {
14019
+ async session(reason) {
14338
14020
  if (this._session && !this._session.client.connected)
14339
14021
  this._session = void 0;
14340
14022
  if (!this._session)
14341
- this._session = await this.deps.openSession(TEMP_DIR);
14023
+ this._session = await this.deps.openSession(TEMP_DIR, reason);
14342
14024
  return this._session;
14343
14025
  }
14344
14026
  async getCaddyfile() {
@@ -14351,7 +14033,7 @@ var CaddyInstant = class {
14351
14033
  }
14352
14034
  get caddyRoot() {
14353
14035
  return join6(
14354
- process7.platform === "win32" ? `${process7.env.AppData}/Caddy` : `${process7.env.HOME}/Library/Application Support/Caddy`,
14036
+ process8.platform === "win32" ? `${process8.env.AppData}/Caddy` : `${process8.env.HOME}/Library/Application Support/Caddy`,
14355
14037
  "./pki/authorities/local"
14356
14038
  );
14357
14039
  }
@@ -14359,7 +14041,7 @@ var CaddyInstant = class {
14359
14041
  return await writeFile2(caddyFilePath, this.caddyfile || "");
14360
14042
  }
14361
14043
  async deleteCaddyfile() {
14362
- return await unlink3(caddyFilePath);
14044
+ return await unlink(caddyFilePath);
14363
14045
  }
14364
14046
  async init() {
14365
14047
  await download();
@@ -14397,9 +14079,15 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14397
14079
  if (!health.healthy)
14398
14080
  throw new Error(formatTlsHealthFailure(targetHost, health));
14399
14081
  }
14082
+ /**
14083
+ * Regenerates the Caddyfile from the config on disk.
14084
+ *
14085
+ * Reading the file rather than a cached view matters here: another project
14086
+ * may have added its route since this instance last looked.
14087
+ */
14400
14088
  async updateCaddyfile() {
14401
- const { configJsonRef } = getCaddyConfig();
14402
- const proxies = Object.values(configJsonRef() || {});
14089
+ const { readProxies } = this.deps.config();
14090
+ const proxies = Object.values(readProxies());
14403
14091
  const ctx = validateTemplateContext({
14404
14092
  caddy_root: this.caddyRoot,
14405
14093
  proxies
@@ -14443,12 +14131,12 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14443
14131
  this._target = target;
14444
14132
  if (!this.inited)
14445
14133
  await this.init();
14446
- const session = await this.session();
14447
14134
  const sourceHost = splitHostPort(source).host;
14448
14135
  const targetHost = splitHostPort(target).host;
14136
+ const session = await this.session({ target: targetHost, https });
14449
14137
  await session.client.call("hosts.add", { ip: sourceHost, host: targetHost });
14450
14138
  consola.success("update host success\n");
14451
- const normalizeBase = (b) => {
14139
+ const normalizeBase2 = (b) => {
14452
14140
  let out = b || "/";
14453
14141
  if (!out.startsWith("/"))
14454
14142
  out = `/${out}`;
@@ -14456,7 +14144,7 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14456
14144
  out = `${out}/`;
14457
14145
  return out;
14458
14146
  };
14459
- const baseNormalized = normalizeBase(base);
14147
+ const baseNormalized = normalizeBase2(base);
14460
14148
  const proxies = [
14461
14149
  {
14462
14150
  target: targetHost,
@@ -14467,27 +14155,12 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14467
14155
  healthCheck
14468
14156
  }
14469
14157
  ];
14470
- const { writeCaddyConfig } = getCaddyConfig();
14471
- writeCaddyConfig(proxies);
14158
+ const { writeCaddyConfig } = this.deps.config();
14159
+ await writeCaddyConfig(proxies, this.proxyKey);
14472
14160
  await this.updateCaddyfile();
14473
- let skipInitialCaddyfileEffect = true;
14474
- this._stopEffects.push(
14475
- effect(() => {
14476
- getCaddyConfig().configJsonRef();
14477
- if (skipInitialCaddyfileEffect) {
14478
- skipInitialCaddyfileEffect = false;
14479
- return;
14480
- }
14481
- void this.updateCaddyfile();
14482
- })
14483
- );
14484
- if (!existsSync5(caddyLockFilePath))
14485
- writeFileSync2(caddyLockFilePath, "");
14486
- if (!this.locked) {
14487
- await session.client.call("port.free", { port: 443 });
14488
- if (process7.platform === "win32" || !https)
14489
- await session.client.call("port.free", { port: 80 });
14490
- }
14161
+ await session.client.call("port.free", { port: 443 });
14162
+ if (process8.platform === "win32" || !https)
14163
+ await session.client.call("port.free", { port: 80 });
14491
14164
  return new Promise((resolve2, reject2) => {
14492
14165
  let startupCheckStarted = false;
14493
14166
  const resolveWhenReady = async () => {
@@ -14501,106 +14174,89 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14501
14174
  }
14502
14175
  resolve2();
14503
14176
  } catch (error) {
14504
- if (!this.locked)
14505
- await this.baseCleanup(restore);
14177
+ await this.baseCleanup(restore);
14506
14178
  reject2(error);
14507
14179
  }
14508
14180
  };
14509
14181
  const setupCleanup = () => {
14510
- process7.on("SIGINT", async () => {
14182
+ process8.on("SIGINT", async () => {
14511
14183
  if (this.stoped)
14512
14184
  return;
14513
- process7.stdin.resume();
14185
+ process8.stdin.resume();
14514
14186
  try {
14515
14187
  await this.baseCleanup(restore);
14516
14188
  } finally {
14517
14189
  this.stoped = true;
14518
- process7.nextTick(() => {
14519
- process7.exit();
14190
+ process8.nextTick(() => {
14191
+ process8.exit();
14520
14192
  });
14521
14193
  }
14522
14194
  });
14523
- const originalExit = process7.exit.bind(process7);
14524
- process7.exit = async (code) => {
14195
+ const originalExit = process8.exit.bind(process8);
14196
+ process8.exit = async (code) => {
14525
14197
  if (this.stoped)
14526
14198
  return originalExit(code);
14527
- process7.stdin.resume();
14199
+ process8.stdin.resume();
14528
14200
  try {
14529
14201
  await this.baseCleanup();
14530
14202
  } finally {
14531
14203
  this.stoped = true;
14532
- process7.nextTick(() => {
14204
+ process8.nextTick(() => {
14533
14205
  originalExit(code);
14534
14206
  });
14535
14207
  }
14536
14208
  };
14537
14209
  };
14538
- if (!this.locked) {
14539
- lockfile.lockSync(caddyLockFilePath);
14540
- setupCleanup();
14541
- void (async () => {
14542
- try {
14543
- const child = new HelperCaddyProcess(session.client);
14544
- this._caddyChild = child;
14545
- await session.client.call("caddy.start");
14546
- child.on("exit", (code) => {
14547
- if (code !== null && code !== 0)
14548
- reject2(new Error(`Caddy exited with code ${code}`));
14549
- });
14550
- child.stderr.on("data", async (data) => {
14551
- const lines = data.toString().split("\n").map((line) => line.trim());
14552
- for (const line of lines) {
14553
- showCaddyLog && line && console.info(line);
14554
- if (isCaddyReloadCancellation(line)) {
14555
- consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14556
- continue;
14557
- }
14558
- try {
14559
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14560
- if (line.includes("parsing caddyfile tokens")) {
14561
- consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14210
+ setupCleanup();
14211
+ void (async () => {
14212
+ try {
14213
+ const child = new HelperCaddyProcess(session.client);
14214
+ this._caddyChild = child;
14215
+ await session.client.call("caddy.start");
14216
+ child.on("exit", (code) => {
14217
+ if (code !== null && code !== 0)
14218
+ reject2(new Error(`Caddy exited with code ${code}`));
14219
+ });
14220
+ child.stderr.on("data", async (data) => {
14221
+ const lines = data.toString().split("\n").map((line) => line.trim());
14222
+ for (const line of lines) {
14223
+ showCaddyLog && line && console.info(line);
14224
+ if (isCaddyReloadCancellation(line)) {
14225
+ consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14226
+ continue;
14227
+ }
14228
+ try {
14229
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14230
+ if (line.includes("parsing caddyfile tokens")) {
14231
+ consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14562
14232
 
14563
14233
  ${line}
14564
14234
  `);
14565
- await this.baseCleanup();
14566
- process7.exit();
14567
- } else {
14568
- consola.error(`${line}
14235
+ await this.baseCleanup();
14236
+ process8.exit();
14237
+ } else {
14238
+ consola.error(`${line}
14569
14239
  `);
14570
- return reject2(line);
14571
- }
14240
+ return reject2(line);
14572
14241
  }
14573
- } catch {
14574
14242
  }
14575
- if (line.includes("config file changed"))
14576
- consola.success("Detect added a new reverse proxy config, restarted.\n");
14577
- if (line.includes("caddy proxying") || line.includes("serving initial"))
14578
- void resolveWhenReady();
14243
+ } catch {
14579
14244
  }
14580
- });
14581
- child.stdout.on("data", (data) => {
14582
- consola.info(data.toString());
14583
- void resolveWhenReady();
14584
- });
14585
- } catch (error) {
14586
- if (!this.locked)
14587
- await this.baseCleanup(restore);
14588
- reject2(error);
14589
- }
14590
- })();
14591
- } else {
14592
- consola.info("Caddy is running in another process.");
14593
- void (async () => {
14594
- try {
14595
- if (https)
14596
- await this.ensureTlsReady(targetHost);
14597
- setupCleanup();
14598
- resolve2();
14599
- } catch (error) {
14600
- reject2(error);
14601
- }
14602
- })();
14603
- }
14245
+ if (line.includes("config file changed"))
14246
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
14247
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
14248
+ void resolveWhenReady();
14249
+ }
14250
+ });
14251
+ child.stdout.on("data", (data) => {
14252
+ consola.info(data.toString());
14253
+ void resolveWhenReady();
14254
+ });
14255
+ } catch (error) {
14256
+ await this.baseCleanup(restore);
14257
+ reject2(error);
14258
+ }
14259
+ })();
14604
14260
  });
14605
14261
  }
14606
14262
  async baseCleanup(restore = true) {
@@ -14624,18 +14280,9 @@ ${line}
14624
14280
  consola.fail("Restore host failed.\n");
14625
14281
  }
14626
14282
  }
14627
- if (!this.locked && !this.stoped) {
14628
- await this.stopCaddy();
14283
+ if (!this.stoped) {
14629
14284
  try {
14630
- await lockfile.unlock(caddyLockFilePath).catch(() => {
14631
- });
14632
- await unlink3(caddyFilePath).catch(() => {
14633
- });
14634
- await unlink3(caddyLockFilePath).catch(() => {
14635
- });
14636
- if (caddyConfig) {
14637
- await caddyConfig.cleanUp();
14638
- }
14285
+ await this.deps.config().removeProxy(this.proxyKey);
14639
14286
  } catch (e) {
14640
14287
  consola.error(e);
14641
14288
  }
@@ -14647,7 +14294,7 @@ ${line}
14647
14294
  var config;
14648
14295
  var caddy;
14649
14296
  var hmrSseBridgeActive = false;
14650
- var cwd = process8.cwd();
14297
+ var cwd = process9.cwd();
14651
14298
  function colorUrl(url2) {
14652
14299
  return c.green(url2.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
14653
14300
  }
@@ -14682,16 +14329,27 @@ async function printForwardProxy() {
14682
14329
  }
14683
14330
  var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
14684
14331
  _printUrls == null ? void 0 : _printUrls();
14332
+ if (isPrivilegeDenied())
14333
+ return;
14685
14334
  if (caddy)
14686
14335
  return;
14687
- caddy = new CaddyInstant();
14688
- caddy.run(source, target, {
14336
+ const instance = new CaddyInstant();
14337
+ caddy = instance;
14338
+ instance.run(source, target, {
14689
14339
  base,
14690
14340
  ...options
14691
14341
  }).then(async () => {
14692
14342
  await printForwardProxy();
14693
14343
  consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14694
14344
  }).catch((e) => {
14345
+ if (caddy === instance)
14346
+ caddy = void 0;
14347
+ if (e instanceof PrivilegeDeniedError) {
14348
+ markPrivilegeDenied();
14349
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14350
+ consola.info("Restart the dev server to enable it again.");
14351
+ return;
14352
+ }
14695
14353
  throw e;
14696
14354
  });
14697
14355
  });
@@ -14747,7 +14405,7 @@ var unpluginFactory = (options) => ({
14747
14405
  },
14748
14406
  webpack(compiler) {
14749
14407
  var _a4, _b3, _c2;
14750
- if (process8.env.NODE_ENV !== "development")
14408
+ if (process9.env.NODE_ENV !== "development")
14751
14409
  return;
14752
14410
  const {
14753
14411
  enable = true,
@@ -14768,9 +14426,11 @@ var unpluginFactory = (options) => ({
14768
14426
  port: 8080,
14769
14427
  ...compiler.options.devServer,
14770
14428
  // @ts-expect-error vuecli
14771
- ...(_a4 = process8.VUE_CLI_SERVICE) == null ? void 0 : _a4.projectOptions.devServer
14429
+ ...(_a4 = process9.VUE_CLI_SERVICE) == null ? void 0 : _a4.projectOptions.devServer
14772
14430
  };
14773
14431
  const source = `${devServer.host}:${devServer.port}`;
14432
+ if (isPrivilegeDenied())
14433
+ return;
14774
14434
  if (caddy)
14775
14435
  return;
14776
14436
  let base = "/";
@@ -14785,15 +14445,16 @@ var unpluginFactory = (options) => ({
14785
14445
  const _close = (_c2 = compiler.close) == null ? void 0 : _c2.bind(compiler);
14786
14446
  if (_close) {
14787
14447
  compiler.close = async (callback) => {
14788
- process8.on("exit", () => {
14448
+ process9.on("exit", () => {
14789
14449
  _close && _close(callback);
14790
14450
  });
14791
14451
  };
14792
14452
  } else {
14793
14453
  options.https = false;
14794
14454
  }
14795
- caddy = new CaddyInstant();
14796
- caddy.run(source, target, {
14455
+ const instance = new CaddyInstant();
14456
+ caddy = instance;
14457
+ instance.run(source, target, {
14797
14458
  base,
14798
14459
  ...options
14799
14460
  }).then(() => {
@@ -14802,12 +14463,20 @@ var unpluginFactory = (options) => ({
14802
14463
  consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14803
14464
  });
14804
14465
  }).catch((e) => {
14466
+ if (caddy === instance)
14467
+ caddy = void 0;
14468
+ if (e instanceof PrivilegeDeniedError) {
14469
+ markPrivilegeDenied();
14470
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14471
+ consola.info("Restart the dev server to enable it again.");
14472
+ return;
14473
+ }
14805
14474
  throw e;
14806
14475
  });
14807
14476
  },
14808
14477
  async rspack(compiler) {
14809
14478
  var _a4, _b3, _c2, _d2;
14810
- if (process8.env.NODE_ENV !== "development")
14479
+ if (process9.env.NODE_ENV !== "development")
14811
14480
  return;
14812
14481
  const {
14813
14482
  enable = true,
@@ -14832,9 +14501,10 @@ var unpluginFactory = (options) => ({
14832
14501
  }))) == null ? void 0 : _b3.content) == null ? void 0 : _c2.server
14833
14502
  };
14834
14503
  const source = `${devServer.host}:${devServer.port}`;
14504
+ if (isPrivilegeDenied())
14505
+ return;
14835
14506
  if (caddy)
14836
14507
  return;
14837
- caddy = new CaddyInstant();
14838
14508
  let base = "/";
14839
14509
  const publicPath = (_d2 = compiler.options.output) == null ? void 0 : _d2.publicPath;
14840
14510
  if (typeof publicPath === "string" && publicPath) {
@@ -14844,13 +14514,23 @@ var unpluginFactory = (options) => ({
14844
14514
  base = `/${base}`;
14845
14515
  if (base !== "/" && !base.endsWith("/"))
14846
14516
  base = `${base}/`;
14847
- caddy.run(source, target, {
14517
+ const instance = new CaddyInstant();
14518
+ caddy = instance;
14519
+ instance.run(source, target, {
14848
14520
  base,
14849
14521
  ...options
14850
14522
  }).then(async () => {
14851
14523
  await printForwardProxy();
14852
14524
  consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14853
14525
  }).catch((e) => {
14526
+ if (caddy === instance)
14527
+ caddy = void 0;
14528
+ if (e instanceof PrivilegeDeniedError) {
14529
+ markPrivilegeDenied();
14530
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14531
+ consola.info("Restart the dev server to enable it again.");
14532
+ return;
14533
+ }
14854
14534
  throw e;
14855
14535
  });
14856
14536
  }