@capybara-hq/kernel 0.1.0-rc.145 → 0.1.0-rc.147

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 (185) hide show
  1. package/dist/admin/extensions.controller.d.ts +0 -11
  2. package/dist/admin/extensions.controller.js +0 -28
  3. package/dist/admin/health.service.d.ts +25 -1
  4. package/dist/admin/health.service.js +50 -18
  5. package/dist/audit/full-access.d.ts +78 -0
  6. package/dist/audit/full-access.js +283 -0
  7. package/dist/automations/automations.service.d.ts +1 -0
  8. package/dist/automations/automations.service.js +3 -1
  9. package/dist/automations/calendar.js +3 -1
  10. package/dist/automations/grant-rules.d.ts +2 -1
  11. package/dist/automations/grant-rules.js +8 -1
  12. package/dist/automations/unattended.d.ts +13 -1
  13. package/dist/automations/unattended.js +13 -1
  14. package/dist/catalog/admin-catalog.controller.d.ts +8 -0
  15. package/dist/catalog/admin-catalog.controller.js +8 -2
  16. package/dist/catalog/admin-catalog.schemas.d.ts +10 -0
  17. package/dist/catalog/admin-catalog.schemas.js +8 -1
  18. package/dist/catalog/catalog-content.d.ts +6 -0
  19. package/dist/catalog/catalog-scope.service.d.ts +22 -2
  20. package/dist/catalog/catalog-scope.service.js +27 -3
  21. package/dist/catalog/catalog.service.js +19 -2
  22. package/dist/catalog/marketplaces.service.d.ts +1 -1
  23. package/dist/catalog/org-catalog.service.d.ts +8 -1
  24. package/dist/catalog/org-catalog.service.js +36 -3
  25. package/dist/catalog/platform-components.js +3 -2
  26. package/dist/catalog/platform-import-update.d.ts +2 -0
  27. package/dist/catalog/platform-import-update.js +8 -1
  28. package/dist/catalog/plugin-connectors.d.ts +11 -0
  29. package/dist/catalog/plugin-connectors.js +33 -0
  30. package/dist/catalog/plugin-import.d.ts +35 -15
  31. package/dist/catalog/plugin-import.js +110 -35
  32. package/dist/catalog/plugin-install.js +6 -0
  33. package/dist/catalog/provenance.d.ts +71 -0
  34. package/dist/catalog/provenance.js +112 -0
  35. package/dist/config/auto-approve.d.ts +16 -0
  36. package/dist/config/auto-approve.js +24 -0
  37. package/dist/config/capacity-presets.d.ts +243 -0
  38. package/dist/config/capacity-presets.js +195 -0
  39. package/dist/config/env.d.ts +2 -1
  40. package/dist/config/env.js +6 -1
  41. package/dist/config/load.js +15 -0
  42. package/dist/config/schema.d.ts +46 -9
  43. package/dist/config/schema.js +154 -30
  44. package/dist/ctx/create-ctx.d.ts +16 -0
  45. package/dist/ctx/create-ctx.js +269 -34
  46. package/dist/ctx/net.d.ts +5 -1
  47. package/dist/ctx/net.js +62 -12
  48. package/dist/db/kernel-schema.d.ts +31 -0
  49. package/dist/db/migrator.js +0 -36
  50. package/dist/dial-in/routes.js +1 -1
  51. package/dist/erasure/org-batches.js +1 -6
  52. package/dist/erasure/org-catalog.js +6 -2
  53. package/dist/erasure/org-rules.js +1 -0
  54. package/dist/erasure/org-worker.js +0 -13
  55. package/dist/errors.d.ts +6 -0
  56. package/dist/errors.js +6 -0
  57. package/dist/extensions/admin-ops.d.ts +14 -1
  58. package/dist/extensions/admin-ops.js +30 -3
  59. package/dist/extensions/admin-view.d.ts +21 -1
  60. package/dist/extensions/admin-view.js +43 -0
  61. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  62. package/dist/extensions/bootstrap-packages.js +1 -1
  63. package/dist/extensions/bootstrap-review.d.ts +251 -0
  64. package/dist/extensions/bootstrap-review.js +676 -0
  65. package/dist/extensions/bootstrap.d.ts +21 -1
  66. package/dist/extensions/bootstrap.js +72 -2
  67. package/dist/extensions/cli.d.ts +6 -0
  68. package/dist/extensions/cli.js +4 -0
  69. package/dist/extensions/enabled.d.ts +3 -0
  70. package/dist/extensions/execution-realm.d.ts +96 -0
  71. package/dist/extensions/execution-realm.js +141 -0
  72. package/dist/extensions/extensions.module.js +12 -0
  73. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  74. package/dist/extensions/full-access-disclosure.js +57 -0
  75. package/dist/extensions/grant-epoch.d.ts +9 -2
  76. package/dist/extensions/grant-epoch.js +13 -2
  77. package/dist/extensions/host.d.ts +96 -4
  78. package/dist/extensions/host.js +411 -33
  79. package/dist/extensions/installs.d.ts +18 -0
  80. package/dist/extensions/installs.js +28 -0
  81. package/dist/extensions/instance.d.ts +2 -0
  82. package/dist/extensions/instance.js +1 -0
  83. package/dist/extensions/isolated/admission.d.ts +23 -2
  84. package/dist/extensions/isolated/admission.js +32 -7
  85. package/dist/extensions/isolated/authorization.d.ts +8 -2
  86. package/dist/extensions/isolated/authorization.js +11 -3
  87. package/dist/extensions/isolated/broker.d.ts +3 -0
  88. package/dist/extensions/isolated/broker.js +50 -14
  89. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  90. package/dist/extensions/isolated/configured-package.js +2 -0
  91. package/dist/extensions/isolated/lanes.d.ts +44 -3
  92. package/dist/extensions/isolated/lanes.js +263 -80
  93. package/dist/extensions/isolated/metrics.d.ts +146 -0
  94. package/dist/extensions/isolated/metrics.js +304 -0
  95. package/dist/extensions/isolated/revision.d.ts +7 -1
  96. package/dist/extensions/isolated/revision.js +26 -5
  97. package/dist/extensions/isolated/rpc.d.ts +5 -0
  98. package/dist/extensions/isolated/rpc.js +7 -2
  99. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  100. package/dist/extensions/isolated/sandbox.js +50 -0
  101. package/dist/extensions/isolated/status.d.ts +79 -0
  102. package/dist/extensions/isolated/status.js +216 -0
  103. package/dist/extensions/isolated/tier.d.ts +127 -2
  104. package/dist/extensions/isolated/tier.js +266 -7
  105. package/dist/extensions/isolated/usage.d.ts +134 -0
  106. package/dist/extensions/isolated/usage.js +322 -0
  107. package/dist/extensions/ledger.d.ts +5 -0
  108. package/dist/extensions/ledger.js +16 -0
  109. package/dist/extensions/lifecycle.d.ts +42 -2
  110. package/dist/extensions/lifecycle.js +100 -4
  111. package/dist/extensions/org-config.js +11 -0
  112. package/dist/extensions/package.d.ts +14 -0
  113. package/dist/extensions/package.js +23 -0
  114. package/dist/extensions/permission-view.d.ts +2 -2
  115. package/dist/extensions/permissions.controller.d.ts +35 -0
  116. package/dist/extensions/permissions.controller.js +98 -0
  117. package/dist/extensions/permissions.schemas.d.ts +288 -0
  118. package/dist/extensions/permissions.schemas.js +96 -0
  119. package/dist/extensions/permissions.service.d.ts +116 -0
  120. package/dist/extensions/permissions.service.js +428 -0
  121. package/dist/extensions/realm-retirement.d.ts +65 -0
  122. package/dist/extensions/realm-retirement.js +150 -0
  123. package/dist/extensions/registry.d.ts +6 -0
  124. package/dist/extensions/registry.js +8 -0
  125. package/dist/extensions/review-hash.d.ts +114 -0
  126. package/dist/extensions/review-hash.js +145 -0
  127. package/dist/extensions/revision-approvals.d.ts +58 -3
  128. package/dist/extensions/revision-approvals.js +135 -14
  129. package/dist/extensions/revision-grants.d.ts +10 -0
  130. package/dist/extensions/revision-review.d.ts +144 -0
  131. package/dist/extensions/revision-review.js +297 -0
  132. package/dist/extensions/revocation-leases.d.ts +273 -0
  133. package/dist/extensions/revocation-leases.js +533 -0
  134. package/dist/extensions/revocation.d.ts +78 -0
  135. package/dist/extensions/revocation.js +205 -0
  136. package/dist/extensions/state.module.js +12 -0
  137. package/dist/git/run-end.d.ts +35 -7
  138. package/dist/git/run-end.js +87 -38
  139. package/dist/http/api.module.js +2 -0
  140. package/dist/identity/audit.d.ts +2 -1
  141. package/dist/identity/audit.js +4 -17
  142. package/dist/index.d.ts +10 -2
  143. package/dist/index.js +10 -2
  144. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  145. package/dist/infra/config/kernel-config.service.js +21 -0
  146. package/dist/infra/outbox/registry.d.ts +13 -0
  147. package/dist/infra/outbox/registry.js +8 -0
  148. package/dist/lifecycle/kernel-lifecycle.d.ts +27 -1
  149. package/dist/lifecycle/kernel-lifecycle.js +83 -22
  150. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  151. package/dist/net/private-endpoint-preflight.js +417 -0
  152. package/dist/net/private-endpoints.d.ts +68 -0
  153. package/dist/net/private-endpoints.js +164 -0
  154. package/dist/net/public-address.d.ts +14 -0
  155. package/dist/net/public-address.js +15 -1
  156. package/dist/net/safe-fetch.d.ts +2 -1
  157. package/dist/net/safe-fetch.js +10 -3
  158. package/dist/overrides.d.ts +9 -1
  159. package/dist/overrides.js +4 -0
  160. package/dist/packages/official-publisher.d.ts +65 -1
  161. package/dist/packages/official-publisher.js +171 -46
  162. package/dist/packages/provenance.d.ts +11 -0
  163. package/dist/packages/provenance.js +24 -0
  164. package/dist/platform/exclusions.js +4 -4
  165. package/dist/platform/ops/automations.ops.js +1 -1
  166. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  167. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  168. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  169. package/dist/platform/platform-ops.module.d.ts +2 -1
  170. package/dist/platform/platform-ops.module.js +2 -0
  171. package/dist/platform/route-schemas.js +2 -0
  172. package/dist/retention/purge-batch.js +10 -14
  173. package/dist/runtime/maintenance.d.ts +4 -2
  174. package/dist/runtime/maintenance.js +16 -3
  175. package/dist/runtime/run-finish.d.ts +3 -3
  176. package/dist/runtime/run-finish.js +7 -3
  177. package/dist/sandbox/permission-availability.d.ts +17 -2
  178. package/dist/sandbox/permission-availability.js +22 -1
  179. package/dist/sandbox/permission-facts.js +7 -1
  180. package/dist/tools/builtins/sandbox/common.js +2 -0
  181. package/dist/tools/pipeline.d.ts +2 -1
  182. package/dist/tools/pipeline.js +7 -2
  183. package/package.json +4 -3
  184. package/src/migrations/0238_extension_usage.sql +40 -0
  185. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -0,0 +1,417 @@
