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

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-5R33PUJP.js → chunk-AQLHWJ4E.js} +994 -796
  3. package/dist/{chunk-2P7SUCQ3.js → chunk-EY3HXBJ4.js} +0 -26
  4. package/dist/chunk-RKHJN6KY.js +53 -0
  5. package/dist/chunk-WOMR3ZLM.js +17 -0
  6. package/dist/esbuild.cjs +1090 -864
  7. package/dist/esbuild.js +4 -2
  8. package/dist/index.cjs +1090 -864
  9. package/dist/index.js +4 -2
  10. package/dist/nuxt.cjs +1062 -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 +848 -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 +821 -0
  20. package/dist/rollup.cjs +1090 -864
  21. package/dist/rollup.js +4 -2
  22. package/dist/rspack.cjs +1090 -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 +1090 -864
  29. package/dist/vite.js +4 -2
  30. package/dist/webpack.cjs +1090 -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 +344 -0
  47. package/src/privileged/path-guard.ts +99 -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,799 @@ 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
+ let stderr = "";
13761
+ (_b3 = child.stderr) == null ? void 0 : _b3.on("data", (data) => {
13762
+ stderr = (stderr + data.toString()).slice(-4096);
13763
+ log == null ? void 0 : log(data.toString().trimEnd());
13764
+ });
13765
+ const exited = new Promise((resolve2) => {
13766
+ child.once("error", (error) => {
13767
+ stderr = error.message;
13768
+ });
13769
+ child.once("close", (code) => resolve2(code));
13770
+ });
13771
+ const earlyExit = await Promise.race([
13772
+ exited,
13773
+ new Promise((resolve2) => setTimeout(() => resolve2(void 0), 500))
13774
+ ]);
13775
+ if (earlyExit !== void 0 && earlyExit !== 0) {
13776
+ const detail = stderr.trim();
13777
+ let guidance = "";
13778
+ if (/\b(?:EACCES|EPERM)\b/.test(detail))
13779
+ guidance = " Check the path named above and its parent directories. Fix ownership or access manually; do not use chmod 777.";
13780
+ else if (!direct && /^sudo:/m.test(detail))
13781
+ guidance = " Retry from a terminal where sudo can request permission, or ask an administrator to grant access.";
13782
+ throw new Error(`privileged helper exited with code ${earlyExit}.${detail ? ` ${detail}${guidance}` : " No diagnostic output from the helper or sudo."}`);
13783
+ }
13784
+ }
13785
+ try {
13786
+ const client = await connectClient({ socketPath, token, timeoutMs: connectTimeoutMs });
13787
+ return {
13788
+ client,
13789
+ async close() {
13790
+ await client.close().catch(() => {
13791
+ });
13792
+ child == null ? void 0 : child.unref();
13793
+ }
13794
+ };
13795
+ } catch (error) {
13796
+ try {
13797
+ child == null ? void 0 : child.kill();
13798
+ } catch {
13799
+ }
13800
+ throw error;
13801
+ }
13802
+ }
13803
+ async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
13804
+ try {
13805
+ return await connectClient({ socketPath, token, timeoutMs });
13806
+ } catch {
13807
+ return void 0;
13808
+ }
13809
+ }
13723
13810
 
