unplugin-https-reverse-proxy 4.0.4 → 4.1.0-beta.10

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 (56) hide show
  1. package/README.md +30 -6
  2. package/dist/{chunk-2P7SUCQ3.js → chunk-EY3HXBJ4.js} +0 -26
  3. package/dist/chunk-RKHJN6KY.js +53 -0
  4. package/dist/{chunk-5R33PUJP.js → chunk-U7KAIPZC.js} +981 -796
  5. package/dist/chunk-WOMR3ZLM.js +17 -0
  6. package/dist/esbuild.cjs +1077 -864
  7. package/dist/esbuild.js +4 -2
  8. package/dist/index.cjs +1077 -864
  9. package/dist/index.js +4 -2
  10. package/dist/nuxt.cjs +1049 -850
  11. package/dist/nuxt.js +6 -9
  12. package/dist/privilege-state.cjs +44 -0
  13. package/dist/privilege-state.d.cts +7 -0
  14. package/dist/privilege-state.d.ts +7 -0
  15. package/dist/privilege-state.js +10 -0
  16. package/dist/privileged-helper.cjs +824 -0
  17. package/dist/privileged-helper.d.cts +2 -0
  18. package/dist/privileged-helper.d.ts +2 -0
  19. package/dist/privileged-helper.js +797 -0
  20. package/dist/rollup.cjs +1077 -864
  21. package/dist/rollup.js +4 -2
  22. package/dist/rspack.cjs +1077 -864
  23. package/dist/rspack.js +4 -2
  24. package/dist/utils.cjs +0 -28
  25. package/dist/utils.d.cts +1 -3
  26. package/dist/utils.d.ts +1 -3
  27. package/dist/utils.js +1 -5
  28. package/dist/vite.cjs +1077 -864
  29. package/dist/vite.js +4 -2
  30. package/dist/webpack.cjs +1077 -864
  31. package/dist/webpack.js +4 -2
  32. package/package.json +1 -4
  33. package/src/caddy/caddyfile.ts +3 -0
  34. package/src/caddy/config.ts +195 -53
  35. package/src/caddy/constants.ts +30 -1
  36. package/src/caddy/index.ts +239 -206
  37. package/src/caddy/privileged.ts +124 -0
  38. package/src/caddy/utils.ts +0 -43
  39. package/src/index.ts +49 -22
  40. package/src/nuxt.ts +1 -6
  41. package/src/privilege-state.ts +23 -0
  42. package/src/privileged/bootstrap.ts +289 -0
  43. package/src/privileged/client.ts +288 -0
  44. package/src/privileged/entry.ts +73 -0
  45. package/src/privileged/hosts-file.ts +142 -0
  46. package/src/privileged/launch.ts +332 -0
  47. package/src/privileged/path-guard.ts +74 -0
  48. package/src/privileged/ports.ts +45 -0
  49. package/src/privileged/protocol.ts +111 -0
  50. package/src/privileged/server.ts +578 -0
  51. package/src/privileged/session.ts +169 -0
  52. package/src/privileged/validation.ts +38 -0
  53. package/src/privileged/windows-elevation.ts +80 -0
  54. package/src/privileged-helper.ts +123 -0
  55. package/src/utils.ts +0 -28
  56. package/src/host/index.ts +0 -52