1
+ import { lookup as dnsLookup } from "node:dns/promises";
2
+ import { isIP } from "node:net";
3
+ import semver from "semver";
4
+ import { aliasNetPolicy, matchPrivateEndpoint, } from "./private-endpoints.js";
5
+ import { isLoopbackHost, NetDeniedError, normalizeHost, resolvePublic, } from "./public-address.js";
6
+ /**
7
+ * Where object-store-s3's requests go, as the AWS SDK builds them: path style
8
+ * (`<endpoint>/<bucket>/<key>`) with `forcePathStyle` or an IP-literal endpoint, otherwise
9
+ * virtual-hosted (`<bucket>.<endpoint host>/<key>`, another origin).
10
+ */
11
+ export function s3Target(config) {
12
+ const endpoint = config.endpoint;
13
+ if (typeof endpoint !== "string" || endpoint === "")
14
+ return undefined;
15
+ let u;
16
+ try {
17
+ u = new URL(endpoint);
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ const bucket = typeof config.bucket === "string" ? config.bucket : "";
23
+ const base = u.pathname.replace(/\/+$/, "");
24
+ const pathStyle = config.forcePathStyle === true || isIP(normalizeHost(u.hostname)) !== 0 || bucket === "";
25
+ if (pathStyle)
26
+ return new URL(`${u.origin}${base}/${bucket}`);
27
+ return new URL(`${u.protocol}//${bucket}.${u.host}${base || "/"}`);
28
+ }
29
+ /**
30
+ * Optional provider (a test seam, `KernelAppOptions.overrides`; the kernel never provides it):
31
+ * the brokered pins the bootstrap preflight checks instead of {@link BROKERED_ENDPOINT_PINS}.
32
+ */
33
+ export const BROKERED_ENDPOINT_PINS_SEAM = Symbol("BROKERED_ENDPOINT_PINS_SEAM");
34
+ export const BROKERED_ENDPOINT_PINS = [
35
+ {
36
+ plugin: "object-store-s3",
37
+ alias: "object-store",
38
+ methods: ["GET", "HEAD", "PUT", "POST", "DELETE"],
39
+ target: s3Target,
40
+ ctxNetFrom: undefined,
41
+ },
42
+ ];
43
+ export const PRIVATE_ENDPOINTS_DOC = "docs/deploy/upgrade.md#private-endpoints-for-plugin-egress";
44
+ const envSegment = (s) => s.toUpperCase().replaceAll("-", "_");
45
+ const envPrefix = (alias) => `CAPYBARA_NET__PRIVATE_ENDPOINTS__${envSegment(alias)}`;
46
+ /** Whether `version` is `pin`'s `ctx.net` build. */
47
+ export function routesThroughCtxNet(pin, version) {
48
+ if (pin.ctxNetFrom === undefined)
49
+ return false;
50
+ const v = semver.valid(version);
51
+ return v !== null && semver.gte(v, pin.ctxNetFrom);
52
+ }
53
+ /** The environment variables that add `alias` for `origin`, granted to `plugin`, one per line. */
54
+ export function aliasEnvLines(alias, origin, plugin) {
55
+ const env = envPrefix(alias);
56
+ return `${env}__ORIGIN=${origin}\n${env}__PLUGINS='["${plugin}"]'`;
57
+ }
58
+ /** The env variables and file form that add `alias` for `origin`, granted to `plugin`. */
59
+ export function aliasConfigHint(alias, origin, plugin) {
60
+ const env = envPrefix(alias);
61
+ return (`Add the alias: ${env}__ORIGIN=${origin} and ${env}__PLUGINS='["${plugin}"]' ` +
62
+ `(config file: net.privateEndpoints: {"${alias}": {"origin": "${origin}", "plugins": ["${plugin}"]}}). ` +
63
+ `See ${PRIVATE_ENDPOINTS_DOC}.`);
64
+ }
65
+ const defaultLookup = (host) => dnsLookup(host, { all: true, verbatim: true });
66
+ /** The address check the runtime applies to a no-org request without an alias. */
67
+ const noAliasPolicy = (net) => ({
68
+ allowInsecureLoopback: net.allowInsecureLoopback === true,
69
+ allowPrivateHosts: [],
70
+ trustedOrigins: [],
71
+ extension: { privateHint: "" },
72
+ });
73
+ /**
74
+ * What `ctx.net` would do with `pin`'s platform requests to `target`, using its own matcher and
75
+ * address checks: each method is matched on its own (the alias admitting it), and the host's
76
+ * addresses are checked under each admitting alias's policy (or the no-alias policy).
77
+ */
78
+ async function verdictFor(pin, target, config, lookup) {
79
+ const host = normalizeHost(target.hostname);
80
+ const matches = new Map();
81
+ let anyAlias = true;
82
+ for (const method of pin.methods) {
83
+ let match;
84
+ try {
85
+ match = matchPrivateEndpoint(config.net.privateEndpoints, pin.plugin, target.href, method);
86
+ }
87
+ catch (e) {
88
+ if (!(e instanceof NetDeniedError))
89
+ throw e;
90
+ return { kind: "narrow", alias: aliasesOf(config, pin, target.origin), reason: e.message };
91
+ }
92
+ // no alias of the plugin has the origin: the same for every method
93
+ if (match === undefined) {
94
+ anyAlias = false;
95
+ break;
96
+ }
97
+ matches.set(match.alias, match);
98
+ }
99
+ // without an alias, plain http is refused before any address check (safeFetch)
100
+ if (!anyAlias &&
101
+ target.protocol === "http:" &&
102
+ !(config.net.allowInsecureLoopback === true && isLoopbackHost(host))) {
103
+ return { kind: "missing", http: true };
104
+ }
105
+ const policies = [];
106
+ try {
107
+ if (!anyAlias) {
108
+ policies.push({ policy: noAliasPolicy(config.net) });
109
+ }
110
+ else {
111
+ for (const match of matches.values()) {
112
+ policies.push({
113
+ alias: match.alias,
114
+ policy: {
115
+ ...noAliasPolicy(config.net),
116
+ privateEndpoint: aliasNetPolicy(match, config.extensionHost?.isolation?.engineUrl),
117
+ },
118
+ });
119
+ }
120
+ }
121
+ }
122
+ catch (e) {
123
+ if (!(e instanceof NetDeniedError))
124
+ throw e;
125
+ return { kind: "address", alias: aliasesOf(config, pin, target.origin), reason: e.message };
126
+ }
127
+ for (const { alias, policy } of policies) {
128
+ try {
129
+ await resolvePublic(host, policy, lookup, target.origin);
130
+ }
131
+ catch (e) {
132
+ if (!(e instanceof NetDeniedError))
133
+ throw e;
134
+ if (e.code === "net.dns_failed")
135
+ return { kind: "unresolved" };
136
+ return alias === undefined
137
+ ? { kind: "missing", http: false }
138
+ : { kind: "address", alias, reason: e.message };
139
+ }
140
+ }
141
+ return { kind: "ok" };
142
+ }
143
+ const aliasesOf = (config, pin, origin) => Object.entries(config.net.privateEndpoints)
144
+ .filter(([, e]) => {
145
+ try {
146
+ return e.plugins.includes(pin.plugin) && new URL(e.origin).origin === origin;
147
+ }
148
+ catch {
149
+ return false;
150
+ }
151
+ })
152
+ .map(([name]) => name)
153
+ .join(", ");
154
+ /** The settings that widen `alias` to admit `pin`'s requests to `target`. */
155
+ function widenEnv(config, alias, pin, target) {
156
+ const existing = config.net.privateEndpoints[alias];
157
+ const env = envPrefix(alias);
158
+ const lines = [];
159
+ const prefix = target.pathname.replace(/\/+$/, "") || "/";
160
+ const current = existing?.pathPrefix.replace(/\/+$/, "") ?? "";
161
+ if (current !== "" && prefix !== current && !prefix.startsWith(`${current}/`)) {
162
+ lines.push(`${env}__PATH_PREFIX=${prefix}`);
163
+ }
164
+ const methods = existing?.methods;
165
+ if (methods !== undefined && pin.methods.some((m) => !methods.includes(m))) {
166
+ const all = [...new Set([...methods, ...pin.methods])];
167
+ lines.push(`${env}__METHODS='${JSON.stringify(all)}'`);
168
+ }
169
+ return lines.join("\n");
170
+ }
171
+ /** A gap's kind, message and fixing settings from a verdict (shared by both checks). */
172
+ function gapFrom(o) {
173
+ const { caller, verdict, target } = o;
174
+ const plugin = caller.plugin;
175
+ const origin = target.origin;
176
+ const effect = o.ctxNet === true
177
+ ? `${plugin} ${o.version} reaches it through ctx.net, which refuses it`
178
+ : o.ctxNet === false
179
+ ? `the ${plugin} build that reaches it through ctx.net will refuse it`
180
+ : `${plugin} reaches it through ctx.net (now, or once it is updated), which refuses it`;
181
+ let alias = o.alias;
182
+ let problem;
183
+ let env;
184
+ switch (verdict.kind) {
185
+ case "missing":
186
+ problem = `${verdict.http ? "uses plain http" : "is a private address"} and no net.privateEndpoints alias grants it to ${plugin}: ${effect}. ${aliasConfigHint(alias, origin, plugin)}`;
187
+ env = aliasEnvLines(alias, origin, plugin);
188
+ break;
189
+ case "narrow":
190
+ alias = verdict.alias.split(", ")[0] ?? alias;
191
+ env = widenEnv(o.config, alias, caller, target);
192
+ problem = `is not admitted by the net.privateEndpoints alias ${verdict.alias} (${verdict.reason}): ${effect}. The alias must allow ${caller.methods.join(", ")} on ${target.pathname}. See ${PRIVATE_ENDPOINTS_DOC}.`;
193
+ break;
194
+ case "address": {
195
+ alias = verdict.alias.split(", ")[0] ?? alias;
196
+ const loopback = /loopback/.test(verdict.reason);
197
+ env = loopback ? `${envPrefix(alias)}__ALLOW_LOOPBACK=true` : "";
198
+ problem = `resolves to an address the net.privateEndpoints alias ${verdict.alias} may not reach (${verdict.reason}): ${effect}. ${loopback ? "Set allowLoopback on the alias" : "Point the plugin at another address"}. See ${PRIVATE_ENDPOINTS_DOC}.`;
199
+ break;
200
+ }
201
+ default:
202
+ problem = `does not resolve where this check runs, so it cannot tell whether ${plugin} needs an alias. If the endpoint is private, add one. ${aliasConfigHint(alias, origin, plugin)}`;
203
+ env = aliasEnvLines(alias, origin, plugin);
204
+ }
205
+ return {
206
+ plugin,
207
+ version: o.version,
208
+ kind: verdict.kind,
209
+ origin,
210
+ alias,
211
+ ctxNet: o.ctxNet,
212
+ ...(o.field !== undefined && { field: o.field }),
213
+ blocking: o.ctxNet === true && verdict.kind !== "unresolved",
214
+ message: `${plugin}'s ${o.label} ${origin} ${problem}`,
215
+ env,
216
+ };
217
+ }
218
+ /**
219
+ * The gaps of the given pins (`{ name, version }`: a bootstrap manifest's entries, or the
220
+ * installed versions): for each brokered pin present, where its requests go (`pin.target` over
221
+ * its effective deployment config: `extensionConfig` from file / env / Nacos over the config
222
+ * stored in PG) when `ctx.net` would not admit them ({@link verdictFor}). A certain gap blocks the
223
+ * pin's `ctx.net` build; a host that does not resolve where the check runs is only a warning (the
224
+ * check cannot tell; the runtime refusal then names the alias).
225
+ */
226
+ export async function privateEndpointGaps(o) {
227
+ const gaps = [];
228
+ for (const pin of o.brokered ?? BROKERED_ENDPOINT_PINS) {
229
+ const entry = o.pins.find((p) => p.name === pin.plugin);
230
+ if (entry === undefined)
231
+ continue;
232
+ const fromFile = (o.config.extensionConfig[pin.plugin] ?? {});
233
+ const effective = { ...((await o.storedConfig(pin.plugin)) ?? {}), ...fromFile };
234
+ const target = pin.target(effective);
235
+ if (target === undefined)
236
+ continue;
237
+ const origin = target.origin;
238
+ const verdict = await verdictFor(pin, target, o.config, o.lookup ?? defaultLookup);
239
+ if (verdict.kind === "ok")
240
+ continue;
241
+ const ctxNet = routesThroughCtxNet(pin, entry.version);
242
+ gaps.push(gapFrom({
243
+ caller: pin,
244
+ version: entry.version,
245
+ alias: pin.alias,
246
+ target,
247
+ verdict,
248
+ ctxNet,
249
+ label: "platform endpoint",
250
+ config: o.config,
251
+ }));
252
+ }
253
+ return gaps;
254
+ }
255
+ /** Methods the generic scan checks an alias against (a URL field's requests are unknown). */
256
+ const GENERIC_METHODS = ["GET", "POST"];
257
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
258
+ /**
259
+ * The URL values of `value` that the deployment JSON Schema declares as URLs (`format: "uri"` or
260
+ * `"url"`, as `z.url()` emits), with their paths: through `properties`, `items`, `prefixItems`,
261
+ * `additionalProperties`, local `$ref`s and `anyOf` / `oneOf` / `allOf` branches.
262
+ */
263
+ export function urlFields(schema, value, root = schema, path = "", depth = 0) {
264
+ if (!isObj(schema) || depth > 24)
265
+ return [];
266
+ if (typeof schema.$ref === "string" && schema.$ref.startsWith("#/")) {
267
+ let node = root;
268
+ for (const seg of schema.$ref.slice(2).split("/"))
269
+ node = isObj(node) ? node[seg] : undefined;
270
+ return urlFields(node, value, root, path, depth + 1);
271
+ }
272
+ const out = [];
273
+ for (const key of ["anyOf", "oneOf", "allOf"]) {
274
+ const branches = schema[key];
275
+ if (Array.isArray(branches)) {
276
+ for (const b of branches)
277
+ out.push(...urlFields(b, value, root, path, depth + 1));
278
+ }
279
+ }
280
+ if (typeof value === "string" && (schema.format === "uri" || schema.format === "url")) {
281
+ out.push({ path, url: value });
282
+ }
283
+ if (isObj(value)) {
284
+ const props = isObj(schema.properties) ? schema.properties : {};
285
+ for (const [k, v] of Object.entries(value)) {
286
+ const sub = props[k] ?? (isObj(schema.additionalProperties) ? schema.additionalProperties : undefined);
287
+ out.push(...urlFields(sub, v, root, path === "" ? k : `${path}.${k}`, depth + 1));
288
+ }
289
+ }
290
+ if (Array.isArray(value)) {
291
+ const prefix = Array.isArray(schema.prefixItems) ? schema.prefixItems : [];
292
+ value.forEach((v, i) => {
293
+ out.push(...urlFields(prefix[i] ?? schema.items, v, root, `${path}[${i}]`, depth + 1));
294
+ });
295
+ }
296
+ // a value found through two branches is reported once
297
+ return out.filter((f, i) => out.findIndex((g) => g.path === f.path) === i);
298
+ }
299
+ /**
300
+ * The generic platform URL check (warnings only, never a refusal): every URL field of an enabled
301
+ * extension's effective platform deployment config (file / env / Nacos over PG) that `ctx.net`
302
+ * would refuse for a request made outside an organization: a private or loopback address or plain
303
+ * http without an admitting alias, an alias that does not admit it, or a host that does not
304
+ * resolve here. `configUrlFetch` sends the platform's own value there (SDK), and the kernel's copy
305
+ * of the SDK serves already installed plugins too, so the gap may apply from this kernel release.
306
+ * Plugins the brokered check covers ({@link BROKERED_ENDPOINT_PINS}) are skipped. One gap per
307
+ * plugin and origin.
308
+ */
309
+ export async function platformUrlGaps(o) {
310
+ const skip = new Set(o.skip ?? BROKERED_ENDPOINT_PINS.map((p) => p.plugin));
311
+ const gaps = [];
312
+ for (const ext of o.extensions) {
313
+ if (skip.has(ext.name))
314
+ continue;
315
+ const fromFile = (o.config.extensionConfig[ext.name] ?? {});
316
+ const effective = { ...(ext.stored ?? {}), ...fromFile };
317
+ const seen = new Set();
318
+ for (const { path, url } of urlFields(ext.schema, effective)) {
319
+ let target;
320
+ try {
321
+ target = new URL(url);
322
+ }
323
+ catch {
324
+ continue;
325
+ }
326
+ if (target.protocol !== "http:" && target.protocol !== "https:")
327
+ continue;
328
+ if (seen.has(target.origin))
329
+ continue;
330
+ seen.add(target.origin);
331
+ const caller = { plugin: ext.name, methods: GENERIC_METHODS };
332
+ const verdict = await verdictFor(caller, target, o.config, o.lookup ?? defaultLookup);
333
+ if (verdict.kind === "ok")
334
+ continue;
335
+ gaps.push(gapFrom({
336
+ caller,
337
+ version: ext.version,
338
+ alias: ext.name,
339
+ target,
340
+ verdict,
341
+ ctxNet: null,
342
+ label: `platform setting ${path}`,
343
+ field: path,
344
+ config: o.config,
345
+ }));
346
+ }
347
+ }
348
+ return gaps;
349
+ }
350
+ /**
351
+ * The enabled extensions installed from packages (`extension_installs` with `desired_state =
352
+ * 'enabled'`), with their deployment config schema and the config stored in PG.
353
+ */
354
+ export async function enabledExtensionsForScan(db) {
355
+ const rows = await db
356
+ .selectFrom("extension_installs")
357
+ .innerJoin("extension_packages", "extension_packages.sha256", "extension_installs.sha256")
358
+ .leftJoin("extension_deployment_configs", "extension_deployment_configs.plugin", "extension_installs.name")
359
+ .select([
360
+ "extension_installs.name as name",
361
+ "extension_installs.version as version",
362
+ "extension_packages.section as section",
363
+ "extension_deployment_configs.config as stored",
364
+ ])
365
+ .where("extension_installs.desired_state", "=", "enabled")
366
+ .execute();
367
+ return rows.map((r) => ({
368
+ name: r.name,
369
+ version: r.version,
370
+ schema: r.section?.configSchemas
371
+ ?.deployment,
372
+ stored: r.stored ?? undefined,
373
+ }));
374
+ }
375
+ /** The bootstrap step refused: a brokered pin's private endpoint has no alias (see the header). */
376
+ export class PrivateEndpointMissingError extends Error {
377
+ gaps;
378
+ constructor(gaps) {
379
+ super(`bootstrap refused before installing anything: ${gaps.map((g) => g.message).join(" ")}`);
380
+ this.gaps = gaps;
381
+ this.name = "PrivateEndpointMissingError";
382
+ }
383
+ }
384
+ /**
385
+ * The deployment config of a plugin stored in PG (`extension_deployment_configs`, saved by a super
386
+ * admin), without its secret fields (they live in `capybara.secrets` and are never read here);
387
+ * undefined when none is stored.
388
+ */
389
+ export async function storedDeploymentConfig(db, plugin) {
390
+ const row = await db
391
+ .selectFrom("extension_deployment_configs")
392
+ .select("config")
393
+ .where("plugin", "=", plugin)
394
+ .executeTakeFirst();
395
+ return row?.config;
396
+ }
397
+ /**
398
+ * The deployment's private endpoint gaps: the installed brokered pins ({@link privateEndpointGaps})
399
+ * and every URL field of an enabled extension ({@link platformUrlGaps}). Resolves their hosts.
400
+ * Read by the admin health and the isolation status (plan task 1.4j).
401
+ */
402
+ export async function readDeploymentPrivateEndpointGaps(db, config) {
403
+ const installed = await db
404
+ .selectFrom("extension_installs")
405
+ .select(["name", "version"])
406
+ .where("name", "in", BROKERED_ENDPOINT_PINS.map((p) => p.plugin))
407
+ .execute();
408
+ const [pinned, generic] = await Promise.all([
409
+ privateEndpointGaps({
410
+ config,
411
+ pins: installed,
412
+ storedConfig: (plugin) => storedDeploymentConfig(db, plugin),
413
+ }),
414
+ enabledExtensionsForScan(db).then((extensions) => platformUrlGaps({ config, extensions })),
415
+ ]);
416
+ return [...pinned, ...generic];
417
+ }
@@ -0,0 +1,68 @@
1
+ import { type NetPolicy } from "./public-address.js";
2
+ /**
3
+ * `net.privateEndpoints` (extension permission model spec, "Egress, configuration and secret
4
+ * custody"): named private destinations a super admin grants to named plugins. A request through
5
+ * `ctx.net.fetch` made outside an organization (no `orgId`) to exactly an alias's origin (scheme,
6
+ * host and port), under its path prefix and with one of its methods, by a plugin the alias names,
7
+ * may reach the private addresses that origin resolves to. The address checks still run at
8
+ * resolution and the connection is pinned to the checked addresses; link-local and cloud metadata
9
+ * addresses stay refused; loopback only when the alias sets `allowLoopback`; the isolation tier's
10
+ * Engine API proxy (`extensionHost.isolation.engineUrl`) never. An alias request never uses
11
+ * `net.httpsProxy`: it connects directly, so its host is resolved and checked by the kernel.
12
+ *
13
+ * An org-bound request (`orgId` given) uses that org's allowed internal endpoints only: an alias
14
+ * is the platform's grant for the platform's own endpoints, not for a URL an org configured.
15
+ */
16
+ /** One configured alias (the parsed form of a `net.privateEndpoints` entry). */
17
+ export type PrivateEndpoint = {
18
+ origin: string;
19
+ pathPrefix: string;
20
+ methods?: string[] | undefined;
21
+ plugins: string[];
22
+ allowLoopback: boolean;
23
+ };
24
+ export declare const PRIVATE_ENDPOINT_ALIAS_RE: RegExp;
25
+ export declare const PRIVATE_ENDPOINT_METHODS: readonly ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
26
+ /** Why an alias origin is invalid (English), or undefined. */
27
+ export declare function privateEndpointOriginProblem(value: string): string | undefined;
28
+ /** Why a path prefix is invalid (English), or undefined. */
29
+ export declare function privateEndpointPathPrefixProblem(value: string): string | undefined;
30
+ /** The alias that admits a request, as the `NetPolicy.privateEndpoint` it needs. */
31
+ export type PrivateEndpointMatch = {
32
+ alias: string;
33
+ origin: string;
34
+ allowLoopback: boolean;
35
+ };
36
+ /**
37
+ * The alias admitting `plugin`'s `method` request to `url`, or undefined when no alias granted to
38
+ * the plugin has the URL's origin (the request is then judged like any other). Throws
39
+ * {@link NetDeniedError} `net.private_address` when an alias granted to the plugin has the origin
40
+ * but none admits the path or method: the destination is private and only the alias reaches it.
41
+ */
42
+ export declare function matchPrivateEndpoint(endpoints: Readonly<Record<string, PrivateEndpoint>>, plugin: string, url: string, method: string, headers?: RequestInit["headers"]): PrivateEndpointMatch | undefined;
43
+ /**
44
+ * Why the configured aliases are refused across sections, or null: an alias on the port of the
45
+ * extension isolation Engine API (`extensionHost.isolation.engineUrl`), whatever its host
46
+ * ({@link aliasNetPolicy} refuses it at request time too).
47
+ */
48
+ export declare function privateEndpointEngineProblem(config: {
49
+ net: {
50
+ privateEndpoints: Readonly<Record<string, {
51
+ origin: string;
52
+ }>>;
53
+ };
54
+ extensionHost: {
55
+ isolation?: {
56
+ engineUrl: string;
57
+ } | undefined;
58
+ };
59
+ }): string | null;
60
+ /**
61
+ * The `NetPolicy.privateEndpoint` of an admitted alias. An alias on the port of the extension
62
+ * isolation Engine API (`engineUrl`) is refused outright, whatever host it names: the Engine may
63
+ * answer on any private address of its host (every interface, loopback, a second NIC), so no
64
+ * private address is admitted on that port. (`net.allowInsecureLoopback`, tests and development
65
+ * only, lifts every loopback refusal of ctx.net on its own, the Engine's included; never set it
66
+ * where the Engine listens on loopback.)
67
+ */
68
+ export declare function aliasNetPolicy(match: PrivateEndpointMatch, engineUrl: string | undefined): NonNullable<NetPolicy["privateEndpoint"]>;
@@ -0,0 +1,164 @@
1
+ import { isIP } from "node:net";
2
+ import { isLinkLocalAddress, isLoopbackHost, isLoopbackOrUnspecifiedAddress, NetDeniedError, normalizeHost, } from "./public-address.js";
3
+ export const PRIVATE_ENDPOINT_ALIAS_RE = /^[a-z][a-z0-9-]{0,62}$/;
4
+ export const PRIVATE_ENDPOINT_METHODS = [
5
+ "GET",
6
+ "HEAD",
7
+ "POST",
8
+ "PUT",
9
+ "PATCH",
10
+ "DELETE",
11
+ "OPTIONS",
12
+ ];
13
+ /** Why an alias origin is invalid (English), or undefined. */
14
+ export function privateEndpointOriginProblem(value) {
15
+ let u;
16
+ try {
17
+ u = new URL(value);
18
+ }
19
+ catch {
20
+ return "must be an http:// or https:// origin such as https://llm-gateway.internal:8443";
21
+ }
22
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
23
+ return "must be an http:// or https:// origin";
24
+ }
25
+ if (u.username !== "" || u.password !== "")
26
+ return "must not carry credentials";
27
+ if ((u.pathname !== "" && u.pathname !== "/") || u.search !== "" || u.hash !== "") {
28
+ return "must be an origin without a path, query or fragment (use pathPrefix for a path)";
29
+ }
30
+ const host = normalizeHost(u.hostname);
31
+ if (isIP(host) !== 0 && isLinkLocalAddress(host)) {
32
+ return "must not be a link-local or cloud metadata address";
33
+ }
34
+ if (isIP(host) !== 0 && !isLoopbackHost(host) && isLoopbackOrUnspecifiedAddress(host)) {
35
+ return "must not be an unspecified address";
36
+ }
37
+ return undefined;
38
+ }
39
+ /** Why a path prefix is invalid (English), or undefined. */
40
+ export function privateEndpointPathPrefixProblem(value) {
41
+ if (!value.startsWith("/"))
42
+ return "must start with /";
43
+ if (/[%\\?#\s]/.test(value))
44
+ return "must not contain %, \\, ?, # or whitespace";
45
+ if (value.split("/").some((seg) => seg === "." || seg === "..")) {
46
+ return "must not contain . or .. segments";
47
+ }
48
+ return undefined;
49
+ }
50
+ function sameOrigin(a, b) {
51
+ try {
52
+ return new URL(a).origin === b;
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ function underPrefix(pathname, prefix) {
59
+ const p = prefix.replace(/\/+$/, "");
60
+ if (p === "")
61
+ return true;
62
+ return pathname === p || pathname.startsWith(`${p}/`);
63
+ }
64
+ /**
65
+ * Whether a path could leave its prefix on some backend although the parsed path stays under it:
66
+ * an encoded slash or backslash, an encoded `%` (a double-decoding hop), a `;` path parameter
67
+ * (`/v1/..;/admin` on Tomcat or Jetty), or a segment that is `.` or `..` or holds a `;` once
68
+ * decoded.
69
+ */
70
+ function ambiguousPath(pathname) {
71
+ if (/%(2f|5c|25)/i.test(pathname) || pathname.includes(";"))
72
+ return true;
73
+ return pathname.split("/").some((seg) => {
74
+ let decoded;
75
+ try {
76
+ decoded = decodeURIComponent(seg);
77
+ }
78
+ catch {
79
+ return true;
80
+ }
81
+ return decoded === "." || decoded === ".." || decoded.includes(";");
82
+ });
83
+ }
84
+ /** Headers by which a backend may run another method than the request line's. */
85
+ const METHOD_OVERRIDE_HEADERS = ["x-http-method-override", "x-http-method", "x-method-override"];
86
+ /**
87
+ * The alias admitting `plugin`'s `method` request to `url`, or undefined when no alias granted to
88
+ * the plugin has the URL's origin (the request is then judged like any other). Throws
89
+ * {@link NetDeniedError} `net.private_address` when an alias granted to the plugin has the origin
90
+ * but none admits the path or method: the destination is private and only the alias reaches it.
91
+ */
92
+ export function matchPrivateEndpoint(endpoints, plugin, url, method, headers) {
93
+ let target;
94
+ try {
95
+ target = new URL(url);
96
+ }
97
+ catch {
98
+ return undefined;
99
+ }
100
+ const granted = Object.entries(endpoints).filter(([, e]) => e.plugins.includes(plugin) && sameOrigin(e.origin, target.origin));
101
+ if (granted.length === 0)
102
+ return undefined;
103
+ const m = method.toUpperCase();
104
+ const ambiguous = ambiguousPath(target.pathname);
105
+ const h = new Headers(headers);
106
+ // a method override in a header or the `_method` query parameter (Rails, Laravel, Symfony); a
107
+ // `_method` form field in the body is not inspected (documented)
108
+ const overridden = METHOD_OVERRIDE_HEADERS.some((name) => h.has(name)) ||
109
+ [...target.searchParams.keys()].some((k) => k.toLowerCase() === "_method");
110
+ for (const [alias, e] of granted) {
111
+ const prefixed = e.pathPrefix.replace(/\/+$/, "") !== "";
112
+ if (prefixed && ambiguous)
113
+ continue;
114
+ if (!underPrefix(target.pathname, e.pathPrefix))
115
+ continue;
116
+ if (e.methods !== undefined && (!e.methods.includes(m) || overridden))
117
+ continue;
118
+ return { alias, origin: target.origin, allowLoopback: e.allowLoopback };
119
+ }
120
+ const host = normalizeHost(target.hostname);
121
+ const names = granted.map(([alias]) => alias).join(", ");
122
+ throw new NetDeniedError("net.private_address", host, `Access to ${host} is refused: the private endpoint ${names} does not allow this method (${m}) or path.`);
123
+ }
124
+ /**
125
+ * Why the configured aliases are refused across sections, or null: an alias on the port of the
126
+ * extension isolation Engine API (`extensionHost.isolation.engineUrl`), whatever its host
127
+ * ({@link aliasNetPolicy} refuses it at request time too).
128
+ */
129
+ export function privateEndpointEngineProblem(config) {
130
+ const engineUrl = config.extensionHost.isolation?.engineUrl;
131
+ if (engineUrl === undefined)
132
+ return null;
133
+ const enginePort = portOf(new URL(engineUrl));
134
+ for (const [alias, e] of Object.entries(config.net.privateEndpoints)) {
135
+ let port;
136
+ try {
137
+ port = portOf(new URL(e.origin));
138
+ }
139
+ catch {
140
+ continue;
141
+ }
142
+ if (port === enginePort) {
143
+ return `net.privateEndpoints.${alias}.origin: must not use port ${enginePort} of the extension isolation Engine API (extensionHost.isolation.engineUrl), on any host`;
144
+ }
145
+ }
146
+ return null;
147
+ }
148
+ const portOf = (u) => u.port || (u.protocol === "https:" ? "443" : "80");
149
+ /**
150
+ * The `NetPolicy.privateEndpoint` of an admitted alias. An alias on the port of the extension
151
+ * isolation Engine API (`engineUrl`) is refused outright, whatever host it names: the Engine may
152
+ * answer on any private address of its host (every interface, loopback, a second NIC), so no
153
+ * private address is admitted on that port. (`net.allowInsecureLoopback`, tests and development
154
+ * only, lifts every loopback refusal of ctx.net on its own, the Engine's included; never set it
155
+ * where the Engine listens on loopback.)
156
+ */
157
+ export function aliasNetPolicy(match, engineUrl) {
158
+ const target = new URL(match.origin);
159
+ if (engineUrl !== undefined && portOf(new URL(engineUrl)) === portOf(target)) {
160
+ const name = normalizeHost(target.hostname);
161
+ throw new NetDeniedError("net.private_address", name, `Access to ${name} is refused: the private endpoint ${match.alias} uses port ${portOf(target)} of the extension isolation Engine API, which an alias never reaches.`);
162
+ }
163
+ return { origin: match.origin, allowLoopback: match.allowLoopback };
164
+ }
@@ -7,6 +7,8 @@ export declare function isForbiddenAddress(ip: string): boolean;
7
7
  export declare function isLinkLocalAddress(ip: string): boolean;
8
8
  /** Loopback (`127.0.0.0/8`, `::1`) or unspecified (`0.0.0.0/8`, `::`), embedded forms included. */
9
9
  export declare function isLoopbackOrUnspecifiedAddress(ip: string): boolean;
10
+ /** Loopback only (`127.0.0.0/8`, `::1`, embedded forms included), never unspecified. */
11
+ export declare function isLoopbackAddress(ip: string): boolean;
10
12
  /** A hostname normalized for comparison: lower case, no IPv6 brackets, no trailing dots. */
11
13
  export declare function normalizeHost(host: string): string;
12
14
  /** `localhost`, `127.0.0.0/8` or `::1` (as written in a URL). */
@@ -43,6 +45,18 @@ export type NetPolicy = {
43
45
  */
44
46
  extension?: {
45
47
  privateHint: string;
48
+ /** Appended to a refused plain-http URL (a request made outside an org: the alias to add). */
49
+ insecureHint?: string;
50
+ };
51
+ /**
52
+ * A `net.privateEndpoints` alias admitted this extension request (`private-endpoints.ts`): a
53
+ * request to exactly `origin` may resolve to private addresses (link-local and metadata stay
54
+ * refused; loopback only with `allowLoopback`), may use plain http when the origin is http, and
55
+ * never uses the egress proxy.
56
+ */
57
+ privateEndpoint?: {
58
+ origin: string;
59
+ allowLoopback: boolean;
46
60
  };
47
61
  };
48
62
  export type LookupFn = (host: string) => Promise<{