@apifuse/provider-sdk 2.2.0-beta.4 → 2.2.0-beta.40

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 (303) hide show
  1. package/AUTHORING.md +501 -13
  2. package/CHANGELOG.md +165 -1
  3. package/README.md +72 -14
  4. package/SUBMISSION.md +1 -1
  5. package/bin/apifuse-check.ts +88 -4
  6. package/bin/apifuse-dev.ts +38 -5
  7. package/bin/apifuse-pack-check.ts +22 -2
  8. package/bin/apifuse-pack-smoke.ts +57 -2
  9. package/bin/apifuse-pack-types.ts +356 -38
  10. package/bin/apifuse-perf.ts +14 -13
  11. package/bin/apifuse-record.ts +691 -68
  12. package/bin/apifuse-submit-check.ts +518 -37
  13. package/bin/apifuse-sync-assets.ts +117 -0
  14. package/bin/submit-check-delimited-text.ts +50 -0
  15. package/dist/auth-turn/index.d.ts +3 -3
  16. package/dist/auth-turn/index.js +1 -1
  17. package/dist/auth.d.ts +14 -0
  18. package/dist/auth.js +67 -0
  19. package/dist/ceremonies/index.d.ts +16 -0
  20. package/dist/ceremonies/index.js +141 -36
  21. package/dist/cli/commands.d.ts +1 -1
  22. package/dist/cli/commands.js +8 -0
  23. package/dist/cli/create.d.ts +3 -0
  24. package/dist/cli/create.js +34 -35
  25. package/dist/cli/prompt-assets.d.ts +80 -0
  26. package/dist/cli/prompt-assets.js +743 -0
  27. package/dist/cli/templates/provider/AGENTS.md.tpl +17 -8
  28. package/dist/cli/templates/provider/Dockerfile.tpl +1 -1
  29. package/dist/cli/templates/provider/README.md.tpl +4 -4
  30. package/dist/cli/templates/provider/index.ts.tpl +6 -3
  31. package/dist/cli/templates/provider/operations/ping.ts.tpl +2 -1
  32. package/dist/config/loader.d.ts +177 -16
  33. package/dist/config/loader.js +424 -127
  34. package/dist/contract-serialization.js +4 -8
  35. package/dist/contract-types.d.ts +1 -0
  36. package/dist/contract.js +2 -0
  37. package/dist/declaration-validation.d.ts +32 -0
  38. package/dist/declaration-validation.js +207 -0
  39. package/dist/define.d.ts +51 -25
  40. package/dist/define.js +752 -38
  41. package/dist/error-resolution.d.ts +4 -0
  42. package/dist/error-resolution.js +122 -0
  43. package/dist/errors.d.ts +18 -0
  44. package/dist/errors.js +40 -0
  45. package/dist/fixture-sanitization.d.ts +28 -0
  46. package/dist/fixture-sanitization.js +217 -0
  47. package/dist/health-scenario.d.ts +1842 -0
  48. package/dist/health-scenario.js +624 -0
  49. package/dist/index.d.ts +19 -9
  50. package/dist/index.js +10 -6
  51. package/dist/lint.d.ts +6 -1
  52. package/dist/lint.js +362 -3
  53. package/dist/native-address.d.ts +43 -0
  54. package/dist/native-address.js +281 -0
  55. package/dist/native-egress-policy.d.ts +31 -0
  56. package/dist/native-egress-policy.js +288 -0
  57. package/dist/observability.d.ts +5 -2
  58. package/dist/observability.js +48 -1
  59. package/dist/provider.d.ts +8 -2
  60. package/dist/provider.js +3 -1
  61. package/dist/runtime/auth-flow.d.ts +5 -1
  62. package/dist/runtime/auth-flow.js +6 -0
  63. package/dist/runtime/browser.d.ts +1 -0
  64. package/dist/runtime/browser.js +492 -49
  65. package/dist/runtime/cache.d.ts +1 -0
  66. package/dist/runtime/cache.js +169 -15
  67. package/dist/runtime/choice-wordlist.d.ts +9 -0
  68. package/dist/runtime/choice-wordlist.js +138 -0
  69. package/dist/runtime/choice.d.ts +13 -1
  70. package/dist/runtime/choice.js +490 -102
  71. package/dist/runtime/executor.d.ts +2 -2
  72. package/dist/runtime/executor.js +26 -2
  73. package/dist/runtime/http.d.ts +1 -0
  74. package/dist/runtime/http.js +515 -53
  75. package/dist/runtime/instrumentation.d.ts +2 -2
  76. package/dist/runtime/instrumentation.js +366 -8
  77. package/dist/runtime/native-network-errors.d.ts +33 -0
  78. package/dist/runtime/native-network-errors.js +69 -0
  79. package/dist/runtime/native-network.d.ts +96 -0
  80. package/dist/runtime/native-network.js +1232 -0
  81. package/dist/runtime/ocr.d.ts +29 -0
  82. package/dist/runtime/ocr.js +440 -0
  83. package/dist/runtime/proxy-errors.js +6 -2
  84. package/dist/runtime/proxy-nodemaven.d.ts +56 -0
  85. package/dist/runtime/proxy-nodemaven.js +146 -0
  86. package/dist/runtime/proxy-telemetry.d.ts +80 -1
  87. package/dist/runtime/proxy-telemetry.js +154 -47
  88. package/dist/runtime/redirects.d.ts +29 -0
  89. package/dist/runtime/redirects.js +36 -0
  90. package/dist/runtime/redis.d.ts +1 -1
  91. package/dist/runtime/redis.js +4 -2
  92. package/dist/runtime/request-options.d.ts +68 -1
  93. package/dist/runtime/request-options.js +548 -0
  94. package/dist/runtime/resolver-config.d.ts +6 -0
  95. package/dist/runtime/resolver-config.js +6 -0
  96. package/dist/runtime/resolver-public.d.ts +1 -0
  97. package/dist/runtime/resolver-public.js +1 -0
  98. package/dist/runtime/resolver-shared.d.ts +3 -0
  99. package/dist/runtime/resolver-shared.js +12 -0
  100. package/dist/runtime/resolver-vendors/bindings.d.ts +48 -0
  101. package/dist/runtime/resolver-vendors/bindings.js +40 -0
  102. package/dist/runtime/resolver-vendors/browser.d.ts +22 -0
  103. package/dist/runtime/resolver-vendors/browser.js +377 -0
  104. package/dist/runtime/resolver-vendors/capsolver.d.ts +22 -0
  105. package/dist/runtime/resolver-vendors/capsolver.js +526 -0
  106. package/dist/runtime/resolver-vendors/hosts.d.ts +2 -0
  107. package/dist/runtime/resolver-vendors/hosts.js +33 -0
  108. package/dist/runtime/resolver-vendors/twocaptcha.d.ts +24 -0
  109. package/dist/runtime/resolver-vendors/twocaptcha.js +407 -0
  110. package/dist/runtime/resolver-vendors/types.d.ts +94 -0
  111. package/dist/runtime/resolver-vendors/types.js +96 -0
  112. package/dist/runtime/resolver.d.ts +60 -0
  113. package/dist/runtime/resolver.js +737 -0
  114. package/dist/runtime/secrets.d.ts +27 -0
  115. package/dist/runtime/secrets.js +51 -0
  116. package/dist/runtime/state.d.ts +3 -0
  117. package/dist/runtime/state.js +277 -71
  118. package/dist/runtime/stealth-cookies.d.ts +20 -0
  119. package/dist/runtime/stealth-cookies.js +111 -0
  120. package/dist/runtime/stealth.d.ts +28 -3
  121. package/dist/runtime/stealth.js +519 -255
  122. package/dist/runtime/stt.js +1 -12
  123. package/dist/runtime/timeout.d.ts +5 -0
  124. package/dist/runtime/timeout.js +12 -0
  125. package/dist/runtime/trace-config.d.ts +12 -0
  126. package/dist/runtime/trace-config.js +61 -0
  127. package/dist/serve.d.ts +1 -1
  128. package/dist/serve.js +1 -1
  129. package/dist/server/index.d.ts +5 -3
  130. package/dist/server/index.js +3 -3
  131. package/dist/server/self-test-input-tokens.d.ts +2 -1
  132. package/dist/server/self-test-input-tokens.js +18 -14
  133. package/dist/server/self-test.d.ts +114 -0
  134. package/dist/server/self-test.js +784 -148
  135. package/dist/server/serve-implementation.d.ts +213 -0
  136. package/dist/server/serve-implementation.js +2173 -0
  137. package/dist/server/serve.d.ts +1 -70
  138. package/dist/server/serve.js +1 -1130
  139. package/dist/server/trace-output.d.ts +4 -0
  140. package/dist/server/trace-output.js +20 -0
  141. package/dist/server/types.d.ts +30 -5
  142. package/dist/server/types.js +13 -1
  143. package/dist/stateful/errors.d.ts +19 -0
  144. package/dist/stateful/errors.js +24 -0
  145. package/dist/stateful/http-provider-event-emitter.d.ts +40 -0
  146. package/dist/stateful/http-provider-event-emitter.js +237 -0
  147. package/dist/stateful/http-session-owner-registry.d.ts +44 -0
  148. package/dist/stateful/http-session-owner-registry.js +210 -0
  149. package/dist/stateful/index.d.ts +18 -0
  150. package/dist/stateful/index.js +18 -0
  151. package/dist/stateful/provider-event-delivery-failures.d.ts +32 -0
  152. package/dist/stateful/provider-event-delivery-failures.js +43 -0
  153. package/dist/stateful/provider-event-pipeline-metrics.d.ts +46 -0
  154. package/dist/stateful/provider-event-pipeline-metrics.js +48 -0
  155. package/dist/stateful/provider-event-pipeline.d.ts +50 -0
  156. package/dist/stateful/provider-event-pipeline.js +1 -0
  157. package/dist/stateful/provider-events.d.ts +101 -0
  158. package/dist/stateful/provider-events.js +289 -0
  159. package/dist/stateful/session-key.d.ts +15 -0
  160. package/dist/stateful/session-key.js +86 -0
  161. package/dist/stateful/stateful-provider-adapter-context.d.ts +5 -0
  162. package/dist/stateful/stateful-provider-adapter-context.js +42 -0
  163. package/dist/stateful/stateful-provider-adapter-metrics.d.ts +15 -0
  164. package/dist/stateful/stateful-provider-adapter-metrics.js +21 -0
  165. package/dist/stateful/stateful-provider-adapter.d.ts +98 -0
  166. package/dist/stateful/stateful-provider-adapter.js +287 -0
  167. package/dist/stateful/stateful-provider-observability.d.ts +62 -0
  168. package/dist/stateful/stateful-provider-observability.js +161 -0
  169. package/dist/stateful/stateful-provider-owner-forwarder.d.ts +41 -0
  170. package/dist/stateful/stateful-provider-owner-forwarder.js +215 -0
  171. package/dist/stateful/stateful-provider-runtime-context.d.ts +32 -0
  172. package/dist/stateful/stateful-provider-runtime-context.js +60 -0
  173. package/dist/stateful/stateful-provider-runtime-executor.d.ts +34 -0
  174. package/dist/stateful/stateful-provider-runtime-executor.js +52 -0
  175. package/dist/stateful/stateful-provider-session-routing.d.ts +67 -0
  176. package/dist/stateful/stateful-provider-session-routing.js +345 -0
  177. package/dist/stateful/stateful-provider-session-runtime.d.ts +98 -0
  178. package/dist/stateful/stateful-provider-session-runtime.js +245 -0
  179. package/dist/stateful-signing.d.ts +18 -0
  180. package/dist/stateful-signing.js +27 -0
  181. package/dist/stealth/profiles.js +16 -7
  182. package/dist/stream-evidence.d.ts +74 -0
  183. package/dist/stream-evidence.js +785 -0
  184. package/dist/stream.js +7 -1
  185. package/dist/testing/index.d.ts +2 -1
  186. package/dist/testing/index.js +2 -1
  187. package/dist/testing/run.d.ts +32 -2
  188. package/dist/testing/run.js +489 -21
  189. package/dist/trace-sanitization.d.ts +5 -0
  190. package/dist/trace-sanitization.js +45 -0
  191. package/dist/types.d.ts +545 -23
  192. package/dist/types.js +1 -0
  193. package/package.json +44 -5
  194. package/src/auth-turn/index.ts +1 -1
  195. package/src/auth.ts +118 -0
  196. package/src/ceremonies/index.ts +189 -46
  197. package/src/cli/commands.ts +10 -0
  198. package/src/cli/create.ts +42 -35
  199. package/src/cli/prompt-assets.ts +865 -0
  200. package/src/cli/templates/provider/AGENTS.md.tpl +17 -8
  201. package/src/cli/templates/provider/Dockerfile.tpl +1 -1
  202. package/src/cli/templates/provider/README.md.tpl +4 -4
  203. package/src/cli/templates/provider/index.ts.tpl +6 -3
  204. package/src/cli/templates/provider/operations/ping.ts.tpl +2 -1
  205. package/src/config/loader.ts +665 -163
  206. package/src/contract-serialization.ts +5 -7
  207. package/src/contract-types.ts +1 -0
  208. package/src/contract.ts +2 -0
  209. package/src/declaration-validation.ts +266 -0
  210. package/src/define.ts +970 -87
  211. package/src/error-resolution.ts +127 -0
  212. package/src/errors.ts +52 -0
  213. package/src/fixture-sanitization.ts +248 -0
  214. package/src/health-scenario.ts +875 -0
  215. package/src/index.ts +204 -8
  216. package/src/lint.ts +408 -4
  217. package/src/native-address.ts +340 -0
  218. package/src/native-egress-policy.ts +358 -0
  219. package/src/observability.ts +51 -1
  220. package/src/provider.ts +133 -0
  221. package/src/runtime/auth-flow.ts +12 -0
  222. package/src/runtime/browser.ts +661 -63
  223. package/src/runtime/cache.ts +189 -14
  224. package/src/runtime/choice-wordlist.ts +145 -0
  225. package/src/runtime/choice.ts +631 -120
  226. package/src/runtime/executor.ts +40 -7
  227. package/src/runtime/http.ts +641 -61
  228. package/src/runtime/instrumentation.ts +520 -15
  229. package/src/runtime/native-network-errors.ts +99 -0
  230. package/src/runtime/native-network.ts +1605 -0
  231. package/src/runtime/ocr.ts +523 -0
  232. package/src/runtime/proxy-errors.ts +12 -4
  233. package/src/runtime/proxy-nodemaven.ts +221 -0
  234. package/src/runtime/proxy-telemetry.ts +244 -75
  235. package/src/runtime/redirects.ts +66 -0
  236. package/src/runtime/redis.ts +7 -2
  237. package/src/runtime/request-options.ts +680 -1
  238. package/src/runtime/resolver-config.ts +6 -0
  239. package/src/runtime/resolver-public.ts +20 -0
  240. package/src/runtime/resolver-shared.ts +17 -0
  241. package/src/runtime/resolver-vendors/bindings.ts +56 -0
  242. package/src/runtime/resolver-vendors/browser.ts +533 -0
  243. package/src/runtime/resolver-vendors/capsolver.ts +700 -0
  244. package/src/runtime/resolver-vendors/hosts.ts +38 -0
  245. package/src/runtime/resolver-vendors/twocaptcha.ts +539 -0
  246. package/src/runtime/resolver-vendors/types.ts +212 -0
  247. package/src/runtime/resolver.ts +1103 -0
  248. package/src/runtime/secrets.ts +64 -0
  249. package/src/runtime/state.ts +394 -77
  250. package/src/runtime/stealth-cookies.ts +132 -0
  251. package/src/runtime/stealth.ts +675 -289
  252. package/src/runtime/stt.ts +1 -19
  253. package/src/runtime/timeout.ts +18 -0
  254. package/src/runtime/trace-config.ts +77 -0
  255. package/src/serve.ts +6 -1
  256. package/src/server/index.ts +37 -2
  257. package/src/server/self-test-input-tokens.ts +29 -14
  258. package/src/server/self-test.ts +1025 -175
  259. package/src/server/serve-implementation.ts +3250 -0
  260. package/src/server/serve.ts +1 -1626
  261. package/src/server/trace-output.ts +32 -0
  262. package/src/server/types.ts +13 -1
  263. package/src/stateful/README.md +146 -0
  264. package/src/stateful/errors.ts +35 -0
  265. package/src/stateful/http-provider-event-emitter.ts +314 -0
  266. package/src/stateful/http-session-owner-registry.ts +306 -0
  267. package/src/stateful/index.ts +18 -0
  268. package/src/stateful/provider-event-delivery-failures.ts +80 -0
  269. package/src/stateful/provider-event-pipeline-metrics.ts +95 -0
  270. package/src/stateful/provider-event-pipeline.ts +61 -0
  271. package/src/stateful/provider-events.ts +462 -0
  272. package/src/stateful/session-key.ts +111 -0
  273. package/src/stateful/stateful-provider-adapter-context.ts +59 -0
  274. package/src/stateful/stateful-provider-adapter-metrics.ts +48 -0
  275. package/src/stateful/stateful-provider-adapter.ts +562 -0
  276. package/src/stateful/stateful-provider-observability.ts +261 -0
  277. package/src/stateful/stateful-provider-owner-forwarder.ts +287 -0
  278. package/src/stateful/stateful-provider-runtime-context.ts +92 -0
  279. package/src/stateful/stateful-provider-runtime-executor.ts +96 -0
  280. package/src/stateful/stateful-provider-session-routing.ts +546 -0
  281. package/src/stateful/stateful-provider-session-runtime.ts +403 -0
  282. package/src/stateful-signing.ts +46 -0
  283. package/src/stealth/profiles.ts +17 -7
  284. package/src/stream-evidence.ts +988 -0
  285. package/src/stream.ts +8 -1
  286. package/src/testing/index.ts +10 -1
  287. package/src/testing/run.ts +658 -15
  288. package/src/trace-sanitization.ts +63 -0
  289. package/src/types.ts +660 -38
  290. package/dist/cli/templates/provider/CLAUDE.md.tpl +0 -1
  291. package/src/cli/templates/provider/CLAUDE.md.tpl +0 -1
  292. /package/dist/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  293. /package/dist/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  294. /package/dist/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  295. /package/dist/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  296. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  297. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
  298. /package/src/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  299. /package/src/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  300. /package/src/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  301. /package/src/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  302. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  303. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
