@outerlayer/cli 0.37.0-next.20261105010834 → 0.38.0-next.20261105124419

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 (126) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +13 -5
  3. package/dist/{agent-setup-DUE6IXPP.js → agent-setup-JEUFYIPH.js} +7 -7
  4. package/dist/{agent-subcommand-C625JDSN.js → agent-subcommand-GR6FUDOR.js} +1 -1
  5. package/dist/{bridge-UHNGV6DM.js → bridge-POOKFVVM.js} +2 -2
  6. package/dist/{build-ALG3MYX2.js → build-L2I4A2E6.js} +7 -7
  7. package/dist/{build-disk-JU2QHE64.js → build-disk-JXDTAY5A.js} +5 -5
  8. package/dist/build-info.json +1 -1
  9. package/dist/{builder-4LK2FDCX.js → builder-MV5A5KOW.js} +4 -4
  10. package/dist/{caller-JQC4VW36.js → caller-XIG74H56.js} +7 -7
  11. package/dist/{check-PJ5FLDTD.js → check-LYPMBZU5.js} +38 -38
  12. package/dist/{chunk-R2IPYS6A.js → chunk-3AJKX3FY.js} +3 -3
  13. package/dist/{chunk-XMIUPI5N.js → chunk-3FVSLRXZ.js} +1 -1
  14. package/dist/{chunk-WCJCGFVQ.js → chunk-3YULN4UC.js} +1 -1
  15. package/dist/{chunk-EDEBGBPL.js → chunk-7423RCC2.js} +2 -2
  16. package/dist/{chunk-RFCAK6OI.js → chunk-BBHBVDET.js} +3 -3
  17. package/dist/{chunk-6BS4DDCY.js → chunk-BG3X4UPN.js} +5 -5
  18. package/dist/{chunk-OG6RJXQ3.js → chunk-CFXCMHUO.js} +1 -1
  19. package/dist/{chunk-IJU6DMQA.js → chunk-D46NGZOG.js} +1 -1
  20. package/dist/{chunk-4U57GP2X.js → chunk-DPBSA2A3.js} +2 -2
  21. package/dist/{chunk-3LT6REKE.js → chunk-EL46EW3V.js} +1 -1
  22. package/dist/{chunk-Q2JDKHOR.js → chunk-FFEZDIDM.js} +32 -24
  23. package/dist/{chunk-4TDBM3PK.js → chunk-G6BDSNSO.js} +3 -3
  24. package/dist/{chunk-KE5NFPP2.js → chunk-GDYUTUUU.js} +5 -5
  25. package/dist/{chunk-2LXO2YIW.js → chunk-GLPQBMON.js} +3 -3
  26. package/dist/{chunk-HOTRWPVM.js → chunk-GSSCNJ6F.js} +1 -1
  27. package/dist/{chunk-ZRITZJ36.js → chunk-H273QEFX.js} +2 -2
  28. package/dist/{chunk-N3FPRSUZ.js → chunk-H3N7Q4ZE.js} +2 -2
  29. package/dist/{chunk-LUQWY7BX.js → chunk-HODTWJUB.js} +2 -2
  30. package/dist/{chunk-G43WGW64.js → chunk-HUZPRUNL.js} +3 -3
  31. package/dist/{chunk-RXWFZB3P.js → chunk-HZ7BKQH4.js} +1 -1
  32. package/dist/{chunk-E2DJ6TWB.js → chunk-J6M3QBZ4.js} +1 -2
  33. package/dist/{chunk-62RPMJXQ.js → chunk-KEUMMQXT.js} +3 -3
  34. package/dist/{chunk-XPIFUWWY.js → chunk-L5ZU6BDL.js} +9 -9
  35. package/dist/{chunk-LNTZH3UL.js → chunk-LDWLK3SO.js} +2 -2
  36. package/dist/{chunk-77RLQS5V.js → chunk-LJTQLJY7.js} +6 -6
  37. package/dist/{chunk-NBGBMZE4.js → chunk-LXZNM5VB.js} +1 -1
  38. package/dist/{chunk-KSSHEWPV.js → chunk-M2YIRI4M.js} +855 -522
  39. package/dist/{chunk-OLZVQCDX.js → chunk-MEWH2KP3.js} +1 -1
  40. package/dist/{chunk-4A7D2HWQ.js → chunk-MFQZ4YB2.js} +3 -3
  41. package/dist/{chunk-LVZ3UV7T.js → chunk-MTOTUOVL.js} +1 -1
  42. package/dist/{chunk-Q6FXWSN3.js → chunk-MTWLACRR.js} +5 -5
  43. package/dist/{chunk-YLJXRXPX.js → chunk-PGWNGQNM.js} +1 -1
  44. package/dist/{chunk-PNZN656P.js → chunk-RHJC4BFN.js} +1 -1
  45. package/dist/{chunk-KCNL7KX2.js → chunk-SKMSAH7E.js} +5 -5
  46. package/dist/{chunk-HN76DIHX.js → chunk-SKTLYF3W.js} +3 -3
  47. package/dist/{chunk-GBCQ3KHH.js → chunk-T3E7R6RM.js} +2 -2
  48. package/dist/{chunk-ZEHCE7ZE.js → chunk-TE6GQJRW.js} +1 -1
  49. package/dist/{chunk-P2UH4EBF.js → chunk-U3YQTCAX.js} +413 -270
  50. package/dist/{chunk-MITBH4LH.js → chunk-UXR7PP74.js} +1 -1
  51. package/dist/{chunk-ZHOPDD7U.js → chunk-V4ALUVM7.js} +2 -2
  52. package/dist/{chunk-GQA54433.js → chunk-VK27VYPT.js} +2 -2
  53. package/dist/{chunk-FYPVUT27.js → chunk-VRJKRJLT.js} +1 -1
  54. package/dist/{chunk-JNGKTJ7L.js → chunk-VSF7YDGF.js} +5 -5
  55. package/dist/{chunk-JO2FOEZE.js → chunk-W4KFRTFB.js} +2 -2
  56. package/dist/{chunk-VTJ5MGGC.js → chunk-XLZOJPOD.js} +3 -3
  57. package/dist/{chunk-2QFRAMJX.js → chunk-XXSTLXIV.js} +1 -1
  58. package/dist/{chunk-G62P3EFL.js → chunk-YFOZG7QW.js} +3 -3
  59. package/dist/{chunk-MZ2OOMOT.js → chunk-YHBRCUSH.js} +1 -1
  60. package/dist/{chunk-IHPJFMSV.js → chunk-YVCZDPEY.js} +2 -2
  61. package/dist/{chunk-QK43VKE4.js → chunk-YXEI5FEI.js} +7 -7
  62. package/dist/{chunk-XGJXLITW.js → chunk-Z4VSLXAS.js} +1 -1
  63. package/dist/{claude-launcher-HW5YVYWR.js → claude-launcher-B3E7YQ7I.js} +1 -1
  64. package/dist/{cli-K62CS6XW.js → cli-EP4ERRKA.js} +114 -114
  65. package/dist/{command-EG54FHMR.js → command-W3QDOBVS.js} +32 -32
  66. package/dist/{config-CZJINZN5.js → config-4AL4H4O6.js} +6 -6
  67. package/dist/{connect-cmd-4ZEF4WNR.js → connect-cmd-KLQSLHOG.js} +5 -5
  68. package/dist/{container-start-JBYD2XG4.js → container-start-LQH2INFF.js} +30 -30
  69. package/dist/{context-show-cmd-JYV7RKMC.js → context-show-cmd-BTLIXLYY.js} +6 -6
  70. package/dist/{control-plane-launch-HLFLGLW6.js → control-plane-launch-VPATGJOX.js} +5 -5
  71. package/dist/{demo-record-cmd-MDPZD53Q.js → demo-record-cmd-THSOAV2Z.js} +2 -2
  72. package/dist/{demo-voice-cmd-4JEXQP4I.js → demo-voice-cmd-WZTG4EOA.js} +11 -11
  73. package/dist/{docker-F4S3PBPD.js → docker-RZSABDTP.js} +4 -4
  74. package/dist/{doctor-MXWODPPL.js → doctor-3DZ6WX3N.js} +32 -32
  75. package/dist/{emit-artifact-cmd-QDYKKQT5.js → emit-artifact-cmd-LSOMCAWB.js} +10 -10
  76. package/dist/{emit-criteria-cmd-OCLNKIL4.js → emit-criteria-cmd-QGXJEVQQ.js} +7 -7
  77. package/dist/{emit-demo-cmd-RO3OXK4U.js → emit-demo-cmd-DQBIIGD3.js} +11 -11
  78. package/dist/{emit-finding-cmd-M4OKFZPF.js → emit-finding-cmd-Q2AVCU7I.js} +7 -7
  79. package/dist/{emit-result-cmd-CUTNYSOQ.js → emit-result-cmd-UCIWLIXJ.js} +9 -9
  80. package/dist/{emit-step-cmd-SY54AQYM.js → emit-step-cmd-M2EUH4MC.js} +7 -7
  81. package/dist/{exec-client-3ZVMZRZD.js → exec-client-CACFKEHG.js} +3 -3
  82. package/dist/{find-unit-5ALT2LU3.js → find-unit-5MZ7BHRD.js} +8 -8
  83. package/dist/{findings-cmd-246XYZSE.js → findings-cmd-DLJSGR2Z.js} +7 -7
  84. package/dist/{fleet-readiness-SOSSKSII.js → fleet-readiness-BXCAJXUJ.js} +5 -5
  85. package/dist/{governing-source-2UXHLXCS.js → governing-source-LWLFMQ2W.js} +9 -9
  86. package/dist/{guest-init-ZNSEHMXA.js → guest-init-TJQFOKPW.js} +4 -4
  87. package/dist/{hook-fast-27GO6BM2.js → hook-fast-5BMJYJBP.js} +1 -1
  88. package/dist/{host-checks-RK5TC3TX.js → host-checks-NZEMJCEM.js} +28 -28
  89. package/dist/{pending-625SL7WI.js → host-key-5ZQYRJ4E.js} +3 -3
  90. package/dist/{image-tag-WQB5HVLI.js → image-tag-JSSECZZE.js} +3 -3
  91. package/dist/index.js +4 -4
  92. package/dist/{init-CSWMBTTM.js → init-334GEUWV.js} +28 -28
  93. package/dist/{init-GH74PR4K.js → init-MSMRHTHS.js} +28 -28
  94. package/dist/{init-agent-54VT3S3Z.js → init-agent-CMZKNDGD.js} +28 -28
  95. package/dist/{init-cmd-AIUYATFU.js → init-cmd-L5XCJGZE.js} +10 -10
  96. package/dist/{init-update-BIHC42CB.js → init-update-SQEBAU2E.js} +8 -8
  97. package/dist/{install-cmd-YMPTGHE4.js → install-cmd-MFPQWUDC.js} +5 -5
  98. package/dist/{logs-HIXNEXBT.js → logs-F3IASZEW.js} +2 -2
  99. package/dist/{loop-P7NDQS3G.js → loop-6HY663IL.js} +37 -37
  100. package/dist/{machine-UEW4P7I6.js → machine-XIKOX7WS.js} +28 -28
  101. package/dist/{mcp-serve-cmd-4EGVZBCK.js → mcp-serve-cmd-KIP3JUYE.js} +4 -4
  102. package/dist/{paths-AGOA7QX6.js → paths-HU7EYF2U.js} +2 -2
  103. package/dist/{host-key-ZRJ4CGFC.js → pending-WNHJ5I2H.js} +3 -3
  104. package/dist/{pidfile-H2DZIODT.js → pidfile-UYKW6PT2.js} +3 -3
  105. package/dist/{record-UHMPQIUU.js → record-UJ6R33UZ.js} +3 -3
  106. package/dist/{runner-env-YPIZG3VG.js → runner-env-NDXVB5YY.js} +8 -8
  107. package/dist/{runner-identity-RPRUONRJ.js → runner-identity-YXGTTBKA.js} +4 -4
  108. package/dist/{runner-key-PNZTLOK5.js → runner-key-CO6357IF.js} +28 -28
  109. package/dist/{session-sender-B526LNJ6.js → session-sender-YJDE2SEH.js} +10 -10
  110. package/dist/{spec-cmd-6TZVHED2.js → spec-cmd-V7JOMHZF.js} +8 -8
  111. package/dist/{state-ALHXVNOS.js → state-CG5CTXKH.js} +3 -3
  112. package/dist/{status-X7IK4XQU.js → status-3XYAF6ZY.js} +28 -28
  113. package/dist/{sync-cmd-NMWPCIFU.js → sync-cmd-RSSBSQXL.js} +9 -9
  114. package/dist/{update-steps-R7AQAO6R.js → update-steps-NCHAZ5KA.js} +29 -29
  115. package/dist/{watch-INJRAQRE.js → watch-FTHG5QVH.js} +9 -9
  116. package/dist/{work-claim-cmd-YE4MVGZH.js → work-claim-cmd-7MLYX5OA.js} +13 -13
  117. package/dist/{work-cmd-6JUZHKXN.js → work-cmd-WVRZ3ONW.js} +7 -7
  118. package/dist/{work-comment-cmd-KK7H6F67.js → work-comment-cmd-6AEA5UOR.js} +9 -9
  119. package/dist/{work-demo-cmd-32PXKPZK.js → work-demo-cmd-67SOL7WG.js} +7 -7
  120. package/dist/{work-logs-cmd-QYSBE2SP.js → work-logs-cmd-Y5VTLE6R.js} +7 -7
  121. package/dist/{work-open-pr-cmd-PSATZ2BK.js → work-open-pr-cmd-OVGDDLWM.js} +8 -8
  122. package/dist/{work-pr-cmd-BEYPR7TL.js → work-pr-cmd-Z5PB457N.js} +7 -7
  123. package/dist/{work-proofs-cmd-Y7WZNTI3.js → work-proofs-cmd-CAFCKTPD.js} +8 -8
  124. package/dist/{work-proofs-record-5DCQQT23.js → work-proofs-record-SYYCUSBA.js} +14 -14
  125. package/dist/{work-stop-cmd-MUSKJC5M.js → work-stop-cmd-CF4W4NXI.js} +7 -7
  126. package/package.json +5 -3