13724
- // src/caddy/log.ts
13725
- function isCaddyReloadCancellation(line) {
13811
+ // src/privileged/session.ts
13812
+ function tokenPath(runtimeDir) {
13813
+ return (0, import_node_path3.join)(runtimeDir, "helper.token");
13814
+ }
13815
+ function sessionSocketPath(runtimeDir) {
13816
+ if ((0, import_node_os4.platform)() === "win32")
13817
+ return `\\\\.\\pipe\\uhrp-${import_node_buffer.Buffer.from(runtimeDir).toString("hex").slice(0, 40)}`;
13818
+ return (0, import_node_path3.join)(runtimeDir, "helper.sock");
13819
+ }
13820
+ async function openHelperSession(scope2) {
13821
+ const socketPath = sessionSocketPath(scope2.runtimeDir);
13822
+ const release = await acquireStartLock(scope2.runtimeDir);
13726
13823
  try {
13727
- const entry = JSON.parse(line);
13728
- return entry.logger === "tls" && typeof entry.error === "string" && entry.error.endsWith("context canceled");
13824
+ const reused = await tryReuse(socketPath, scope2);
13825
+ if (reused)
13826
+ return reused;
13827
+ return await startNew(socketPath, scope2);
13828
+ } finally {
13829
+ release();
13830
+ }
13831
+ }
13832
+ async function tryReuse(socketPath, scope2) {
13833
+ if (!(0, import_node_fs3.existsSync)(socketPath) && (0, import_node_os4.platform)() !== "win32")
13834
+ return void 0;
13835
+ const token = await readToken(scope2.runtimeDir);
13836
+ if (!token)
13837
+ return void 0;
13838
+ const reused = await connectExistingHelper(socketPath, token);
13839
+ if (!reused)
13840
+ return void 0;
13841
+ return {
13842
+ client: reused,
13843
+ reused: true,
13844
+ close: async () => {
13845
+ await reused.close();
13846
+ }
13847
+ };
13848
+ }
13849
+ async function startNew(socketPath, scope2) {
13850
+ const token = createHelperToken();
13851
+ const started = await startPrivilegedHelper({
13852
+ socketPath,
13853
+ token,
13854
+ helperEntry: scope2.helperEntry,
13855
+ helperArgs: scope2.helperArgs,
13856
+ sudoCommand: scope2.sudoCommand,
13857
+ skipAuth: scope2.skipAuth,
13858
+ direct: scope2.direct,
13859
+ env: scope2.env,
13860
+ caddyStoragePath: scope2.caddyStoragePath,
13861
+ caddyBin: scope2.caddyBin,
13862
+ caddyConfigPath: scope2.caddyConfigPath,
13863
+ caddyAdminSocket: scope2.caddyAdminSocket,
13864
+ reason: scope2.reason,
13865
+ log: scope2.log
13866
+ });
13867
+ await writeToken(scope2.runtimeDir, token);
13868
+ return {
13869
+ client: started.client,
13870
+ reused: false,
13871
+ close: async () => {
13872
+ await started.close();
13873
+ }
13874
+ };
13875
+ }
13876
+ async function acquireStartLock(runtimeDir) {
13877
+ const lockPath = (0, import_node_path3.join)(runtimeDir, "helper.start.lock");
13878
+ try {
13879
+ await (0, import_promises.writeFile)(lockPath, "", { flag: "a" });
13729
13880
  } catch {
13730
- return false;
13731
13881
  }
13882
+ const release = await lockfile2.lock(lockPath, {
13883
+ realpath: false,
13884
+ stale: 3e4,
13885
+ retries: { retries: 100, minTimeout: 50, maxTimeout: 200 }
13886
+ });
13887
+ return () => {
13888
+ void release().catch(() => {
13889
+ });
13890
+ };
13891
+ }
13892
+ async function readToken(runtimeDir) {
13893
+ try {
13894
+ const content = await (0, import_promises.readFile)(tokenPath(runtimeDir), "utf8");
13895
+ const token = content.trim();
13896
+ return token === "" ? void 0 : token;
13897
+ } catch {
13898
+ return void 0;
13899
+ }
13900
+ }
13901
+ async function writeToken(runtimeDir, token) {
13902
+ try {
13903
+ await (0, import_promises.writeFile)(tokenPath(runtimeDir), token, { mode: 384 });
13904
+ } catch {
13905
+ }
13906
+ }
13907
+
13908
+ // src/caddy/privileged.ts
13909
+ var import_meta = {};
13910
+ function resolvePrivilegedEnv() {
13911
+ const moduleDir = typeof __dirname === "string" ? __dirname : (0, import_node_path4.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
13912
+ const resolved = resolveHelperEntry({ moduleDir });
13913
+ return { helperEntry: resolved.entry, helperArgs: resolved.args };
13914
+ }
13915
+ var HelperCaddyProcess = class extends import_node_events.EventEmitter {
13916
+ constructor(client) {
13917
+ super();
13918
+ this.client = client;
13919
+ this.stdout = new import_node_events.EventEmitter();
13920
+ this.stderr = new import_node_events.EventEmitter();
13921
+ this.finished = false;
13922
+ this.unsubscribe = client.onEvent((event) => this.handleEvent(event));
13923
+ }
13924
+ handleEvent(event) {
13925
+ if (event.type !== "event")
13926
+ return;
13927
+ if (event.kind === "caddy.stdout") {
13928
+ this.stdout.emit("data", import_node_buffer2.Buffer.from(event.data));
13929
+ return;
13930
+ }
13931
+ if (event.kind === "caddy.stderr") {
13932
+ this.stderr.emit("data", import_node_buffer2.Buffer.from(event.data));
13933
+ return;
13934
+ }
13935
+ if (event.kind === "caddy.exit") {
13936
+ this.finished = true;
13937
+ this.emit("exit", event.code, event.signal);
13938
+ }
13939
+ }
13940
+ /** Asks the helper to stop Caddy; the helper also stops it on disconnect. */
13941
+ kill() {
13942
+ this.unsubscribe();
13943
+ if (this.finished)
13944
+ return;
13945
+ this.finished = true;
13946
+ void this.client.call("caddy.stop").catch(() => {
13947
+ });
13948
+ }
13949
+ };
13950
+ function caddyStoragePath() {
13951
+ 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");
13952
+ }
13953
+ function openPrivilegedSession(runtimeDir, options) {
13954
+ const env2 = resolvePrivilegedEnv();
13955
+ return openHelperSession({
13956
+ runtimeDir,
13957
+ helperEntry: env2.helperEntry,
13958
+ helperArgs: env2.helperArgs,
13959
+ direct: options.direct,
13960
+ // Caddy keeps its PKI under the user's home; the helper runs it as root, so
13961
+ // it must know which tree to hand back afterwards.
13962
+ caddyStoragePath: caddyStoragePath(),
13963
+ // The binary and Caddyfile are fixed here: the privileged helper must never
13964
+ // execute a path supplied over the socket.
13965
+ caddyBin: options.caddyBin,
13966
+ caddyConfigPath: options.caddyConfigPath,
13967
+ caddyAdminSocket: options.caddyAdminSocket,
13968
+ reason: options.reason,
13969
+ log: options.log
13970
+ });
13732
13971
  }
13733
13972
 
13734
13973
  // src/caddy/tls-health.ts
@@ -13813,40 +14052,8 @@ function formatTlsHealthFailure(hostname, result) {
13813
14052
  }
13814
14053
 
13815
14054
  // src/caddy/utils.ts
13816
- var import_node_child_process3 = require("child_process");
13817
- var import_node_net = require("net");
13818
14055
  var import_ora = __toESM(require("ora"), 1);
13819
14056
  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
14057
  function getNumber(number2) {
13851
14058
  if (number2 <= 0)
13852
14059
  return "0%";
@@ -13885,26 +14092,26 @@ async function download() {
13885
14092
  if (await testCaddy())
13886
14093
  return caddyPath;
13887
14094
  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);
14095
+ if (!(0, import_node_fs4.existsSync)(TEMP_DIR)) {
14096
+ (0, import_node_fs4.mkdirSync)(TEMP_DIR, { recursive: true });
14097
+ (0, import_node_fs4.chmodSync)(TEMP_DIR, 448);
13891
14098
  }
13892
- const file = (0, import_node_fs3.createWriteStream)(caddyPath);
13893
- let _platform = (0, import_node_os3.platform)().toString();
14099
+ const file = (0, import_node_fs4.createWriteStream)(caddyPath);
14100
+ let _platform = (0, import_node_os5.platform)().toString();
13894
14101
  _platform === "win32" && (_platform = "windows");
13895
- let _arch = import_node_process4.default.arch.toString();
14102
+ let _arch = import_node_process8.default.arch.toString();
13896
14103
  _arch === "x64" && (_arch = "amd64");
13897
14104
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
13898
14105
  if (!support)
13899
14106
  return reject2(new Error("not support"));
13900
14107
  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;
14108
+ (0, import_node_fs4.existsSync)(caddyPath) && (0, import_node_fs4.unlinkSync)(caddyPath);
14109
+ const httpProxy = import_node_process8.default.env.HTTP_PROXY || import_node_process8.default.env.http_proxy;
14110
+ const httpsProxy = import_node_process8.default.env.HTTPS_PROXY || import_node_process8.default.env.https_proxy;
13904
14111
  const httpAgent = httpProxy ? new import_http_proxy_agent.HttpProxyAgent(httpProxy) : void 0;
13905
14112
  const httpsAgent = httpsProxy ? new import_https_proxy_agent.HttpsProxyAgent(httpsProxy) : void 0;
13906
14113
  const chmodCaddyOnce = once(() => {
13907
- (0, import_node_fs3.chmodSync)(caddyPath, 511);
14114
+ (0, import_node_fs4.chmodSync)(caddyPath, 493);
13908
14115
  });
13909
14116
  import_got_cjs.got.stream(dowmloadLink, {
13910
14117
  agent: {
@@ -13916,9 +14123,9 @@ async function download() {
13916
14123
  chmodCaddyOnce();
13917
14124
  }).pipe(file).on("finish", () => {
13918
14125
  logProgressOver();
13919
- if (import_node_process4.default.platform === "win32")
14126
+ if (import_node_process8.default.platform === "win32")
13920
14127
  return resolve2(caddyPath);
13921
- (0, import_node_fs3.chmodSync)(caddyPath, 511);
14128
+ (0, import_node_fs4.chmodSync)(caddyPath, 493);
13922
14129
  resolve2(caddyPath);
13923
14130
  }).on("error", (err) => {
13924
14131
  reject2(err);
@@ -13926,26 +14133,41 @@ async function download() {
13926
14133
  });
13927
14134
  }
13928
14135
  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", () => {
14136
+ return new Promise((resolve2) => {
14137
+ if (!(0, import_node_fs4.existsSync)(caddyPath))
13935
14138
  return resolve2(false);
14139
+ try {
14140
+ (0, import_node_fs4.chmodSync)(caddyPath, 493);
14141
+ } catch {
14142
+ }
14143
+ (0, import_node_child_process3.execFile)(caddyPath, [], { timeout: 1e4 }, (error, stdout) => {
14144
+ if (error && !stdout)
14145
+ return resolve2(false);
14146
+ resolve2(stdout.length > 0);
13936
14147
  });
13937
- child.on("error", (err) => {
13938
- return reject2(err);
13939
- });
13940
- child.stdout.on("data", (_data) => {
13941
- return resolve2(true);
13942
- });
13943
14148
  });
13944
14149
  }
14150
+ function caddyRootPath() {
14151
+ return (0, import_node_path5.join)(
14152
+ import_node_process8.default.platform === "win32" ? `${import_node_process8.default.env.AppData}/Caddy` : `${import_node_process8.default.env.HOME}/Library/Application Support/Caddy`,
14153
+ "./pki/authorities/local"
14154
+ );
14155
+ }
14156
+ async function renderCaddyfile(proxies) {
14157
+ const ctx = validateTemplateContext({
14158
+ caddy_root: caddyRootPath(),
14159
+ admin_socket: caddyAdminSocketPath,
14160
+ proxies: Object.values(proxies)
14161
+ });
14162
+ const content = await genCaddyfile(ctx);
14163
+ const temp = `${caddyFilePath}.${import_node_process8.default.pid}.tmp`;
14164
+ await (0, import_promises2.writeFile)(temp, content);
14165
+ await (0, import_promises2.rename)(temp, caddyFilePath);
14166
+ }
13945
14167
  var caddyConfig;
13946
14168
  function getCaddyConfig() {
13947
14169
  if (!caddyConfig) {
13948
- caddyConfig = useCaddyConfig();
14170
+ caddyConfig = useCaddyConfig({ renderCaddyfile });
13949
14171
  }
13950
14172
  return caddyConfig;
13951
14173
  }
@@ -13960,80 +14182,92 @@ function splitHostPort(addr) {
13960
14182
  }
13961
14183
  return { host: addr.slice(0, lastColon), port: addr.slice(lastColon + 1) };
13962
14184
  }
14185
+ var defaultDependencies = {
14186
+ openSession: (runtimeDir, reason) => openPrivilegedSession(runtimeDir, {
14187
+ log: (message) => consola.debug(message),
14188
+ // Both paths are fixed here, before any socket traffic: the privileged
14189
+ // helper must never execute something named in a request.
14190
+ caddyBin: caddyPath,
14191
+ caddyConfigPath: caddyFilePath,
14192
+ caddyAdminSocket: caddyAdminSocketPath,
14193
+ reason
14194
+ }),
14195
+ config: () => getCaddyConfig()
14196
+ };
13963
14197
  var CaddyInstant = class {
13964
- constructor() {
14198
+ constructor(deps = {}) {
13965
14199
  this.inited = false;
13966
14200
  this.stoped = false;
13967
- /** has locked when start */
13968
- this.locked = false;
13969
14201
  this._stopEffects = [];
13970
- testCaddy().then(async () => {
13971
- this.inited = true;
13972
- });
13973
- this.locked = this.checkLock();
14202
+ /** Identifies this instance's routes in the shared config. */
14203
+ this.proxyKey = `${import_node_process8.default.pid}-${Math.random().toString(36).slice(2, 8)}`;
14204
+ this.deps = { ...defaultDependencies, ...deps };
13974
14205
  }
13975
- checkLock() {
13976
- if (!(0, import_node_fs3.existsSync)(caddyLockFilePath))
13977
- (0, import_node_fs3.writeFileSync)(caddyLockFilePath, "");
13978
- return lockfile.checkSync(caddyLockFilePath);
14206
+ /**
14207
+ * Connects to the privileged helper, starting it once if needed. It is
14208
+ * reused across instances so a second dev server does not ask for a
14209
+ * password again.
14210
+ */
14211
+ async session(reason) {
14212
+ if (this._session && !this._session.client.connected)
14213
+ this._session = void 0;
14214
+ if (!this._session)
14215
+ this._session = await this.deps.openSession(TEMP_DIR, reason);
14216
+ return this._session;
13979
14217
  }
13980
14218
  async getCaddyfile() {
13981
- if (!(0, import_node_fs3.existsSync)(caddyFilePath)) {
14219
+ if (!(0, import_node_fs4.existsSync)(caddyFilePath)) {
13982
14220
  this.caddyfile = "";
13983
14221
  return "";
13984
14222
  }
13985
- this.caddyfile = await (0, import_promises3.readFile)(caddyFilePath, "utf-8");
14223
+ this.caddyfile = await (0, import_promises2.readFile)(caddyFilePath, "utf-8");
13986
14224
  return this.caddyfile;
13987
14225
  }
13988
14226
  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
- );
14227
+ return caddyRootPath();
13993
14228
  }
13994
14229
  async writeCaddyfile() {
13995
- return await (0, import_promises3.writeFile)(caddyFilePath, this.caddyfile || "");
14230
+ return await (0, import_promises2.writeFile)(caddyFilePath, this.caddyfile || "");
13996
14231
  }
13997
14232
  async deleteCaddyfile() {
13998
- return await (0, import_promises3.unlink)(caddyFilePath);
14233
+ return await (0, import_promises2.unlink)(caddyFilePath);
13999
14234
  }
14000
14235
  async init() {
14001
14236
  await download();
14002
14237
  this.inited = true;
14003
14238
  }
14239
+ /**
14240
+ * Hands the Caddy storage directory back to the developer. Local CA data
14241
+ * created by an earlier root-owned run must stay readable for `tls internal`
14242
+ * to keep serving the same certificate the browser already trusts.
14243
+ */
14244
+ /**
14245
+ * Installs Caddy's local root CA so the browser stops warning about
14246
+ * `tls internal` certificates. Generating the CA and trusting it are separate
14247
+ * steps: a new CA appears whenever the previous one expires or the storage is
14248
+ * replaced, so this runs on every start instead of once.
14249
+ *
14250
+ * The helper owns both the binary path and the command, so nothing here can
14251
+ * be turned into an arbitrary root execution.
14252
+ */
14253
+ async trustLocalCa(session) {
14254
+ try {
14255
+ const result = await session.client.call("ca.trust");
14256
+ if (result.trusted)
14257
+ consola.debug(`Caddy local CA is trusted
14258
+ ${result.output}`);
14259
+ } catch (error) {
14260
+ consola.warn(
14261
+ `could not install the Caddy root certificate automatically: ${error.message}
14262
+ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14263
+ );
14264
+ }
14265
+ }
14004
14266
  async ensureTlsReady(targetHost) {
14005
14267
  const health = await waitForLocalTls(targetHost);
14006
14268
  if (!health.healthy)
14007
14269
  throw new Error(formatTlsHealthFailure(targetHost, health));
14008
14270
  }
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
14271
  /**
14038
14272
  * @param source like `127.0.0.1:8080`
14039
14273
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
@@ -14054,10 +14288,10 @@ var CaddyInstant = class {
14054
14288
  await this.init();
14055
14289
  const sourceHost = splitHostPort(source).host;
14056
14290
  const targetHost = splitHostPort(target).host;
14057
- if (!await addHost(sourceHost, targetHost))
14058
- throw new Error("update host failed");
14291
+ const session = await this.session({ target: targetHost, https });
14292
+ await session.client.call("hosts.add", { ip: sourceHost, host: targetHost });
14059
14293
  consola.success("update host success\n");
14060
- const normalizeBase = (b) => {
14294
+ const normalizeBase2 = (b) => {
14061
14295
  let out = b || "/";
14062
14296
  if (!out.startsWith("/"))
14063
14297
  out = `/${out}`;
@@ -14065,7 +14299,7 @@ var CaddyInstant = class {
14065
14299
  out = `${out}/`;
14066
14300
  return out;
14067
14301
  };
14068
- const baseNormalized = normalizeBase(base);
14302
+ const baseNormalized = normalizeBase2(base);
14069
14303
  const proxies = [
14070
14304
  {
14071
14305
  target: targetHost,
@@ -14076,176 +14310,138 @@ var CaddyInstant = class {
14076
14310
  healthCheck
14077
14311
  }
14078
14312
  ];
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
- }
14313
+ const { writeCaddyConfig } = this.deps.config();
14314
+ await writeCaddyConfig(proxies, this.proxyKey);
14315
+ await session.client.call("port.free", { port: 443 });
14316
+ if (import_node_process8.default.platform === "win32" || !https)
14317
+ await session.client.call("port.free", { port: 80 });
14101
14318
  return new Promise((resolve2, reject2) => {
14102
- var _a4, _b3;
14103
14319
  let startupCheckStarted = false;
14104
14320
  const resolveWhenReady = async () => {
14105
14321
  if (startupCheckStarted)
14106
14322
  return;
14107
14323
  startupCheckStarted = true;
14108
14324
  try {
14109
- if (https)
14325
+ if (https) {
14326
+ await this.trustLocalCa(session);
14110
14327
  await this.ensureTlsReady(targetHost);
14328
+ }
14111
14329
  resolve2();
14112
14330
  } catch (error) {
14113
- if (!this.locked)
14114
- await this.baseCleanup(restore);
14331
+ await this.baseCleanup(restore);
14115
14332
  reject2(error);
14116
14333
  }
14117
14334
  };
14118
14335
  const setupCleanup = () => {
14119
- import_node_process4.default.on("SIGINT", async () => {
14336
+ import_node_process8.default.on("SIGINT", async () => {
14120
14337
  if (this.stoped)
14121
14338
  return;
14122
- import_node_process4.default.stdin.resume();
14339
+ import_node_process8.default.stdin.resume();
14123
14340
  try {
14124
14341
  await this.baseCleanup(restore);
14125
14342
  } finally {
14126
14343
  this.stoped = true;
14127
- import_node_process4.default.nextTick(() => {
14128
- import_node_process4.default.exit();
14344
+ import_node_process8.default.nextTick(() => {
14345
+ import_node_process8.default.exit();
14129
14346
  });
14130
14347
  }
14131
14348
  });
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
- });
14349
+ const originalExit = import_node_process8.default.exit.bind(import_node_process8.default);
14350
+ import_node_process8.default.exit = async (code) => {
14154
14351
  if (this.stoped)
14155
14352
  return originalExit(code);
14156
- import_node_process4.default.stdin.resume();
14353
+ import_node_process8.default.stdin.resume();
14157
14354
  try {
14158
14355
  await this.baseCleanup();
14159
14356
  } finally {
14160
14357
  this.stoped = true;
14161
- import_node_process4.default.nextTick(() => {
14358
+ import_node_process8.default.nextTick(() => {
14162
14359
  originalExit(code);
14163
14360
  });
14164
14361
  }
14165
14362
  };
14166
14363
  };
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}
14364
+ setupCleanup();
14365
+ void (async () => {
14366
+ try {
14367
+ const child = new HelperCaddyProcess(session.client);
14368
+ this._caddyChild = child;
14369
+ const started = await session.client.call("caddy.start");
14370
+ child.on("exit", (code) => {
14371
+ if (code !== null && code !== 0)
14372
+ reject2(new Error(`Caddy exited with code ${code}`));
14373
+ });
14374
+ if ((started == null ? void 0 : started.started) === false) {
14375
+ consola.info("Caddy is already running; added this route to it.");
14376
+ void resolveWhenReady();
14377
+ return;
14378
+ }
14379
+ child.stderr.on("data", async (data) => {
14380
+ const lines = data.toString().split("\n").map((line) => line.trim());
14381
+ for (const line of lines) {
14382
+ showCaddyLog && line && console.info(line);
14383
+ if (isCaddyReloadCancellation(line)) {
14384
+ consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14385
+ continue;
14386
+ }
14387
+ try {
14388
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14389
+ if (line.includes("parsing caddyfile tokens")) {
14390
+ consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14185
14391
 
14186
14392
  ${line}
14187
14393
  `);
14188
- await this.baseCleanup();
14189
- import_node_process4.default.exit();
14190
- } else {
14191
- consola.error(`${line}
14394
+ await this.baseCleanup();
14395
+ import_node_process8.default.exit();
14396
+ } else {
14397
+ consola.error(`${line}
14192
14398
  `);
14193
- return reject2(line);
14399
+ return reject2(line);
14400
+ }
14194
14401
  }
14402
+ } catch {
14195
14403
  }
14196
- } catch {
14404
+ if (line.includes("config file changed"))
14405
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
14406
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
14407
+ void resolveWhenReady();
14197
14408
  }
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
- }
14409
+ });
14410
+ child.stdout.on("data", (data) => {
14411
+ consola.info(data.toString());
14412
+ void resolveWhenReady();
14413
+ });
14414
+ } catch (error) {
14415
+ await this.baseCleanup(restore);
14416
+ reject2(error);
14417
+ }
14418
+ })();
14222
14419
  });
14223
14420
  }
14224
14421
  async baseCleanup(restore = true) {
14422
+ var _a4;
14225
14423
  this._stopEffects.forEach((fn) => fn());
14424
+ this._stopEffects.length = 0;
14226
14425
  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");
14426
+ if (restore && this._source && this._target && this._session) {
14427
+ const sourceHost = splitHostPort(this._source).host;
14428
+ const targetHost = splitHostPort(this._target).host;
14429
+ await this._session.client.call("hosts.remove", { ip: sourceHost, host: targetHost });
14430
+ if (sourceHost === "localhost")
14431
+ await this._session.client.call("hosts.remove", { ip: "127.0.0.1", host: targetHost });
14432
+ consola.success("Restore host success.\n");
14232
14433
  }
14233
14434
  } catch (e) {
14234
- consola.error(e);
14235
- consola.fail("Restore host failed.\n");
14435
+ if (((_a4 = this._session) == null ? void 0 : _a4.client.connected) === false) {
14436
+ consola.debug("hosts entries are restored by the privileged helper on disconnect");
14437
+ } else {
14438
+ consola.error(e);
14439
+ consola.fail("Restore host failed.\n");
14440
+ }
14236
14441
  }
14237
- if (!this.locked && !this.stoped) {
14238
- await this.stopCaddy();
14442
+ if (!this.stoped) {
14239
14443
  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
- }
14444
+ await this.deps.config().removeProxy(this.proxyKey);
14249
14445
  } catch (e) {
14250
14446
  consola.error(e);
14251
14447
  }
@@ -14487,11 +14683,20 @@ var hmrSseBridgeClientScript = `
14487
14683
  })();
14488
14684
  `;
14489
14685
 
14686
+ // src/privilege-state.ts
14687
+ var denied = false;
14688
+ function markPrivilegeDenied() {
14689
+ denied = true;
14690
+ }
14691
+ function isPrivilegeDenied() {
14692
+ return denied;
14693
+ }
14694
+
14490
14695
  // src/index.ts
14491
14696
  var config;
14492
14697
  var caddy;
14493
14698
  var hmrSseBridgeActive = false;
14494
- var cwd = import_node_process5.default.cwd();
14699
+ var cwd = import_node_process9.default.cwd();
14495
14700
  function colorUrl(url2) {
14496
14701
  return import_picocolors2.default.green(url2.replace(/:(\d+)\//, (_, port) => `:${import_picocolors2.default.bold(port)}/`));
14497
14702
  }
@@ -14526,16 +14731,27 @@ async function printForwardProxy() {
14526
14731
  }
14527
14732
  var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
14528
14733
  _printUrls == null ? void 0 : _printUrls();
14734
+ if (isPrivilegeDenied())
14735
+ return;
14529
14736
  if (caddy)
14530
14737
  return;
14531
- caddy = new CaddyInstant();
14532
- caddy.run(source, target, {
14738
+ const instance = new CaddyInstant();
14739
+ caddy = instance;
14740
+ instance.run(source, target, {
14533
14741
  base,
14534
14742
  ...options
14535
14743
  }).then(async () => {
14536
14744
  await printForwardProxy();
14537
14745
  consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14538
14746
  }).catch((e) => {
14747
+ if (caddy === instance)
14748
+ caddy = void 0;
14749
+ if (e instanceof PrivilegeDeniedError) {
14750
+ markPrivilegeDenied();
14751
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14752
+ consola.info("Restart the dev server to enable it again.");
14753
+ return;
14754
+ }
14539
14755
  throw e;
14540
14756
  });
14541
14757
  });
@@ -14556,10 +14772,6 @@ var unpluginFactory = (options) => ({
14556
14772
  } = options;
14557
14773
  if (!enable)
14558
14774
  return;
14559
- if (!isAdmin()) {
14560
- consola.warn("please run as administrator");
14561
- return;
14562
- }
14563
14775
  if (!target) {
14564
14776
  consola.fail("please provide target");
14565
14777
  return;
@@ -14595,7 +14807,7 @@ var unpluginFactory = (options) => ({
14595
14807
  },
14596
14808
  webpack(compiler) {
14597
14809
  var _a4, _b3, _c2;
14598
- if (import_node_process5.default.env.NODE_ENV !== "development")
14810
+ if (import_node_process9.default.env.NODE_ENV !== "development")
14599
14811
  return;
14600
14812
  const {
14601
14813
  enable = true,
@@ -14603,10 +14815,6 @@ var unpluginFactory = (options) => ({
14603
14815
  } = options;
14604
14816
  if (!enable)
14605
14817
  return;
14606
- if (!isAdmin()) {
14607
- consola.warn("please run as administrator");
14608
- return;
14609
- }
14610
14818
  if (!target) {
14611
14819
  consola.fail("please provide target");
14612
14820
  return;
@@ -14620,9 +14828,11 @@ var unpluginFactory = (options) => ({
14620
14828
  port: 8080,
14621
14829
  ...compiler.options.devServer,
14622
14830
  // @ts-expect-error vuecli
14623
- ...(_a4 = import_node_process5.default.VUE_CLI_SERVICE) == null ? void 0 : _a4.projectOptions.devServer
14831
+ ...(_a4 = import_node_process9.default.VUE_CLI_SERVICE) == null ? void 0 : _a4.projectOptions.devServer
14624
14832
  };
14625
14833
  const source = `${devServer.host}:${devServer.port}`;
14834
+ if (isPrivilegeDenied())
14835
+ return;
14626
14836
  if (caddy)
14627
14837
  return;
14628
14838
  let base = "/";
@@ -14637,15 +14847,16 @@ var unpluginFactory = (options) => ({
14637
14847
  const _close = (_c2 = compiler.close) == null ? void 0 : _c2.bind(compiler);
14638
14848
  if (_close) {
14639
14849
  compiler.close = async (callback) => {
14640
- import_node_process5.default.on("exit", () => {
14850
+ import_node_process9.default.on("exit", () => {
14641
14851
  _close && _close(callback);
14642
14852
  });
14643
14853
  };
14644
14854
  } else {
14645
14855
  options.https = false;
14646
14856
  }
14647
- caddy = new CaddyInstant();
14648
- caddy.run(source, target, {
14857
+ const instance = new CaddyInstant();
14858
+ caddy = instance;
14859
+ instance.run(source, target, {
14649
14860
  base,
14650
14861
  ...options
14651
14862
  }).then(() => {
@@ -14654,12 +14865,20 @@ var unpluginFactory = (options) => ({
14654
14865
  consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14655
14866
  });
14656
14867
  }).catch((e) => {
14868
+ if (caddy === instance)
14869
+ caddy = void 0;
14870
+ if (e instanceof PrivilegeDeniedError) {
14871
+ markPrivilegeDenied();
14872
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14873
+ consola.info("Restart the dev server to enable it again.");
14874
+ return;
14875
+ }
14657
14876
  throw e;
14658
14877
  });
14659
14878
  },
14660
14879
  async rspack(compiler) {
14661
14880
  var _a4, _b3, _c2, _d2;
14662
- if (import_node_process5.default.env.NODE_ENV !== "development")
14881
+ if (import_node_process9.default.env.NODE_ENV !== "development")
14663
14882
  return;
14664
14883
  const {
14665
14884
  enable = true,
@@ -14667,10 +14886,6 @@ var unpluginFactory = (options) => ({
14667
14886
  } = options;
14668
14887
  if (!enable)
14669
14888
  return;
14670
- if (!isAdmin()) {
14671
- consola.warn("please run as administrator");
14672
- return;
14673
- }
14674
14889
  if (!target) {
14675
14890
  consola.fail("please provide target");
14676
14891
  return;
@@ -14688,9 +14903,10 @@ var unpluginFactory = (options) => ({
14688
14903
  }))) == null ? void 0 : _b3.content) == null ? void 0 : _c2.server
14689
14904
  };
14690
14905
  const source = `${devServer.host}:${devServer.port}`;
14906
+ if (isPrivilegeDenied())
14907
+ return;
14691
14908
  if (caddy)
14692
14909
  return;
14693
- caddy = new CaddyInstant();
14694
14910
  let base = "/";
14695
14911
  const publicPath = (_d2 = compiler.options.output) == null ? void 0 : _d2.publicPath;
14696
14912
  if (typeof publicPath === "string" && publicPath) {
@@ -14700,13 +14916,23 @@ var unpluginFactory = (options) => ({
14700
14916
  base = `/${base}`;
14701
14917
  if (base !== "/" && !base.endsWith("/"))
14702
14918
  base = `${base}/`;
14703
- caddy.run(source, target, {
14919
+ const instance = new CaddyInstant();
14920
+ caddy = instance;
14921
+ instance.run(source, target, {
14704
14922
  base,
14705
14923
  ...options
14706
14924
  }).then(async () => {
14707
14925
  await printForwardProxy();
14708
14926
  consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14709
14927
  }).catch((e) => {
14928
+ if (caddy === instance)
14929
+ caddy = void 0;
14930
+ if (e instanceof PrivilegeDeniedError) {
14931
+ markPrivilegeDenied();
14932
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14933
+ consola.info("Restart the dev server to enable it again.");
14934
+ return;
14935
+ }
14710
14936
  throw e;
14711
14937
  });
14712
14938
  }