@@ -0,0 +1,340 @@
1
+ import { domainToASCII } from "node:url";
2
+
3
+ const STRICT_IPV4_PATTERN =
4
+ /^(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})$/;
5
+ const DECIMAL_COMPONENT_PATTERN = /^\d+$/;
6
+ const HEX_COMPONENT_PATTERN = /^0[xX][\da-fA-F]+$/;
7
+ const IPV6_GROUP_PATTERN = /^[\da-fA-F]{1,4}$/;
8
+ const FORMAT_CONTROL_PATTERN = /\p{Cf}/u;
9
+ const RESERVED_EGRESS_HOST_DELIMITERS = ["/", "\\", "?", "#", "@", "[", "]", " ", "%"];
10
+
11
+ const IPV4_MAPPED_PREFIX = Uint8Array.of(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff);
12
+ const IPV4_COMPATIBLE_MIN = Uint8Array.of(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2);
13
+ const IPV4_COMPATIBLE_MAX = Uint8Array.of(
14
+ 0,
15
+ 0,
16
+ 0,
17
+ 0,
18
+ 0,
19
+ 0,
20
+ 0,
21
+ 0,
22
+ 0,
23
+ 0,
24
+ 0,
25
+ 0,
26
+ 0xff,
27
+ 0xff,
28
+ 0xff,
29
+ 0xff,
30
+ );
31
+
32
+ export type EgressHostKind = "ipv4" | "ipv6" | "ipv4-mapped-ipv6" | "numeric-ambiguous" | "dns";
33
+
34
+ export type EgressHostCanonicalizationFailure =
35
+ | "not-string"
36
+ | "reserved-delimiter"
37
+ | "control-character"
38
+ | "whitespace"
39
+ | "canonicalization-empty";
40
+
41
+ export type EgressHostCanonicalizationResult =
42
+ | { readonly ok: true; readonly host: string }
43
+ | { readonly ok: false; readonly reason: EgressHostCanonicalizationFailure };
44
+
45
+ export type Ipv6CidrOverlap = "ipv4-mapped" | "ipv4-compatible";
46
+
47
+ export type Ipv6CidrParseResult =
48
+ | { readonly ok: true; readonly network: Uint8Array; readonly prefix: number }
49
+ | {
50
+ readonly ok: false;
51
+ readonly reason: "malformed";
52
+ readonly overlap?: Ipv6CidrOverlap;
53
+ }
54
+ | { readonly ok: false; readonly reason: "non-canonical-network" };
55
+
56
+ export function parseStrictIpv4(value: string): number | undefined {
57
+ const match = STRICT_IPV4_PATTERN.exec(value);
58
+ if (!match || match[0] !== value) return undefined;
59
+ const [, first, second, third, fourth] = match;
60
+ if (first === undefined || second === undefined || third === undefined || fourth === undefined)
61
+ return undefined;
62
+ const octets = [Number(first), Number(second), Number(third), Number(fourth)];
63
+ if (octets.some((octet) => octet > 255)) return undefined;
64
+ const [a, b, c, d] = octets;
65
+ if (a === undefined || b === undefined || c === undefined || d === undefined) return undefined;
66
+ return (a * 0x1000000 + b * 0x10000 + c * 0x100 + d) >>> 0;
67
+ }
68
+
69
+ function ipv4HexGroups(value: string): readonly [string, string] | undefined {
70
+ const address = parseStrictIpv4(value);
71
+ if (address === undefined) return undefined;
72
+ return [((address >>> 16) & 0xffff).toString(16), (address & 0xffff).toString(16)];
73
+ }
74
+
75
+ /** Parse the RFC 4291 IPv6 text forms accepted at both policy and runtime boundaries. */
76
+ export function parseIpv6(value: string): Uint8Array | undefined {
77
+ if (!value || value.includes("%") || value.includes("[") || value.includes("]")) return undefined;
78
+ if (value.indexOf("::") !== value.lastIndexOf("::")) return undefined;
79
+
80
+ let text = value;
81
+ if (text.includes(".")) {
82
+ const finalColon = text.lastIndexOf(":");
83
+ if (finalColon < 0) return undefined;
84
+ const groups = ipv4HexGroups(text.slice(finalColon + 1));
85
+ if (!groups) return undefined;
86
+ text = `${text.slice(0, finalColon + 1)}${groups[0]}:${groups[1]}`;
87
+ }
88
+
89
+ const compression = text.indexOf("::");
90
+ let groups: string[];
91
+ if (compression >= 0) {
92
+ const leftText = text.slice(0, compression);
93
+ const rightText = text.slice(compression + 2);
94
+ const left = leftText ? leftText.split(":") : [];
95
+ const right = rightText ? rightText.split(":") : [];
96
+ if (
97
+ left.some((group) => !IPV6_GROUP_PATTERN.test(group)) ||
98
+ right.some((group) => !IPV6_GROUP_PATTERN.test(group)) ||
99
+ left.length + right.length >= 8
100
+ )
101
+ return undefined;
102
+ groups = [...left, ...Array<string>(8 - left.length - right.length).fill("0"), ...right];
103
+ } else {
104
+ groups = text.split(":");
105
+ if (groups.length !== 8 || groups.some((group) => !IPV6_GROUP_PATTERN.test(group)))
106
+ return undefined;
107
+ }
108
+
109
+ const bytes = new Uint8Array(16);
110
+ for (let index = 0; index < groups.length; index += 1) {
111
+ const group = groups[index];
112
+ if (group === undefined) return undefined;
113
+ const parsed = Number.parseInt(group, 16);
114
+ bytes[index * 2] = parsed >>> 8;
115
+ bytes[index * 2 + 1] = parsed & 0xff;
116
+ }
117
+ return bytes;
118
+ }
119
+
120
+ function prefixMatches(address: Uint8Array, network: Uint8Array, prefix: number): boolean {
121
+ const wholeBytes = Math.floor(prefix / 8);
122
+ for (let index = 0; index < wholeBytes; index += 1) {
123
+ if (address[index] !== network[index]) return false;
124
+ }
125
+ const remainingBits = prefix % 8;
126
+ if (remainingBits === 0) return true;
127
+ const mask = (0xff << (8 - remainingBits)) & 0xff;
128
+ return ((address[wholeBytes] ?? 0) & mask) === ((network[wholeBytes] ?? 0) & mask);
129
+ }
130
+
131
+ function compareIpv6(left: Uint8Array, right: Uint8Array): number {
132
+ for (let index = 0; index < 16; index += 1) {
133
+ const difference = (left[index] ?? 0) - (right[index] ?? 0);
134
+ if (difference !== 0) return difference;
135
+ }
136
+ return 0;
137
+ }
138
+
139
+ function cidrMaximum(network: Uint8Array, prefix: number): Uint8Array {
140
+ const maximum = network.slice();
141
+ for (let bit = prefix; bit < 128; bit += 1) {
142
+ const byteIndex = Math.floor(bit / 8);
143
+ maximum[byteIndex] = (maximum[byteIndex] ?? 0) | (1 << (7 - (bit % 8)));
144
+ }
145
+ return maximum;
146
+ }
147
+
148
+ function rangesOverlap(
149
+ leftMin: Uint8Array,
150
+ leftMax: Uint8Array,
151
+ rightMin: Uint8Array,
152
+ rightMax: Uint8Array,
153
+ ): boolean {
154
+ return compareIpv6(leftMin, rightMax) <= 0 && compareIpv6(rightMin, leftMax) <= 0;
155
+ }
156
+
157
+ function ipv6CidrOverlap(network: Uint8Array, prefix: number): Ipv6CidrOverlap | undefined {
158
+ const maximum = cidrMaximum(network, prefix);
159
+ const mappedMin = new Uint8Array(16);
160
+ mappedMin.set(IPV4_MAPPED_PREFIX);
161
+ const mappedMax = mappedMin.slice();
162
+ mappedMax.fill(0xff, 12);
163
+ if (rangesOverlap(network, maximum, mappedMin, mappedMax)) return "ipv4-mapped";
164
+ if (rangesOverlap(network, maximum, IPV4_COMPATIBLE_MIN, IPV4_COMPATIBLE_MAX))
165
+ return "ipv4-compatible";
166
+ return undefined;
167
+ }
168
+
169
+ export function parseIpv4Cidr(
170
+ value: string,
171
+ ):
172
+ | { readonly ok: true; readonly network: number; readonly prefix: number }
173
+ | { readonly ok: false; readonly reason: "malformed" | "non-canonical-network" } {
174
+ const separator = value.indexOf("/");
175
+ if (separator <= 0 || separator !== value.lastIndexOf("/"))
176
+ return { ok: false, reason: "malformed" };
177
+ const address = parseStrictIpv4(value.slice(0, separator));
178
+ const prefixText = value.slice(separator + 1);
179
+ const prefix = Number(prefixText);
180
+ if (
181
+ address === undefined ||
182
+ !Number.isInteger(prefix) ||
183
+ prefix < 0 ||
184
+ prefix > 32 ||
185
+ String(prefix) !== prefixText
186
+ )
187
+ return { ok: false, reason: "malformed" };
188
+ const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
189
+ const network = (address & mask) >>> 0;
190
+ if (address !== network) return { ok: false, reason: "non-canonical-network" };
191
+ return { ok: true, network, prefix };
192
+ }
193
+
194
+ export function parseIpv6Cidr(value: string): Ipv6CidrParseResult {
195
+ const separator = value.indexOf("/");
196
+ if (separator <= 0 || separator !== value.lastIndexOf("/"))
197
+ return { ok: false, reason: "malformed" };
198
+ const address = parseIpv6(value.slice(0, separator));
199
+ const prefixText = value.slice(separator + 1);
200
+ const prefix = Number(prefixText);
201
+ if (
202
+ address === undefined ||
203
+ !Number.isInteger(prefix) ||
204
+ prefix < 0 ||
205
+ prefix > 128 ||
206
+ String(prefix) !== prefixText
207
+ )
208
+ return { ok: false, reason: "malformed" };
209
+ const network = address.slice();
210
+ const wholeBytes = Math.floor(prefix / 8);
211
+ const remainingBits = prefix % 8;
212
+ if (remainingBits > 0) {
213
+ const mask = (0xff << (8 - remainingBits)) & 0xff;
214
+ network[wholeBytes] = (network[wholeBytes] ?? 0) & mask;
215
+ }
216
+ network.fill(0, wholeBytes + (remainingBits > 0 ? 1 : 0));
217
+ if (compareIpv6(address, network) !== 0) return { ok: false, reason: "non-canonical-network" };
218
+ const overlap = ipv6CidrOverlap(network, prefix);
219
+ if (overlap) return { ok: false, reason: "malformed", overlap };
220
+ return { ok: true, network, prefix };
221
+ }
222
+
223
+ export function ipv4InCidr(address: number, cidr: string): boolean {
224
+ const parsed = parseIpv4Cidr(cidr);
225
+ if (!parsed.ok) return false;
226
+ return (
227
+ parsed.prefix === 0 ||
228
+ address >>> (32 - parsed.prefix) === parsed.network >>> (32 - parsed.prefix)
229
+ );
230
+ }
231
+
232
+ export function ipv6InCidr(address: Uint8Array, cidr: string): boolean {
233
+ if (address.length !== 16) return false;
234
+ const parsed = parseIpv6Cidr(cidr);
235
+ return parsed.ok && prefixMatches(address, parsed.network, parsed.prefix);
236
+ }
237
+
238
+ export function embeddedIpv4FromIpv6(address: Uint8Array): number | undefined {
239
+ if (address.length !== 16) return undefined;
240
+ const mapped = IPV4_MAPPED_PREFIX.every((byte, index) => address[index] === byte);
241
+ const compatible = address.slice(0, 12).every((byte) => byte === 0);
242
+ const embedded =
243
+ ((address[12] ?? 0) * 0x1000000 +
244
+ (address[13] ?? 0) * 0x10000 +
245
+ (address[14] ?? 0) * 0x100 +
246
+ (address[15] ?? 0)) >>>
247
+ 0;
248
+ if (mapped || (compatible && embedded !== 0 && embedded !== 1)) return embedded;
249
+ return undefined;
250
+ }
251
+
252
+ export function formatIpv6(address: Uint8Array): string {
253
+ if (address.length !== 16) throw new TypeError("IPv6 addresses must contain exactly 16 bytes");
254
+ const groups = Array.from({ length: 8 }, (_, index) =>
255
+ (((address[index * 2] ?? 0) << 8) | (address[index * 2 + 1] ?? 0)).toString(16),
256
+ );
257
+ let bestStart = -1;
258
+ let bestLength = 0;
259
+ for (let index = 0; index < groups.length; ) {
260
+ if (groups[index] !== "0") {
261
+ index += 1;
262
+ continue;
263
+ }
264
+ let end = index + 1;
265
+ while (end < groups.length && groups[end] === "0") end += 1;
266
+ if (end - index > bestLength && end - index >= 2) {
267
+ bestStart = index;
268
+ bestLength = end - index;
269
+ }
270
+ index = end;
271
+ }
272
+ if (bestStart < 0) return groups.join(":");
273
+ const left = groups.slice(0, bestStart).join(":");
274
+ const right = groups.slice(bestStart + bestLength).join(":");
275
+ return `${left}::${right}`;
276
+ }
277
+
278
+ /** The single family and ambiguity classifier used by policy and runtime matching. */
279
+ export function classifyEgressHost(host: string): EgressHostKind {
280
+ if (
281
+ hasReservedEgressHostDelimiter(host) ||
282
+ hasEgressHostControlCharacter(host) ||
283
+ /\s/u.test(host)
284
+ )
285
+ return "numeric-ambiguous";
286
+ if (parseStrictIpv4(host) !== undefined) return "ipv4";
287
+ const ipv6 = parseIpv6(host);
288
+ if (ipv6) return embeddedIpv4FromIpv6(ipv6) === undefined ? "ipv6" : "ipv4-mapped-ipv6";
289
+ if (host.includes(":")) return "numeric-ambiguous";
290
+ const labels = host.split(".");
291
+ if (
292
+ labels.every(
293
+ (label) =>
294
+ DECIMAL_COMPONENT_PATTERN.exec(label)?.[0] === label ||
295
+ HEX_COMPONENT_PATTERN.exec(label)?.[0] === label,
296
+ )
297
+ )
298
+ return "numeric-ambiguous";
299
+ return "dns";
300
+ }
301
+
302
+ export function hasReservedEgressHostDelimiter(value: string): boolean {
303
+ return RESERVED_EGRESS_HOST_DELIMITERS.some((delimiter) => value.includes(delimiter));
304
+ }
305
+
306
+ export function hasEgressHostControlCharacter(value: string): boolean {
307
+ for (let index = 0; index < value.length; index += 1) {
308
+ const code = value.charCodeAt(index);
309
+ if (code <= 31 || code === 127) return true;
310
+ }
311
+ return FORMAT_CONTROL_PATTERN.test(value);
312
+ }
313
+
314
+ export function canonicalizeEgressHost(value: unknown): EgressHostCanonicalizationResult {
315
+ if (typeof value !== "string") return { ok: false, reason: "not-string" };
316
+ if (hasReservedEgressHostDelimiter(value)) return { ok: false, reason: "reserved-delimiter" };
317
+ if (hasEgressHostControlCharacter(value)) return { ok: false, reason: "control-character" };
318
+ if (/\s/u.test(value)) return { ok: false, reason: "whitespace" };
319
+ const raw = value.trim();
320
+ if (!raw) return { ok: false, reason: "canonicalization-empty" };
321
+
322
+ const ipv6 = parseIpv6(raw);
323
+ if (ipv6) return { ok: true, host: formatIpv6(ipv6) };
324
+
325
+ // Classify the spelling with one optional root-label dot removed before IDNA.
326
+ // This keeps resolver-numeric ASCII forms from being widened into canonical IPv4.
327
+ const numericCandidate = raw.endsWith(".") ? raw.slice(0, -1) : raw;
328
+ const normalizedNumericCandidate = numericCandidate.toLowerCase();
329
+ if (classifyEgressHost(normalizedNumericCandidate) === "numeric-ambiguous")
330
+ return { ok: true, host: normalizedNumericCandidate };
331
+
332
+ let ascii: string;
333
+ try {
334
+ ascii = domainToASCII(raw).toLowerCase().replace(/\.$/, "");
335
+ } catch {
336
+ return { ok: false, reason: "canonicalization-empty" };
337
+ }
338
+ if (!ascii || /^\.+$/.test(ascii)) return { ok: false, reason: "canonicalization-empty" };
339
+ return { ok: true, host: ascii };
340
+ }
@@ -0,0 +1,358 @@
1
+ import type {
2
+ NativeProviderConfig,
3
+ NativeTcpDynamicEgressRule,
4
+ NativeTcpEgressRule,
5
+ NativeTcpPortRange,
6
+ NativeTcpTlsMode,
7
+ } from "./types.js";
8
+ import {
9
+ canonicalizeEgressHost,
10
+ classifyEgressHost,
11
+ formatIpv6,
12
+ parseIpv4Cidr,
13
+ parseIpv6Cidr,
14
+ } from "./native-address.js";
15
+
16
+ type NativeNetworkDeclaration = NonNullable<NativeProviderConfig["network"]>;
17
+
18
+ const NATIVE_PROVIDER_FIELD_RECORD = {
19
+ network: true,
20
+ } satisfies { readonly [K in keyof Required<NativeProviderConfig>]: true };
21
+ const NATIVE_NETWORK_FIELD_RECORD = {
22
+ tcp: true,
23
+ dynamicTcp: true,
24
+ } satisfies { readonly [K in keyof Required<NativeNetworkDeclaration>]: true };
25
+ const NATIVE_TCP_RULE_FIELD_RECORD = {
26
+ host: true,
27
+ ports: true,
28
+ tls: true,
29
+ } satisfies { readonly [K in keyof Required<NativeTcpEgressRule>]: true };
30
+ const NATIVE_DYNAMIC_TCP_RULE_FIELD_RECORD = {
31
+ sourceHost: true,
32
+ sourceHostSuffixes: true,
33
+ sourceIpv4Cidrs: true,
34
+ sourceIpv6Cidrs: true,
35
+ sourcePorts: true,
36
+ sourcePortRanges: true,
37
+ targetHostSuffixes: true,
38
+ targetIpv4Cidrs: true,
39
+ targetIpv6Cidrs: true,
40
+ targetPorts: true,
41
+ targetPortRanges: true,
42
+ tls: true,
43
+ ttlMs: true,
44
+ maxGrants: true,
45
+ } satisfies { readonly [K in keyof Required<NativeTcpDynamicEgressRule>]: true };
46
+ const NATIVE_TCP_PORT_RANGE_FIELD_RECORD = {
47
+ start: true,
48
+ end: true,
49
+ } satisfies { readonly [K in keyof Required<NativeTcpPortRange>]: true };
50
+
51
+ const NATIVE_PROVIDER_FIELDS = Object.keys(NATIVE_PROVIDER_FIELD_RECORD);
52
+ const NATIVE_NETWORK_FIELDS = Object.keys(NATIVE_NETWORK_FIELD_RECORD);
53
+ const NATIVE_TCP_RULE_FIELDS = Object.keys(NATIVE_TCP_RULE_FIELD_RECORD);
54
+ const NATIVE_DYNAMIC_TCP_RULE_FIELDS = Object.keys(NATIVE_DYNAMIC_TCP_RULE_FIELD_RECORD);
55
+ const NATIVE_TCP_PORT_RANGE_FIELDS = Object.keys(NATIVE_TCP_PORT_RANGE_FIELD_RECORD);
56
+
57
+ export type StaticEgressRuleSnapshot = {
58
+ readonly host: string;
59
+ readonly ports: readonly number[];
60
+ readonly tls: NativeTcpTlsMode;
61
+ };
62
+
63
+ export type DynamicEgressRuleSnapshot = {
64
+ readonly sourceHost?: string;
65
+ readonly sourceHostSuffixes: readonly string[];
66
+ readonly sourceIpv4Cidrs: readonly string[];
67
+ readonly sourceIpv6Cidrs: readonly string[];
68
+ readonly sourcePorts: readonly number[];
69
+ readonly sourcePortRanges: readonly NativeTcpPortRange[];
70
+ readonly targetHostSuffixes: readonly string[];
71
+ readonly targetIpv4Cidrs: readonly string[];
72
+ readonly targetIpv6Cidrs: readonly string[];
73
+ readonly targetPorts: readonly number[];
74
+ readonly targetPortRanges: readonly NativeTcpPortRange[];
75
+ readonly tls: NativeTcpTlsMode;
76
+ readonly ttlMs?: number;
77
+ readonly maxGrants?: number;
78
+ };
79
+
80
+ export type NativeEgressPolicySnapshot = {
81
+ readonly staticRules: readonly StaticEgressRuleSnapshot[];
82
+ readonly dynamicRules: readonly DynamicEgressRuleSnapshot[];
83
+ };
84
+
85
+ export class NativeEgressPolicyValidationError extends Error {
86
+ constructor(message: string) {
87
+ super(message);
88
+ this.name = "NativeEgressPolicyValidationError";
89
+ }
90
+ }
91
+
92
+ function fail(message: string): never {
93
+ throw new NativeEgressPolicyValidationError(message);
94
+ }
95
+
96
+ function dataRecord(
97
+ value: unknown,
98
+ fieldPath: string,
99
+ allowed: readonly string[],
100
+ ): Record<string, unknown> {
101
+ if (!value || typeof value !== "object" || Array.isArray(value))
102
+ fail(`${fieldPath} must be an object`);
103
+ const prototype = Reflect.getPrototypeOf(value);
104
+ if (prototype !== Object.prototype && prototype !== null)
105
+ fail(`${fieldPath} must be a plain object`);
106
+ const record: Record<string, unknown> = {};
107
+ for (const key of Reflect.ownKeys(value)) {
108
+ if (typeof key !== "string") fail(`${fieldPath} must not contain symbol fields`);
109
+ if (!allowed.includes(key)) fail(`Unknown field ${fieldPath}.${key}`);
110
+ const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
111
+ if (!descriptor || !("value" in descriptor)) fail(`${fieldPath}.${key} must be a data field`);
112
+ record[key] = descriptor.value;
113
+ }
114
+ return record;
115
+ }
116
+
117
+ function dataArray(value: unknown, fieldPath: string): readonly unknown[] {
118
+ if (!Array.isArray(value)) fail(`${fieldPath} must be an array`);
119
+ const result: unknown[] = [];
120
+ for (const key of Reflect.ownKeys(value)) {
121
+ if (key === "length") continue;
122
+ if (typeof key !== "string" || !/^(?:0|[1-9]\d*)$/.test(key))
123
+ fail(`${fieldPath} must not contain non-index fields`);
124
+ const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
125
+ if (!descriptor || !("value" in descriptor)) fail(`${fieldPath}[${key}] must be a data field`);
126
+ result[Number(key)] = descriptor.value;
127
+ }
128
+ if (result.length !== value.length) fail(`${fieldPath} must not be sparse`);
129
+ for (let index = 0; index < result.length; index += 1) {
130
+ if (!(index in result)) fail(`${fieldPath} must not be sparse`);
131
+ }
132
+ return result;
133
+ }
134
+
135
+ function host(value: unknown, fieldPath: string, suffix = false): string {
136
+ if (typeof value === "string" && value.includes("*"))
137
+ fail(`${fieldPath} must be an exact ${suffix ? "DNS suffix" : "hostname"}, not a wildcard`);
138
+ const canonical = canonicalizeEgressHost(value);
139
+ if (!canonical.ok) fail(`${fieldPath} must be a non-empty hostname`);
140
+ const kind = classifyEgressHost(canonical.host);
141
+ if (kind === "numeric-ambiguous")
142
+ fail(`${fieldPath} value is an unresolvable numeric-ambiguous spelling`);
143
+ if (suffix && kind !== "dns") {
144
+ const family = kind === "ipv4" ? "IPv4" : "IPv6";
145
+ fail(`${fieldPath} must be a DNS suffix, not an ${family} literal`);
146
+ }
147
+ return canonical.host;
148
+ }
149
+
150
+ function port(value: unknown, fieldPath: string): number {
151
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1 || value > 65_535)
152
+ fail(`${fieldPath} must be an integer from 1 to 65535`);
153
+ return value;
154
+ }
155
+
156
+ function ports(value: unknown, fieldPath: string): readonly number[] {
157
+ return dataArray(value, fieldPath).map((value, index) => port(value, `${fieldPath}[${index}]`));
158
+ }
159
+
160
+ function hostSuffixes(value: unknown, fieldPath: string): readonly string[] {
161
+ return dataArray(value, fieldPath).map((value, index) =>
162
+ host(value, `${fieldPath}[${index}]`, true),
163
+ );
164
+ }
165
+
166
+ function ipv4Cidrs(value: unknown, fieldPath: string): readonly string[] {
167
+ const seen = new Set<string>();
168
+ return dataArray(value, fieldPath).map((value, index) => {
169
+ const cidrPath = `${fieldPath}[${index}]`;
170
+ if (typeof value !== "string") fail(`${cidrPath} must be an IPv4 CIDR in a.b.c.d/nn form`);
171
+ const parsed = parseIpv4Cidr(value);
172
+ if (!parsed.ok) {
173
+ if (parsed.reason === "non-canonical-network")
174
+ fail(`${cidrPath} must use the canonical network address with no host bits set`);
175
+ fail(`${cidrPath} must be an IPv4 CIDR in a.b.c.d/nn form`);
176
+ }
177
+ const duplicateKey = `${parsed.network}/${parsed.prefix}`;
178
+ if (seen.has(duplicateKey)) fail(`${fieldPath} must not contain duplicate CIDRs`);
179
+ seen.add(duplicateKey);
180
+ return value;
181
+ });
182
+ }
183
+
184
+ function ipv6Cidrs(value: unknown, fieldPath: string): readonly string[] {
185
+ const seen = new Set<string>();
186
+ return dataArray(value, fieldPath).map((value, index) => {
187
+ const cidrPath = `${fieldPath}[${index}]`;
188
+ if (typeof value !== "string") fail(`${cidrPath} must be an IPv6 CIDR in address/nn form`);
189
+ const parsed = parseIpv6Cidr(value);
190
+ if (!parsed.ok) {
191
+ if (parsed.reason === "non-canonical-network")
192
+ fail(`${cidrPath} must use the canonical network address with no host bits set`);
193
+ if (parsed.overlap === "ipv4-mapped")
194
+ fail(`${cidrPath} overlaps IPv4-mapped ::ffff:0:0/96 address space`);
195
+ if (parsed.overlap === "ipv4-compatible")
196
+ fail(`${cidrPath} overlaps IPv4-compatible ::/96 address space`);
197
+ fail(`${cidrPath} must be an IPv6 CIDR in address/nn form`);
198
+ }
199
+ const duplicateKey = `${formatIpv6(parsed.network)}/${parsed.prefix}`;
200
+ if (seen.has(duplicateKey)) fail(`${fieldPath} must not contain duplicate CIDRs`);
201
+ seen.add(duplicateKey);
202
+ return value;
203
+ });
204
+ }
205
+
206
+ function ranges(value: unknown, fieldPath: string): readonly NativeTcpPortRange[] {
207
+ return dataArray(value, fieldPath).map((value, index) => {
208
+ const rangePath = `${fieldPath}[${index}]`;
209
+ const record = dataRecord(value, rangePath, NATIVE_TCP_PORT_RANGE_FIELDS);
210
+ const start = port(record.start, `${rangePath}.start`);
211
+ const end = port(record.end, `${rangePath}.end`);
212
+ if (start > end) fail(`${rangePath}.start must not exceed end`);
213
+ return { start, end };
214
+ });
215
+ }
216
+
217
+ function tls(value: unknown, fieldPath: string): NativeTcpTlsMode {
218
+ if (value !== "required" && value !== "allowed" && value !== "disabled")
219
+ fail(`${fieldPath} must be required, allowed, or disabled`);
220
+ return value;
221
+ }
222
+
223
+ function positiveInteger(value: unknown, fieldPath: string): number {
224
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)
225
+ fail(`${fieldPath} must be a positive integer`);
226
+ return value;
227
+ }
228
+
229
+ export function parseNativeEgressPolicy(value: unknown): NativeEgressPolicySnapshot {
230
+ try {
231
+ const policy = dataRecord(value, "native.network", NATIVE_NETWORK_FIELDS);
232
+ const staticRules =
233
+ policy.tcp === undefined
234
+ ? []
235
+ : dataArray(policy.tcp, "native.network.tcp").map((value, index) => {
236
+ const fieldPath = `native.network.tcp[${index}]`;
237
+ const rule = dataRecord(value, fieldPath, NATIVE_TCP_RULE_FIELDS);
238
+ const declaredPorts = ports(rule.ports, `${fieldPath}.ports`);
239
+ if (declaredPorts.length === 0) fail(`${fieldPath}.ports must not be empty`);
240
+ return {
241
+ host: host(rule.host, `${fieldPath}.host`),
242
+ ports: declaredPorts,
243
+ tls: tls(rule.tls, `${fieldPath}.tls`),
244
+ };
245
+ });
246
+ const dynamicRules =
247
+ policy.dynamicTcp === undefined
248
+ ? []
249
+ : dataArray(policy.dynamicTcp, "native.network.dynamicTcp").map((value, index) => {
250
+ const fieldPath = `native.network.dynamicTcp[${index}]`;
251
+ const rule = dataRecord(value, fieldPath, NATIVE_DYNAMIC_TCP_RULE_FIELDS);
252
+ const sourceHost =
253
+ rule.sourceHost === undefined
254
+ ? undefined
255
+ : host(rule.sourceHost, `${fieldPath}.sourceHost`);
256
+ const sourceHostSuffixes =
257
+ rule.sourceHostSuffixes === undefined
258
+ ? []
259
+ : hostSuffixes(rule.sourceHostSuffixes, `${fieldPath}.sourceHostSuffixes`);
260
+ const sourceIpv4Cidrs =
261
+ rule.sourceIpv4Cidrs === undefined
262
+ ? []
263
+ : ipv4Cidrs(rule.sourceIpv4Cidrs, `${fieldPath}.sourceIpv4Cidrs`);
264
+ const sourceIpv6Cidrs =
265
+ rule.sourceIpv6Cidrs === undefined
266
+ ? []
267
+ : ipv6Cidrs(rule.sourceIpv6Cidrs, `${fieldPath}.sourceIpv6Cidrs`);
268
+ if (
269
+ sourceHost === undefined &&
270
+ sourceHostSuffixes.length === 0 &&
271
+ sourceIpv4Cidrs.length === 0 &&
272
+ sourceIpv6Cidrs.length === 0
273
+ )
274
+ fail(
275
+ `${fieldPath} must declare sourceHost or a non-empty sourceHostSuffixes, sourceIpv4Cidrs, or sourceIpv6Cidrs list`,
276
+ );
277
+ const sourcePorts =
278
+ rule.sourcePorts === undefined
279
+ ? []
280
+ : ports(rule.sourcePorts, `${fieldPath}.sourcePorts`);
281
+ const sourcePortRanges =
282
+ rule.sourcePortRanges === undefined
283
+ ? []
284
+ : ranges(rule.sourcePortRanges, `${fieldPath}.sourcePortRanges`);
285
+ if (sourcePorts.length === 0 && sourcePortRanges.length === 0)
286
+ fail(`${fieldPath} must declare a non-empty sourcePorts or sourcePortRanges list`);
287
+ const targetHostSuffixes =
288
+ rule.targetHostSuffixes === undefined
289
+ ? []
290
+ : hostSuffixes(rule.targetHostSuffixes, `${fieldPath}.targetHostSuffixes`);
291
+ const targetIpv4Cidrs =
292
+ rule.targetIpv4Cidrs === undefined
293
+ ? []
294
+ : ipv4Cidrs(rule.targetIpv4Cidrs, `${fieldPath}.targetIpv4Cidrs`);
295
+ const targetIpv6Cidrs =
296
+ rule.targetIpv6Cidrs === undefined
297
+ ? []
298
+ : ipv6Cidrs(rule.targetIpv6Cidrs, `${fieldPath}.targetIpv6Cidrs`);
299
+ if (
300
+ targetHostSuffixes.length === 0 &&
301
+ targetIpv4Cidrs.length === 0 &&
302
+ targetIpv6Cidrs.length === 0
303
+ )
304
+ fail(
305
+ `${fieldPath} must declare a non-empty targetHostSuffixes, targetIpv4Cidrs, or targetIpv6Cidrs list`,
306
+ );
307
+ const targetPorts =
308
+ rule.targetPorts === undefined
309
+ ? []
310
+ : ports(rule.targetPorts, `${fieldPath}.targetPorts`);
311
+ const targetPortRanges =
312
+ rule.targetPortRanges === undefined
313
+ ? []
314
+ : ranges(rule.targetPortRanges, `${fieldPath}.targetPortRanges`);
315
+ if (targetPorts.length === 0 && targetPortRanges.length === 0)
316
+ fail(`${fieldPath} must declare a non-empty targetPorts or targetPortRanges list`);
317
+ return {
318
+ ...(sourceHost === undefined ? {} : { sourceHost }),
319
+ sourceHostSuffixes,
320
+ sourceIpv4Cidrs,
321
+ sourceIpv6Cidrs,
322
+ sourcePorts,
323
+ sourcePortRanges,
324
+ targetHostSuffixes,
325
+ targetIpv4Cidrs,
326
+ targetIpv6Cidrs,
327
+ targetPorts,
328
+ targetPortRanges,
329
+ tls: tls(rule.tls, `${fieldPath}.tls`),
330
+ ...(rule.ttlMs === undefined
331
+ ? {}
332
+ : { ttlMs: positiveInteger(rule.ttlMs, `${fieldPath}.ttlMs`) }),
333
+ ...(rule.maxGrants === undefined
334
+ ? {}
335
+ : { maxGrants: positiveInteger(rule.maxGrants, `${fieldPath}.maxGrants`) }),
336
+ };
337
+ });
338
+ return { staticRules, dynamicRules };
339
+ } catch (error) {
340
+ if (error instanceof NativeEgressPolicyValidationError) throw error;
341
+ throw new NativeEgressPolicyValidationError(
342
+ "Native egress policy could not be inspected safely",
343
+ );
344
+ }
345
+ }
346
+
347
+ export function validateNativeProviderConfig(value: unknown): void {
348
+ if (value === undefined) return;
349
+ try {
350
+ const native = dataRecord(value, "native", NATIVE_PROVIDER_FIELDS);
351
+ if (native.network !== undefined) parseNativeEgressPolicy(native.network);
352
+ } catch (error) {
353
+ if (error instanceof NativeEgressPolicyValidationError) throw error;
354
+ throw new NativeEgressPolicyValidationError(
355
+ "Native provider config could not be inspected safely",
356
+ );
357
+ }
358
+ }