@@ -1,517 +1,295 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'node:module';
3
- import { builtInNames, TARGET_TUNNEL, TARGET_LEASE, destinationTarget, builtInDestinations, builtInEnvironment, managedAgentCredential, agentCredential, destinationPort } from './chunk-FV52S3JR.js';
3
+ import { builtInEnvironment, managedAgentCredential, agentCredential, builtInNames, TARGET_TUNNEL, TARGET_LEASE, destinationTarget, builtInDestinations, destinationPort } from './chunk-FV52S3JR.js';
4
4
  import { strippedVariables } from './chunk-P4YTEF6T.js';
5
5
  import { defaultAgents } from './chunk-UZNSGMUZ.js';
6
6
  import { PROVIDERS } from './chunk-QJKW4MKH.js';
7
- import { existsSync, unlinkSync, chmodSync } from 'fs';
7
+ import { MIN_SCRUBBED_LITERAL } from './chunk-ZQNYV4OZ.js';
8
+ import { mkdirSync, writeFileSync, existsSync, unlinkSync, chmodSync } from 'fs';
8
9
  import { request as request$1, createServer } from 'http';
9
10
  import { request } from 'https';
10
- import { createServer as createServer$1 } from 'net';
11
+ import { isIP, createServer as createServer$1 } from 'net';
11
12
  import { join } from 'path';
12
- import { lookup } from 'dns';
13
+ import { generateKeyPairSync, randomBytes, X509Certificate, createHash, sign } from 'crypto';
14
+ import { rootCertificates } from 'tls';
13
15
 
14
16
  createRequire(import.meta.url);
15
17
 