package/dist/rspack.cjs CHANGED
@@ -35,486 +35,30 @@ __export(rspack_exports, {
35
35
  module.exports = __toCommonJS(rspack_exports);
36
36
 
37
37
  // src/index.ts
38
- var import_node_process5 = __toESM(require("process"), 1);
38
+ var import_node_process9 = __toESM(require("process"), 1);
39
39
  var import_console_table_printer = require("console-table-printer");
40
40
  var import_picocolors2 = __toESM(require("picocolors"), 1);
41
41
  var import_unplugin = require("unplugin");
42
42
 
43
43
  // src/caddy/index.ts
44
- var import_node_child_process4 = require("child_process");
45
- var import_node_fs3 = require("fs");
46
- var import_promises3 = require("fs/promises");
47
- var import_node_os3 = require("os");
48
- var import_node_path3 = require("path");
49
- var import_node_process4 = __toESM(require("process"), 1);
50
-
51
- // node_modules/.pnpm/alien-signals@2.0.7/node_modules/alien-signals/esm/system.mjs
52
- var ReactiveFlags;
53
- (function(ReactiveFlags2) {
54
- ReactiveFlags2[ReactiveFlags2["None"] = 0] = "None";
55
- ReactiveFlags2[ReactiveFlags2["Mutable"] = 1] = "Mutable";
56
- ReactiveFlags2[ReactiveFlags2["Watching"] = 2] = "Watching";
57
- ReactiveFlags2[ReactiveFlags2["RecursedCheck"] = 4] = "RecursedCheck";
58
- ReactiveFlags2[ReactiveFlags2["Recursed"] = 8] = "Recursed";
59
- ReactiveFlags2[ReactiveFlags2["Dirty"] = 16] = "Dirty";
60
- ReactiveFlags2[ReactiveFlags2["Pending"] = 32] = "Pending";
61
- })(ReactiveFlags || (ReactiveFlags = {}));
62
- function createReactiveSystem({ update, notify: notify2, unwatched }) {
63
- let currentVersion = 0;
64
- return {
65
- link: link2,
66
- unlink: unlink4,
67
- propagate: propagate2,
68
- checkDirty: checkDirty2,
69
- endTracking: endTracking2,
70
- startTracking: startTracking2,
71
- shallowPropagate: shallowPropagate2
72
- };
73
- function link2(dep, sub) {
74
- const prevDep = sub.depsTail;
75
- if (prevDep !== void 0 && prevDep.dep === dep) {
76
- return;
77
- }
78
- const nextDep = prevDep !== void 0 ? prevDep.nextDep : sub.deps;
79
- if (nextDep !== void 0 && nextDep.dep === dep) {
80
- nextDep.version = currentVersion;
81
- sub.depsTail = nextDep;
82
- return;
83
- }
84
- const prevSub = dep.subsTail;
85
- if (prevSub !== void 0 && prevSub.version === currentVersion && prevSub.sub === sub) {
86
- return;
87
- }
88
- const newLink = sub.depsTail = dep.subsTail = {
89
- version: currentVersion,
90
- dep,
91
- sub,
92
- prevDep,
93
- nextDep,
94
- prevSub,
95
- nextSub: void 0
96
- };
97
- if (nextDep !== void 0) {
98
- nextDep.prevDep = newLink;
99
- }
100
- if (prevDep !== void 0) {
101
- prevDep.nextDep = newLink;
102
- } else {
103
- sub.deps = newLink;
104
- }
105
- if (prevSub !== void 0) {
106
- prevSub.nextSub = newLink;
107
- } else {
108
- dep.subs = newLink;
109
- }
110
- }
111
- function unlink4(link3, sub = link3.sub) {
112
- const dep = link3.dep;
113
- const prevDep = link3.prevDep;
114
- const nextDep = link3.nextDep;
115
- const nextSub = link3.nextSub;
116
- const prevSub = link3.prevSub;
117
- if (nextDep !== void 0) {
118
- nextDep.prevDep = prevDep;
119
- } else {
120
- sub.depsTail = prevDep;
121
- }
122
- if (prevDep !== void 0) {
123
- prevDep.nextDep = nextDep;
124
- } else {
125
- sub.deps = nextDep;
126
- }
127
- if (nextSub !== void 0) {
128
- nextSub.prevSub = prevSub;
129
- } else {
130
- dep.subsTail = prevSub;
131
- }
132
- if (prevSub !== void 0) {
133
- prevSub.nextSub = nextSub;
134
- } else if ((dep.subs = nextSub) === void 0) {
135
- unwatched(dep);
136
- }
137
- return nextDep;
138
- }
139
- function propagate2(link3) {
140
- let next2 = link3.nextSub;
141
- let stack;
142
- top:
143
- do {
144
- const sub = link3.sub;
145
- let flags = sub.flags;
146
- if (!(flags & 60)) {
147
- sub.flags = flags | 32;
148
- } else if (!(flags & 12)) {
149
- flags = 0;
150
- } else if (!(flags & 4)) {
151
- sub.flags = flags & ~8 | 32;
152
- } else if (!(flags & 48) && isValidLink(link3, sub)) {
153
- sub.flags = flags | 40;
154
- flags &= 1;
155
- } else {
156
- flags = 0;
157
- }
158
- if (flags & 2) {
159
- notify2(sub);
160
- }
161
- if (flags & 1) {
162
- const subSubs = sub.subs;
163
- if (subSubs !== void 0) {
164
- const nextSub = (link3 = subSubs).nextSub;
165
- if (nextSub !== void 0) {
166
- stack = { value: next2, prev: stack };
167
- next2 = nextSub;
168
- }
169
- continue;
170
- }
171
- }
172
- if ((link3 = next2) !== void 0) {
173
- next2 = link3.nextSub;
174
- continue;
175
- }
176
- while (stack !== void 0) {
177
- link3 = stack.value;
178
- stack = stack.prev;
179
- if (link3 !== void 0) {
180
- next2 = link3.nextSub;
181
- continue top;
182
- }
183
- }
184
- break;
185
- } while (true);
186
- }
187
- function startTracking2(sub) {
188
- ++currentVersion;
189
- sub.depsTail = void 0;
190
- sub.flags = sub.flags & ~56 | 4;
191
- }
192
- function endTracking2(sub) {
193
- const depsTail = sub.depsTail;
194
- let toRemove = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
195
- while (toRemove !== void 0) {
196
- toRemove = unlink4(toRemove, sub);
197
- }
198
- sub.flags &= ~4;
199
- }
200
- function checkDirty2(link3, sub) {
201
- let stack;
202
- let checkDepth = 0;
203
- top:
204
- do {
205
- const dep = link3.dep;
206
- const flags = dep.flags;
207
- let dirty = false;
208
- if (sub.flags & 16) {
209
- dirty = true;
210
- } else if ((flags & 17) === 17) {
211
- if (update(dep)) {
212
- const subs = dep.subs;
213
- if (subs.nextSub !== void 0) {
214
- shallowPropagate2(subs);
215
- }
216
- dirty = true;
217
- }
218
- } else if ((flags & 33) === 33) {
219
- if (link3.nextSub !== void 0 || link3.prevSub !== void 0) {
220
- stack = { value: link3, prev: stack };
221
- }
222
- link3 = dep.deps;
223
- sub = dep;
224
- ++checkDepth;
225
- continue;
226
- }
227
- if (!dirty) {
228
- const nextDep = link3.nextDep;
229
- if (nextDep !== void 0) {
230
- link3 = nextDep;
231
- continue;
232
- }
233
- }
234
- while (checkDepth--) {
235
- const firstSub = sub.subs;
236
- const hasMultipleSubs = firstSub.nextSub !== void 0;
237
- if (hasMultipleSubs) {
238
- link3 = stack.value;
239
- stack = stack.prev;
240
- } else {
241
- link3 = firstSub;
242
- }
243
- if (dirty) {
244
- if (update(sub)) {
245
- if (hasMultipleSubs) {
246
- shallowPropagate2(firstSub);
247
- }
248
- sub = link3.sub;
249
- continue;
250
- }
251
- } else {
252
- sub.flags &= ~32;
253
- }
254
- sub = link3.sub;
255
- const nextDep = link3.nextDep;
256
- if (nextDep !== void 0) {
257
- link3 = nextDep;
258
- continue top;
259
- }
260
- dirty = false;
261
- }
262
- return dirty;
263
- } while (true);
264
- }
265
- function shallowPropagate2(link3) {
266
- do {
267
- const sub = link3.sub;
268
- const flags = sub.flags;
269
- if ((flags & 48) === 32) {
270
- sub.flags = flags | 16;
271
- if (flags & 2) {
272
- notify2(sub);
273
- }
274
- }
275
- } while ((link3 = link3.nextSub) !== void 0);
276
- }
277
- function isValidLink(checkLink, sub) {
278
- let link3 = sub.depsTail;
279
- while (link3 !== void 0) {
280
- if (link3 === checkLink) {
281
- return true;
282
- }
283
- link3 = link3.prevDep;
284
- }
285
- return false;
286
- }
287
- }
288
-
289
- // node_modules/.pnpm/alien-signals@2.0.7/node_modules/alien-signals/esm/index.mjs
290
- var queuedEffects = [];
291
- var { link, unlink, propagate, checkDirty, endTracking, startTracking, shallowPropagate } = createReactiveSystem({
292
- update(signal2) {
293
- if ("getter" in signal2) {
294
- return updateComputed(signal2);
295
- } else {
296
- return updateSignal(signal2, signal2.value);
297
- }
298
- },
299
- notify,
300
- unwatched(node2) {
301
- if ("getter" in node2) {
302
- let toRemove = node2.deps;
303
- if (toRemove !== void 0) {
304
- node2.flags = 17;
305
- do {
306
- toRemove = unlink(toRemove, node2);
307
- } while (toRemove !== void 0);
308
- }
309
- } else if (!("previousValue" in node2)) {
310
- effectOper.call(node2);
311
- }
312
- }
313
- });
314
- var batchDepth = 0;
315
- var notifyIndex = 0;
316
- var queuedEffectsLength = 0;
317
- var activeSub;
318
- var activeScope;
319
- function setCurrentSub(sub) {
320
- const prevSub = activeSub;
321
- activeSub = sub;
322
- return prevSub;
323
- }
324
- function signal(initialValue) {
325
- return signalOper.bind({
326
- previousValue: initialValue,
327
- value: initialValue,
328
- subs: void 0,
329
- subsTail: void 0,
330
- flags: 1
331
- });
332
- }
333
- function computed(getter) {
334
- return computedOper.bind({
335
- value: void 0,
336
- subs: void 0,
337
- subsTail: void 0,
338
- deps: void 0,
339
- depsTail: void 0,
340
- flags: 17,
341
- getter
342
- });
343
- }
344
- function effect(fn) {
345
- const e = {
346
- fn,
347
- subs: void 0,
348
- subsTail: void 0,
349
- deps: void 0,
350
- depsTail: void 0,
351
- flags: 2
352
- };
353
- if (activeSub !== void 0) {
354
- link(e, activeSub);
355
- } else if (activeScope !== void 0) {
356
- link(e, activeScope);
357
- }
358
- const prev = setCurrentSub(e);
359
- try {
360
- e.fn();
361
- } finally {
362
- setCurrentSub(prev);
363
- }
364
- return effectOper.bind(e);
365
- }
366
- function updateComputed(c3) {
367
- const prevSub = setCurrentSub(c3);
368
- startTracking(c3);
369
- try {
370
- const oldValue = c3.value;
371
- return oldValue !== (c3.value = c3.getter(oldValue));
372
- } finally {
373
- setCurrentSub(prevSub);
374
- endTracking(c3);
375
- }
376
- }
377
- function updateSignal(s, value2) {
378
- s.flags = 1;
379
- return s.previousValue !== (s.previousValue = value2);
380
- }
381
- function notify(e) {
382
- const flags = e.flags;
383
- if (!(flags & 64)) {
384
- e.flags = flags | 64;
385
- const subs = e.subs;
386
- if (subs !== void 0) {
387
- notify(subs.sub);
388
- } else {
389
- queuedEffects[queuedEffectsLength++] = e;
390
- }
391
- }
392
- }
393
- function run(e, flags) {
394
- if (flags & 16 || flags & 32 && checkDirty(e.deps, e)) {
395
- const prev = setCurrentSub(e);
396
- startTracking(e);
397
- try {
398
- e.fn();
399
- } finally {
400
- setCurrentSub(prev);
401
- endTracking(e);
402
- }
403
- return;
404
- } else if (flags & 32) {
405
- e.flags = flags & ~32;
406
- }
407
- let link2 = e.deps;
408
- while (link2 !== void 0) {
409
- const dep = link2.dep;
410
- const depFlags = dep.flags;
411
- if (depFlags & 64) {
412
- run(dep, dep.flags = depFlags & ~64);
413
- }
414
- link2 = link2.nextDep;
415
- }
416
- }
417
- function flush() {
418
- while (notifyIndex < queuedEffectsLength) {
419
- const effect2 = queuedEffects[notifyIndex];
420
- queuedEffects[notifyIndex++] = void 0;
421
- run(effect2, effect2.flags &= ~64);
422
- }
423
- notifyIndex = 0;
424
- queuedEffectsLength = 0;
425
- }
426
- function computedOper() {
427
- const flags = this.flags;
428
- if (flags & 16 || flags & 32 && checkDirty(this.deps, this)) {
429
- if (updateComputed(this)) {
430
- const subs = this.subs;
431
- if (subs !== void 0) {
432
- shallowPropagate(subs);
433
- }
434
- }
435
- } else if (flags & 32) {
436
- this.flags = flags & ~32;
437
- }
438
- if (activeSub !== void 0) {
439
- link(this, activeSub);
440
- } else if (activeScope !== void 0) {
441
- link(this, activeScope);
442
- }
443
- return this.value;
444
- }
445
- function signalOper(...value2) {
446
- if (value2.length) {
447
- if (this.value !== (this.value = value2[0])) {
448
- this.flags = 17;
449
- const subs = this.subs;
450
- if (subs !== void 0) {
451
- propagate(subs);
452
- if (!batchDepth) {
453
- flush();
454
- }
455
- }
456
- }
457
- } else {
458
- const value3 = this.value;
459
- if (this.flags & 16) {
460
- if (updateSignal(this, value3)) {
461
- const subs = this.subs;
462
- if (subs !== void 0) {
463
- shallowPropagate(subs);
464
- }
465
- }
466
- }
467
- if (activeSub !== void 0) {
468
- link(this, activeSub);
469
- }
470
- return value3;
471
- }
472
- }
473
- function effectOper() {
474
- let dep = this.deps;
475
- while (dep !== void 0) {
476
- dep = unlink(dep, this);
477
- }
478
- const sub = this.subs;
479
- if (sub !== void 0) {
480
- unlink(sub);
481
- }
482
- this.flags = 0;
483
- }
484
-
485
- // src/caddy/index.ts
44
+ var import_node_child_process3 = require("child_process");
45
+ var import_node_fs4 = require("fs");
46
+ var import_promises2 = require("fs/promises");
47
+ var import_node_os5 = require("os");
48
+ var import_node_path5 = require("path");
49
+ var import_node_process8 = __toESM(require("process"), 1);
486
50
  var import_got_cjs = require("got-cjs");
487
51
  var import_http_proxy_agent = require("http-proxy-agent");
488
52
  var import_https_proxy_agent = require("https-proxy-agent");
489
- var lockfile = __toESM(require("proper-lockfile"), 1);
490
-
491
- // src/host/index.ts
492
- var import_node_child_process2 = require("child_process");
493
- var import_node_fs = require("fs");
494
- var import_node_process2 = __toESM(require("process"), 1);
495
- var import_node_util = require("util");
496
- var import_hostile = __toESM(require("hostile"), 1);
497
53
 
498
54
  // src/utils.ts
499
- var import_node_child_process = require("child_process");
500
- var import_promises = require("fs/promises");
501
55
  var import_node_os = require("os");
502
- var import_node_path = __toESM(require("path"), 1);
503
- var import_node_process = __toESM(require("process"), 1);
504
56
  var import_consola = require("consola");
505
57
  var import_picocolors = __toESM(require("picocolors"), 1);
506
58
  var import_qrcode_terminal = __toESM(require("qrcode-terminal"), 1);
507
59
  var consola = (0, import_consola.createConsola)({
508
60
  level: 3
509
61
  }).withTag("reverse-proxy");
510
- async function chmodRecursive(_path, mode) {
511
- await (0, import_promises.chmod)(_path, mode);
512
- if ((await (0, import_promises.stat)(_path)).isDirectory()) {
513
- const children = await (0, import_promises.readdir)(_path);
514
- for (const child of children)
515
- await chmodRecursive(import_node_path.default.join(_path, child), mode);
516
- }
517
- }
518
62
  function once(fn) {
519
63
  let called = false;
520
64
  return (...args2) => {
@@ -524,18 +68,6 @@ function once(fn) {
524
68
  return fn(...args2);
525
69
  };
526
70
  }
527
- function isAdmin() {
528
- if (import_node_process.default.platform === "win32") {
529
- try {
530
- (0, import_node_child_process.execSync)("net session", { stdio: "ignore" });
531
- return true;
532
- } catch {
533
- return false;
534
- }
535
- } else {
536
- return !!(import_node_process.default.getuid && import_node_process.default.getuid() === 0);
537
- }
538
- }
539
71
  function getIpv4List() {
540
72
  const interfaces = (0, import_node_os.networkInterfaces)();
541
73
  return Object.values(interfaces).flatMap((nInterface) => nInterface ?? []).filter(
@@ -550,44 +82,6 @@ async function generateQrcode(input) {
550
82
  });
551
83
  }
552
84
 
553
- // src/host/index.ts
554
- var _setHost = (0, import_node_util.promisify)(import_hostile.default.set);
555
- var _removeHost = (0, import_node_util.promisify)(import_hostile.default.remove);
556
- function getPathOfSystemHostsPath() {
557
- return import_node_process2.default.platform === "win32" ? `${import_node_process2.default.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
558
- }
559
- async function syncHost() {
560
- return new Promise((resolve2, _reject) => {
561
- (0, import_node_child_process2.exec)(
562
- import_node_process2.default.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
563
- (error, _stdout, _stderr) => {
564
- if (error) {
565
- consola.error(`exec error: ${error}`);
566
- return resolve2(false);
567
- }
568
- return resolve2(true);
569
- }
570
- );
571
- });
572
- }
573
- async function addHost(ip2, host) {
574
- if (import_node_process2.default.platform !== "win32")
575
- (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
576
- await _setHost("127.0.0.1", "localhost");
577
- await _setHost(ip2, host);
578
- if (ip2 === "localhost")
579
- await _setHost("127.0.0.1", host);
580
- return await syncHost();
581
- }
582
- async function removeHost(ip2, host) {
583
- if (import_node_process2.default.platform !== "win32")
584
- (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
585
- await _removeHost(ip2, host);
586
- if (ip2 === "localhost")
587
- await _removeHost("127.0.0.1", host);
588
- return await syncHost();
589
- }
590
-
591
85
  // node_modules/.pnpm/@ark+util@0.46.0/node_modules/@ark/util/out/arrays.js
592
86
  var liftArray = (data) => Array.isArray(data) ? data : [data];
593
87
  var spliterate = (arr, predicate) => {
@@ -1215,29 +709,29 @@ var timeWithUnnecessarySeconds = /:\d\d:00$/;
1215
709
  var pad = (value2, length) => String(value2).padStart(length, "0");
1216
710
 
1217
711
  // node_modules/.pnpm/@ark+util@0.46.0/node_modules/@ark/util/out/path.js
1218
- var appendStringifiedKey = (path2, prop, ...[opts]) => {
712
+ var appendStringifiedKey = (path, prop, ...[opts]) => {
1219
713
  const stringifySymbol = (opts == null ? void 0 : opts.stringifySymbol) ?? printable;
1220
- let propAccessChain = path2;
714
+ let propAccessChain = path;
1221
715
  switch (typeof prop) {
1222
716
  case "string":
1223
- propAccessChain = isDotAccessible(prop) ? path2 === "" ? prop : `${path2}.${prop}` : `${path2}[${JSON.stringify(prop)}]`;
717
+ propAccessChain = isDotAccessible(prop) ? path === "" ? prop : `${path}.${prop}` : `${path}[${JSON.stringify(prop)}]`;
1224
718
  break;
1225
719
  case "number":
1226
- propAccessChain = `${path2}[${prop}]`;
720
+ propAccessChain = `${path}[${prop}]`;
1227
721
  break;
1228
722
  case "symbol":
1229
- propAccessChain = `${path2}[${stringifySymbol(prop)}]`;
723
+ propAccessChain = `${path}[${stringifySymbol(prop)}]`;
1230
724
  break;
1231
725
  default:
1232
726
  if (opts == null ? void 0 : opts.stringifyNonKey)
1233
- propAccessChain = `${path2}[${opts.stringifyNonKey(prop)}]`;
727
+ propAccessChain = `${path}[${opts.stringifyNonKey(prop)}]`;
1234
728
  else {
1235
729
  throwParseError(`${printable(prop)} must be a PropertyKey or stringifyNonKey must be passed to options`);
1236
730
  }
1237
731
  }
1238
732
  return propAccessChain;
1239
733
  };
1240
- var stringifyPath = (path2, ...opts) => path2.reduce((s, k) => appendStringifiedKey(s, k, ...opts), "");
734
+ var stringifyPath = (path, ...opts) => path.reduce((s, k) => appendStringifiedKey(s, k, ...opts), "");
1241
735
  var ReadonlyPath = class extends ReadonlyArray {
1242
736
  // alternate strategy for caching since the base object is frozen
1243
737
  cache = {};
@@ -1264,8 +758,8 @@ var ReadonlyPath = class extends ReadonlyArray {
1264
758
  return this.cache.stringifyAncestors;
1265
759
  let propString = "";
1266
760
  const result = [propString];
1267
- for (const path2 of this) {
1268
- propString = appendStringifiedKey(propString, path2);
761
+ for (const path of this) {
762
+ propString = appendStringifiedKey(propString, path);
1269
763
  result.push(propString);
1270
764
  }
1271
765
  return this.cache.stringifyAncestors = result;
@@ -1858,15 +1352,15 @@ var ArkErrors = class _ArkErrors extends ReadonlyArray {
1858
1352
  /**
1859
1353
  * @internal
1860
1354
  */
1861
- affectsPath(path2) {
1355
+ affectsPath(path) {
1862
1356
  if (this.length === 0)
1863
1357
  return false;
1864
1358
  return (
1865
1359
  // this would occur if there is an existing error at a prefix of path
1866
1360
  // e.g. the path is ["foo", "bar"] and there is an error at ["foo"]
1867
- path2.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path
1361
+ path.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path
1868
1362
  // e.g. the path is ["foo"] and there is an error at ["foo", "bar"]
1869
- path2.stringify() in this.byAncestorPath
1363
+ path.stringify() in this.byAncestorPath
1870
1364
  );
1871
1365
  }
1872
1366
  /**
@@ -2073,22 +1567,22 @@ var Traversal = class {
2073
1567
  while (this.queuedMorphs.length) {
2074
1568
  const queuedMorphs = this.queuedMorphs;
2075
1569
  this.queuedMorphs = [];
2076
- for (const { path: path2, morphs } of queuedMorphs) {
2077
- if (this.errors.affectsPath(path2))
1570
+ for (const { path, morphs } of queuedMorphs) {
1571
+ if (this.errors.affectsPath(path))
2078
1572
  continue;
2079
- this.applyMorphsAtPath(path2, morphs);
1573
+ this.applyMorphsAtPath(path, morphs);
2080
1574
  }
2081
1575
  }
2082
1576
  }
2083
- applyMorphsAtPath(path2, morphs) {
2084
- const key = path2.at(-1);
1577
+ applyMorphsAtPath(path, morphs) {
1578
+ const key = path.at(-1);
2085
1579
  let parent;
2086
1580
  if (key !== void 0) {
2087
1581
  parent = this.root;
2088
- for (let pathIndex = 0; pathIndex < path2.length - 1; pathIndex++)
2089
- parent = parent[path2[pathIndex]];
1582
+ for (let pathIndex = 0; pathIndex < path.length - 1; pathIndex++)
1583
+ parent = parent[path[pathIndex]];
2090
1584
  }
2091
- this.path = [...path2];
1585
+ this.path = [...path];
2092
1586
  for (const morph of morphs) {
2093
1587
  const morphIsNode = isNode(morph);
2094
1588
  const result = morph(parent === void 0 ? this.root : parent[key], this);
@@ -2458,15 +1952,15 @@ var NodeSelector = {
2458
1952
  normalize: (selector) => typeof selector === "function" ? { boundary: "references", method: "filter", where: selector } : typeof selector === "string" ? isKeyOf(selector, NodeSelector.applyBoundary) ? { method: "filter", boundary: selector } : { boundary: "references", method: "filter", kind: selector } : { boundary: "references", method: "filter", ...selector }
2459
1953
  };
2460
1954
  var writeSelectAssertionMessage = (from, selector) => `${from} had no references matching ${printable(selector)}.`;
2461
- var typePathToPropString = (path2) => stringifyPath(path2, {
1955
+ var typePathToPropString = (path) => stringifyPath(path, {
2462
1956
  stringifyNonKey: (node2) => node2.expression
2463
1957
  });
2464
1958
  var referenceMatcher = /"(\$ark\.[^"]+)"/g;
2465
1959
  var compileMeta = (metaJson) => JSON.stringify(metaJson).replaceAll(referenceMatcher, "$1");
2466
- var flatRef = (path2, node2) => ({
2467
- path: path2,
1960
+ var flatRef = (path, node2) => ({
1961
+ path,
2468
1962
  node: node2,
2469
- propString: typePathToPropString(path2)
1963
+ propString: typePathToPropString(path)
2470
1964
  });
2471
1965
  var flatRefsAreEqual = (l, r) => l.propString === r.propString && l.node.equals(r.node);
2472
1966
  var appendUniqueFlatRefs = (existing, refs) => appendUnique(existing, refs, {
@@ -2502,12 +1996,12 @@ var Disjoint = class _Disjoint extends Array {
2502
1996
  }
2503
1997
  describeReasons() {
2504
1998
  if (this.length === 1) {
2505
- const { path: path2, l, r } = this[0];
2506
- const pathString = stringifyPath(path2);
1999
+ const { path, l, r } = this[0];
2000
+ const pathString = stringifyPath(path);
2507
2001
  return writeUnsatisfiableExpressionError(`Intersection${pathString && ` at ${pathString}`} of ${describeReasons(l, r)}`);
2508
2002
  }
2509
2003
  return `The following intersections result in unsatisfiable types:
2510
- \u2022 ${this.map(({ path: path2, l, r }) => `${path2}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`;
2004
+ \u2022 ${this.map(({ path, l, r }) => `${path}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`;
2511
2005
  }
2512
2006
  throw() {
2513
2007
  return throwParseError(this.describeReasons());
@@ -3867,10 +3361,10 @@ var BaseRoot = class extends BaseNode {
3867
3361
  });
3868
3362
  });
3869
3363
  }
3870
- get(...path2) {
3871
- if (path2[0] === void 0)
3364
+ get(...path) {
3365
+ if (path[0] === void 0)
3872
3366
  return this;
3873
- return this.$.schema(this.applyStructuralOperation("get", path2));
3367
+ return this.$.schema(this.applyStructuralOperation("get", path));
3874
3368
  }
3875
3369
  extract(r) {
3876
3370
  const rNode = this.$.parseDefinition(r);
@@ -4805,13 +4299,13 @@ var implementation17 = implementNode({
4805
4299
  description: (node2) => node2.distribute((branch) => branch.description, describeBranches),
4806
4300
  expected: (ctx) => {
4807
4301
  const byPath = groupBy(ctx.errors, "propString");
4808
- const pathDescriptions = Object.entries(byPath).map(([path2, errors]) => {
4302
+ const pathDescriptions = Object.entries(byPath).map(([path, errors]) => {
4809
4303
  const branchesAtPath = [];
4810
4304
  for (const errorAtPath of errors)
4811
4305
  appendUnique(branchesAtPath, errorAtPath.expected);
4812
4306
  const expected = describeBranches(branchesAtPath);
4813
4307
  const actual = errors.every((e) => e.actual === errors[0].actual) ? errors[0].actual : printable(errors[0].data);
4814
- return `${path2 && `${path2} `}must be ${expected}${actual && ` (was ${actual})`}`;
4308
+ return `${path && `${path} `}must be ${expected}${actual && ` (was ${actual})`}`;
4815
4309
  });
4816
4310
  return describeBranches(pathDescriptions);
4817
4311
  },
@@ -5175,10 +4669,10 @@ var orderCandidates = (candidates, originalBranches) => {
5175
4669
  });
5176
4670
  return viableCandidates;
5177
4671
  };
5178
- var discriminantCaseToNode = (caseDiscriminant, path2, $) => {
4672
+ var discriminantCaseToNode = (caseDiscriminant, path, $) => {
5179
4673
  let node2 = caseDiscriminant === "undefined" ? $.node("unit", { unit: void 0 }) : caseDiscriminant === "null" ? $.node("unit", { unit: null }) : caseDiscriminant === "boolean" ? $.units([true, false]) : caseDiscriminant;
5180
- for (let i = path2.length - 1; i >= 0; i--) {
5181
- const key = path2[i];
4674
+ for (let i = path.length - 1; i >= 0; i--) {
4675
+ const key = path[i];
5182
4676
  node2 = $.node("intersection", typeof key === "number" ? {
5183
4677
  proto: "Array",
5184
4678
  // create unknown for preceding elements (could be optimized with safe imports)
@@ -5190,7 +4684,7 @@ var discriminantCaseToNode = (caseDiscriminant, path2, $) => {
5190
4684
  }
5191
4685
  return node2;
5192
4686
  };
5193
- var optionallyChainPropString = (path2) => path2.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data");
4687
+ var optionallyChainPropString = (path) => path.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data");
5194
4688
  var serializedTypeOfDescriptions = registeredReference(jsTypeOfDescriptions);
5195
4689
  var serializedPrintable = registeredReference(printable);
5196
4690
  var Union = {
@@ -6148,7 +5642,7 @@ var StructureNode = class extends BaseConstraint {
6148
5642
  return throwParseError(writeInvalidKeysMessage(this.expression, invalidKeys));
6149
5643
  }
6150
5644
  }
6151
- get(indexer, ...path2) {
5645
+ get(indexer, ...path) {
6152
5646
  var _a4;
6153
5647
  let value2;
6154
5648
  let required = false;
@@ -6185,7 +5679,7 @@ var StructureNode = class extends BaseConstraint {
6185
5679
  }
6186
5680
  return throwParseError(writeInvalidKeysMessage(this.expression, [key]));
6187
5681
  }
6188
- const result = value2.get(...path2);
5682
+ const result = value2.get(...path);
6189
5683
  return required ? result : result.or($ark.intrinsic.undefined);
6190
5684
  }
6191
5685
  pick(...keys) {
@@ -8911,7 +8405,7 @@ function isIterator(val) {
8911
8405
  function escapeRegex(str) {
8912
8406
  return str.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
8913
8407
  }
8914
- function promisify2(fn) {
8408
+ function promisify(fn) {
8915
8409
  return function(...args2) {
8916
8410
  return new Promise((resolve2, reject2) => {
8917
8411
  fn(...args2, (err, result) => {
@@ -10247,8 +9741,8 @@ function requireResolve(file) {
10247
9741
  const require2 = (0, import_module3.createRequire)(process.cwd() + "/");
10248
9742
  return require2.resolve(file);
10249
9743
  }
10250
- var statAsync = promisify2(import_fs.stat);
10251
- var readFileAsync = promisify2(import_fs.readFile);
9744
+ var statAsync = promisify(import_fs.stat);
9745
+ var readFileAsync = promisify(import_fs.readFile);
10252
9746
  function exists(filepath) {
10253
9747
  return __awaiter(this, void 0, void 0, function* () {
10254
9748
  try {
@@ -11490,10 +10984,10 @@ var Loader = class {
11490
10984
  yield filepath;
11491
10985
  }
11492
10986
  }
11493
- dirname(path2) {
10987
+ dirname(path) {
11494
10988
  const fs2 = this.options.fs;
11495
10989
  assert(fs2.dirname, "`fs.dirname` is required for relative reference");
11496
- return fs2.dirname(path2);
10990
+ return fs2.dirname(path);
11497
10991
  }
11498
10992
  lookupError(file, roots) {
11499
10993
  const err = new Error("ENOENT");
@@ -13444,6 +12938,7 @@ var ProxyType = type({
13444
12938
  });
13445
12939
  var CaddyContext = type({
13446
12940
  caddy_root: "string",
12941
+ admin_socket: "string",
13447
12942
  proxies: ProxyType.array()
13448
12943
  });
13449
12944
  function validateTemplateContext(ctx) {
@@ -13455,6 +12950,8 @@ function validateTemplateContext(ctx) {
13455
12950
  var caddyTemplate = `{
13456
12951
  debug
13457
12952
  auto_https disable_redirects ignore_loaded_certs
12953
+ skip_install_trust
12954
+ admin unix/{{ admin_socket }}
13458
12955
  }
13459
12956
 
13460
12957
  :7601 {
@@ -13535,27 +13032,37 @@ async function genCaddyfile(ctx) {
13535
13032
  }
13536
13033
 
13537
13034
  // src/caddy/config.ts
13538
- var import_node_fs2 = require("fs");
13539
- var import_promises2 = require("fs/promises");
13035
+ var import_node_fs = require("fs");
13036
+ var import_node_process2 = __toESM(require("process"), 1);
13037
+ var lockfile = __toESM(require("proper-lockfile"), 1);
13540
13038
 
13541
13039
  // src/caddy/constants.ts
13542
13040
  var import_node_os2 = __toESM(require("os"), 1);
13543
- var import_node_path2 = require("path");
13544
- var import_node_process3 = __toESM(require("process"), 1);
13041
+ var import_node_path = require("path");
13042
+ var import_node_process = __toESM(require("process"), 1);
13545
13043
  var import_dotenv_flow = __toESM(require("dotenv-flow"), 1);
13546
13044
  import_dotenv_flow.default.config({
13547
13045
  silent: true
13548
13046
  });
13549
- function resolvePath(path2) {
13550
- if (path2.startsWith("~"))
13551
- return (0, import_node_path2.join)(import_node_os2.default.homedir() || "", path2.slice(1));
13552
- return path2;
13553
- }
13554
- var TEMP_DIR = resolvePath(import_node_process3.default.env.UHRP_CADDY_PATH || import_node_process3.default.env.TEMP || import_node_process3.default.env.TMPDIR || "/tmp");
13555
- var caddyPath = (0, import_node_path2.join)(TEMP_DIR, `caddy${import_node_process3.default.platform === "win32" ? ".exe" : ""}`);
13556
- var caddyFilePath = (0, import_node_path2.join)(TEMP_DIR, "CADDYFILE");
13557
- var caddyConfigPath = (0, import_node_path2.join)(TEMP_DIR, ".CADDYFILE.config.json");
13558
- var caddyLockFilePath = (0, import_node_path2.join)(TEMP_DIR, "caddylock");
13047
+ function resolvePath(path) {
13048
+ if (path.startsWith("~"))
13049
+ return (0, import_node_path.join)(import_node_os2.default.homedir() || "", path.slice(1));
13050
+ return path;
13051
+ }
13052
+ function defaultTempDir() {
13053
+ const fromEnv = import_node_process.default.env.TEMP || import_node_process.default.env.TMPDIR;
13054
+ if (fromEnv)
13055
+ return resolvePath(fromEnv);
13056
+ if (import_node_process.default.platform === "linux")
13057
+ return (0, import_node_path.join)(import_node_process.default.env.XDG_CACHE_HOME || (0, import_node_path.join)(import_node_os2.default.homedir(), ".cache"), "uhrp");
13058
+ return "/tmp";
13059
+ }
13060
+ var TEMP_DIR = resolvePath(import_node_process.default.env.UHRP_CADDY_PATH || defaultTempDir());
13061
+ var caddyPath = (0, import_node_path.join)(TEMP_DIR, `caddy${import_node_process.default.platform === "win32" ? ".exe" : ""}`);
13062
+ var caddyFilePath = (0, import_node_path.join)(TEMP_DIR, "CADDYFILE");
13063
+ var caddyConfigPath = (0, import_node_path.join)(TEMP_DIR, ".CADDYFILE.config.json");
13064
+ var caddyLockFilePath = (0, import_node_path.join)(TEMP_DIR, "caddylock");
13065
+ var caddyAdminSocketPath = (0, import_node_path.join)(TEMP_DIR, "caddy-admin.sock");
13559
13066
  var supportList = [
13560
13067
  {
13561
13068
  platform: "dragonfly",
@@ -13668,67 +13175,786 @@ var supportList = [
13668
13175
  ];
13669
13176
 
13670
13177
  // src/caddy/config.ts
13671
- function useCaddyConfig() {
13672
- const configContentRef = signal("{}");
13673
- const configJsonRef = computed(() => {
13178
+ function isAlive(pid) {
13179
+ if (pid === void 0)
13180
+ return true;
13181
+ try {
13182
+ import_node_process2.default.kill(pid, 0);
13183
+ return true;
13184
+ } catch {
13185
+ return false;
13186
+ }
13187
+ }
13188
+ function readConfig(path = caddyConfigPath) {
13189
+ if (!(0, import_node_fs.existsSync)(path))
13190
+ return {};
13191
+ let parsed2;
13192
+ try {
13193
+ parsed2 = JSON.parse((0, import_node_fs.readFileSync)(path, "utf-8"));
13194
+ } catch {
13195
+ return {};
13196
+ }
13197
+ const alive = {};
13198
+ for (const [key, entry] of Object.entries(parsed2)) {
13199
+ if (isAlive(entry == null ? void 0 : entry.ownerPid))
13200
+ alive[key] = entry;
13201
+ }
13202
+ return alive;
13203
+ }
13204
+ function writeConfig(proxies, path = caddyConfigPath) {
13205
+ const content = JSON.stringify(proxies, null, 2);
13206
+ const temp = `${path}.${import_node_process2.default.pid}.tmp`;
13207
+ (0, import_node_fs.writeFileSync)(temp, content);
13208
+ (0, import_node_fs.renameSync)(temp, path);
13209
+ }
13210
+ function useCaddyConfig(options = {}) {
13211
+ const lock3 = options.lock ?? createFileLock();
13212
+ const configPath = options.configPath ?? caddyConfigPath;
13213
+ async function mutate(apply) {
13214
+ var _a4;
13215
+ const release = await lock3.acquire();
13674
13216
  try {
13675
- return JSON.parse(configContentRef());
13676
- } catch {
13217
+ const proxies = readConfig(configPath);
13218
+ apply(proxies);
13219
+ writeConfig(proxies, configPath);
13220
+ await ((_a4 = options.renderCaddyfile) == null ? void 0 : _a4.call(options, proxies));
13221
+ return proxies;
13222
+ } finally {
13223
+ release();
13224
+ }
13225
+ }
13226
+ return {
13227
+ configJsonRef: () => (0, import_node_fs.existsSync)(configPath) ? readConfig(configPath) : void 0,
13228
+ async writeCaddyConfig(_proxies, key) {
13229
+ await mutate((proxies) => {
13230
+ for (const p of _proxies)
13231
+ proxies[routeKey(p, key)] = { ...p, base: normalizeBase(p.base), ownerPid: import_node_process2.default.pid };
13232
+ });
13233
+ },
13234
+ async removeProxy(key) {
13235
+ await mutate((current) => {
13236
+ for (const route of Object.keys(current)) {
13237
+ if (route.endsWith(`#${key}`))
13238
+ delete current[route];
13239
+ }
13240
+ });
13241
+ },
13242
+ readProxies: () => readConfig(configPath),
13243
+ async cleanUp() {
13244
+ removeConfigFile(configPath);
13245
+ }
13246
+ };
13247
+ }
13248
+ function removeConfigFile(path = caddyConfigPath) {
13249
+ try {
13250
+ if ((0, import_node_fs.existsSync)(path))
13251
+ (0, import_node_fs.unlinkSync)(path);
13252
+ } catch {
13253
+ }
13254
+ }
13255
+ function normalizeBase(base) {
13256
+ let out = base || "/";
13257
+ if (!out.startsWith("/"))
13258
+ out = `/${out}`;
13259
+ if (out !== "/" && !out.endsWith("/"))
13260
+ out = `${out}/`;
13261
+ return out;
13262
+ }
13263
+ function routeKey(proxy, ownerKey) {
13264
+ return `${proxy.target}${proxy.portSuffix}${normalizeBase(proxy.base)}#${ownerKey}`;
13265
+ }
13266
+ function createFileLock() {
13267
+ return {
13268
+ async acquire() {
13269
+ if (!(0, import_node_fs.existsSync)(caddyConfigPath))
13270
+ (0, import_node_fs.writeFileSync)(caddyConfigPath, "{}");
13271
+ const release = await lockfile.lock(caddyConfigPath, {
13272
+ realpath: false,
13273
+ stale: 1e4,
13274
+ retries: { retries: 20, minTimeout: 10, maxTimeout: 100 }
13275
+ });
13276
+ return () => {
13277
+ void release().catch(() => {
13278
+ });
13279
+ };
13280
+ }
13281
+ };
13282
+ }
13283
+
13284
+ // src/caddy/log.ts
13285
+ function isCaddyReloadCancellation(line) {
13286
+ try {
13287
+ const entry = JSON.parse(line);
13288
+ return entry.logger === "tls" && typeof entry.error === "string" && entry.error.endsWith("context canceled");
13289
+ } catch {
13290
+ return false;
13291
+ }
13292
+ }
13293
+
13294
+ // src/caddy/privileged.ts
13295
+ var import_node_buffer2 = require("buffer");
13296
+ var import_node_events = require("events");
13297
+ var import_node_path4 = require("path");
13298
+ var import_node_process7 = __toESM(require("process"), 1);
13299
+ var import_node_url = require("url");
13300
+
13301
+ // src/privileged/entry.ts
13302
+ var import_node_fs2 = require("fs");
13303
+ var import_node_path2 = require("path");
13304
+ var import_node_process3 = __toESM(require("process"), 1);
13305
+ function resolveHelperEntry(options) {
13306
+ const { moduleDir, nodeBin = import_node_process3.default.execPath, exists: exists2 = import_node_fs2.existsSync } = options;
13307
+ for (const name of ["privileged-helper.js", "privileged-helper.cjs", "privileged-helper.mjs"]) {
13308
+ const candidate = findUp(moduleDir, name, exists2);
13309
+ if (candidate)
13310
+ return { entry: nodeBin, args: [candidate] };
13311
+ }
13312
+ const source = findUp(moduleDir, "privileged-helper.ts", exists2);
13313
+ const tsxCli = findUp(moduleDir, "node_modules/tsx/dist/cli.mjs", exists2);
13314
+ if (source && tsxCli)
13315
+ return { entry: nodeBin, args: [tsxCli, source] };
13316
+ throw new Error(`privileged helper entry not found in ${moduleDir}. Build the package first.`);
13317
+ }
13318
+ function findUp(from, relative, exists2) {
13319
+ let current = from;
13320
+ while (true) {
13321
+ const candidate = (0, import_node_path2.join)(current, relative);
13322
+ if (exists2(candidate))
13323
+ return candidate;
13324
+ const parent = (0, import_node_path2.dirname)(current);
13325
+ if (parent === current)
13677
13326
  return void 0;
13327
+ current = parent;
13328
+ }
13329
+ }
13330
+
13331
+ // src/privileged/session.ts
13332
+ var import_node_buffer = require("buffer");
13333
+ var import_node_fs3 = require("fs");
13334
+ var import_promises = require("fs/promises");
13335
+ var import_node_os4 = require("os");
13336
+ var import_node_path3 = require("path");
13337
+ var lockfile2 = __toESM(require("proper-lockfile"), 1);
13338
+
13339
+ // src/privileged/launch.ts
13340
+ var import_node_child_process2 = require("child_process");
13341
+ var import_node_crypto = require("crypto");
13342
+ var import_node_os3 = require("os");
13343
+ var import_node_process6 = __toESM(require("process"), 1);
13344
+
13345
+ // src/privileged/client.ts
13346
+ var import_node_net = require("net");
13347
+ var import_node_process4 = __toESM(require("process"), 1);
13348
+
13349
+ // src/privileged/protocol.ts
13350
+ function serializeMessage(message) {
13351
+ return `${JSON.stringify(message)}
13352
+ `;
13353
+ }
13354
+ function splitLines(buffer, chunk) {
13355
+ const parts = (buffer + chunk).split("\n");
13356
+ const rest = parts.pop() ?? "";
13357
+ return { lines: parts.filter((line) => line.trim() !== ""), rest };
13358
+ }
13359
+ function isRecord(value2) {
13360
+ return typeof value2 === "object" && value2 !== null;
13361
+ }
13362
+ function decodeMessage(line) {
13363
+ let parsed2;
13364
+ try {
13365
+ parsed2 = JSON.parse(line);
13366
+ } catch (error) {
13367
+ return { ok: false, error: `invalid JSON: ${error.message}` };
13368
+ }
13369
+ if (!isRecord(parsed2))
13370
+ return { ok: false, error: "message must be an object" };
13371
+ if (parsed2.type === "event") {
13372
+ if (typeof parsed2.kind !== "string")
13373
+ return { ok: false, error: "event.kind must be a string" };
13374
+ return { ok: true, message: parsed2 };
13375
+ }
13376
+ if (typeof parsed2.id !== "number")
13377
+ return { ok: false, error: "response.id must be a number" };
13378
+ if (parsed2.ok === true)
13379
+ return { ok: true, message: { id: parsed2.id, ok: true, result: parsed2.result } };
13380
+ if (parsed2.ok === false) {
13381
+ const error = isRecord(parsed2.error) ? parsed2.error : {};
13382
+ return {
13383
+ ok: true,
13384
+ message: {
13385
+ id: parsed2.id,
13386
+ ok: false,
13387
+ error: {
13388
+ message: typeof error.message === "string" ? error.message : "helper request failed",
13389
+ code: typeof error.code === "string" ? error.code : void 0
13390
+ }
13391
+ }
13392
+ };
13393
+ }
13394
+ return { ok: false, error: "response.ok must be a boolean" };
13395
+ }
13396
+
13397
+ // src/privileged/client.ts
13398
+ var FORWARDED_ENV_KEYS = [
13399
+ "HOME",
13400
+ "USER",
13401
+ "LOGNAME",
13402
+ "TMPDIR",
13403
+ "HTTP_PROXY",
13404
+ "HTTPS_PROXY",
13405
+ "http_proxy",
13406
+ "https_proxy",
13407
+ "NO_PROXY",
13408
+ "no_proxy"
13409
+ ];
13410
+ function collectForwardedEnv(source = import_node_process4.default.env) {
13411
+ const result = {};
13412
+ for (const key of FORWARDED_ENV_KEYS) {
13413
+ const value2 = source[key];
13414
+ if (typeof value2 === "string" && value2 !== "")
13415
+ result[key] = value2;
13416
+ }
13417
+ return result;
13418
+ }
13419
+ var HelperConnectionError = class extends Error {
13420
+ constructor(message) {
13421
+ super(message);
13422
+ this.name = "HelperConnectionError";
13423
+ }
13424
+ };
13425
+ function openSocket(socketPath) {
13426
+ return new Promise((resolve2, reject2) => {
13427
+ const socket = (0, import_node_net.connect)(socketPath);
13428
+ function onConnect() {
13429
+ socket.removeListener("error", onError);
13430
+ resolve2(socket);
13678
13431
  }
13679
- });
13680
- function setConfigContent() {
13681
- if (!(0, import_node_fs2.existsSync)(caddyConfigPath)) {
13682
- (0, import_node_fs2.writeFileSync)(caddyConfigPath, "{}");
13432
+ function onError(error) {
13433
+ socket.removeListener("connect", onConnect);
13434
+ reject2(error);
13683
13435
  }
13436
+ socket.once("error", onError);
13437
+ socket.once("connect", onConnect);
13438
+ });
13439
+ }
13440
+ async function connectClient(options) {
13441
+ const {
13442
+ socketPath,
13443
+ token,
13444
+ timeoutMs = 12e4,
13445
+ retryIntervalMs = 100,
13446
+ callTimeoutMs = 3e4
13447
+ } = options;
13448
+ const deadline = Date.now() + timeoutMs;
13449
+ let lastError;
13450
+ while (Date.now() < deadline) {
13684
13451
  try {
13685
- configContentRef((0, import_node_fs2.readFileSync)(caddyConfigPath, "utf-8"));
13686
- } catch {
13687
- configContentRef("");
13452
+ return await handshake(socketPath, token, callTimeoutMs);
13453
+ } catch (error) {
13454
+ lastError = error;
13455
+ const code = lastError.code;
13456
+ if (code === "EACCES" || lastError instanceof HelperConnectionError)
13457
+ throw lastError;
13458
+ await new Promise((resolve2) => setTimeout(resolve2, retryIntervalMs));
13688
13459
  }
13689
13460
  }
13690
- if (!(0, import_node_fs2.existsSync)(caddyConfigPath)) {
13691
- (0, import_node_fs2.writeFileSync)(caddyConfigPath, "{}");
13692
- }
13693
- const watchCaddyConfig = (0, import_node_fs2.watch)(caddyConfigPath, () => {
13694
- setConfigContent();
13461
+ throw new HelperConnectionError(
13462
+ `privileged helper is not reachable at ${socketPath}: ${(lastError == null ? void 0 : lastError.message) ?? "timed out"}`
13463
+ );
13464
+ }
13465
+ function handshake(socketPath, token, callTimeoutMs) {
13466
+ return new Promise((resolve2, reject2) => {
13467
+ void openSocket(socketPath).then((socket) => {
13468
+ let buffer = "";
13469
+ let settled = false;
13470
+ const fail = (error) => {
13471
+ if (settled)
13472
+ return;
13473
+ settled = true;
13474
+ socket.destroy();
13475
+ reject2(error);
13476
+ };
13477
+ const onData = (chunk) => {
13478
+ if (settled)
13479
+ return;
13480
+ const split2 = splitLines(buffer, chunk.toString("utf8"));
13481
+ buffer = split2.rest;
13482
+ const line = split2.lines[0];
13483
+ if (line === void 0)
13484
+ return;
13485
+ let hello;
13486
+ try {
13487
+ hello = JSON.parse(line);
13488
+ } catch (error) {
13489
+ return fail(new HelperConnectionError(`invalid handshake reply: ${error.message}`));
13490
+ }
13491
+ if (hello.type !== "handshake")
13492
+ return fail(new HelperConnectionError("helper did not answer the handshake"));
13493
+ if (!hello.ok)
13494
+ return fail(new HelperConnectionError(hello.reason ?? "helper rejected the handshake"));
13495
+ settled = true;
13496
+ socket.removeListener("data", onData);
13497
+ socket.removeListener("error", onError);
13498
+ const remaining = split2.lines.slice(1);
13499
+ resolve2(createClient(socket, [split2.rest, ...remaining].filter(Boolean).join("\n"), callTimeoutMs));
13500
+ };
13501
+ function onError(error) {
13502
+ fail(error);
13503
+ }
13504
+ socket.on("data", onData);
13505
+ socket.on("error", onError);
13506
+ const greeting = { type: "handshake", token };
13507
+ socket.write(serializeMessage(greeting));
13508
+ }, reject2);
13509
+ });
13510
+ }
13511
+ function createClient(socket, initialBuffer, callTimeoutMs) {
13512
+ let buffer = initialBuffer;
13513
+ let connected = true;
13514
+ let nextId = 1;
13515
+ const pending = /* @__PURE__ */ new Map();
13516
+ const listeners = /* @__PURE__ */ new Set();
13517
+ socket.on("data", (chunk) => {
13518
+ const split2 = splitLines(buffer, chunk.toString("utf8"));
13519
+ buffer = split2.rest;
13520
+ for (const line of split2.lines) {
13521
+ const decoded = decodeMessage(line);
13522
+ if (!decoded.ok)
13523
+ continue;
13524
+ const message = decoded.message;
13525
+ if (!("id" in message)) {
13526
+ for (const listener of listeners)
13527
+ listener(message);
13528
+ continue;
13529
+ }
13530
+ const entry = pending.get(message.id);
13531
+ if (!entry)
13532
+ continue;
13533
+ pending.delete(message.id);
13534
+ clearTimeout(entry.timer);
13535
+ if (message.ok)
13536
+ entry.resolve(message.result);
13537
+ else
13538
+ entry.reject(new Error(message.error.message));
13539
+ }
13695
13540
  });
13696
- function writeCaddyConfig(_proxies) {
13697
- const proxies = configJsonRef() || {};
13698
- _proxies.forEach((p) => {
13699
- let base = p.base || "/";
13700
- if (!base.startsWith("/"))
13701
- base = `/${base}`;
13702
- if (base !== "/" && !base.endsWith("/"))
13703
- base = `${base}/`;
13704
- const index = `${p.target}${p.portSuffix}${base}`;
13705
- proxies[index] = { ...p, base };
13541
+ const disconnect = () => {
13542
+ if (!connected)
13543
+ return;
13544
+ connected = false;
13545
+ for (const [id, entry] of pending) {
13546
+ clearTimeout(entry.timer);
13547
+ pending.delete(id);
13548
+ entry.reject(new HelperConnectionError("privileged helper connection closed"));
13549
+ }
13550
+ };
13551
+ socket.on("close", disconnect);
13552
+ socket.on("error", disconnect);
13553
+ function call(method, params) {
13554
+ if (!connected)
13555
+ return Promise.reject(new HelperConnectionError("privileged helper is not connected"));
13556
+ const id = nextId++;
13557
+ const request = { id, method, params };
13558
+ return new Promise((resolve2, reject2) => {
13559
+ const timer = setTimeout(() => {
13560
+ pending.delete(id);
13561
+ reject2(new HelperConnectionError(`privileged helper did not answer "${method}" in time`));
13562
+ }, callTimeoutMs);
13563
+ pending.set(id, { resolve: resolve2, reject: reject2, timer });
13564
+ socket.write(serializeMessage(request));
13706
13565
  });
13707
- const content = JSON.stringify(proxies, null, 2);
13708
- configContentRef(content);
13709
- return (0, import_node_fs2.writeFileSync)(caddyConfigPath, content);
13710
13566
  }
13711
- async function cleanUp() {
13712
- await (0, import_promises2.unlink)(caddyConfigPath).catch(() => {
13567
+ return {
13568
+ get connected() {
13569
+ return connected;
13570
+ },
13571
+ call,
13572
+ onEvent(listener) {
13573
+ listeners.add(listener);
13574
+ return () => {
13575
+ listeners.delete(listener);
13576
+ };
13577
+ },
13578
+ async close() {
13579
+ disconnect();
13580
+ socket.destroy();
13581
+ }
13582
+ };
13583
+ }
13584
+
13585
+ // src/privileged/windows-elevation.ts
13586
+ var import_node_child_process = require("child_process");
13587
+ var import_node_process5 = __toESM(require("process"), 1);
13588
+ function quotePowerShell(value2) {
13589
+ return `'${value2.replace(/'/g, "''")}'`;
13590
+ }
13591
+ function buildElevationCommand(options) {
13592
+ const argumentList = options.args.map(quotePowerShell).join(",");
13593
+ const parts = [
13594
+ "Start-Process",
13595
+ "-FilePath",
13596
+ quotePowerShell(options.file)
13597
+ ];
13598
+ if (argumentList)
13599
+ parts.push("-ArgumentList", argumentList);
13600
+ if (options.cwd)
13601
+ parts.push("-WorkingDirectory", quotePowerShell(options.cwd));
13602
+ parts.push("-Verb", "RunAs");
13603
+ parts.push("-WindowStyle", "Hidden");
13604
+ return parts.join(" ");
13605
+ }
13606
+ function spawnElevatedOnWindows(options) {
13607
+ return new Promise((resolve2, reject2) => {
13608
+ const script = buildElevationCommand(options);
13609
+ const child = (0, import_node_child_process.spawn)(
13610
+ "powershell.exe",
13611
+ ["-NoProfile", "-NonInteractive", "-Command", script],
13612
+ { stdio: "ignore", windowsHide: true }
13613
+ );
13614
+ child.once("error", reject2);
13615
+ child.once("exit", (code) => {
13616
+ if (code === 0)
13617
+ return resolve2(child);
13618
+ reject2(new Error(
13619
+ `administrator permission was not granted (PowerShell exited with ${code}). Accept the UAC prompt to let the plugin edit the hosts file and bind ports 80/443.`
13620
+ ));
13713
13621
  });
13714
- configContentRef("{}");
13715
- watchCaddyConfig.close();
13622
+ });
13623
+ }
13624
+
13625
+ // src/privileged/launch.ts
13626
+ function createHelperToken() {
13627
+ return (0, import_node_crypto.randomBytes)(24).toString("hex");
13628
+ }
13629
+ function describePasswordReason(target, https) {
13630
+ const port = https ? "443" : "80";
13631
+ return [
13632
+ `reverse proxy needs administrator permission for ${target}`,
13633
+ ` \xB7 bind port ${port}${https ? ` for https://${target}` : ""}`,
13634
+ ` \xB7 add ${target} to the hosts file`,
13635
+ "",
13636
+ "This is the only prompt; the rest of the dev server keeps running as you.",
13637
+ "Press Ctrl+C at the prompt to skip the proxy and keep the dev server."
13638
+ ];
13639
+ }
13640
+ async function authenticateSudo(sudoCommand = "sudo", options = {}) {
13641
+ if ((0, import_node_os3.platform)() === "win32")
13642
+ return { ok: true };
13643
+ if ((0, import_node_child_process2.spawnSync)(sudoCommand, ["-n", "true"], { stdio: "ignore" }).status === 0)
13644
+ return { ok: true };
13645
+ if (options.target && !options.quiet) {
13646
+ for (const line of describePasswordReason(options.target, options.https ?? false))
13647
+ import_node_process6.default.stderr.write(`${line}
13648
+ `);
13649
+ import_node_process6.default.stderr.write("\n");
13716
13650
  }
13717
- return {
13718
- configJsonRef,
13719
- writeCaddyConfig,
13720
- cleanUp
13651
+ let interrupted = false;
13652
+ const onSigint = () => {
13653
+ interrupted = true;
13654
+ };
13655
+ import_node_process6.default.on("SIGINT", onSigint);
13656
+ try {
13657
+ const { status, signal } = await runPrompt(sudoCommand);
13658
+ if (status === 0)
13659
+ return { ok: true };
13660
+ const cancelled = interrupted || signal === "SIGINT";
13661
+ return {
13662
+ ok: false,
13663
+ denied: true,
13664
+ message: cancelled ? "administrator permission was cancelled" : "administrator permission is required to edit the hosts file and bind ports 80/443"
13665
+ };
13666
+ } finally {
13667
+ import_node_process6.default.off("SIGINT", onSigint);
13668
+ }
13669
+ }
13670
+ function runPrompt(sudoCommand) {
13671
+ return new Promise((resolve2) => {
13672
+ const restore = takeBackTerminal();
13673
+ const child = (0, import_node_child_process2.spawn)(sudoCommand, ["-v"], { stdio: "inherit" });
13674
+ const finish = (result) => {
13675
+ restore();
13676
+ resolve2(result);
13677
+ };
13678
+ child.on("error", () => finish({ status: 1, signal: null }));
13679
+ child.on("exit", (status, signal) => finish({ status, signal }));
13680
+ });
13681
+ }
13682
+ function takeBackTerminal() {
13683
+ const stdin = import_node_process6.default.stdin;
13684
+ if (!stdin.isTTY || typeof stdin.setRawMode !== "function")
13685
+ return () => {
13686
+ };
13687
+ const wasRaw = stdin.isRaw === true;
13688
+ stdin.pause();
13689
+ try {
13690
+ stdin.setRawMode(false);
13691
+ } catch {
13692
+ stdin.resume();
13693
+ return () => {
13694
+ };
13695
+ }
13696
+ return () => {
13697
+ if (wasRaw) {
13698
+ try {
13699
+ stdin.setRawMode(true);
13700
+ } catch {
13701
+ }
13702
+ }
13703
+ stdin.resume();
13721
13704
  };
13722
13705
  }
13706
+ var PrivilegeDeniedError = class extends Error {
13707
+ constructor(message) {
13708
+ super(message);
13709
+ this.name = "PrivilegeDeniedError";
13710
+ }
13711
+ };
13712
+ async function startPrivilegedHelper(options) {
13713
+ var _a4, _b3;
13714
+ const {
13715
+ socketPath,
13716
+ token,
13717
+ helperEntry,
13718
+ helperArgs = [],
13719
+ sudoCommand = "sudo",
13720
+ skipAuth = false,
13721
+ direct = false,
13722
+ env: env2 = import_node_process6.default.env,
13723
+ log,
13724
+ connectTimeoutMs = 12e4
13725
+ } = options;
13726
+ if (!skipAuth && !direct) {
13727
+ const auth = await authenticateSudo(sudoCommand, options.reason);
13728
+ if (!auth.ok) {
13729
+ const message = auth.message ?? "administrator permission is required";
13730
+ throw auth.denied ? new PrivilegeDeniedError(message) : new Error(message);
13731
+ }
13732
+ }
13733
+ const forwarded = collectForwardedEnv(env2);
13734
+ const forwardedArgs = Object.entries(forwarded).map(([key, value2]) => `${key}=${value2}`);
13735
+ const childArgv = [
13736
+ ...helperArgs,
13737
+ "--socket",
13738
+ socketPath,
13739
+ "--token",
13740
+ token,
13741
+ ...typeof import_node_process6.default.getuid === "function" ? ["--owner-uid", String(import_node_process6.default.getuid())] : [],
13742
+ ...typeof import_node_process6.default.getgid === "function" ? ["--owner-gid", String(import_node_process6.default.getgid())] : [],
13743
+ ...options.caddyStoragePath ? ["--caddy-storage", options.caddyStoragePath] : [],
13744
+ "--caddy",
13745
+ options.caddyBin,
13746
+ "--caddy-config",
13747
+ options.caddyConfigPath,
13748
+ ...options.caddyAdminSocket ? ["--caddy-admin", options.caddyAdminSocket] : []
13749
+ ];
13750
+ let child;
13751
+ if (!direct && (0, import_node_os3.platform)() === "win32") {
13752
+ await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: import_node_process6.default.cwd() });
13753
+ } else {
13754
+ const command = direct ? helperEntry : sudoCommand;
13755
+ const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
13756
+ child = (0, import_node_child_process2.spawn)(command, spawnArgs, {
13757
+ stdio: ["ignore", "pipe", "pipe"]
13758
+ });
13759
+ (_a4 = child.stdout) == null ? void 0 : _a4.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13760
+ (_b3 = child.stderr) == null ? void 0 : _b3.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13761
+ const exited = new Promise((resolve2) => child.once("exit", (code) => resolve2(code)));
13762
+ const earlyExit = await Promise.race([
13763
+ exited,
13764
+ new Promise((resolve2) => setTimeout(() => resolve2(void 0), 500))
13765
+ ]);
13766
+ if (earlyExit !== void 0 && earlyExit !== 0) {
13767
+ throw new Error(
13768
+ `privileged helper exited with code ${earlyExit}. Administrator permission was refused, or sudo is not available.`
13769
+ );
13770
+ }
13771
+ }
13772
+ try {
13773
+ const client = await connectClient({ socketPath, token, timeoutMs: connectTimeoutMs });
13774
+ return {
13775
+ client,
13776
+ async close() {
13777
+ await client.close().catch(() => {
13778
+ });
13779
+ child == null ? void 0 : child.unref();
13780
+ }
13781
+ };
13782
+ } catch (error) {
13783
+ try {
13784
+ child == null ? void 0 : child.kill();
13785
+ } catch {
13786
+ }
13787
+ throw error;
13788
+ }
13789
+ }
13790
+ async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
13791
+ try {
13792
+ return await connectClient({ socketPath, token, timeoutMs });
13793
+ } catch {
13794
+ return void 0;
13795
+ }
13796
+ }
13723
13797
 
13724
- // src/caddy/log.ts
13725
- function isCaddyReloadCancellation(line) {
13798
+ // src/privileged/session.ts
13799
+ function tokenPath(runtimeDir) {
13800
+ return (0, import_node_path3.join)(runtimeDir, "helper.token");
13801
+ }
13802
+ function sessionSocketPath(runtimeDir) {
13803
+ if ((0, import_node_os4.platform)() === "win32")
13804
+ return `\\\\.\\pipe\\uhrp-${import_node_buffer.Buffer.from(runtimeDir).toString("hex").slice(0, 40)}`;
13805
+ return (0, import_node_path3.join)(runtimeDir, "helper.sock");
13806
+ }
13807
+ async function openHelperSession(scope2) {
13808
+ const socketPath = sessionSocketPath(scope2.runtimeDir);
13809
+ const release = await acquireStartLock(scope2.runtimeDir);
13726
13810
  try {
13727
- const entry = JSON.parse(line);
13728
- return entry.logger === "tls" && typeof entry.error === "string" && entry.error.endsWith("context canceled");
13811
+ const reused = await tryReuse(socketPath, scope2);
13812
+ if (reused)
13813
+ return reused;
13814
+ return await startNew(socketPath, scope2);
13815
+ } finally {
13816
+ release();
13817
+ }
13818
+ }
13819
+ async function tryReuse(socketPath, scope2) {
13820
+ if (!(0, import_node_fs3.existsSync)(socketPath) && (0, import_node_os4.platform)() !== "win32")
13821
+ return void 0;
13822
+ const token = await readToken(scope2.runtimeDir);
13823
+ if (!token)
13824
+ return void 0;
13825
+ const reused = await connectExistingHelper(socketPath, token);
13826
+ if (!reused)
13827
+ return void 0;
13828
+ return {
13829
+ client: reused,
13830
+ reused: true,
13831
+ close: async () => {
13832
+ await reused.close();
13833
+ }
13834
+ };
13835
+ }
13836
+ async function startNew(socketPath, scope2) {
13837
+ const token = createHelperToken();
13838
+ const started = await startPrivilegedHelper({
13839
+ socketPath,
13840
+ token,
13841
+ helperEntry: scope2.helperEntry,
13842
+ helperArgs: scope2.helperArgs,
13843
+ sudoCommand: scope2.sudoCommand,
13844
+ skipAuth: scope2.skipAuth,
13845
+ direct: scope2.direct,
13846
+ env: scope2.env,
13847
+ caddyStoragePath: scope2.caddyStoragePath,
13848
+ caddyBin: scope2.caddyBin,
13849
+ caddyConfigPath: scope2.caddyConfigPath,
13850
+ caddyAdminSocket: scope2.caddyAdminSocket,
13851
+ reason: scope2.reason,
13852
+ log: scope2.log
13853
+ });
13854
+ await writeToken(scope2.runtimeDir, token);
13855
+ return {
13856
+ client: started.client,
13857
+ reused: false,
13858
+ close: async () => {
13859
+ await started.close();
13860
+ }
13861
+ };
13862
+ }
13863
+ async function acquireStartLock(runtimeDir) {
13864
+ const lockPath = (0, import_node_path3.join)(runtimeDir, "helper.start.lock");
13865
+ try {
13866
+ await (0, import_promises.writeFile)(lockPath, "", { flag: "a" });
13729
13867
  } catch {
13730
- return false;
13731
13868
  }
13869
+ const release = await lockfile2.lock(lockPath, {
13870
+ realpath: false,
13871
+ stale: 3e4,
13872
+ retries: { retries: 100, minTimeout: 50, maxTimeout: 200 }
13873
+ });
13874
+ return () => {
13875
+ void release().catch(() => {
13876
+ });
13877
+ };
13878
+ }
13879
+ async function readToken(runtimeDir) {
13880
+ try {
13881
+ const content = await (0, import_promises.readFile)(tokenPath(runtimeDir), "utf8");
13882
+ const token = content.trim();
13883
+ return token === "" ? void 0 : token;
13884
+ } catch {
13885
+ return void 0;
13886
+ }
13887
+ }
13888
+ async function writeToken(runtimeDir, token) {
13889
+ try {
13890
+ await (0, import_promises.writeFile)(tokenPath(runtimeDir), token, { mode: 384 });
13891
+ } catch {
13892
+ }
13893
+ }
13894
+
13895
+ // src/caddy/privileged.ts
13896
+ var import_meta = {};
13897
+ function resolvePrivilegedEnv() {
13898
+ const moduleDir = typeof __dirname === "string" ? __dirname : (0, import_node_path4.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
13899
+ const resolved = resolveHelperEntry({ moduleDir });
13900
+ return { helperEntry: resolved.entry, helperArgs: resolved.args };
13901
+ }
13902
+ var HelperCaddyProcess = class extends import_node_events.EventEmitter {
13903
+ constructor(client) {
13904
+ super();
13905
+ this.client = client;
13906
+ this.stdout = new import_node_events.EventEmitter();
13907
+ this.stderr = new import_node_events.EventEmitter();
13908
+ this.finished = false;
13909
+ this.unsubscribe = client.onEvent((event) => this.handleEvent(event));
13910
+ }
13911
+ handleEvent(event) {
13912
+ if (event.type !== "event")
13913
+ return;
13914
+ if (event.kind === "caddy.stdout") {
13915
+ this.stdout.emit("data", import_node_buffer2.Buffer.from(event.data));
13916
+ return;
13917
+ }
13918
+ if (event.kind === "caddy.stderr") {
13919
+ this.stderr.emit("data", import_node_buffer2.Buffer.from(event.data));
13920
+ return;
13921
+ }
13922
+ if (event.kind === "caddy.exit") {
13923
+ this.finished = true;
13924
+ this.emit("exit", event.code, event.signal);
13925
+ }
13926
+ }
13927
+ /** Asks the helper to stop Caddy; the helper also stops it on disconnect. */
13928
+ kill() {
13929
+ this.unsubscribe();
13930
+ if (this.finished)
13931
+ return;
13932
+ this.finished = true;
13933
+ void this.client.call("caddy.stop").catch(() => {
13934
+ });
13935
+ }
13936
+ };
13937
+ function caddyStoragePath() {
13938
+ return import_node_process7.default.platform === "win32" ? (0, import_node_path4.join)(import_node_process7.default.env.AppData ?? "", "Caddy") : (0, import_node_path4.join)(import_node_process7.default.env.HOME ?? "", "Library/Application Support/Caddy");
13939
+ }
13940
+ function openPrivilegedSession(runtimeDir, options) {
13941
+ const env2 = resolvePrivilegedEnv();
13942
+ return openHelperSession({
13943
+ runtimeDir,
13944
+ helperEntry: env2.helperEntry,
13945
+ helperArgs: env2.helperArgs,
13946
+ direct: options.direct,
13947
+ // Caddy keeps its PKI under the user's home; the helper runs it as root, so
13948
+ // it must know which tree to hand back afterwards.
13949
+ caddyStoragePath: caddyStoragePath(),
13950
+ // The binary and Caddyfile are fixed here: the privileged helper must never
13951
+ // execute a path supplied over the socket.
13952
+ caddyBin: options.caddyBin,
13953
+ caddyConfigPath: options.caddyConfigPath,
13954
+ caddyAdminSocket: options.caddyAdminSocket,
13955
+ reason: options.reason,
13956
+ log: options.log
13957
+ });
13732
13958
  }
13733
13959
 
13734
13960
  // src/caddy/tls-health.ts
@@ -13813,40 +14039,8 @@ function formatTlsHealthFailure(hostname, result) {
13813
14039
  }
13814
14040
 
13815
14041
  // src/caddy/utils.ts
13816
- var import_node_child_process3 = require("child_process");
13817
- var import_node_net = require("net");
13818
14042
  var import_ora = __toESM(require("ora"), 1);
13819
14043
  var spinner;
13820
- function tryPort(port) {
13821
- return new Promise((resolve2, _reject) => {
13822
- try {
13823
- const server = (0, import_node_net.createServer)().listen(port);
13824
- server.on("listening", () => {
13825
- server.close();
13826
- resolve2(false);
13827
- });
13828
- server.on("error", (err) => {
13829
- if (err.code === "EADDRINUSE")
13830
- resolve2(true);
13831
- server.close();
13832
- });
13833
- } catch {
13834
- resolve2(true);
13835
- }
13836
- });
13837
- }
13838
- async function kill(port) {
13839
- return new Promise((resolve2, reject2) => {
13840
- (0, import_node_child_process3.exec)(`npx @maxbo/free-port ${port} -s`, (err, stdout, _stderr) => {
13841
- if (err) {
13842
- reject2(err);
13843
- } else {
13844
- consola.log(stdout);
13845
- resolve2();
13846
- }
13847
- });
13848
- });
13849
- }
13850
14044
  function getNumber(number2) {
13851
14045
  if (number2 <= 0)
13852
14046
  return "0%";
@@ -13885,26 +14079,26 @@ async function download() {
13885
14079
  if (await testCaddy())
13886
14080
  return caddyPath;
13887
14081
  return new Promise((resolve2, reject2) => {
13888
- if (!(0, import_node_fs3.existsSync)(TEMP_DIR)) {
13889
- (0, import_node_fs3.mkdirSync)(TEMP_DIR, { recursive: true });
13890
- (0, import_node_fs3.chmodSync)(TEMP_DIR, 511);
14082
+ if (!(0, import_node_fs4.existsSync)(TEMP_DIR)) {
14083
+ (0, import_node_fs4.mkdirSync)(TEMP_DIR, { recursive: true });
14084
+ (0, import_node_fs4.chmodSync)(TEMP_DIR, 448);
13891
14085
  }
13892
- const file = (0, import_node_fs3.createWriteStream)(caddyPath);
13893
- let _platform = (0, import_node_os3.platform)().toString();
14086
+ const file = (0, import_node_fs4.createWriteStream)(caddyPath);
14087
+ let _platform = (0, import_node_os5.platform)().toString();
13894
14088
  _platform === "win32" && (_platform = "windows");
13895
- let _arch = import_node_process4.default.arch.toString();
14089
+ let _arch = import_node_process8.default.arch.toString();
13896
14090
  _arch === "x64" && (_arch = "amd64");
13897
14091
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
13898
14092
  if (!support)
13899
14093
  return reject2(new Error("not support"));
13900
14094
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
13901
- (0, import_node_fs3.existsSync)(caddyPath) && (0, import_node_fs3.unlinkSync)(caddyPath);
13902
- const httpProxy = import_node_process4.default.env.HTTP_PROXY || import_node_process4.default.env.http_proxy;
13903
- const httpsProxy = import_node_process4.default.env.HTTPS_PROXY || import_node_process4.default.env.https_proxy;
14095
+ (0, import_node_fs4.existsSync)(caddyPath) && (0, import_node_fs4.unlinkSync)(caddyPath);
14096
+ const httpProxy = import_node_process8.default.env.HTTP_PROXY || import_node_process8.default.env.http_proxy;
14097
+ const httpsProxy = import_node_process8.default.env.HTTPS_PROXY || import_node_process8.default.env.https_proxy;
13904
14098
  const httpAgent = httpProxy ? new import_http_proxy_agent.HttpProxyAgent(httpProxy) : void 0;
13905
14099
  const httpsAgent = httpsProxy ? new import_https_proxy_agent.HttpsProxyAgent(httpsProxy) : void 0;
13906
14100
  const chmodCaddyOnce = once(() => {
13907
- (0, import_node_fs3.chmodSync)(caddyPath, 511);
14101
+ (0, import_node_fs4.chmodSync)(caddyPath, 493);
13908
14102
  });
13909
14103
  import_got_cjs.got.stream(dowmloadLink, {
13910
14104
  agent: {
@@ -13916,9 +14110,9 @@ async function download() {
13916
14110
  chmodCaddyOnce();
13917
14111
  }).pipe(file).on("finish", () => {
13918
14112
  logProgressOver();
13919
- if (import_node_process4.default.platform === "win32")
14113
+ if (import_node_process8.default.platform === "win32")
13920
14114
  return resolve2(caddyPath);
13921
- (0, import_node_fs3.chmodSync)(caddyPath, 511);
14115
+ (0, import_node_fs4.chmodSync)(caddyPath, 493);
13922
14116
  resolve2(caddyPath);
13923
14117
  }).on("error", (err) => {
13924
14118
  reject2(err);
@@ -13926,26 +14120,41 @@ async function download() {
13926
14120
  });
13927
14121
  }
13928
14122
  function testCaddy() {
13929
- return new Promise((resolve2, reject2) => {
13930
- if (!(0, import_node_fs3.existsSync)(caddyPath))
13931
- return resolve2(false);
13932
- (0, import_node_fs3.chmodSync)(caddyPath, 511);
13933
- const child = import_node_process4.default.platform === "win32" ? (0, import_node_child_process4.spawn)(caddyPath, []) : (0, import_node_child_process4.spawn)("sudo", ["-E", caddyPath]);
13934
- child.on("close", () => {
14123
+ return new Promise((resolve2) => {
14124
+ if (!(0, import_node_fs4.existsSync)(caddyPath))
13935
14125
  return resolve2(false);
14126
+ try {
14127
+ (0, import_node_fs4.chmodSync)(caddyPath, 493);
14128
+ } catch {
14129
+ }
14130
+ (0, import_node_child_process3.execFile)(caddyPath, [], { timeout: 1e4 }, (error, stdout) => {
14131
+ if (error && !stdout)
14132
+ return resolve2(false);
14133
+ resolve2(stdout.length > 0);
13936
14134
  });
13937
- child.on("error", (err) => {
13938
- return reject2(err);
13939
- });
13940
- child.stdout.on("data", (_data) => {
13941
- return resolve2(true);
13942
- });
13943
14135
  });
13944
14136
  }
14137
+ function caddyRootPath() {
14138
+ return (0, import_node_path5.join)(
14139
+ import_node_process8.default.platform === "win32" ? `${import_node_process8.default.env.AppData}/Caddy` : `${import_node_process8.default.env.HOME}/Library/Application Support/Caddy`,
14140
+ "./pki/authorities/local"
14141
+ );
14142
+ }
14143
+ async function renderCaddyfile(proxies) {
14144
+ const ctx = validateTemplateContext({
14145
+ caddy_root: caddyRootPath(),
14146
+ admin_socket: caddyAdminSocketPath,
14147
+ proxies: Object.values(proxies)
14148
+ });
14149
+ const content = await genCaddyfile(ctx);
14150
+ const temp = `${caddyFilePath}.${import_node_process8.default.pid}.tmp`;
14151
+ await (0, import_promises2.writeFile)(temp, content);
14152
+ await (0, import_promises2.rename)(temp, caddyFilePath);
14153
+ }
13945
14154
  var caddyConfig;
13946
14155
  function getCaddyConfig() {
13947
14156
  if (!caddyConfig) {
13948
- caddyConfig = useCaddyConfig();
14157
+ caddyConfig = useCaddyConfig({ renderCaddyfile });
13949
14158
  }
13950
14159
  return caddyConfig;
13951
14160
  }
@@ -13960,80 +14169,92 @@ function splitHostPort(addr) {
13960
14169
  }
13961
14170
  return { host: addr.slice(0, lastColon), port: addr.slice(lastColon + 1) };
13962
14171
  }
14172
+ var defaultDependencies = {
14173
+ openSession: (runtimeDir, reason) => openPrivilegedSession(runtimeDir, {
14174
+ log: (message) => consola.debug(message),
14175
+ // Both paths are fixed here, before any socket traffic: the privileged
14176
+ // helper must never execute something named in a request.
14177
+ caddyBin: caddyPath,
14178
+ caddyConfigPath: caddyFilePath,
14179
+ caddyAdminSocket: caddyAdminSocketPath,
14180
+ reason
14181
+ }),
14182
+ config: () => getCaddyConfig()
14183
+ };
13963
14184
  var CaddyInstant = class {
13964
- constructor() {
14185
+ constructor(deps = {}) {
13965
14186
  this.inited = false;
13966
14187
  this.stoped = false;
13967
- /** has locked when start */
13968
- this.locked = false;
13969
14188
  this._stopEffects = [];
13970
- testCaddy().then(async () => {
13971
- this.inited = true;
13972
- });
13973
- this.locked = this.checkLock();
14189
+ /** Identifies this instance's routes in the shared config. */
14190
+ this.proxyKey = `${import_node_process8.default.pid}-${Math.random().toString(36).slice(2, 8)}`;
14191
+ this.deps = { ...defaultDependencies, ...deps };
13974
14192
  }
13975
- checkLock() {
13976
- if (!(0, import_node_fs3.existsSync)(caddyLockFilePath))
13977
- (0, import_node_fs3.writeFileSync)(caddyLockFilePath, "");
13978
- return lockfile.checkSync(caddyLockFilePath);
14193
+ /**
14194
+ * Connects to the privileged helper, starting it once if needed. It is
14195
+ * reused across instances so a second dev server does not ask for a
14196
+ * password again.
14197
+ */
14198
+ async session(reason) {
14199
+ if (this._session && !this._session.client.connected)
14200
+ this._session = void 0;
14201
+ if (!this._session)
14202
+ this._session = await this.deps.openSession(TEMP_DIR, reason);
14203
+ return this._session;
13979
14204
  }
13980
14205
  async getCaddyfile() {
13981
- if (!(0, import_node_fs3.existsSync)(caddyFilePath)) {
14206
+ if (!(0, import_node_fs4.existsSync)(caddyFilePath)) {
13982
14207
  this.caddyfile = "";
13983
14208
  return "";
13984
14209
  }
13985
- this.caddyfile = await (0, import_promises3.readFile)(caddyFilePath, "utf-8");
14210
+ this.caddyfile = await (0, import_promises2.readFile)(caddyFilePath, "utf-8");
13986
14211
  return this.caddyfile;
13987
14212
  }
13988
14213
  get caddyRoot() {
13989
- return (0, import_node_path3.join)(
13990
- import_node_process4.default.platform === "win32" ? `${import_node_process4.default.env.AppData}/Caddy` : `${import_node_process4.default.env.HOME}/Library/Application Support/Caddy`,
13991
- "./pki/authorities/local"
13992
- );
14214
+ return caddyRootPath();
13993
14215
  }
13994
14216
  async writeCaddyfile() {
13995
- return await (0, import_promises3.writeFile)(caddyFilePath, this.caddyfile || "");
14217
+ return await (0, import_promises2.writeFile)(caddyFilePath, this.caddyfile || "");
13996
14218
  }
13997
14219
  async deleteCaddyfile() {
13998
- return await (0, import_promises3.unlink)(caddyFilePath);
14220
+ return await (0, import_promises2.unlink)(caddyFilePath);
13999
14221
  }
14000
14222
  async init() {
14001
14223
  await download();
14002
14224
  this.inited = true;
14003
14225
  }
14226
+ /**
14227
+ * Hands the Caddy storage directory back to the developer. Local CA data
14228
+ * created by an earlier root-owned run must stay readable for `tls internal`
14229
+ * to keep serving the same certificate the browser already trusts.
14230
+ */
14231
+ /**
14232
+ * Installs Caddy's local root CA so the browser stops warning about
14233
+ * `tls internal` certificates. Generating the CA and trusting it are separate
14234
+ * steps: a new CA appears whenever the previous one expires or the storage is
14235
+ * replaced, so this runs on every start instead of once.
14236
+ *
14237
+ * The helper owns both the binary path and the command, so nothing here can
14238
+ * be turned into an arbitrary root execution.
14239
+ */
14240
+ async trustLocalCa(session) {
14241
+ try {
14242
+ const result = await session.client.call("ca.trust");
14243
+ if (result.trusted)
14244
+ consola.debug(`Caddy local CA is trusted
14245
+ ${result.output}`);
14246
+ } catch (error) {
14247
+ consola.warn(
14248
+ `could not install the Caddy root certificate automatically: ${error.message}
14249
+ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14250
+ );
14251
+ }
14252
+ }
14004
14253
  async ensureTlsReady(targetHost) {
14005
14254
  const health = await waitForLocalTls(targetHost);
14006
14255
  if (!health.healthy)
14007
14256
  throw new Error(formatTlsHealthFailure(targetHost, health));
14008
14257
  }
14009
- async updateCaddyfile() {
14010
- const { configJsonRef } = getCaddyConfig();
14011
- const proxies = Object.values(configJsonRef() || {});
14012
- const ctx = validateTemplateContext({
14013
- caddy_root: this.caddyRoot,
14014
- proxies
14015
- });
14016
- this.caddyfile = await genCaddyfile(ctx);
14017
- await this.writeCaddyfile();
14018
- }
14019
- async stopCaddy() {
14020
- var _a4;
14021
- try {
14022
- await import_got_cjs.got.post("http://127.0.0.1:2019/stop", {
14023
- headers: {
14024
- Origin: "http://localhost:2019"
14025
- },
14026
- retry: {
14027
- limit: 0
14028
- },
14029
- timeout: {
14030
- request: 2e3
14031
- }
14032
- });
14033
- } catch {
14034
- }
14035
- (_a4 = this._caddyChild) == null ? void 0 : _a4.kill();
14036
- }
14037
14258
  /**
14038
14259
  * @param source like `127.0.0.1:8080`
14039
14260
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
@@ -14054,10 +14275,10 @@ var CaddyInstant = class {
14054
14275
  await this.init();
14055
14276
  const sourceHost = splitHostPort(source).host;
14056
14277
  const targetHost = splitHostPort(target).host;
14057
- if (!await addHost(sourceHost, targetHost))
14058
- throw new Error("update host failed");
14278
+ const session = await this.session({ target: targetHost, https });
14279
+ await session.client.call("hosts.add", { ip: sourceHost, host: targetHost });
14059
14280
  consola.success("update host success\n");
14060
- const normalizeBase = (b) => {
14281
+ const normalizeBase2 = (b) => {
14061
14282
  let out = b || "/";
14062
14283
  if (!out.startsWith("/"))
14063
14284
  out = `/${out}`;
@@ -14065,7 +14286,7 @@ var CaddyInstant = class {
14065
14286
  out = `${out}/`;
14066
14287
  return out;
14067
14288
  };
14068
- const baseNormalized = normalizeBase(base);
14289
+ const baseNormalized = normalizeBase2(base);
14069
14290
  const proxies = [
14070
14291
  {
14071
14292
  target: targetHost,
@@ -14076,176 +14297,138 @@ var CaddyInstant = class {
14076
14297
  healthCheck
14077
14298
  }
14078
14299
  ];
14079
- const { writeCaddyConfig } = getCaddyConfig();
14080
- writeCaddyConfig(proxies);
14081
- await this.updateCaddyfile();
14082
- let skipInitialCaddyfileEffect = true;
14083
- this._stopEffects.push(
14084
- effect(() => {
14085
- getCaddyConfig().configJsonRef();
14086
- if (skipInitialCaddyfileEffect) {
14087
- skipInitialCaddyfileEffect = false;
14088
- return;
14089
- }
14090
- void this.updateCaddyfile();
14091
- })
14092
- );
14093
- if (!(0, import_node_fs3.existsSync)(caddyLockFilePath))
14094
- (0, import_node_fs3.writeFileSync)(caddyLockFilePath, "");
14095
- if (!this.locked) {
14096
- if (await tryPort(443))
14097
- await kill(443);
14098
- if ((import_node_process4.default.platform === "win32" || !https) && await tryPort(80))
14099
- await kill(80);
14100
- }
14300
+ const { writeCaddyConfig } = this.deps.config();
14301
+ await writeCaddyConfig(proxies, this.proxyKey);
14302
+ await session.client.call("port.free", { port: 443 });
14303
+ if (import_node_process8.default.platform === "win32" || !https)
14304
+ await session.client.call("port.free", { port: 80 });
14101
14305
  return new Promise((resolve2, reject2) => {
14102
- var _a4, _b3;
14103
14306
  let startupCheckStarted = false;
14104
14307
  const resolveWhenReady = async () => {
14105
14308
  if (startupCheckStarted)
14106
14309
  return;
14107
14310
  startupCheckStarted = true;
14108
14311
  try {
14109
- if (https)
14312
+ if (https) {
14313
+ await this.trustLocalCa(session);
14110
14314
  await this.ensureTlsReady(targetHost);
14315
+ }
14111
14316
  resolve2();
14112
14317
  } catch (error) {
14113
- if (!this.locked)
14114
- await this.baseCleanup(restore);
14318
+ await this.baseCleanup(restore);
14115
14319
  reject2(error);
14116
14320
  }
14117
14321
  };
14118
14322
  const setupCleanup = () => {
14119
- import_node_process4.default.on("SIGINT", async () => {
14323
+ import_node_process8.default.on("SIGINT", async () => {
14120
14324
  if (this.stoped)
14121
14325
  return;
14122
- import_node_process4.default.stdin.resume();
14326
+ import_node_process8.default.stdin.resume();
14123
14327
  try {
14124
14328
  await this.baseCleanup(restore);
14125
14329
  } finally {
14126
14330
  this.stoped = true;
14127
- import_node_process4.default.nextTick(() => {
14128
- import_node_process4.default.exit();
14331
+ import_node_process8.default.nextTick(() => {
14332
+ import_node_process8.default.exit();
14129
14333
  });
14130
14334
  }
14131
14335
  });
14132
- const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
14133
- import_node_process4.default.exit = async (code) => {
14134
- const port = Number(splitHostPort(source).port);
14135
- if (!Number.isNaN(port) && await tryPort(port))
14136
- await kill(port);
14137
- const pwd = import_node_process4.default.cwd();
14138
- const viteCacheDir = `${pwd}/node_modules/.vite`;
14139
- if ((0, import_node_fs3.existsSync)(viteCacheDir))
14140
- await chmodRecursive(viteCacheDir, 511).catch(() => {
14141
- });
14142
- const viteTempCacheDir = `${pwd}/node_modules/.vite-temp`;
14143
- if ((0, import_node_fs3.existsSync)(viteTempCacheDir))
14144
- await chmodRecursive(viteTempCacheDir, 511).catch(() => {
14145
- });
14146
- const nuxtCacheDir = `${pwd}/.nuxt`;
14147
- if ((0, import_node_fs3.existsSync)(nuxtCacheDir))
14148
- await chmodRecursive(nuxtCacheDir, 511).catch(() => {
14149
- });
14150
- const webpackCacheDir = `${pwd}/node_modules/.cache`;
14151
- if ((0, import_node_fs3.existsSync)(webpackCacheDir))
14152
- await chmodRecursive(webpackCacheDir, 511).catch(() => {
14153
- });
14336
+ const originalExit = import_node_process8.default.exit.bind(import_node_process8.default);
14337
+ import_node_process8.default.exit = async (code) => {
14154
14338
  if (this.stoped)
14155
14339
  return originalExit(code);
14156
- import_node_process4.default.stdin.resume();
14340
+ import_node_process8.default.stdin.resume();
14157
14341
  try {
14158
14342
  await this.baseCleanup();
14159
14343
  } finally {
14160
14344
  this.stoped = true;
14161
- import_node_process4.default.nextTick(() => {
14345
+ import_node_process8.default.nextTick(() => {
14162
14346
  originalExit(code);
14163
14347
  });
14164
14348
  }
14165
14349
  };
14166
14350
  };
14167
- if (!this.locked) {
14168
- this._caddyChild = import_node_process4.default.platform !== "win32" ? (0, import_node_child_process4.spawn)("sudo", ["-E", caddyPath, "run", "--config", caddyFilePath, "--watch"]) : (0, import_node_child_process4.spawn)(caddyPath, ["run", "--config", caddyFilePath, "--watch"]);
14169
- lockfile.lockSync(caddyLockFilePath);
14170
- this._caddyChild.on("error", (err) => {
14171
- return reject2(err);
14172
- });
14173
- (_a4 = this._caddyChild.stderr) == null ? void 0 : _a4.on("data", async (data) => {
14174
- const lines = data.toString().split("\n").map((line) => line.trim());
14175
- for (const line of lines) {
14176
- showCaddyLog && line && console.info(line);
14177
- if (isCaddyReloadCancellation(line)) {
14178
- consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14179
- continue;
14180
- }
14181
- try {
14182
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14183
- if (line.includes("parsing caddyfile tokens")) {
14184
- consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14351
+ setupCleanup();
14352
+ void (async () => {
14353
+ try {
14354
+ const child = new HelperCaddyProcess(session.client);
14355
+ this._caddyChild = child;
14356
+ const started = await session.client.call("caddy.start");
14357
+ child.on("exit", (code) => {
14358
+ if (code !== null && code !== 0)
14359
+ reject2(new Error(`Caddy exited with code ${code}`));
14360
+ });
14361
+ if ((started == null ? void 0 : started.started) === false) {
14362
+ consola.info("Caddy is already running; added this route to it.");
14363
+ void resolveWhenReady();
14364
+ return;
14365
+ }
14366
+ child.stderr.on("data", async (data) => {
14367
+ const lines = data.toString().split("\n").map((line) => line.trim());
14368
+ for (const line of lines) {
14369
+ showCaddyLog && line && console.info(line);
14370
+ if (isCaddyReloadCancellation(line)) {
14371
+ consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14372
+ continue;
14373
+ }
14374
+ try {
14375
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14376
+ if (line.includes("parsing caddyfile tokens")) {
14377
+ consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14185
14378
 
14186
14379
  ${line}
14187
14380
  `);
14188
- await this.baseCleanup();
14189
- import_node_process4.default.exit();
14190
- } else {
14191
- consola.error(`${line}
14381
+ await this.baseCleanup();
14382
+ import_node_process8.default.exit();
14383
+ } else {
14384
+ consola.error(`${line}
14192
14385
  `);
14193
- return reject2(line);
14386
+ return reject2(line);
14387
+ }
14194
14388
  }
14389
+ } catch {
14195
14390
  }
14196
- } catch {
14391
+ if (line.includes("config file changed"))
14392
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
14393
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
14394
+ void resolveWhenReady();
14197
14395
  }
14198
- if (line.includes("config file changed"))
14199
- consola.success("Detect added a new reverse proxy config, restarted.\n");
14200
- if (line.includes("caddy proxying") || line.includes("serving initial"))
14201
- void resolveWhenReady();
14202
- }
14203
- });
14204
- (_b3 = this._caddyChild.stdout) == null ? void 0 : _b3.on("data", (_data) => {
14205
- consola.info(_data.toString());
14206
- void resolveWhenReady();
14207
- });
14208
- setupCleanup();
14209
- } else {
14210
- consola.info("Caddy is running in another process.");
14211
- void (async () => {
14212
- try {
14213
- if (https)
14214
- await this.ensureTlsReady(targetHost);
14215
- setupCleanup();
14216
- resolve2();
14217
- } catch (error) {
14218
- reject2(error);
14219
- }
14220
- })();
14221
- }
14396
+ });
14397
+ child.stdout.on("data", (data) => {
14398
+ consola.info(data.toString());
14399
+ void resolveWhenReady();
14400
+ });
14401
+ } catch (error) {
14402
+ await this.baseCleanup(restore);
14403
+ reject2(error);
14404
+ }
14405
+ })();
14222
14406
  });
14223
14407
  }
14224
14408
  async baseCleanup(restore = true) {
14409
+ var _a4;
14225
14410
  this._stopEffects.forEach((fn) => fn());
14411
+ this._stopEffects.length = 0;
14226
14412
  try {
14227
- if (restore && this._source && this._target) {
14228
- if (await removeHost(splitHostPort(this._source).host, splitHostPort(this._target).host))
14229
- consola.success("Restore host success.\n");
14230
- else
14231
- consola.fail("Restore host failed.\n");
14413
+ if (restore && this._source && this._target && this._session) {
14414
+ const sourceHost = splitHostPort(this._source).host;
14415
+ const targetHost = splitHostPort(this._target).host;
14416
+ await this._session.client.call("hosts.remove", { ip: sourceHost, host: targetHost });
14417
+ if (sourceHost === "localhost")
14418
+ await this._session.client.call("hosts.remove", { ip: "127.0.0.1", host: targetHost });
14419
+ consola.success("Restore host success.\n");
14232
14420
  }
14233
14421
  } catch (e) {
14234
- consola.error(e);
14235
- consola.fail("Restore host failed.\n");
14422
+ if (((_a4 = this._session) == null ? void 0 : _a4.client.connected) === false) {
14423
+ consola.debug("hosts entries are restored by the privileged helper on disconnect");
14424
+ } else {
14425
+ consola.error(e);
14426
+ consola.fail("Restore host failed.\n");
14427
+ }
14236
14428
  }
14237
- if (!this.locked && !this.stoped) {
14238
- await this.stopCaddy();
14429
+ if (!this.stoped) {
14239
14430
  try {
14240
- await lockfile.unlock(caddyLockFilePath).catch(() => {
14241
- });
14242
- await (0, import_promises3.unlink)(caddyFilePath).catch(() => {
14243
- });
14244
- await (0, import_promises3.unlink)(caddyLockFilePath).catch(() => {
14245
- });
14246
- if (caddyConfig) {
14247
- await caddyConfig.cleanUp();
14248
- }
14431
+ await this.deps.config().removeProxy(this.proxyKey);
14249
14432
  } catch (e) {
14250
14433
  consola.error(e);
14251
14434
  }
@@ -14487,11 +14670,20 @@ var hmrSseBridgeClientScript = `
14487
14670
  })();
14488
14671
  `;
14489
14672
 
14673
+ // src/privilege-state.ts
14674
+ var denied = false;
14675
+ function markPrivilegeDenied() {
14676
+ denied = true;
14677
+ }
14678
+ function isPrivilegeDenied() {
14679
+ return denied;
14680
+ }
14681
+
14490
14682
  // src/index.ts
14491
14683
  var config;
14492
14684
  var caddy;
14493
14685
  var hmrSseBridgeActive = false;
14494
- var cwd = import_node_process5.default.cwd();
14686
+ var cwd = import_node_process9.default.cwd();
14495
14687
  function colorUrl(url2) {
14496
14688
  return import_picocolors2.default.green(url2.replace(/:(\d+)\//, (_, port) => `:${import_picocolors2.default.bold(port)}/`));
14497
14689
  }
@@ -14526,16 +14718,27 @@ async function printForwardProxy() {
14526
14718
  }
14527
14719
  var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
14528
14720
  _printUrls == null ? void 0 : _printUrls();
14721
+ if (isPrivilegeDenied())
14722
+ return;
14529
14723
  if (caddy)
14530
14724
  return;
14531
- caddy = new CaddyInstant();
14532
- caddy.run(source, target, {
14725
+ const instance = new CaddyInstant();
14726
+ caddy = instance;
14727
+ instance.run(source, target, {
14533
14728
  base,
14534
14729
  ...options
14535
14730
  }).then(async () => {
14536
14731
  await printForwardProxy();
14537
14732
  consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14538
14733
  }).catch((e) => {
14734
+ if (caddy === instance)
14735
+ caddy = void 0;
14736
+ if (e instanceof PrivilegeDeniedError) {
14737
+ markPrivilegeDenied();
14738
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14739
+ consola.info("Restart the dev server to enable it again.");
14740
+ return;
14741
+ }
14539
14742
  throw e;
14540
14743
  });
14541
14744
  });
@@ -14556,10 +14759,6 @@ var unpluginFactory = (options) => ({
14556
14759
  } = options;
14557
14760
  if (!enable)
14558
14761
  return;
14559
- if (!isAdmin()) {
14560
- consola.warn("please run as administrator");
14561
- return;
14562
- }
14563
14762
  if (!target) {
14564
14763
  consola.fail("please provide target");
14565
14764
  return;
@@ -14595,7 +14794,7 @@ var unpluginFactory = (options) => ({
14595
14794
  },
14596
14795
  webpack(compiler) {
14597
14796
  var _a4, _b3, _c2;
14598
- if (import_node_process5.default.env.NODE_ENV !== "development")
14797
+ if (import_node_process9.default.env.NODE_ENV !== "development")
14599
14798
  return;
14600
14799
  const {
14601
14800
  enable = true,
@@ -14603,10 +14802,6 @@ var unpluginFactory = (options) => ({
14603
14802
  } = options;
14604
14803
  if (!enable)
14605
14804
  return;
14606
- if (!isAdmin()) {
14607
- consola.warn("please run as administrator");
14608
- return;
14609
- }
14610
14805
  if (!target) {
14611
14806
  consola.fail("please provide target");
14612
14807
  return;
@@ -14620,9 +14815,11 @@ var unpluginFactory = (options) => ({
14620
14815
  port: 8080,
14621
14816
  ...compiler.options.devServer,
14622
14817
  // @ts-expect-error vuecli
14623
- ...(_a4 = import_node_process5.default.VUE_CLI_SERVICE) == null ? void 0 : _a4.projectOptions.devServer
14818
+ ...(_a4 = import_node_process9.default.VUE_CLI_SERVICE) == null ? void 0 : _a4.projectOptions.devServer
14624
14819
  };
14625
14820
  const source = `${devServer.host}:${devServer.port}`;
14821
+ if (isPrivilegeDenied())
14822
+ return;
14626
14823
  if (caddy)
14627
14824
  return;
14628
14825
  let base = "/";
@@ -14637,15 +14834,16 @@ var unpluginFactory = (options) => ({
14637
14834
  const _close = (_c2 = compiler.close) == null ? void 0 : _c2.bind(compiler);
14638
14835
  if (_close) {
14639
14836
  compiler.close = async (callback) => {
14640
- import_node_process5.default.on("exit", () => {
14837
+ import_node_process9.default.on("exit", () => {
14641
14838
  _close && _close(callback);
14642
14839
  });
14643
14840
  };
14644
14841
  } else {
14645
14842
  options.https = false;
14646
14843
  }
14647
- caddy = new CaddyInstant();
14648
- caddy.run(source, target, {
14844
+ const instance = new CaddyInstant();
14845
+ caddy = instance;
14846
+ instance.run(source, target, {
14649
14847
  base,
14650
14848
  ...options
14651
14849
  }).then(() => {
@@ -14654,12 +14852,20 @@ var unpluginFactory = (options) => ({
14654
14852
  consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14655
14853
  });
14656
14854
  }).catch((e) => {
14855
+ if (caddy === instance)
14856
+ caddy = void 0;
14857
+ if (e instanceof PrivilegeDeniedError) {
14858
+ markPrivilegeDenied();
14859
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14860
+ consola.info("Restart the dev server to enable it again.");
14861
+ return;
14862
+ }
14657
14863
  throw e;
14658
14864
  });
14659
14865
  },
14660
14866
  async rspack(compiler) {
14661
14867
  var _a4, _b3, _c2, _d2;
14662
- if (import_node_process5.default.env.NODE_ENV !== "development")
14868
+ if (import_node_process9.default.env.NODE_ENV !== "development")
14663
14869
  return;
14664
14870
  const {
14665
14871
  enable = true,
@@ -14667,10 +14873,6 @@ var unpluginFactory = (options) => ({
14667
14873
  } = options;
14668
14874
  if (!enable)
14669
14875
  return;
14670
- if (!isAdmin()) {
14671
- consola.warn("please run as administrator");
14672
- return;
14673
- }
14674
14876
  if (!target) {
14675
14877
  consola.fail("please provide target");
14676
14878
  return;
@@ -14688,9 +14890,10 @@ var unpluginFactory = (options) => ({
14688
14890
  }))) == null ? void 0 : _b3.content) == null ? void 0 : _c2.server
14689
14891
  };
14690
14892
  const source = `${devServer.host}:${devServer.port}`;
14893
+ if (isPrivilegeDenied())
14894
+ return;
14691
14895
  if (caddy)
14692
14896
  return;
14693
- caddy = new CaddyInstant();
14694
14897
  let base = "/";
14695
14898
  const publicPath = (_d2 = compiler.options.output) == null ? void 0 : _d2.publicPath;
14696
14899
  if (typeof publicPath === "string" && publicPath) {
@@ -14700,13 +14903,23 @@ var unpluginFactory = (options) => ({
14700
14903
  base = `/${base}`;
14701
14904
  if (base !== "/" && !base.endsWith("/"))
14702
14905
  base = `${base}/`;
14703
- caddy.run(source, target, {
14906
+ const instance = new CaddyInstant();
14907
+ caddy = instance;
14908
+ instance.run(source, target, {
14704
14909
  base,
14705
14910
  ...options
14706
14911
  }).then(async () => {
14707
14912
  await printForwardProxy();
14708
14913
  consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14709
14914
  }).catch((e) => {
14915
+ if (caddy === instance)
14916
+ caddy = void 0;
14917
+ if (e instanceof PrivilegeDeniedError) {
14918
+ markPrivilegeDenied();
14919
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14920
+ consola.info("Restart the dev server to enable it again.");
14921
+ return;
14922
+ }
14710
14923
  throw e;
14711
14924
  });
14712
14925
  }