16
- // src/runner/container/ranges.ts
17
- var V4 = [
18
- ["unspecified", "0.0.0.0/8"],
19
- ["loopback", "127.0.0.0/8"],
20
- ["private", "10.0.0.0/8"],
21
- ["private", "172.16.0.0/12"],
22
- ["private", "192.168.0.0/16"],
23
- ["protocol-assignments", "192.0.0.0/24"],
24
- ["benchmarking", "198.18.0.0/15"],
25
- ["azure-wireserver", "168.63.129.16/32"],
26
- ["link-local", "169.254.0.0/16"],
27
- ["shared-address", "100.64.0.0/10"],
28
- ["multicast", "224.0.0.0/4"],
29
- ["reserved", "240.0.0.0/4"]
30
- ];
31
- var V6 = [
32
- ["unspecified", "::/128"],
33
- ["loopback", "::1/128"],
34
- ["ipv4-mapped", "::ffff:0:0/96"],
35
- ["nat64", "64:ff9b::/96"],
36
- // The location of an embedded IPv4 address depends on the translator's prefix length, so the whole prefix is refused.
37
- ["nat64-local", "64:ff9b:1::/48"],
38
- ["ipv4-compatible", "::/96"],
39
- ["link-local", "fe80::/10"],
40
- ["unique-local", "fc00::/7"],
41
- ["multicast", "ff00::/8"]
42
- ];
43
- var UNPARSEABLE = { name: "unparseable", cidr: "-" };
44
- function parseV4(text) {
45
- const parts = text.split(".");
46
- if (parts.length !== 4) return void 0;
47
- let value = 0;
48
- for (const part of parts) {
49
- if (!/^\d{1,3}$/.test(part)) return void 0;
50
- const octet = Number(part);
51
- if (octet > 255) return void 0;
52
- value = value * 256 + octet;
53
- }
54
- return value;
55
- }
56
- function parseV6(input) {
57
- const zone = input.indexOf("%");
58
- let text = zone === -1 ? input : input.slice(0, zone);
59
- const lastColon = text.lastIndexOf(":");
60
- const tail = text.slice(lastColon + 1);
61
- if (tail.includes(".")) {
62
- const v4 = parseV4(tail);
63
- if (v4 === void 0) return void 0;
64
- text = `${text.slice(0, lastColon + 1)}${(v4 >>> 16).toString(16)}:${(v4 & 65535).toString(16)}`;
65
- }
66
- const halves = text.split("::");
67
- if (halves.length > 2) return void 0;
68
- const groups = (part) => {
69
- if (part === "") return [];
70
- const found = part.split(":");
71
- return found.every((g) => /^[0-9a-fA-F]{1,4}$/.test(g)) ? found : void 0;
72
- };
73
- const head = groups(halves[0]);
74
- const rest = groups(halves[1] ?? "");
75
- if (head === void 0 || rest === void 0) return void 0;
76
- let words;
77
- if (halves.length === 2) {
78
- const missing = 8 - head.length - rest.length;
79
- if (missing < 1) return void 0;
80
- words = [...head, ...Array(missing).fill("0"), ...rest];
81
- } else {
82
- if (head.length !== 8) return void 0;
83
- words = head;
84
- }
85
- return words.reduce((acc, word) => acc << BigInt(16) | BigInt(parseInt(word, 16)), BigInt(0));
18
+ // src/scrub-env.ts
19
+ var SCRUB_ENV_VARIABLE = "OUTERLAYER_SCRUB_ENV";
20
+
21
+ // src/runner/der.ts
22
+ function length(size) {
23
+ if (size < 128) return Buffer.from([size]);
24
+ const bytes = [];
25
+ for (let rest = size; rest > 0; rest = Math.floor(rest / 256)) bytes.unshift(rest % 256);
26
+ return Buffer.from([128 | bytes.length, ...bytes]);
86
27
  }
87
- function build4() {
88
- return V4.map(([name, cidr]) => {
89
- const [address, length] = cidr.split("/");
90
- return { name, cidr, base: parseV4(address), bits: Number(length) };
91
- });
28
+ function tlv(tag, body) {
29
+ return Buffer.concat([Buffer.from([tag]), length(body.length), body]);
92
30
  }
93
- function build6() {
94
- return V6.map(([name, cidr]) => {
95
- const [address, length] = cidr.split("/");
96
- return { name, cidr, base: parseV6(address), bits: Number(length) };
97
- });
31
+ var sequence = (...parts) => tlv(48, Buffer.concat(parts));
32
+ function numberBytes(value) {
33
+ const hex = value.toString(16);
34
+ return Buffer.from(hex.length % 2 === 0 ? hex : `0${hex}`, "hex");
98
35
  }
99
- var RANGES_4 = build4();
100
- var RANGES_6 = build6();
101
- [...RANGES_4, ...RANGES_6].map(({ name, cidr }) => ({ name, cidr }));
102
- function carried6to4(address) {
103
- const v6 = parseV6(address);
104
- if (v6 === void 0 || v6 >> BigInt(112) !== BigInt(8194)) return void 0;
105
- const v4 = Number(v6 >> BigInt(80) & BigInt(4294967295));
106
- return [v4 >>> 24, v4 >>> 16 & 255, v4 >>> 8 & 255, v4 & 255].join(".");
36
+ function integer(value) {
37
+ let bytes = typeof value === "number" ? numberBytes(value) : Buffer.from(value);
38
+ while (bytes.length > 1 && bytes[0] === 0) bytes = bytes.subarray(1);
39
+ if (bytes[0] & 128) bytes = Buffer.concat([Buffer.from([0]), bytes]);
40
+ return tlv(2, bytes);
107
41
  }
108
- function classifyAddress(address) {
109
- const v4 = parseV4(address);
110
- if (v4 !== void 0) {
111
- for (const range of RANGES_4) {
112
- const shift = 32 - range.bits;
113
- if (Math.floor(v4 / 2 ** shift) === Math.floor(range.base / 2 ** shift)) return { name: range.name, cidr: range.cidr };
114
- }
115
- return void 0;
116
- }
117
- const v6 = parseV6(address);
118
- if (v6 === void 0) return UNPARSEABLE;
119
- const carries = carried6to4(address);
120
- if (carries !== void 0) {
121
- const inner = classifyAddress(carries);
122
- return inner === void 0 ? void 0 : { ...inner, carries };
123
- }
124
- for (const range of RANGES_6) {
125
- const shift = BigInt(128 - range.bits);
126
- if (v6 >> shift === range.base >> shift) return { name: range.name, cidr: range.cidr };
42
+ function oid(dotted) {
43
+ const parts = dotted.split(".").map(Number);
44
+ const bytes = [parts[0] * 40 + parts[1]];
45
+ for (const part of parts.slice(2)) {
46
+ const chunk = [part & 127];
47
+ for (let rest = Math.floor(part / 128); rest > 0; rest = Math.floor(rest / 128)) chunk.unshift(rest & 127 | 128);
48
+ bytes.push(...chunk);
127
49
  }
128
- return void 0;
50
+ return tlv(6, Buffer.from(bytes));
51
+ }
52
+ var utf8String = (text) => tlv(12, Buffer.from(text, "utf8"));
53
+ var octetString = (bytes) => tlv(4, bytes);
54
+ var boolean = (value) => tlv(1, Buffer.from([255 ]));
55
+ var bitString = (bytes, unused = 0) => tlv(3, Buffer.concat([Buffer.from([unused]), bytes]));
56
+ function utcTime(date) {
57
+ const two = (n) => String(n).padStart(2, "0");
58
+ const text = `${two(date.getUTCFullYear() % 100)}${two(date.getUTCMonth() + 1)}${two(date.getUTCDate())}${two(date.getUTCHours())}${two(date.getUTCMinutes())}${two(date.getUTCSeconds())}Z`;
59
+ return tlv(23, Buffer.from(text, "ascii"));
60
+ }
61
+ var explicit = (n, body) => tlv(160 | n, body);
62
+ var implicit = (n, bytes) => tlv(128 | n, bytes);
63
+ var IPV4 = /^(?:\d{1,3}\.){3}\d{1,3}$/;
64
+ function isIpAddress(host) {
65
+ return IPV4.test(host) || host.includes(":");
66
+ }
67
+ function addressBytes(address) {
68
+ if (IPV4.test(address)) return Buffer.from(address.split(".").map(Number));
69
+ const [head = "", tail] = address.split("::");
70
+ const groups = (text) => text === "" ? [] : text.split(":").flatMap((group) => group.includes(".") ? [...addressBytes(group)].reduce((pairs, byte, i) => i % 2 === 0 ? [...pairs, byte << 8] : [...pairs.slice(0, -1), pairs.at(-1) | byte], []) : [parseInt(group, 16)]);
71
+ const front = groups(head);
72
+ const back = tail === void 0 ? [] : groups(tail);
73
+ const all = tail === void 0 ? front : [...front, ...Array(8 - front.length - back.length).fill(0), ...back];
74
+ const out = Buffer.alloc(16);
75
+ all.forEach((group, i) => out.writeUInt16BE(group, i * 2));
76
+ return out;
129
77
  }
130
78
 
131
- // src/runner/destinations.ts
132
- var MAX_RELEASED_DESTINATIONS = 20;
133
- function maxDestinations(agents = defaultAgents(), providers = PROVIDERS) {
134
- return MAX_RELEASED_DESTINATIONS - builtInNames(agents, providers).length;
79
+ // src/runner/build-authority.ts
80
+ var ECDSA_SHA256 = "1.2.840.10045.4.3.2";
81
+ var COMMON_NAME = "2.5.4.3";
82
+ var ORGANIZATION = "2.5.4.10";
83
+ var BASIC_CONSTRAINTS = "2.5.29.19";
84
+ var KEY_USAGE = "2.5.29.15";
85
+ var EXTENDED_KEY_USAGE = "2.5.29.37";
86
+ var SUBJECT_ALT_NAME = "2.5.29.17";
87
+ var SUBJECT_KEY_ID = "2.5.29.14";
88
+ var AUTHORITY_KEY_ID = "2.5.29.35";
89
+ var SERVER_AUTH = "1.3.6.1.5.5.7.3.1";
90
+ var VALID_DAYS = 30;
91
+ var BACKDATE_MS = 60 * 60 * 1e3;
92
+ var MAX_COMMON_NAME = 64;
93
+ var name = (common) => sequence(
94
+ tlv(49, sequence(oid(ORGANIZATION), utf8String("OuterLayer build"))),
95
+ tlv(49, sequence(oid(COMMON_NAME), utf8String(common.length > MAX_COMMON_NAME ? common.slice(0, MAX_COMMON_NAME) : common)))
96
+ );
97
+ var extension = (id, critical, value) => sequence(oid(id), ...critical ? [boolean()] : [], octetString(value));
98
+ var keyId = (spki) => createHash("sha1").update(spki).digest();
99
+ function pem(der) {
100
+ return `-----BEGIN CERTIFICATE-----
101
+ ${der.toString("base64").replace(/(.{64})/g, "$1\n").replace(/\n$/, "")}
102
+ -----END CERTIFICATE-----
103
+ `;
135
104
  }
136
- var DESTINATION_BASE_PORT = 3129;
137
- var DESTINATION_NAME = /^[a-z0-9][a-z0-9-]{0,62}$/;
138
- var VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,254}$/;
139
- var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
140
- var HEADER_VARIABLE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
141
- var DESTINATION_KEYS = ["name", "upstream", "header", "env"];
142
- var MAX_SOCKET_PATH_BYTES = 100;
143
- var UPSTREAM_IDLE_MS = 6e5;
144
- function headerVariables(destinations) {
145
- return [...new Set((destinations ?? []).flatMap((d) => d.header.variables))];
105
+ function certificate(input) {
106
+ const notBefore = new Date(input.now.getTime() - BACKDATE_MS);
107
+ const notAfter = new Date(input.now.getTime() + VALID_DAYS * 24 * 60 * 60 * 1e3);
108
+ const algorithm = sequence(oid(ECDSA_SHA256));
109
+ const serial = randomBytes(16);
110
+ serial[0] &= 127;
111
+ const tbs = sequence(
112
+ explicit(0, integer(2)),
113
+ integer(serial),
114
+ algorithm,
115
+ input.issuer.subject,
116
+ sequence(utcTime(notBefore), utcTime(notAfter)),
117
+ input.subject,
118
+ input.publicKey.export({ type: "spki", format: "der" }),
119
+ explicit(3, sequence(...input.extensions))
120
+ );
121
+ const signature = sign("sha256", tbs, { key: input.issuer.key, dsaEncoding: "der" });
122
+ return sequence(tbs, algorithm, bitString(signature));
146
123
  }
147
- function resolveDestinations(given, variables, isReserved, fail, agents = defaultAgents(), providers = PROVIDERS) {
148
- if (!Array.isArray(given)) fail("runner.build.destinations", "must be a list of destinations");
149
- const builtIns = builtInNames(agents, providers);
150
- const most = maxDestinations(agents, providers);
151
- if (given.length > most) {
152
- fail(
153
- "runner.build.destinations",
154
- `lists ${given.length} destinations; a release records at most ${MAX_RELEASED_DESTINATIONS}, and ${builtIns.length} of those are the built-in ${builtIns.join(" and ")} destinations, so a host lists at most ${most}`
155
- );
156
- }
157
- const resolved = [];
158
- const names = /* @__PURE__ */ new Set();
159
- const envNames = /* @__PURE__ */ new Set();
160
- for (const [index, entry] of given.entries()) {
161
- const at = `runner.build.destinations[${index}]`;
162
- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) fail(at, "must be an object");
163
- const record = entry;
164
- for (const key of Object.keys(record)) {
165
- if (!DESTINATION_KEYS.includes(key)) {
166
- fail(`${at}.${key}`, `is not a key a destination accepts; the keys are ${DESTINATION_KEYS.join(", ")}`);
167
- }
168
- }
169
- const name = record.name;
170
- if (typeof name !== "string" || !DESTINATION_NAME.test(name)) {
171
- fail(`${at}.name`, "must be 1 to 63 lower-case letters, digits or hyphens, starting with a letter or digit");
172
- }
173
- if (builtIns.includes(name)) fail(`${at}.name`, `is ${name}, a destination the runner serves itself`);
174
- if (names.has(name)) fail(`${at}.name`, `repeats the destination ${name}`);
175
- names.add(name);
176
- const upstream = parseUpstream(record.upstream, `${at}.upstream`, fail);
177
- const header = parseHeader(record.header, `${at}.header`, fail);
178
- for (const variable of header.variables) {
179
- if (variables.includes(variable)) {
180
- fail(`${at}.header`, `names ${variable}, which build.variables also passes into the build; a secret a build can read is not a destination's`);
181
- }
182
- }
183
- const env = parseEnv(record.env, `${at}.env`, isReserved, fail);
184
- for (const variable of Object.keys(env)) {
185
- if (envNames.has(variable)) fail(`${at}.env`, `sets ${variable}, which another destination sets too`);
186
- envNames.add(variable);
187
- if (variables.includes(variable)) fail(`${at}.env`, `sets ${variable}, which build.variables also passes into the build`);
124
+ function createBuildAuthority(now = /* @__PURE__ */ new Date()) {
125
+ const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
126
+ const spki = publicKey.export({ type: "spki", format: "der" });
127
+ const subject = name(`OuterLayer build authority ${randomBytes(6).toString("hex")}`);
128
+ const id = keyId(spki);
129
+ const issuer = { subject, key: privateKey, keyId: id };
130
+ const der = certificate({
131
+ issuer,
132
+ subject,
133
+ publicKey,
134
+ now,
135
+ extensions: [
136
+ extension(BASIC_CONSTRAINTS, true, sequence(boolean(), integer(0))),
137
+ // keyCertSign and cRLSign: bits 5 and 6, so one unused bit.
138
+ extension(KEY_USAGE, true, bitString(Buffer.from([6]), 1)),
139
+ extension(SUBJECT_KEY_ID, false, octetString(id))
140
+ ]
141
+ });
142
+ const leaves = /* @__PURE__ */ new Map();
143
+ return {
144
+ certificatePem: pem(der),
145
+ certificateDer: der,
146
+ leafFor(host) {
147
+ const kept = leaves.get(host);
148
+ if (kept !== void 0) return kept;
149
+ const pair = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
150
+ const leafSpki = pair.publicKey.export({ type: "spki", format: "der" });
151
+ const alternative = isIpAddress(host) ? implicit(7, addressBytes(host)) : implicit(2, Buffer.from(host, "ascii"));
152
+ const leaf = certificate({
153
+ issuer,
154
+ subject: name(host),
155
+ publicKey: pair.publicKey,
156
+ now,
157
+ extensions: [
158
+ extension(BASIC_CONSTRAINTS, true, sequence()),
159
+ // digitalSignature: bit 0, so seven unused bits. An EC key needs no key encipherment.
160
+ extension(KEY_USAGE, true, bitString(Buffer.from([128]), 7)),
161
+ extension(EXTENDED_KEY_USAGE, false, sequence(oid(SERVER_AUTH))),
162
+ extension(SUBJECT_ALT_NAME, false, sequence(alternative)),
163
+ extension(SUBJECT_KEY_ID, false, octetString(keyId(leafSpki))),
164
+ extension(AUTHORITY_KEY_ID, false, sequence(implicit(0, id)))
165
+ ]
166
+ });
167
+ const made = { certPem: pem(leaf), keyPem: pair.privateKey.export({ type: "pkcs8", format: "pem" }).toString() };
168
+ leaves.set(host, made);
169
+ return made;
188
170
  }
189
- resolved.push({ name, upstream, header, env });
171
+ };
172
+ }
173
+ var held = /* @__PURE__ */ new Map();
174
+ function buildAuthorityFor(jobDir) {
175
+ let authority = held.get(jobDir);
176
+ if (authority === void 0) {
177
+ authority = createBuildAuthority();
178
+ held.set(jobDir, authority);
190
179
  }
191
- for (const [index, destination] of resolved.entries()) {
192
- for (const variable of destination.header.variables) {
193
- if (envNames.has(variable)) {
194
- fail(`runner.build.destinations[${index}].env`, `sets ${variable}, which a destination's header reads as a secret`);
195
- }
180
+ return authority;
181
+ }
182
+ function heldBuildAuthority(jobDir) {
183
+ return jobDir === void 0 ? void 0 : held.get(jobDir);
184
+ }
185
+ function dropBuildAuthority(jobDir) {
186
+ held.delete(jobDir);
187
+ }
188
+ var MAGIC = 4277010157;
189
+ var VERSION = 2;
190
+ var TRUSTED_CERTIFICATE = 2;
191
+ var PASSWORD = "changeit";
192
+ var DIGEST_PHRASE = "Mighty Aphrodite";
193
+ var u16 = (n) => {
194
+ const b = Buffer.alloc(2);
195
+ b.writeUInt16BE(n);
196
+ return b;
197
+ };
198
+ var u32 = (n) => {
199
+ const b = Buffer.alloc(4);
200
+ b.writeUInt32BE(n);
201
+ return b;
202
+ };
203
+ var u64 = (n) => {
204
+ const b = Buffer.alloc(8);
205
+ b.writeBigUInt64BE(BigInt(n));
206
+ return b;
207
+ };
208
+ var utf = (text) => {
209
+ const bytes = Buffer.from(text, "utf8");
210
+ return Buffer.concat([u16(bytes.length), bytes]);
211
+ };
212
+ function writeJks(certificates, now = /* @__PURE__ */ new Date()) {
213
+ const parts = [u32(MAGIC), u32(VERSION), u32(certificates.length)];
214
+ for (const { alias, der } of certificates) parts.push(u32(TRUSTED_CERTIFICATE), utf(alias), u64(now.getTime()), utf("X.509"), u32(der.length), der);
215
+ const body = Buffer.concat(parts);
216
+ const digest = createHash("sha1").update(Buffer.from(PASSWORD, "utf16le").swap16()).update(DIGEST_PHRASE, "utf8").update(body).digest();
217
+ return Buffer.concat([body, digest]);
218
+ }
219
+
220
+ // src/runner/build-trust.ts
221
+ var TRUST_DIR = "/outerlayer/job/trust";
222
+ var BUNDLE_FILE = `${TRUST_DIR}/bundle.crt`;
223
+ var TRUSTSTORE_FILE = `${TRUST_DIR}/truststore.jks`;
224
+ var TRUST_STORE_OPTION = `-Djavax.net.ssl.trustStore=${TRUSTSTORE_FILE}`;
225
+ var CERTIFICATE_BLOCK = /-----BEGIN CERTIFICATE-----[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----/g;
226
+ function certificatesIn(text) {
227
+ const found = [];
228
+ for (const [block] of text.matchAll(CERTIFICATE_BLOCK)) {
229
+ try {
230
+ found.push(new X509Certificate(block));
231
+ } catch {
196
232
  }
197
233
  }
198
- return resolved;
234
+ return found;
199
235
  }
200
- function parseUpstream(value, key, fail) {
201
- if (typeof value !== "string") fail(key, "must be an https:// address");
202
- let url;
203
- try {
204
- url = new URL(value);
205
- } catch {
206
- fail(key, `${JSON.stringify(value)} is not an https:// address`);
207
- }
208
- if (url.protocol !== "https:") fail(key, `${JSON.stringify(value)} is not an https:// address: a destination's secret is only ever sent over TLS`);
209
- if (url.username !== "" || url.password !== "") fail(key, "must not carry a login; the credential goes in the header");
210
- if (url.search !== "" || url.hash !== "") fail(key, "must not carry a query or a fragment");
211
- return url.href;
236
+ function trustFilesFor(authority, imageBundlePem) {
237
+ let roots = certificatesIn(imageBundlePem ?? "");
238
+ if (roots.length === 0) roots = rootCertificates.flatMap((text) => certificatesIn(text));
239
+ const ours = new X509Certificate(authority.certificatePem);
240
+ const unique = /* @__PURE__ */ new Map();
241
+ for (const cert of [...roots, ours]) unique.set(cert.fingerprint256, cert);
242
+ const all = [...unique.values()];
243
+ return {
244
+ authorityCrt: authority.certificatePem,
245
+ bundleCrt: all.map((cert) => cert.toString()).join(""),
246
+ truststoreJks: writeJks(
247
+ all.map((cert) => ({ alias: createHash("sha1").update(cert.raw).digest("hex"), der: cert.raw }))
248
+ )
249
+ };
212
250
  }
213
- function parseHeader(value, key, fail) {
214
- if (typeof value !== "string") fail(key, 'must be a string such as "Authorization: Bearer ${NPM_TOKEN}"');
215
- const colon = value.indexOf(":");
216
- if (colon === -1) fail(key, 'must be "Name: value", with a colon');
217
- const name = value.slice(0, colon).trim();
218
- const text = value.slice(colon + 1).trim();
219
- if (!HEADER_NAME.test(name)) fail(key, `names the header ${JSON.stringify(name)}, which is not a header name`);
220
- if (text === "") fail(key, "has an empty value");
221
- if (/[\r\n\0]/.test(text)) fail(key, "has a value with a line break in it");
222
- const variables = [...new Set([...text.matchAll(HEADER_VARIABLE)].map((m) => m[1]))];
223
- return { name, value: text, variables };
251
+ var JAVA_OPTION = /(?:[^\s"']+|"[^"]*"?|'[^']*'?)+/g;
252
+ function optionsOf(text) {
253
+ return text.match(JAVA_OPTION) ?? [];
224
254
  }
225
- function parseEnv(value, key, isReserved, fail) {
226
- if (value === void 0) return {};
227
- if (typeof value !== "object" || value === null || Array.isArray(value)) fail(key, "must be an object of variable names and values");
228
- const env = {};
229
- for (const [name, text] of Object.entries(value)) {
230
- if (!VARIABLE_NAME.test(name)) fail(key, `names ${JSON.stringify(name)}, which is not a variable name`);
231
- if (isReserved(name)) fail(key, `names ${name}, which the runner sets itself`);
232
- if (typeof text !== "string") fail(key, `gives ${name} a value that is not a string`);
233
- env[name] = text;
234
- }
235
- return env;
255
+ function mergeJavaOptions(team) {
256
+ const kept = optionsOf(team ?? "").filter((option) => option !== TRUST_STORE_OPTION);
257
+ return [...kept, TRUST_STORE_OPTION].join(" ");
236
258
  }
237
- function destinationEnvironment(destinations, localFor) {
238
- const env = {};
239
- for (const [index, destination] of (destinations ?? []).entries()) {
240
- for (const [name, value] of Object.entries(destination.env)) env[name] = value.split("{local}").join(localFor(index));
241
- }
242
- return env;
259
+ function trustEnvironment(jobDir) {
260
+ if (heldBuildAuthority(jobDir) === void 0) return {};
261
+ return {
262
+ NODE_EXTRA_CA_CERTS: BUNDLE_FILE,
263
+ REQUESTS_CA_BUNDLE: BUNDLE_FILE,
264
+ CARGO_HTTP_CAINFO: BUNDLE_FILE,
265
+ SSL_CERT_FILE: BUNDLE_FILE,
266
+ CURL_CA_BUNDLE: BUNDLE_FILE,
267
+ GIT_SSL_CAINFO: BUNDLE_FILE,
268
+ JAVA_TOOL_OPTIONS: TRUST_STORE_OPTION
269
+ };
243
270
  }
244
- function containerLocalAddress(index) {
245
- return `http://127.0.0.1:${DESTINATION_BASE_PORT + index}/`;
271
+ var IMAGE_BUNDLES = ["/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/ca-bundle.pem", "/etc/ssl/cert.pem"];
272
+ function readBundleScript() {
273
+ return `for ca in ${IMAGE_BUNDLES.join(" ")}; do if [ -f "$ca" ]; then cat "$ca"; exit 0; fi; done; exit 0`;
246
274
  }
247
- function destinationSocketPath(buildDir, index) {
248
- return join(buildDir, `dest-${index}.sock`);
275
+ function writeTrustFiles(dir, authority, imageBundlePem) {
276
+ const files = trustFilesFor(authority, imageBundlePem);
277
+ mkdirSync(dir, { recursive: true });
278
+ writeFileSync(join(dir, "authority.crt"), files.authorityCrt, { mode: 420 });
279
+ writeFileSync(join(dir, "bundle.crt"), files.bundleCrt, { mode: 420 });
280
+ writeFileSync(join(dir, "truststore.jks"), files.truststoreJks, { mode: 420 });
249
281
  }
250
- function respond(res, status, body) {
251
- if (res.headersSent) {
252
- res.destroy();
253
- return;
254
- }
255
- res.writeHead(status, { "Content-Type": "text/plain", "Content-Length": Buffer.byteLength(body), Connection: "close" });
256
- res.end(body);
257
- }
258
- function expandHeader(header, env) {
259
- for (const name of header.variables) {
260
- if (env[name] === void 0 || env[name] === "") return { missing: name };
261
- }
262
- return { value: header.value.replace(HEADER_VARIABLE, (_match, name) => env[name]) };
263
- }
264
- var publicLookup = (hostname, options, callback) => {
265
- lookup(hostname, { all: true, family: options.family ?? 0 }, (err, addresses) => {
266
- if (err) return callback(err, "", 0);
267
- const allowed = addresses.filter(({ address }) => classifyAddress(address) === void 0);
268
- if (allowed.length === 0) return callback(Object.assign(new Error(`${hostname} resolves to a private address`), { code: "EACCES" }), "", 0);
269
- if (options.all === true) return callback(null, allowed);
270
- callback(null, allowed[0].address, allowed[0].family);
271
- });
272
- };
273
- async function startDestination(input) {
274
- const { destination, hostEnv } = input;
275
- const upstream = new URL(destination.upstream);
276
- const prefix = upstream.pathname.replace(/\/+$/, "");
277
- const secure = upstream.protocol === "https:";
278
- const send = input.request ?? (secure ? request : request$1);
279
- const headerName = destination.header.name.toLowerCase();
280
- const dropped = /* @__PURE__ */ new Set(["host", "authorization", "proxy-authorization", "cookie", "connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade", ...input.drop ?? []]);
281
- const handle = (req, res) => {
282
- let finished = false;
283
- const finish = (ok) => {
284
- if (finished) return;
285
- finished = true;
286
- input.onFinished?.(destination.name, ok);
287
- };
288
- res.on("finish", () => finish(true));
289
- res.on("close", () => finish(false));
290
- const fail = (status, body) => {
291
- finish(false);
292
- respond(res, status, body);
293
- };
294
- const target = req.url ?? "";
295
- if (!target.startsWith("/")) {
296
- fail(400, "send an origin-form request path\n");
297
- return;
298
- }
299
- if (input.guardUpstream === true) {
300
- if (req.method === "TRACE") {
301
- fail(405, "TRACE is not sent to this destination\n");
302
- return;
303
- }
304
- if (target.split(/[/?#]/).some((segment) => /^(\.|%2e){2}$/i.test(segment))) {
305
- fail(400, "send a request path without .. segments\n");
306
- return;
307
- }
308
- }
309
- const expanded = expandHeader(destination.header, hostEnv);
310
- if ("missing" in expanded) {
311
- fail(502, `the destination ${destination.name} cannot be reached: ${expanded.missing} is not set in the runner's environment
312
- `);
313
- return;
314
- }
315
- const headers = {};
316
- for (const [name, value] of Object.entries(req.headers)) {
317
- if (!dropped.has(name)) headers[name] = value;
318
- }
319
- headers.host = upstream.host;
320
- headers[headerName] = expanded.value;
321
- let forwarded;
322
- try {
323
- forwarded = send(
324
- {
325
- protocol: upstream.protocol,
326
- hostname: upstream.hostname,
327
- port: upstream.port === "" ? secure ? 443 : 80 : Number(upstream.port),
328
- method: req.method,
329
- path: `${prefix}${target}`,
330
- headers,
331
- ...input.ca === void 0 ? {} : { ca: input.ca },
332
- ...input.guardUpstream === true && input.allowPrivateUpstream !== true ? { lookup: publicLookup } : {}
333
- },
334
- (answer) => {
335
- res.writeHead(answer.statusCode ?? 502, answer.headers);
336
- answer.on("error", () => res.destroy());
337
- answer.on("close", () => {
338
- if (!answer.complete) {
339
- finish(false);
340
- res.destroy();
341
- }
342
- });
343
- answer.pipe(res);
344
- }
345
- );
346
- } catch {
347
- fail(502, `the destination ${destination.name} cannot be reached: its header value was refused
348
- `);
349
- return;
350
- }
351
- input.onUsed?.(destination.name);
352
- forwarded.setTimeout(UPSTREAM_IDLE_MS, () => forwarded.destroy());
353
- res.on("close", () => forwarded.destroy());
354
- forwarded.on("error", (err) => {
355
- input.onUpstreamError?.(destination.name, typeof err.code === "string" ? err.code : "unknown");
356
- fail(502, `the upstream of the destination ${destination.name} could not be reached
357
- `);
358
- });
359
- req.pipe(forwarded);
360
- };
361
- const sockets = /* @__PURE__ */ new Set();
362
- const server = createServer(handle);
363
- server.on("connection", (socket) => {
364
- sockets.add(socket);
365
- socket.on("close", () => sockets.delete(socket));
366
- });
367
- const listeners = [server];
368
- const served = {};
369
- if (input.socketPath !== void 0) {
370
- if (Buffer.byteLength(input.socketPath) > MAX_SOCKET_PATH_BYTES) {
371
- throw new Error(`${input.socketPath} is too long for a Unix socket; keep the runner's config file nearer the root of the filesystem`);
372
- }
373
- if (input.listenOn !== void 0) {
374
- await input.listenOn(server);
375
- } else {
376
- if (existsSync(input.socketPath)) unlinkSync(input.socketPath);
377
- await new Promise((resolve, reject) => {
378
- server.once("error", reject);
379
- server.listen(input.socketPath, () => resolve());
380
- });
381
- chmodSync(input.socketPath, 438);
382
- }
383
- served.socketPath = input.socketPath;
384
- }
385
- if (input.port !== void 0) {
386
- const tcp = createServer$1((socket) => server.emit("connection", socket));
387
- await new Promise((resolve, reject) => {
388
- tcp.once("error", reject);
389
- tcp.listen(input.port, "127.0.0.1", () => resolve());
390
- });
391
- listeners.push(tcp);
392
- const address = tcp.address();
393
- served.port = address.port;
394
- }
395
- const close = async () => {
396
- for (const socket of sockets) socket.destroy();
397
- await Promise.all(listeners.map((listener) => new Promise((resolve) => listener.close(() => resolve()))));
398
- };
399
- return { ...served, acceptStream: (stream) => void server.emit("connection", stream), listener: () => input.socketPath === void 0 ? void 0 : server, close };
400
- }
401
- async function startBuildServices(input) {
402
- const streamed = input.serve === "stream";
403
- const listenOnFor = (socket) => {
404
- const listenOn = input.inherit?.(socket);
405
- return listenOn === void 0 ? {} : { listenOn };
406
- };
407
- const listeners = {};
408
- const tunnel = await input.startTunnel(join(input.buildDir, "tunnel.sock"), {
409
- ...input.tunnelOptions,
410
- ...streamed ? { socket: false } : {},
411
- ...streamed ? {} : listenOnFor("tunnel.sock"),
412
- ...input.allowHosts === void 0 ? {} : { allowHosts: input.allowHosts },
413
- ...input.egress === void 0 ? {} : { egress: input.egress },
414
- recordPath: join(input.jobDir, "tunnel.json")
415
- });
416
- const servers = [];
417
- const targets = /* @__PURE__ */ new Map();
418
- const tunnelListener = tunnel.listener?.();
419
- if (tunnelListener !== void 0) listeners["tunnel.sock"] = tunnelListener;
420
- if (streamed) targets.set(TARGET_TUNNEL, (stream) => tunnel.acceptStream(stream));
421
- if (streamed && input.lease !== void 0) targets.set(TARGET_LEASE, (stream) => input.lease.accept(stream));
422
- const closeAll = async () => {
423
- await Promise.all(servers.map((s) => s.close()));
424
- await tunnel.close();
425
- };
426
- try {
427
- const destinationPorts = [];
428
- const builtInPorts = {};
429
- for (const [index, destination] of input.destinations.entries()) {
430
- const server = await startDestination({
431
- destination,
432
- ...input.serve === "tcp" || streamed ? {} : { socketPath: destinationSocketPath(input.buildDir, index) },
433
- ...input.serve === "tcp" || streamed ? {} : listenOnFor(`dest-${index}.sock`),
434
- ...input.serve === "socket" || streamed ? {} : { port: input.ports?.destinations?.[index] ?? 0 },
435
- hostEnv: input.hostEnv,
436
- onUsed: (name) => tunnel.destinationUsed(name),
437
- onUpstreamError: (name, code) => input.log?.(`route ${name} could not reach its upstream: ${code}`),
438
- onFinished: (name, ok) => tunnel.routeFinished(name, ok),
439
- ...input.destinationOptions
440
- });
441
- servers.push(server);
442
- tunnel.routeServed(destination.name);
443
- input.log?.(`route ${destination.name} served to the build`);
444
- const listener = server.listener?.();
445
- if (listener !== void 0) listeners[`dest-${index}.sock`] = listener;
446
- targets.set(destinationTarget(index), (stream) => server.acceptStream(stream));
447
- if (server.port !== void 0) destinationPorts.push(server.port);
448
- }
449
- for (const factory of input.factory ?? []) {
450
- const server = await startDestination({
451
- destination: factory.destination,
452
- ...input.serve === "tcp" || streamed ? {} : { socketPath: destinationSocketPath(input.buildDir, factory.index) },
453
- ...input.serve === "tcp" || streamed ? {} : listenOnFor(`dest-${factory.index}.sock`),
454
- ...input.serve === "socket" || streamed ? {} : { port: 0 },
455
- hostEnv: factory.hostEnv,
456
- guardUpstream: true,
457
- onUsed: (name) => tunnel.destinationUsed(name),
458
- onUpstreamError: (name, code) => input.log?.(`route ${name} could not reach its upstream: ${code}`),
459
- onFinished: (name, ok) => tunnel.routeFinished(name, ok),
460
- ...input.destinationOptions
461
- });
462
- servers.push(server);
463
- tunnel.routeServed(factory.destination.name);
464
- input.log?.(`route ${factory.destination.name} served to the build`);
465
- const listener = server.listener?.();
466
- if (listener !== void 0) listeners[`dest-${factory.index}.sock`] = listener;
467
- targets.set(destinationTarget(factory.index), (stream) => server.acceptStream(stream));
468
- }
469
- const builtIns = input.builtIns === void 0 ? [] : builtInDestinations({ ...input.builtIns, hostEnv: input.hostEnv }, input.builtIns.agents, input.builtIns.providers);
470
- for (const builtIn of builtIns) {
471
- const server = await startDestination({
472
- destination: builtIn.destination,
473
- ...input.serve === "tcp" || streamed ? {} : { socketPath: join(input.buildDir, builtIn.socket) },
474
- ...input.serve === "tcp" || streamed ? {} : listenOnFor(builtIn.socket),
475
- ...input.serve === "socket" || streamed ? {} : { port: input.ports?.builtIns?.[builtIn.destination.name] ?? 0 },
476
- hostEnv: builtIn.hostEnv,
477
- drop: builtIn.drop,
478
- onUsed: (name) => tunnel.destinationUsed(name),
479
- onUpstreamError: (name, code) => input.log?.(`route ${name} could not reach its upstream: ${code}`),
480
- onFinished: (name, ok) => tunnel.routeFinished(name, ok),
481
- ...input.destinationOptions
482
- });
483
- servers.push(server);
484
- tunnel.routeServed(builtIn.destination.name);
485
- input.log?.(`route ${builtIn.destination.name} served to the build`);
486
- const listener = server.listener?.();
487
- if (listener !== void 0) listeners[builtIn.socket] = listener;
488
- targets.set(builtIn.destination.name, (stream) => server.acceptStream(stream));
489
- if (server.port !== void 0) builtInPorts[builtIn.destination.name] = server.port;
490
- }
491
- return { ...tunnel, streams: {
492
- accept: (target, stream) => {
493
- const serve = targets.get(target);
494
- if (serve === void 0) return false;
495
- serve(stream);
496
- return true;
497
- }
498
- }, destinationPorts, builtInPorts, listeners, close: closeAll };
499
- } catch (err) {
500
- await closeAll();
501
- throw err;
502
- }
503
- }
504
-
505
- // src/runner/commit-identity.ts
506
- var NOREPLY_SUFFIX = "@users.noreply.github.com";
507
- var MAX_LENGTH = 200;
508
- function parseIdentity(value) {
509
- if (typeof value !== "object" || value === null) return void 0;
510
- const { name, email } = value;
511
- if (typeof name !== "string" || typeof email !== "string") return void 0;
512
- if (name.trim() === "" || name.length > MAX_LENGTH || /[\r\n\0<>]/.test(name)) return void 0;
513
- if (email.length > MAX_LENGTH || !email.endsWith(NOREPLY_SUFFIX) || /[\s\0<>]/.test(email) || email.length === NOREPLY_SUFFIX.length) return void 0;
514
- return { name, email };
282
+
283
+ // src/runner/commit-identity.ts
284
+ var NOREPLY_SUFFIX = "@users.noreply.github.com";
285
+ var MAX_LENGTH = 200;
286
+ function parseIdentity(value) {
287
+ if (typeof value !== "object" || value === null) return void 0;
288
+ const { name: name2, email } = value;
289
+ if (typeof name2 !== "string" || typeof email !== "string") return void 0;
290
+ if (name2.trim() === "" || name2.length > MAX_LENGTH || /[\r\n\0<>]/.test(name2)) return void 0;
291
+ if (email.length > MAX_LENGTH || !email.endsWith(NOREPLY_SUFFIX) || /[\s\0<>]/.test(email) || email.length === NOREPLY_SUFFIX.length) return void 0;
292
+ return { name: name2, email };
515
293
  }
516
294
  function parseClaimIdentity(data) {
517
295
  const author = parseIdentity(data.commitAuthor);
@@ -590,9 +368,6 @@ function primaryOf(repositories) {
590
368
  return repositories.find((entry) => entry.primary) ?? repositories[0];
591
369
  }
592
370
 
593
- // src/scrub-env.ts
594
- var SCRUB_ENV_VARIABLE = "OUTERLAYER_SCRUB_ENV";
595
-
596
371
  // src/runner/container/environment.ts
597
372
  var RELAY_PORT = 3128;
598
373
  var JOB_MOUNT = "/outerlayer/job";
@@ -613,6 +388,23 @@ function lifecycleWorkdir(repositories, governingRepository) {
613
388
  return entry === void 0 ? CHECKOUT_DIR : checkoutPath(entry);
614
389
  }
615
390
  var MAX_HOSTS = 200;
391
+ var JAVA_OPTIONS = "JAVA_TOOL_OPTIONS";
392
+ function applyTrust(env, image) {
393
+ if (env.trust === void 0) return env;
394
+ const literals = { ...env.literals };
395
+ const passed = { ...env.passed };
396
+ for (const [name2, value] of Object.entries(env.trust)) {
397
+ if (name2 === JAVA_OPTIONS) continue;
398
+ literals[name2] = value;
399
+ delete passed[name2];
400
+ }
401
+ const option = env.trust[JAVA_OPTIONS];
402
+ if (option !== void 0) {
403
+ literals[JAVA_OPTIONS] = mergeJavaOptions(passed[JAVA_OPTIONS] ?? env.literals[JAVA_OPTIONS] ?? image?.[JAVA_OPTIONS]);
404
+ delete passed[JAVA_OPTIONS];
405
+ }
406
+ return { ...env, literals, passed };
407
+ }
616
408
  function tokenVariables() {
617
409
  return ["GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"];
618
410
  }
@@ -670,8 +462,8 @@ function runnerLiterals(repository, repositories = [], unpinnedRuntimes, missing
670
462
  ...missingSetupScripts === void 0 || missingSetupScripts.length === 0 ? {} : { OUTERLAYER_MISSING_SETUP_SCRIPTS: JSON.stringify(missingSetupScripts) }
671
463
  };
672
464
  }
673
- function containerBuiltInAddress(name, agents) {
674
- return `http://127.0.0.1:${destinationPort(name, agents)}`;
465
+ function containerBuiltInAddress(name2, agents) {
466
+ return `http://127.0.0.1:${destinationPort(name2, agents)}`;
675
467
  }
676
468
  function reservedNames() {
677
469
  return /* @__PURE__ */ new Set([
@@ -682,26 +474,26 @@ function reservedNames() {
682
474
  ...toolProxyVariables()
683
475
  ]);
684
476
  }
685
- function isReservedVariable(name) {
686
- return name.startsWith("OUTERLAYER_") || reservedNames().has(name);
477
+ function isReservedVariable(name2) {
478
+ return name2.startsWith("OUTERLAYER_") || reservedNames().has(name2);
687
479
  }
688
- function isRefusedInConfig(name) {
689
- return isReservedVariable(name) && !githubVariables().has(name);
480
+ function isRefusedInConfig(name2) {
481
+ return isReservedVariable(name2) && !githubVariables().has(name2);
690
482
  }
691
- function isMiseVariableAllowed(name, agents) {
692
- return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) && !isReservedVariable(name) && !strippedVariables(agents).includes(name);
483
+ function isMiseVariableAllowed(name2, agents) {
484
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name2) && !isReservedVariable(name2) && !strippedVariables(agents).includes(name2);
693
485
  }
694
486
  function withMiseVariables(env, variables) {
695
487
  if (variables === void 0) return env;
696
488
  const passed = { ...env.passed };
697
489
  const literals = { ...env.literals };
698
- for (const [name, value] of Object.entries(variables)) {
699
- if (name === "PATH") {
700
- if (!(name in env.literals) && passed[name] === void 0) literals[name] = value;
490
+ for (const [name2, value] of Object.entries(variables)) {
491
+ if (name2 === "PATH") {
492
+ if (!(name2 in env.literals) && passed[name2] === void 0) literals[name2] = value;
701
493
  continue;
702
494
  }
703
- if (!isMiseVariableAllowed(name) || name in env.literals || passed[name] !== void 0) continue;
704
- passed[name] = value;
495
+ if (!isMiseVariableAllowed(name2) || name2 in env.literals || passed[name2] !== void 0) continue;
496
+ passed[name2] = value;
705
497
  }
706
498
  return { ...env, literals, passed };
707
499
  }
@@ -709,8 +501,8 @@ var NO_VARIABLES = [];
709
501
  function buildEnvironment(input) {
710
502
  const authored = authorEnvironment(input.identity?.author);
711
503
  const recipe = {};
712
- for (const [name, value] of Object.entries(input.containerEnv)) {
713
- if (!isReservedVariable(name) && !(name in authored)) recipe[name] = value;
504
+ for (const [name2, value] of Object.entries(input.containerEnv)) {
505
+ if (!isReservedVariable(name2) && !(name2 in authored)) recipe[name2] = value;
714
506
  }
715
507
  const builtIns = input.builtIns === true;
716
508
  const credentialVariables = strippedVariables(input.agents);
@@ -724,28 +516,28 @@ function buildEnvironment(input) {
724
516
  const variables = [];
725
517
  const skippedTokenVariables = [];
726
518
  if (input.factoryVariables !== void 0) {
727
- for (const { name, value } of input.factoryVariables) {
728
- if (isReservedVariable(name) || name in authored) continue;
729
- if (builtIns && credentialVariables.includes(name)) continue;
730
- passed[name] = value;
731
- variables.push(name);
519
+ for (const { name: name2, value } of input.factoryVariables) {
520
+ if (isReservedVariable(name2) || name2 in authored) continue;
521
+ if (builtIns && credentialVariables.includes(name2)) continue;
522
+ passed[name2] = value;
523
+ variables.push(name2);
732
524
  }
733
525
  if (variables.length > 0) passed[SCRUB_ENV_VARIABLE] = variables.join(",");
734
526
  } else {
735
- for (const name of input.config.build?.variables ?? NO_VARIABLES) {
736
- if (tokenVariables().includes(name)) {
737
- skippedTokenVariables.push(name);
527
+ for (const name2 of input.config.build?.variables ?? NO_VARIABLES) {
528
+ if (tokenVariables().includes(name2)) {
529
+ skippedTokenVariables.push(name2);
738
530
  continue;
739
531
  }
740
- const value = input.hostEnv[name];
741
- if (value === void 0 || isReservedVariable(name) || name in authored) continue;
742
- if (builtIns && credentialVariables.includes(name)) continue;
743
- passed[name] = value;
744
- variables.push(name);
532
+ const value = input.hostEnv[name2];
533
+ if (value === void 0 || isReservedVariable(name2) || name2 in authored) continue;
534
+ if (builtIns && credentialVariables.includes(name2)) continue;
535
+ passed[name2] = value;
536
+ variables.push(name2);
745
537
  }
746
538
  }
747
539
  const destinations = destinationEnvironment(input.config.build?.destinations, containerLocalAddress);
748
- const builtInLiterals = builtIns ? builtInEnvironment((name) => containerBuiltInAddress(name, input.agents), input.config.managed === true ? managedAgentCredential(input.agents) : agentCredential(input.hostEnv, {}, input.agents), input.agents) : {};
540
+ const builtInLiterals = builtIns ? builtInEnvironment((name2) => containerBuiltInAddress(name2, input.agents), input.config.managed === true ? managedAgentCredential(input.agents) : agentCredential(input.hostEnv, {}, input.agents), input.agents) : {};
749
541
  const hooksPath = input.identity?.hooksPath;
750
542
  const hooks = {};
751
543
  if (hooksPath !== void 0) {
@@ -771,7 +563,8 @@ function buildEnvironment(input) {
771
563
  },
772
564
  passed,
773
565
  variables,
774
- skippedTokenVariables
566
+ skippedTokenVariables,
567
+ ...input.trustEnvironment === void 0 || Object.keys(input.trustEnvironment).length === 0 ? {} : { trust: input.trustEnvironment }
775
568
  },
776
569
  input.miseVariables
777
570
  );
@@ -786,14 +579,15 @@ function checkEnvironment(input) {
786
579
  containerEnv: input.containerEnv,
787
580
  builtIns: false,
788
581
  factoryVariables: input.factoryVariables,
789
- proxiedEnvironment: input.proxiedEnvironment
582
+ proxiedEnvironment: input.proxiedEnvironment,
583
+ trustEnvironment: input.trustEnvironment
790
584
  });
791
585
  const withheld = /* @__PURE__ */ new Set(["OUTERLAYER_URL", "OUTERLAYER_API_KEY", ...strippedVariables()]);
792
586
  const literals = { OUTERLAYER_EVAL_INPUT: EVAL_INPUT_DIR, OUTERLAYER_CHECK_ITEMS: CHECK_ITEMS_FILE };
793
- for (const [name, value] of Object.entries(env.literals)) if (!withheld.has(name)) literals[name] = value;
587
+ for (const [name2, value] of Object.entries(env.literals)) if (!withheld.has(name2)) literals[name2] = value;
794
588
  const passed = {};
795
- for (const [name, value] of Object.entries(env.passed)) if (!withheld.has(name)) passed[name] = value;
796
- return { literals, passed };
589
+ for (const [name2, value] of Object.entries(env.passed)) if (!withheld.has(name2)) passed[name2] = value;
590
+ return { literals, passed, ...env.trust === void 0 ? {} : { trust: env.trust } };
797
591
  }
798
592
  function parseIsolation(value) {
799
593
  return value === "container" || value === "vm" ? value : "shared-user";
@@ -832,8 +626,547 @@ function withTunnelRecord(environment, record, onlyWhenUsed = false) {
832
626
  var MAX_ROUTES = 32;
833
627
  function routesOf(counts) {
834
628
  if (counts === void 0) return {};
835
- const routes = Object.entries(counts).sort(([a], [b]) => a < b ? -1 : 1).slice(0, MAX_ROUTES).map(([name, { requests, failures }]) => ({ name, requests, failures: Math.min(failures, requests) }));
629
+ const routes = Object.entries(counts).sort(([a], [b]) => a < b ? -1 : 1).slice(0, MAX_ROUTES).map(([name2, { requests, failures }]) => ({ name: name2, requests, failures: Math.min(failures, requests) }));
836
630
  return routes.length === 0 ? {} : { routes };
837
631
  }
838
632
 
839
- export { BUILD_HOME, CHECKOUT_DIR, CHECK_ITEMS_FILE, DESTINATION_BASE_PORT, EVAL_INPUT_DIR, JOB_MOUNT, PROXY_WARNING_FLAG, RELAY_PORT, SCRUB_ENV_VARIABLE, authorEnvironment, buildEnvironment, carried6to4, checkEnvironment, checkoutPath, classifyAddress, commitIdentityRecord, containerLocalAddress, destinationEnvironment, headerVariables, isMiseVariableAllowed, isRefusedInConfig, isReservedVariable, lifecycleWorkdir, maxDestinations, parseClaimIdentity, parseClaimedRepositories, parseIsolation, parseUnreachable, primaryOf, proxyEnvironment, repositoriesOf, repositoryPath, resolveDestinations, sharedUserEnvironment, startBuildServices, tokenHeader, withGitConfig, withHooksPath, withMiseVariables, withTokenHeader, withTunnelRecord };
633
+ // src/runner/container/ranges.ts
634
+ var V4 = [
635
+ ["unspecified", "0.0.0.0/8"],
636
+ ["loopback", "127.0.0.0/8"],
637
+ ["private", "10.0.0.0/8"],
638
+ ["private", "172.16.0.0/12"],
639
+ ["private", "192.168.0.0/16"],
640
+ ["protocol-assignments", "192.0.0.0/24"],
641
+ ["benchmarking", "198.18.0.0/15"],
642
+ ["azure-wireserver", "168.63.129.16/32"],
643
+ ["link-local", "169.254.0.0/16"],
644
+ ["shared-address", "100.64.0.0/10"],
645
+ ["multicast", "224.0.0.0/4"],
646
+ ["reserved", "240.0.0.0/4"]
647
+ ];
648
+ var V6 = [
649
+ ["unspecified", "::/128"],
650
+ ["loopback", "::1/128"],
651
+ ["ipv4-mapped", "::ffff:0:0/96"],
652
+ ["nat64", "64:ff9b::/96"],
653
+ // The location of an embedded IPv4 address depends on the translator's prefix length, so the whole prefix is refused.
654
+ ["nat64-local", "64:ff9b:1::/48"],
655
+ ["ipv4-compatible", "::/96"],
656
+ ["link-local", "fe80::/10"],
657
+ ["unique-local", "fc00::/7"],
658
+ ["multicast", "ff00::/8"]
659
+ ];
660
+ var UNPARSEABLE = { name: "unparseable", cidr: "-" };
661
+ function parseV4(text) {
662
+ const parts = text.split(".");
663
+ if (parts.length !== 4) return void 0;
664
+ let value = 0;
665
+ for (const part of parts) {
666
+ if (!/^\d{1,3}$/.test(part)) return void 0;
667
+ const octet = Number(part);
668
+ if (octet > 255) return void 0;
669
+ value = value * 256 + octet;
670
+ }
671
+ return value;
672
+ }
673
+ function parseV6(input) {
674
+ const zone = input.indexOf("%");
675
+ let text = zone === -1 ? input : input.slice(0, zone);
676
+ const lastColon = text.lastIndexOf(":");
677
+ const tail = text.slice(lastColon + 1);
678
+ if (tail.includes(".")) {
679
+ const v4 = parseV4(tail);
680
+ if (v4 === void 0) return void 0;
681
+ text = `${text.slice(0, lastColon + 1)}${(v4 >>> 16).toString(16)}:${(v4 & 65535).toString(16)}`;
682
+ }
683
+ const halves = text.split("::");
684
+ if (halves.length > 2) return void 0;
685
+ const groups = (part) => {
686
+ if (part === "") return [];
687
+ const found = part.split(":");
688
+ return found.every((g) => /^[0-9a-fA-F]{1,4}$/.test(g)) ? found : void 0;
689
+ };
690
+ const head = groups(halves[0]);
691
+ const rest = groups(halves[1] ?? "");
692
+ if (head === void 0 || rest === void 0) return void 0;
693
+ let words;
694
+ if (halves.length === 2) {
695
+ const missing = 8 - head.length - rest.length;
696
+ if (missing < 1) return void 0;
697
+ words = [...head, ...Array(missing).fill("0"), ...rest];
698
+ } else {
699
+ if (head.length !== 8) return void 0;
700
+ words = head;
701
+ }
702
+ return words.reduce((acc, word) => acc << BigInt(16) | BigInt(parseInt(word, 16)), BigInt(0));
703
+ }
704
+ function build4() {
705
+ return V4.map(([name2, cidr]) => {
706
+ const [address, length2] = cidr.split("/");
707
+ return { name: name2, cidr, base: parseV4(address), bits: Number(length2) };
708
+ });
709
+ }
710
+ function build6() {
711
+ return V6.map(([name2, cidr]) => {
712
+ const [address, length2] = cidr.split("/");
713
+ return { name: name2, cidr, base: parseV6(address), bits: Number(length2) };
714
+ });
715
+ }
716
+ var RANGES_4 = build4();
717
+ var RANGES_6 = build6();
718
+ [...RANGES_4, ...RANGES_6].map(({ name: name2, cidr }) => ({ name: name2, cidr }));
719
+ function carried6to4(address) {
720
+ const v6 = parseV6(address);
721
+ if (v6 === void 0 || v6 >> BigInt(112) !== BigInt(8194)) return void 0;
722
+ const v4 = Number(v6 >> BigInt(80) & BigInt(4294967295));
723
+ return [v4 >>> 24, v4 >>> 16 & 255, v4 >>> 8 & 255, v4 & 255].join(".");
724
+ }
725
+ function classifyAddress(address) {
726
+ const v4 = parseV4(address);
727
+ if (v4 !== void 0) {
728
+ for (const range of RANGES_4) {
729
+ const shift = 32 - range.bits;
730
+ if (Math.floor(v4 / 2 ** shift) === Math.floor(range.base / 2 ** shift)) return { name: range.name, cidr: range.cidr };
731
+ }
732
+ return void 0;
733
+ }
734
+ const v6 = parseV6(address);
735
+ if (v6 === void 0) return UNPARSEABLE;
736
+ const carries = carried6to4(address);
737
+ if (carries !== void 0) {
738
+ const inner = classifyAddress(carries);
739
+ return inner === void 0 ? void 0 : { ...inner, carries };
740
+ }
741
+ for (const range of RANGES_6) {
742
+ const shift = BigInt(128 - range.bits);
743
+ if (v6 >> shift === range.base >> shift) return { name: range.name, cidr: range.cidr };
744
+ }
745
+ return void 0;
746
+ }
747
+
748
+ // src/runner/proxied-variables.ts
749
+ var MAX_NAME_IN_ROUTE = 40;
750
+ var STAND_IN = "olvar_placeholder-not-a-real-value";
751
+ function routeNameOf(variables, variable) {
752
+ const position = Math.max(0, variables.indexOf(variable));
753
+ const readable = variable.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, MAX_NAME_IN_ROUTE).replace(/-+$/g, "");
754
+ return readable === "" ? `var-${position}` : `var-${position}-${readable}`;
755
+ }
756
+ function hostKeyOf(upstream) {
757
+ const url = new URL(upstream);
758
+ return { host: url.hostname.replace(/^\[|\]$/g, "").toLowerCase(), port: url.port === "" ? 443 : Number(url.port) };
759
+ }
760
+ function pathPrefixOf(upstream) {
761
+ return new URL(upstream).pathname.replace(/\/+$/, "");
762
+ }
763
+ function variablesFor(variables, host, port) {
764
+ const name2 = host.toLowerCase();
765
+ return variables.filter((variable) => {
766
+ const key = hostKeyOf(variable.upstream);
767
+ return key.host === name2 && key.port === port;
768
+ }).sort((a, b) => pathPrefixOf(b.upstream).length - pathPrefixOf(a.upstream).length);
769
+ }
770
+ function variableForPath(candidates, target) {
771
+ const path = target.split(/[?#]/)[0] ?? "";
772
+ return candidates.find((variable) => {
773
+ const prefix = pathPrefixOf(variable.upstream);
774
+ return prefix === "" || path === prefix || path.startsWith(`${prefix}/`);
775
+ });
776
+ }
777
+ var VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,254}$/;
778
+ function parseProxied(given, malformed) {
779
+ if (given === void 0) return { proxied: [] };
780
+ if (!Array.isArray(given)) return { problem: malformed };
781
+ if (given.length > maxDestinations()) {
782
+ return { problem: `the gateway sent ${given.length} variables for a service; a build holds at most ${maxDestinations()}` };
783
+ }
784
+ const proxied = [];
785
+ const names = /* @__PURE__ */ new Set();
786
+ for (const entry of given) {
787
+ if (typeof entry !== "object" || entry === null) return { problem: malformed };
788
+ const { name: name2, value, upstream, header } = entry;
789
+ if (typeof name2 !== "string" || typeof value !== "string" || typeof upstream !== "string") return { problem: malformed };
790
+ if (typeof header !== "object" || header === null) return { problem: malformed };
791
+ const { name: headerName, value: headerValue } = header;
792
+ if (typeof headerName !== "string" || typeof headerValue !== "string") return { problem: malformed };
793
+ if (!VARIABLE_NAME.test(name2)) return { problem: `the factory's build variable ${JSON.stringify(name2)} is not a variable name` };
794
+ if (names.has(name2)) return { problem: `the factory's build variable ${name2} is listed twice` };
795
+ names.add(name2);
796
+ if (value.trim().length < MIN_SCRUBBED_LITERAL) {
797
+ return { problem: `the value of the factory's build variable ${name2} has fewer than ${MIN_SCRUBBED_LITERAL} characters, so the runner could not remove it from logs and transcripts` };
798
+ }
799
+ if ([...headerValue.matchAll(/\$\{([^}]*)\}/g)].some((match) => match[1] !== "VALUE") || !headerValue.includes("${VALUE}")) {
800
+ return { problem: `the header of the factory's build variable ${name2} must name \${VALUE} and no other variable` };
801
+ }
802
+ let reason;
803
+ let resolvedUpstream = upstream;
804
+ try {
805
+ const resolved = resolveDestinations(
806
+ [{ name: "service", upstream, header: `${headerName}: ${headerValue.replace(/\$\{VALUE\}/g, `\${${name2}}`)}` }],
807
+ [],
808
+ isReservedVariable,
809
+ (key, why) => {
810
+ throw new Error(`${key} ${why}`);
811
+ }
812
+ );
813
+ resolvedUpstream = resolved[0].upstream;
814
+ const host = new URL(resolvedUpstream).hostname.replace(/^\[|\]$/g, "");
815
+ if (isIP(host) !== 0 && classifyAddress(host) !== void 0) throw new Error(`upstream ${host} is a private address`);
816
+ } catch (err) {
817
+ reason = err instanceof Error ? err.message : "is refused";
818
+ }
819
+ if (reason !== void 0) return { problem: `the service of the factory's build variable ${name2}: ${reason}` };
820
+ proxied.push({ name: name2, value, upstream: resolvedUpstream, header: { name: headerName, value: headerValue } });
821
+ }
822
+ return { proxied };
823
+ }
824
+
825
+ // src/runner/destinations.ts
826
+ var MAX_RELEASED_DESTINATIONS = 20;
827
+ function maxDestinations(agents = defaultAgents(), providers = PROVIDERS) {
828
+ return MAX_RELEASED_DESTINATIONS - builtInNames(agents, providers).length;
829
+ }
830
+ var DESTINATION_BASE_PORT = 3129;
831
+ var DESTINATION_NAME = /^[a-z0-9][a-z0-9-]{0,62}$/;
832
+ var VARIABLE_NAME2 = /^[A-Za-z_][A-Za-z0-9_]{0,254}$/;
833
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
834
+ var HEADER_VARIABLE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
835
+ var DESTINATION_KEYS = ["name", "upstream", "header", "env"];
836
+ var MAX_SOCKET_PATH_BYTES = 100;
837
+ var UPSTREAM_IDLE_MS = 6e5;
838
+ function headerVariables(destinations) {
839
+ return [...new Set((destinations ?? []).flatMap((d) => d.header.variables))];
840
+ }
841
+ function resolveDestinations(given, variables, isReserved, fail, agents = defaultAgents(), providers = PROVIDERS) {
842
+ if (!Array.isArray(given)) fail("runner.build.destinations", "must be a list of destinations");
843
+ const builtIns = builtInNames(agents, providers);
844
+ const most = maxDestinations(agents, providers);
845
+ if (given.length > most) {
846
+ fail(
847
+ "runner.build.destinations",
848
+ `lists ${given.length} destinations; a release records at most ${MAX_RELEASED_DESTINATIONS}, and ${builtIns.length} of those are the built-in ${builtIns.join(" and ")} destinations, so a host lists at most ${most}`
849
+ );
850
+ }
851
+ const resolved = [];
852
+ const names = /* @__PURE__ */ new Set();
853
+ const envNames = /* @__PURE__ */ new Set();
854
+ for (const [index, entry] of given.entries()) {
855
+ const at = `runner.build.destinations[${index}]`;
856
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) fail(at, "must be an object");
857
+ const record = entry;
858
+ for (const key of Object.keys(record)) {
859
+ if (!DESTINATION_KEYS.includes(key)) {
860
+ fail(`${at}.${key}`, `is not a key a destination accepts; the keys are ${DESTINATION_KEYS.join(", ")}`);
861
+ }
862
+ }
863
+ const name2 = record.name;
864
+ if (typeof name2 !== "string" || !DESTINATION_NAME.test(name2)) {
865
+ fail(`${at}.name`, "must be 1 to 63 lower-case letters, digits or hyphens, starting with a letter or digit");
866
+ }
867
+ if (builtIns.includes(name2)) fail(`${at}.name`, `is ${name2}, a destination the runner serves itself`);
868
+ if (names.has(name2)) fail(`${at}.name`, `repeats the destination ${name2}`);
869
+ names.add(name2);
870
+ const upstream = parseUpstream(record.upstream, `${at}.upstream`, fail);
871
+ const header = parseHeader(record.header, `${at}.header`, fail);
872
+ for (const variable of header.variables) {
873
+ if (variables.includes(variable)) {
874
+ fail(`${at}.header`, `names ${variable}, which build.variables also passes into the build; a secret a build can read is not a destination's`);
875
+ }
876
+ }
877
+ const env = parseEnv(record.env, `${at}.env`, isReserved, fail);
878
+ for (const variable of Object.keys(env)) {
879
+ if (envNames.has(variable)) fail(`${at}.env`, `sets ${variable}, which another destination sets too`);
880
+ envNames.add(variable);
881
+ if (variables.includes(variable)) fail(`${at}.env`, `sets ${variable}, which build.variables also passes into the build`);
882
+ }
883
+ resolved.push({ name: name2, upstream, header, env });
884
+ }
885
+ for (const [index, destination] of resolved.entries()) {
886
+ for (const variable of destination.header.variables) {
887
+ if (envNames.has(variable)) {
888
+ fail(`runner.build.destinations[${index}].env`, `sets ${variable}, which a destination's header reads as a secret`);
889
+ }
890
+ }
891
+ }
892
+ return resolved;
893
+ }
894
+ function parseUpstream(value, key, fail) {
895
+ if (typeof value !== "string") fail(key, "must be an https:// address");
896
+ let url;
897
+ try {
898
+ url = new URL(value);
899
+ } catch {
900
+ fail(key, `${JSON.stringify(value)} is not an https:// address`);
901
+ }
902
+ if (url.protocol !== "https:") fail(key, `${JSON.stringify(value)} is not an https:// address: a destination's secret is only ever sent over TLS`);
903
+ if (url.username !== "" || url.password !== "") fail(key, "must not carry a login; the credential goes in the header");
904
+ if (url.search !== "" || url.hash !== "") fail(key, "must not carry a query or a fragment");
905
+ return url.href;
906
+ }
907
+ function parseHeader(value, key, fail) {
908
+ if (typeof value !== "string") fail(key, 'must be a string such as "Authorization: Bearer ${NPM_TOKEN}"');
909
+ const colon = value.indexOf(":");
910
+ if (colon === -1) fail(key, 'must be "Name: value", with a colon');
911
+ const name2 = value.slice(0, colon).trim();
912
+ const text = value.slice(colon + 1).trim();
913
+ if (!HEADER_NAME.test(name2)) fail(key, `names the header ${JSON.stringify(name2)}, which is not a header name`);
914
+ if (text === "") fail(key, "has an empty value");
915
+ if (/[\r\n\0]/.test(text)) fail(key, "has a value with a line break in it");
916
+ const variables = [...new Set([...text.matchAll(HEADER_VARIABLE)].map((m) => m[1]))];
917
+ return { name: name2, value: text, variables };
918
+ }
919
+ function parseEnv(value, key, isReserved, fail) {
920
+ if (value === void 0) return {};
921
+ if (typeof value !== "object" || value === null || Array.isArray(value)) fail(key, "must be an object of variable names and values");
922
+ const env = {};
923
+ for (const [name2, text] of Object.entries(value)) {
924
+ if (!VARIABLE_NAME2.test(name2)) fail(key, `names ${JSON.stringify(name2)}, which is not a variable name`);
925
+ if (isReserved(name2)) fail(key, `names ${name2}, which the runner sets itself`);
926
+ if (typeof text !== "string") fail(key, `gives ${name2} a value that is not a string`);
927
+ env[name2] = text;
928
+ }
929
+ return env;
930
+ }
931
+ function destinationEnvironment(destinations, localFor) {
932
+ const env = {};
933
+ for (const [index, destination] of (destinations ?? []).entries()) {
934
+ for (const [name2, value] of Object.entries(destination.env)) env[name2] = value.split("{local}").join(localFor(index));
935
+ }
936
+ return env;
937
+ }
938
+ function containerLocalAddress(index) {
939
+ return `http://127.0.0.1:${DESTINATION_BASE_PORT + index}/`;
940
+ }
941
+ function destinationSocketPath(buildDir, index) {
942
+ return join(buildDir, `dest-${index}.sock`);
943
+ }
944
+ function droppedRequestHeaders(extra = []) {
945
+ return /* @__PURE__ */ new Set(["host", "authorization", "proxy-authorization", "cookie", "connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade", ...extra]);
946
+ }
947
+ function hasDotDotSegment(target) {
948
+ return target.split(/[/?#]/).some((segment) => /^(\.|%2e){2}$/i.test(segment));
949
+ }
950
+ function respond(res, status, body) {
951
+ if (res.headersSent) {
952
+ res.destroy();
953
+ return;
954
+ }
955
+ res.writeHead(status, { "Content-Type": "text/plain", "Content-Length": Buffer.byteLength(body), Connection: "close" });
956
+ res.end(body);
957
+ }
958
+ function expandHeader(header, env) {
959
+ for (const name2 of header.variables) {
960
+ if (env[name2] === void 0 || env[name2] === "") return { missing: name2 };
961
+ }
962
+ return { value: header.value.replace(HEADER_VARIABLE, (_match, name2) => env[name2]) };
963
+ }
964
+ async function startDestination(input) {
965
+ const { destination, hostEnv } = input;
966
+ const upstream = new URL(destination.upstream);
967
+ const prefix = upstream.pathname.replace(/\/+$/, "");
968
+ const secure = upstream.protocol === "https:";
969
+ const send = input.request ?? (secure ? request : request$1);
970
+ const headerName = destination.header.name.toLowerCase();
971
+ const dropped = droppedRequestHeaders(input.drop);
972
+ const handle = (req, res) => {
973
+ let finished = false;
974
+ const finish = (ok) => {
975
+ if (finished) return;
976
+ finished = true;
977
+ input.onFinished?.(destination.name, ok);
978
+ };
979
+ res.on("finish", () => finish(true));
980
+ res.on("close", () => finish(false));
981
+ const fail = (status, body) => {
982
+ finish(false);
983
+ respond(res, status, body);
984
+ };
985
+ const target = req.url ?? "";
986
+ if (!target.startsWith("/")) {
987
+ fail(400, "send an origin-form request path\n");
988
+ return;
989
+ }
990
+ const expanded = expandHeader(destination.header, hostEnv);
991
+ if ("missing" in expanded) {
992
+ fail(502, `the destination ${destination.name} cannot be reached: ${expanded.missing} is not set in the runner's environment
993
+ `);
994
+ return;
995
+ }
996
+ const headers = {};
997
+ for (const [name2, value] of Object.entries(req.headers)) {
998
+ if (!dropped.has(name2)) headers[name2] = value;
999
+ }
1000
+ headers.host = upstream.host;
1001
+ headers[headerName] = expanded.value;
1002
+ let forwarded;
1003
+ try {
1004
+ forwarded = send(
1005
+ {
1006
+ protocol: upstream.protocol,
1007
+ hostname: upstream.hostname,
1008
+ port: upstream.port === "" ? secure ? 443 : 80 : Number(upstream.port),
1009
+ method: req.method,
1010
+ path: `${prefix}${target}`,
1011
+ headers,
1012
+ ...input.ca === void 0 ? {} : { ca: input.ca }
1013
+ },
1014
+ (answer) => {
1015
+ res.writeHead(answer.statusCode ?? 502, answer.headers);
1016
+ answer.on("error", () => res.destroy());
1017
+ answer.on("close", () => {
1018
+ if (!answer.complete) {
1019
+ finish(false);
1020
+ res.destroy();
1021
+ }
1022
+ });
1023
+ answer.pipe(res);
1024
+ }
1025
+ );
1026
+ } catch {
1027
+ fail(502, `the destination ${destination.name} cannot be reached: its header value was refused
1028
+ `);
1029
+ return;
1030
+ }
1031
+ input.onUsed?.(destination.name);
1032
+ forwarded.setTimeout(UPSTREAM_IDLE_MS, () => forwarded.destroy());
1033
+ res.on("close", () => forwarded.destroy());
1034
+ forwarded.on("error", (err) => {
1035
+ input.onUpstreamError?.(destination.name, typeof err.code === "string" ? err.code : "unknown");
1036
+ fail(502, `the upstream of the destination ${destination.name} could not be reached
1037
+ `);
1038
+ });
1039
+ req.pipe(forwarded);
1040
+ };
1041
+ const sockets = /* @__PURE__ */ new Set();
1042
+ const server = createServer(handle);
1043
+ server.on("connection", (socket) => {
1044
+ sockets.add(socket);
1045
+ socket.on("close", () => sockets.delete(socket));
1046
+ });
1047
+ const listeners = [server];
1048
+ const served = {};
1049
+ if (input.socketPath !== void 0) {
1050
+ if (Buffer.byteLength(input.socketPath) > MAX_SOCKET_PATH_BYTES) {
1051
+ throw new Error(`${input.socketPath} is too long for a Unix socket; keep the runner's config file nearer the root of the filesystem`);
1052
+ }
1053
+ if (input.listenOn !== void 0) {
1054
+ await input.listenOn(server);
1055
+ } else {
1056
+ if (existsSync(input.socketPath)) unlinkSync(input.socketPath);
1057
+ await new Promise((resolve, reject) => {
1058
+ server.once("error", reject);
1059
+ server.listen(input.socketPath, () => resolve());
1060
+ });
1061
+ chmodSync(input.socketPath, 438);
1062
+ }
1063
+ served.socketPath = input.socketPath;
1064
+ }
1065
+ if (input.port !== void 0) {
1066
+ const tcp = createServer$1((socket) => server.emit("connection", socket));
1067
+ await new Promise((resolve, reject) => {
1068
+ tcp.once("error", reject);
1069
+ tcp.listen(input.port, "127.0.0.1", () => resolve());
1070
+ });
1071
+ listeners.push(tcp);
1072
+ const address = tcp.address();
1073
+ served.port = address.port;
1074
+ }
1075
+ const close = async () => {
1076
+ for (const socket of sockets) socket.destroy();
1077
+ await Promise.all(listeners.map((listener) => new Promise((resolve) => listener.close(() => resolve()))));
1078
+ };
1079
+ return { ...served, acceptStream: (stream) => void server.emit("connection", stream), listener: () => input.socketPath === void 0 ? void 0 : server, close };
1080
+ }
1081
+ async function startBuildServices(input) {
1082
+ const streamed = input.serve === "stream";
1083
+ const listenOnFor = (socket) => {
1084
+ const listenOn = input.inherit?.(socket);
1085
+ return listenOn === void 0 ? {} : { listenOn };
1086
+ };
1087
+ const listeners = {};
1088
+ const tunnel = await input.startTunnel(join(input.buildDir, "tunnel.sock"), {
1089
+ ...input.tunnelOptions,
1090
+ ...streamed ? { socket: false } : {},
1091
+ ...streamed ? {} : listenOnFor("tunnel.sock"),
1092
+ ...input.allowHosts === void 0 ? {} : { allowHosts: input.allowHosts },
1093
+ ...input.egress === void 0 ? {} : { egress: input.egress },
1094
+ ...input.decrypt === void 0 ? {} : { decrypt: input.decrypt },
1095
+ recordPath: join(input.jobDir, "tunnel.json")
1096
+ });
1097
+ const servers = [];
1098
+ const targets = /* @__PURE__ */ new Map();
1099
+ const tunnelListener = tunnel.listener?.();
1100
+ if (tunnelListener !== void 0) listeners["tunnel.sock"] = tunnelListener;
1101
+ if (streamed) targets.set(TARGET_TUNNEL, (stream) => tunnel.acceptStream(stream));
1102
+ if (streamed && input.lease !== void 0) targets.set(TARGET_LEASE, (stream) => input.lease.accept(stream));
1103
+ const closeAll = async () => {
1104
+ await Promise.all(servers.map((s) => s.close()));
1105
+ await tunnel.close();
1106
+ };
1107
+ try {
1108
+ const destinationPorts = [];
1109
+ const builtInPorts = {};
1110
+ for (const [index, destination] of input.destinations.entries()) {
1111
+ const server = await startDestination({
1112
+ destination,
1113
+ ...input.serve === "tcp" || streamed ? {} : { socketPath: destinationSocketPath(input.buildDir, index) },
1114
+ ...input.serve === "tcp" || streamed ? {} : listenOnFor(`dest-${index}.sock`),
1115
+ ...input.serve === "socket" || streamed ? {} : { port: input.ports?.destinations?.[index] ?? 0 },
1116
+ hostEnv: input.hostEnv,
1117
+ onUsed: (name2) => tunnel.destinationUsed(name2),
1118
+ onUpstreamError: (name2, code) => input.log?.(`route ${name2} could not reach its upstream: ${code}`),
1119
+ onFinished: (name2, ok) => tunnel.routeFinished(name2, ok),
1120
+ ...input.destinationOptions
1121
+ });
1122
+ servers.push(server);
1123
+ tunnel.routeServed(destination.name);
1124
+ input.log?.(`route ${destination.name} served to the build`);
1125
+ const listener = server.listener?.();
1126
+ if (listener !== void 0) listeners[`dest-${index}.sock`] = listener;
1127
+ targets.set(destinationTarget(index), (stream) => server.acceptStream(stream));
1128
+ if (server.port !== void 0) destinationPorts.push(server.port);
1129
+ }
1130
+ const proxied = input.decrypt?.variables() ?? [];
1131
+ for (const variable of proxied) {
1132
+ const route = routeNameOf(proxied, variable);
1133
+ tunnel.routeServed(route);
1134
+ input.log?.(`route ${route} served to the build`);
1135
+ }
1136
+ const builtIns = input.builtIns === void 0 ? [] : builtInDestinations({ ...input.builtIns, hostEnv: input.hostEnv }, input.builtIns.agents, input.builtIns.providers);
1137
+ for (const builtIn of builtIns) {
1138
+ const server = await startDestination({
1139
+ destination: builtIn.destination,
1140
+ ...input.serve === "tcp" || streamed ? {} : { socketPath: join(input.buildDir, builtIn.socket) },
1141
+ ...input.serve === "tcp" || streamed ? {} : listenOnFor(builtIn.socket),
1142
+ ...input.serve === "socket" || streamed ? {} : { port: input.ports?.builtIns?.[builtIn.destination.name] ?? 0 },
1143
+ hostEnv: builtIn.hostEnv,
1144
+ drop: builtIn.drop,
1145
+ onUsed: (name2) => tunnel.destinationUsed(name2),
1146
+ onUpstreamError: (name2, code) => input.log?.(`route ${name2} could not reach its upstream: ${code}`),
1147
+ onFinished: (name2, ok) => tunnel.routeFinished(name2, ok),
1148
+ ...input.destinationOptions
1149
+ });
1150
+ servers.push(server);
1151
+ tunnel.routeServed(builtIn.destination.name);
1152
+ input.log?.(`route ${builtIn.destination.name} served to the build`);
1153
+ const listener = server.listener?.();
1154
+ if (listener !== void 0) listeners[builtIn.socket] = listener;
1155
+ targets.set(builtIn.destination.name, (stream) => server.acceptStream(stream));
1156
+ if (server.port !== void 0) builtInPorts[builtIn.destination.name] = server.port;
1157
+ }
1158
+ return { ...tunnel, streams: {
1159
+ accept: (target, stream) => {
1160
+ const serve = targets.get(target);
1161
+ if (serve === void 0) return false;
1162
+ serve(stream);
1163
+ return true;
1164
+ }
1165
+ }, destinationPorts, builtInPorts, listeners, close: closeAll };
1166
+ } catch (err) {
1167
+ await closeAll();
1168
+ throw err;
1169
+ }
1170
+ }
1171
+
1172
+ export { BUILD_HOME, CHECKOUT_DIR, CHECK_ITEMS_FILE, DESTINATION_BASE_PORT, EVAL_INPUT_DIR, IMAGE_BUNDLES, JOB_MOUNT, PROXY_WARNING_FLAG, RELAY_PORT, SCRUB_ENV_VARIABLE, STAND_IN, applyTrust, authorEnvironment, buildAuthorityFor, buildEnvironment, carried6to4, checkEnvironment, checkoutPath, classifyAddress, commitIdentityRecord, containerLocalAddress, destinationEnvironment, dropBuildAuthority, droppedRequestHeaders, hasDotDotSegment, headerVariables, heldBuildAuthority, hostKeyOf, isMiseVariableAllowed, isRefusedInConfig, isReservedVariable, lifecycleWorkdir, parseClaimIdentity, parseClaimedRepositories, parseIsolation, parseProxied, parseUnreachable, primaryOf, proxyEnvironment, readBundleScript, repositoriesOf, repositoryPath, resolveDestinations, routeNameOf, sharedUserEnvironment, startBuildServices, tokenHeader, trustEnvironment, variableForPath, variablesFor, withGitConfig, withHooksPath, withMiseVariables, withTokenHeader, withTunnelRecord, writeTrustFiles };