@capybara-hq/kernel 0.1.0-rc.36 → 0.1.0-rc.38

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 (351) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.d.ts +3 -2
  3. package/dist/admin/admin.module.js +9 -5
  4. package/dist/admin/audit-log.service.d.ts +51 -0
  5. package/dist/admin/{platform-audit.service.js → audit-log.service.js} +20 -12
  6. package/dist/admin/audit.controller.d.ts +18 -6
  7. package/dist/admin/audit.controller.js +36 -6
  8. package/dist/admin/audit.schemas.d.ts +9 -1
  9. package/dist/admin/audit.schemas.js +22 -2
  10. package/dist/admin/org-network.controller.d.ts +30 -0
  11. package/dist/admin/org-network.controller.js +77 -0
  12. package/dist/admin/org-network.schemas.d.ts +16 -0
  13. package/dist/admin/org-network.schemas.js +27 -0
  14. package/dist/admin/org-network.service.d.ts +41 -0
  15. package/dist/admin/org-network.service.js +101 -0
  16. package/dist/admin/outbox-dead.controller.d.ts +4 -6
  17. package/dist/admin/outbox-dead.controller.js +9 -6
  18. package/dist/admin/outbox-dead.schemas.d.ts +16 -0
  19. package/dist/admin/outbox-dead.schemas.js +25 -1
  20. package/dist/admin/outbox-dead.service.d.ts +16 -7
  21. package/dist/admin/outbox-dead.service.js +34 -10
  22. package/dist/admin/overview.service.d.ts +3 -3
  23. package/dist/admin/overview.service.js +0 -1
  24. package/dist/agents/agent-lookup.js +2 -10
  25. package/dist/agents/agents.service.js +9 -20
  26. package/dist/agents/definition.d.ts +3 -51
  27. package/dist/agents/definition.js +4 -254
  28. package/dist/agents/org-templates.js +2 -6
  29. package/dist/agents/readiness.controller.d.ts +4 -12
  30. package/dist/agents/readiness.controller.js +4 -12
  31. package/dist/agents/readiness.service.d.ts +23 -11
  32. package/dist/agents/readiness.service.js +31 -14
  33. package/dist/agents/templates.d.ts +0 -6
  34. package/dist/agents/templates.js +8 -34
  35. package/dist/background/store.d.ts +2 -0
  36. package/dist/background/store.js +3 -1
  37. package/dist/background/wake-rules.js +2 -1
  38. package/dist/catalog/admin-catalog.controller.d.ts +1 -2
  39. package/dist/catalog/admin-catalog.controller.js +1 -2
  40. package/dist/catalog/appearance.service.js +1 -3
  41. package/dist/catalog/catalog-content.d.ts +1 -1
  42. package/dist/catalog/catalog-content.js +1 -4
  43. package/dist/catalog/catalog-items.js +3 -3
  44. package/dist/catalog/catalog-scope.service.d.ts +10 -28
  45. package/dist/catalog/catalog-scope.service.js +22 -73
  46. package/dist/catalog/cli.d.ts +0 -11
  47. package/dist/catalog/cli.js +0 -20
  48. package/dist/catalog/component-scope.service.js +0 -2
  49. package/dist/catalog/component-state.js +2 -2
  50. package/dist/catalog/install-status.d.ts +6 -0
  51. package/dist/catalog/install-status.js +6 -0
  52. package/dist/catalog/job-ids.d.ts +0 -4
  53. package/dist/catalog/job-ids.js +0 -4
  54. package/dist/catalog/marketplaces.service.d.ts +1 -1
  55. package/dist/catalog/org-catalog.service.d.ts +2 -0
  56. package/dist/catalog/org-catalog.service.js +8 -3
  57. package/dist/catalog/org-extension-switch.d.ts +7 -2
  58. package/dist/catalog/org-extension-switch.js +56 -9
  59. package/dist/catalog/org-plugin-uploads.d.ts +6 -15
  60. package/dist/catalog/org-plugin-uploads.js +9 -27
  61. package/dist/catalog/owned-items.js +1 -3
  62. package/dist/catalog/platform-import-update.js +1 -1
  63. package/dist/catalog/plugin-import.d.ts +15 -13
  64. package/dist/catalog/plugin-import.js +21 -30
  65. package/dist/catalog/plugin-install.d.ts +3 -43
  66. package/dist/catalog/plugin-install.js +8 -150
  67. package/dist/catalog/plugin-package.d.ts +5 -10
  68. package/dist/catalog/plugin-package.js +12 -33
  69. package/dist/catalog/plugin-upgrade.js +5 -4
  70. package/dist/catalog/scope-jobs.d.ts +34 -34
  71. package/dist/catalog/scope-jobs.js +50 -37
  72. package/dist/catalog/scope-orgs.d.ts +1 -1
  73. package/dist/catalog/scope-orgs.js +1 -2
  74. package/dist/catalog/scope-sync-workers.d.ts +4 -3
  75. package/dist/catalog/scope-sync-workers.js +18 -6
  76. package/dist/catalog/scope-sync.d.ts +56 -59
  77. package/dist/catalog/scope-sync.js +96 -166
  78. package/dist/catalog/unshare.d.ts +3 -4
  79. package/dist/catalog/unshare.js +5 -8
  80. package/dist/channels/job-ids.d.ts +2 -6
  81. package/dist/channels/job-ids.js +2 -6
  82. package/dist/channels/outbound.d.ts +1 -1
  83. package/dist/channels/outbound.js +1 -1
  84. package/dist/channels/supervisor.d.ts +2 -3
  85. package/dist/channels/supervisor.js +2 -3
  86. package/dist/client/client-access.service.js +1 -1
  87. package/dist/config/env.js +19 -1
  88. package/dist/config/load.d.ts +0 -6
  89. package/dist/config/load.js +8 -27
  90. package/dist/config/schema.d.ts +54 -47
  91. package/dist/config/schema.js +198 -42
  92. package/dist/conversations/attachments.service.d.ts +10 -3
  93. package/dist/conversations/attachments.service.js +49 -16
  94. package/dist/conversations/conversations.controller.d.ts +0 -39
  95. package/dist/conversations/conversations.controller.js +0 -39
  96. package/dist/conversations/event-log.js +4 -1
  97. package/dist/conversations/events.d.ts +71 -46
  98. package/dist/conversations/events.js +124 -112
  99. package/dist/conversations/media-types.d.ts +25 -0
  100. package/dist/conversations/media-types.js +38 -0
  101. package/dist/conversations/queue.d.ts +3 -1
  102. package/dist/conversations/queue.service.js +9 -2
  103. package/dist/conversations/titles.js +6 -0
  104. package/dist/ctx/create-ctx.d.ts +8 -1
  105. package/dist/ctx/create-ctx.js +13 -3
  106. package/dist/ctx/net.d.ts +50 -0
  107. package/dist/ctx/net.js +67 -0
  108. package/dist/ctx/secrets.d.ts +24 -7
  109. package/dist/ctx/secrets.js +97 -30
  110. package/dist/db/kernel-schema.d.ts +27 -6
  111. package/dist/devices/devices.service.js +2 -1
  112. package/dist/errors.d.ts +10 -2
  113. package/dist/errors.js +10 -2
  114. package/dist/evals/reconstruct.d.ts +4 -17
  115. package/dist/evals/reconstruct.js +13 -53
  116. package/dist/evals/recorded-tools.d.ts +0 -27
  117. package/dist/evals/recorded-tools.js +2 -92
  118. package/dist/evals/run-replay.d.ts +1 -6
  119. package/dist/evals/run-replay.js +10 -17
  120. package/dist/evals/sets.service.d.ts +17 -5
  121. package/dist/evals/sets.service.js +33 -12
  122. package/dist/evals/snapshot.d.ts +1 -2
  123. package/dist/evals/snapshot.js +4 -17
  124. package/dist/extensions/admin-ops.d.ts +6 -1
  125. package/dist/extensions/admin-ops.js +17 -4
  126. package/dist/extensions/admin-view.d.ts +7 -4
  127. package/dist/extensions/admin-view.js +27 -21
  128. package/dist/extensions/bootstrap.js +0 -1
  129. package/dist/extensions/cli.js +0 -1
  130. package/dist/extensions/extensions.module.js +3 -0
  131. package/dist/extensions/host.d.ts +9 -4
  132. package/dist/extensions/host.js +14 -8
  133. package/dist/extensions/installs.d.ts +1 -3
  134. package/dist/extensions/instance.d.ts +0 -2
  135. package/dist/extensions/instance.js +0 -3
  136. package/dist/extensions/org-config.d.ts +4 -4
  137. package/dist/extensions/org-config.js +13 -22
  138. package/dist/extensions/package.d.ts +6 -6
  139. package/dist/extensions/package.js +3 -7
  140. package/dist/extensions/permission-view.d.ts +2 -4
  141. package/dist/extensions/plugin-items.d.ts +21 -1
  142. package/dist/extensions/plugin-items.js +28 -0
  143. package/dist/extensions/sync.js +5 -10
  144. package/dist/extensions/unavailable.js +0 -1
  145. package/dist/http/api.module.js +4 -1
  146. package/dist/identity/audit.d.ts +0 -12
  147. package/dist/identity/audit.js +0 -27
  148. package/dist/identity/auth.controller.js +5 -9
  149. package/dist/identity/cookies.d.ts +4 -9
  150. package/dist/identity/cookies.js +8 -32
  151. package/dist/identity/initial-passwords.d.ts +1 -1
  152. package/dist/identity/initial-passwords.js +1 -2
  153. package/dist/identity/sessions.d.ts +0 -6
  154. package/dist/identity/sessions.js +0 -18
  155. package/dist/inbox/platform-inbox.service.d.ts +33 -1
  156. package/dist/inbox/platform-inbox.service.js +56 -6
  157. package/dist/index.d.ts +4 -2
  158. package/dist/index.js +4 -2
  159. package/dist/infra/cli/master-key-rewrap.d.ts +15 -0
  160. package/dist/infra/cli/master-key-rewrap.js +24 -0
  161. package/dist/infra/config/kernel-config.service.js +0 -17
  162. package/dist/infra/database/transaction-host.d.ts +32 -1
  163. package/dist/infra/database/transaction-host.js +30 -4
  164. package/dist/infra/database/xact-lock.d.ts +16 -0
  165. package/dist/infra/database/xact-lock.js +28 -1
  166. package/dist/infra/health/health.controller.js +8 -0
  167. package/dist/infra/health/process-fault.d.ts +16 -0
  168. package/dist/infra/health/process-fault.js +49 -0
  169. package/dist/infra/lifecycle/process-guards.d.ts +8 -2
  170. package/dist/infra/lifecycle/process-guards.js +12 -3
  171. package/dist/infra/lifecycle/shutdown-signals.d.ts +10 -1
  172. package/dist/infra/lifecycle/shutdown-signals.js +28 -13
  173. package/dist/infra/outbox/outbox.service.d.ts +12 -9
  174. package/dist/infra/outbox/outbox.service.js +22 -26
  175. package/dist/infra/outbox/registry.d.ts +15 -7
  176. package/dist/infra/outbox/registry.js +39 -23
  177. package/dist/lifecycle/kernel-lifecycle.js +1 -7
  178. package/dist/models/enablement.d.ts +5 -6
  179. package/dist/models/enablement.js +7 -14
  180. package/dist/net/public-address.d.ts +21 -1
  181. package/dist/net/public-address.js +56 -10
  182. package/dist/net/safe-fetch.d.ts +4 -1
  183. package/dist/net/safe-fetch.js +15 -4
  184. package/dist/orgs/directory-sync.js +2 -0
  185. package/dist/orgs/members.service.js +5 -0
  186. package/dist/orgs/network-allowances.service.d.ts +79 -0
  187. package/dist/orgs/network-allowances.service.js +371 -0
  188. package/dist/orgs/offboarding.d.ts +3 -1
  189. package/dist/orgs/offboarding.js +9 -2
  190. package/dist/orgs/org-lock.d.ts +28 -2
  191. package/dist/orgs/org-lock.js +59 -4
  192. package/dist/orgs/orgs.controller.d.ts +11 -2
  193. package/dist/orgs/orgs.controller.js +19 -3
  194. package/dist/orgs/orgs.module.d.ts +3 -2
  195. package/dist/orgs/orgs.module.js +6 -2
  196. package/dist/orgs/orgs.schemas.d.ts +12 -0
  197. package/dist/orgs/orgs.schemas.js +5 -0
  198. package/dist/orgs/orgs.service.js +6 -1
  199. package/dist/orgs/settings.controller.d.ts +3 -2
  200. package/dist/orgs/settings.service.d.ts +59 -14
  201. package/dist/orgs/settings.service.js +102 -20
  202. package/dist/overrides.d.ts +7 -7
  203. package/dist/overrides.js +4 -4
  204. package/dist/packages/tgz.d.ts +0 -2
  205. package/dist/packages/tgz.js +0 -2
  206. package/dist/platform/exclusions.js +0 -5
  207. package/dist/platform/operation.js +1 -1
  208. package/dist/platform/ops/admin.ops.d.ts +2 -2
  209. package/dist/platform/ops/admin.ops.js +9 -6
  210. package/dist/platform/ops/agents.ops.js +1 -1
  211. package/dist/platform/ops/connectors.ops.js +46 -1
  212. package/dist/platform/ops/evals.ops.js +1 -64
  213. package/dist/platform/ops/extensions-admin.ops.js +1 -1
  214. package/dist/platform/ops/inbox.ops.js +16 -3
  215. package/dist/platform/ops/org-plugins.ops.js +1 -1
  216. package/dist/platform/ops/orgs.ops.d.ts +11 -3
  217. package/dist/platform/ops/orgs.ops.js +139 -5
  218. package/dist/platform/ops/outbox.ops.js +5 -5
  219. package/dist/platform/route-schemas.js +3 -0
  220. package/dist/roles/worker-role.d.ts +2 -3
  221. package/dist/roles/worker-role.js +3 -13
  222. package/dist/runtime/checkpointer.d.ts +3 -0
  223. package/dist/runtime/checkpointer.js +7 -4
  224. package/dist/runtime/context/build.d.ts +56 -18
  225. package/dist/runtime/context/build.js +143 -50
  226. package/dist/runtime/context/compaction.d.ts +1 -3
  227. package/dist/runtime/context/compaction.js +42 -8
  228. package/dist/runtime/context/run-context.js +1 -2
  229. package/dist/runtime/context/skills.d.ts +27 -56
  230. package/dist/runtime/context/skills.js +42 -114
  231. package/dist/runtime/context/tool-changes.d.ts +3 -3
  232. package/dist/runtime/context/tool-changes.js +6 -16
  233. package/dist/runtime/hook-calls.d.ts +6 -6
  234. package/dist/runtime/hook-calls.js +7 -7
  235. package/dist/runtime/langgraph-loop.js +9 -3
  236. package/dist/runtime/maintenance.d.ts +3 -11
  237. package/dist/runtime/maintenance.js +5 -20
  238. package/dist/runtime/model-call.d.ts +5 -0
  239. package/dist/runtime/model-call.js +48 -36
  240. package/dist/runtime/providers.d.ts +33 -35
  241. package/dist/runtime/providers.js +64 -109
  242. package/dist/runtime/run-context.service.js +7 -22
  243. package/dist/runtime/run-deletion.d.ts +6 -0
  244. package/dist/runtime/run-deletion.js +39 -16
  245. package/dist/runtime/run-execution.d.ts +56 -3
  246. package/dist/runtime/run-execution.js +81 -11
  247. package/dist/runtime/run-finish.js +2 -1
  248. package/dist/runtime/run-liveness.d.ts +11 -0
  249. package/dist/runtime/run-liveness.js +19 -0
  250. package/dist/runtime/run-orphan-check.job.js +2 -1
  251. package/dist/runtime/run-queue.js +8 -16
  252. package/dist/runtime/run-worker.d.ts +2 -2
  253. package/dist/runtime/run-worker.js +8 -6
  254. package/dist/runtime/step-log.d.ts +5 -0
  255. package/dist/runtime/step-log.js +9 -4
  256. package/dist/runtime/subagents/definition.d.ts +16 -20
  257. package/dist/runtime/subagents/definition.js +27 -27
  258. package/dist/runtime/subagents/dispatch.d.ts +6 -2
  259. package/dist/runtime/subagents/dispatch.js +17 -3
  260. package/dist/runtime/subagents/org-agents.js +1 -2
  261. package/dist/runtime/subagents/preamble.d.ts +3 -2
  262. package/dist/runtime/subagents/preamble.js +3 -2
  263. package/dist/runtime/subagents/render.d.ts +1 -2
  264. package/dist/runtime/subagents/render.js +1 -2
  265. package/dist/runtime/subagents/skill-fork.d.ts +2 -4
  266. package/dist/runtime/subagents/template-skills.d.ts +47 -0
  267. package/dist/runtime/subagents/template-skills.js +76 -0
  268. package/dist/runtime/waits.js +3 -1
  269. package/dist/schedules/effective-settings.d.ts +9 -3
  270. package/dist/schedules/effective-settings.js +5 -4
  271. package/dist/schedules/fire.js +11 -0
  272. package/dist/schedules/scheduled-tasks.service.js +5 -0
  273. package/dist/schedules/unattended.d.ts +2 -0
  274. package/dist/schedules/unattended.js +6 -1
  275. package/dist/skills/agent-skills.service.js +1 -2
  276. package/dist/skills/catalog.d.ts +1 -3
  277. package/dist/skills/catalog.js +1 -3
  278. package/dist/skills/conversation-catalog.d.ts +1 -2
  279. package/dist/skills/conversation-catalog.js +1 -2
  280. package/dist/skills/usable.js +2 -3
  281. package/dist/storage/storage.service.js +9 -1
  282. package/dist/tools/approvals.service.js +2 -4
  283. package/dist/tools/builtin-names.d.ts +2 -9
  284. package/dist/tools/builtin-names.js +4 -13
  285. package/dist/tools/builtins/sandbox/bash.js +3 -3
  286. package/dist/tools/builtins/sandbox/common.d.ts +7 -13
  287. package/dist/tools/builtins/sandbox/common.js +8 -115
  288. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +10 -0
  289. package/dist/tools/builtins/sandbox/fetch-attachment.js +119 -0
  290. package/dist/tools/builtins/sandbox/glob.js +1 -3
  291. package/dist/tools/builtins/sandbox/grep.js +3 -5
  292. package/dist/tools/builtins/sandbox/index.d.ts +8 -5
  293. package/dist/tools/builtins/sandbox/index.js +10 -5
  294. package/dist/tools/builtins/sandbox/read.js +3 -2
  295. package/dist/tools/builtins/tool-search.d.ts +4 -7
  296. package/dist/tools/builtins/tool-search.js +6 -10
  297. package/dist/tools/connector-account-policies.d.ts +30 -3
  298. package/dist/tools/connector-account-policies.js +54 -7
  299. package/dist/tools/connector-content.js +1 -0
  300. package/dist/tools/connectors.controller.d.ts +24 -11
  301. package/dist/tools/connectors.controller.js +35 -6
  302. package/dist/tools/connectors.schemas.d.ts +14 -1
  303. package/dist/tools/connectors.schemas.js +14 -2
  304. package/dist/tools/connectors.service.d.ts +22 -0
  305. package/dist/tools/connectors.service.js +65 -6
  306. package/dist/tools/drift.d.ts +6 -2
  307. package/dist/tools/drift.js +10 -5
  308. package/dist/tools/git-push-policy.d.ts +4 -1
  309. package/dist/tools/git-push-policy.js +3 -1
  310. package/dist/tools/info.d.ts +1 -7
  311. package/dist/tools/info.js +5 -18
  312. package/dist/tools/job-ids.d.ts +0 -4
  313. package/dist/tools/job-ids.js +1 -6
  314. package/dist/tools/pipeline.d.ts +4 -10
  315. package/dist/tools/pipeline.js +17 -62
  316. package/dist/tools/policy.d.ts +6 -2
  317. package/dist/tools/policy.js +14 -12
  318. package/dist/tools/registry.js +1 -5
  319. package/dist/ui/views.d.ts +5 -5
  320. package/dist/ui/views.js +10 -16
  321. package/package.json +3 -3
  322. package/src/migrations/0137_audit_org_idx.sql +5 -0
  323. package/src/migrations/0138_plugin_install_status_no_upgrading.sql +18 -0
  324. package/src/migrations/0139_retire_legacy_forms.sql +183 -0
  325. package/src/migrations/0140_retire_history_forms.sql +148 -0
  326. package/src/migrations/0141_install_ledger_promoted_rows.sql +36 -0
  327. package/src/migrations/0142_backfill_event_fields.sql +74 -0
  328. package/src/migrations/0143_backfill_model_call_fields.sql +105 -0
  329. package/src/migrations/0144_retire_frozen_definition_keys.sql +163 -0
  330. package/src/migrations/0145_org_network_allowances.sql +12 -0
  331. package/dist/admin/platform-audit.service.d.ts +0 -41
  332. package/dist/conversations/job-ids.d.ts +0 -6
  333. package/dist/conversations/job-ids.js +0 -6
  334. package/dist/extensions/job-ids.d.ts +0 -6
  335. package/dist/extensions/job-ids.js +0 -6
  336. package/dist/infra/queue/retired-schedulers.d.ts +0 -7
  337. package/dist/infra/queue/retired-schedulers.js +0 -9
  338. package/dist/orgs/job-ids.d.ts +0 -8
  339. package/dist/orgs/job-ids.js +0 -8
  340. package/dist/runtime/context/legacy-text.d.ts +0 -22
  341. package/dist/runtime/context/legacy-text.js +0 -37
  342. package/dist/runtime/job-ids.d.ts +0 -10
  343. package/dist/runtime/job-ids.js +0 -10
  344. package/dist/runtime/retired-schedulers.d.ts +0 -7
  345. package/dist/runtime/retired-schedulers.js +0 -31
  346. package/dist/storage/job-ids.d.ts +0 -6
  347. package/dist/storage/job-ids.js +0 -6
  348. package/dist/tools/legacy-data.d.ts +0 -34
  349. package/dist/tools/legacy-data.js +0 -76
  350. package/dist/tools/legacy-keys.d.ts +0 -51
  351. package/dist/tools/legacy-keys.js +0 -114
@@ -0,0 +1,371 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { randomUUID } from "node:crypto";
11
+ import { BlockList, isIP } from "node:net";
12
+ import { Inject, Injectable, Module } from "@nestjs/common";
13
+ import { publicSuffixWildcard } from "../devices/public-suffix.js";
14
+ import { ApiError } from "../errors.js";
15
+ import { audit } from "../identity/audit.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { TransactionHost } from "../infra/database/transaction-host.js";
18
+ import { Transactional } from "../infra/database/transactional.decorator.js";
19
+ import { normalizeHost, parseCidr, privateHostEntryProblem } from "../net/public-address.js";
20
+ import { OrgLock, OrgLockModule } from "./org-lock.js";
21
+ /**
22
+ * Org network allowances (plugin safe fetch spec): the internal endpoints a super admin lets one
23
+ * org's extension requests (`ctx.net.fetch` made for that org) reach although they resolve to
24
+ * private or loopback addresses. Stored in `capybara.org_network_allowances`, read from PG on every
25
+ * call (no in-process cache: a removal takes effect on the next request on every replica).
26
+ *
27
+ * An entry is one of:
28
+ * - a hostname or a `*.domain` wildcard (https, any port; the domain has at least two labels and is
29
+ * not a known public suffix);
30
+ * - an IP address or a CIDR (IP-literal URL hosts only, within `MIN_CIDR_PREFIX`);
31
+ * - an origin `http(s)://host[:port]`: exactly that scheme, host and port, plain http included.
32
+ * Link-local and cloud metadata addresses (`100.100.100.200`, `fd00:ec2::254`), loopback and
33
+ * unspecified addresses are never allowed (`localhost` names included), nor IPv6 forms that embed an IPv4 address, so entries naming them are refused.
34
+ */
35
+ /** The most entries one org may hold. */
36
+ export const ORG_NETWORK_ALLOWANCES_MAX = 200;
37
+ const ENTRY_MAX_LENGTH = 300;
38
+ /** How much of a refused entry an error echoes back. */
39
+ const ECHO_MAX_LENGTH = 200;
40
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
41
+ /**
42
+ * Ranges no entry may overlap, with the reason. Only ranges of the entry's own family are compared
43
+ * (Node's `BlockList` matches v4-mapped addresses across families, which would refuse every IPv4
44
+ * entry against `::ffff:0:0/96`). `inside` ranges (single metadata addresses inside private ranges)
45
+ * refuse only entries within them: a CIDR such as `fd00::/16` stays valid, and the runtime check
46
+ * (`net/public-address.ts`) refuses the metadata address itself whatever the entries.
47
+ */
48
+ const REFUSED_RANGES = [
49
+ ...[
50
+ ["169.254.0.0", 16, "ipv4"],
51
+ ["fe80::", 10, "ipv6"],
52
+ ].map((cidr) => ({
53
+ cidr,
54
+ reason: "link-local addresses (including cloud metadata) are never allowed",
55
+ })),
56
+ ...[
57
+ ["100.100.100.200", 32, "ipv4"], // Alibaba Cloud
58
+ ["fd00:ec2::254", 128, "ipv6"], // AWS IMDS over IPv6
59
+ ].map((cidr) => ({
60
+ cidr,
61
+ reason: "cloud metadata endpoints are never allowed",
62
+ inside: true,
63
+ })),
64
+ ...[
65
+ ["127.0.0.0", 8, "ipv4"],
66
+ ["0.0.0.0", 8, "ipv4"],
67
+ ["::", 128, "ipv6"],
68
+ ["::1", 128, "ipv6"],
69
+ ].map((cidr) => ({
70
+ cidr,
71
+ reason: "loopback and unspecified addresses (the kernel's own host) are never allowed",
72
+ })),
73
+ ...[
74
+ ["::ffff:0:0", 96, "ipv6"], // v4-mapped
75
+ ["::ffff:0:0:0", 96, "ipv6"], // SIIT
76
+ ["::", 96, "ipv6"], // v4-compatible
77
+ ["64:ff9b::", 96, "ipv6"], // NAT64
78
+ ["2002::", 16, "ipv6"], // 6to4
79
+ ].map((cidr) => ({
80
+ cidr,
81
+ reason: "IPv6 addresses that embed an IPv4 address are not accepted: write the IPv4 address",
82
+ })),
83
+ ];
84
+ const LOOPBACK_NAME = "localhost names (the kernel's own host) are never allowed";
85
+ /** Whether two CIDRs of one family overlap: aligned ranges overlap iff one holds the other's start. */
86
+ function overlaps([a, ap, af], [b, bp, bf]) {
87
+ if (af !== bf)
88
+ return false;
89
+ const ra = new BlockList();
90
+ ra.addSubnet(a, ap, af);
91
+ const rb = new BlockList();
92
+ rb.addSubnet(b, bp, bf);
93
+ return ra.check(b, bf) || rb.check(a, af);
94
+ }
95
+ /** Whether `inner` lies within `outer` (one family). */
96
+ function within(inner, outer) {
97
+ return overlaps(inner, outer) && inner[1] >= outer[1];
98
+ }
99
+ /** The reason an IP or CIDR (as a CIDR) touches a refused range, or null. */
100
+ function refusedRangeProblem(cidr) {
101
+ return (REFUSED_RANGES.find((r) => (r.inside ? within(cidr, r.cidr) : overlaps(cidr, r.cidr)))
102
+ ?.reason ?? null);
103
+ }
104
+ const asCidr = (ip) => isIP(ip) === 4 ? [ip, 32, "ipv4"] : [ip.toLowerCase(), 128, "ipv6"];
105
+ /** The canonical spelling of an IPv6 address (`FD00:0::1` -> `fd00::1`). */
106
+ const canonicalV6 = (ip) => new URL(`http://[${ip}]`).hostname.slice(1, -1);
107
+ const isLocalhostName = (h) => h === "localhost" || h.endsWith(".localhost");
108
+ /** A last label a URL parser reads as a number (`2130706433`, `0x7f.1`): an IP in disguise. */
109
+ const numericLastLabel = (h) => /^(\d+|0x[0-9a-f]*)$/i.test(h.split(".").pop() ?? "");
110
+ const isOrigin = (entry) => entry.includes("://");
111
+ /** Why a hostname or IP (normalized, no wildcard, no CIDR) may not be allowed, or null. */
112
+ function hostProblem(host) {
113
+ if (isIP(host) !== 0)
114
+ return refusedRangeProblem(asCidr(host));
115
+ if (privateHostEntryProblem(host) !== null)
116
+ return null; // the caller reports the syntax
117
+ if (isLocalhostName(host))
118
+ return LOOPBACK_NAME;
119
+ if (numericLastLabel(host))
120
+ return "a numeric host must be written as a dotted IP address";
121
+ return null;
122
+ }
123
+ /** Why a plain host entry (hostname, IP or CIDR, no wildcard or scheme) is invalid, or null. */
124
+ function hostEntryProblem(entry) {
125
+ const cidr = parseCidr(entry);
126
+ if (cidr)
127
+ return privateHostEntryProblem(entry) ?? refusedRangeProblem(cidr);
128
+ const host = normalizeHost(entry);
129
+ if (/^[^/[\]]+:\d+$/.test(host) && isIP(host) === 0) {
130
+ return "a host with a port must be written as an origin such as http://host:8080";
131
+ }
132
+ if (privateHostEntryProblem(entry) !== null) {
133
+ return "must be a hostname, a *.domain wildcard, an IP address, a CIDR such as 10.1.0.0/16 or an origin such as http://host:8080";
134
+ }
135
+ return hostProblem(host);
136
+ }
137
+ /** Why a `*.domain` entry is invalid, or null. */
138
+ function wildcardProblem(entry) {
139
+ const base = normalizeHost(entry.slice(2));
140
+ if (!entry.startsWith("*.") ||
141
+ base === "" ||
142
+ isIP(base) !== 0 ||
143
+ parseCidr(base) ||
144
+ privateHostEntryProblem(base) !== null ||
145
+ numericLastLabel(base)) {
146
+ return "a wildcard must be written *.domain, e.g. *.corp.example";
147
+ }
148
+ if (isLocalhostName(base))
149
+ return LOOPBACK_NAME;
150
+ return publicSuffixWildcard(`*.${base}`);
151
+ }
152
+ /** The origin's host: WHATWG-normalized (numeric forms become dotted IPs), without trailing dots. */
153
+ const originHost = (url) => normalizeHost(url.hostname);
154
+ /** Why an origin entry is invalid, or null. */
155
+ function originProblem(entry) {
156
+ let url;
157
+ try {
158
+ url = new URL(entry);
159
+ }
160
+ catch {
161
+ return "is not a valid origin such as http://host:8080";
162
+ }
163
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
164
+ return "an origin must use http or https";
165
+ }
166
+ if (url.username !== "" || url.password !== "")
167
+ return "an origin must not carry credentials";
168
+ if (url.search !== "" || entry.includes("?"))
169
+ return "an origin has no query";
170
+ if (url.hash !== "" || entry.includes("#"))
171
+ return "an origin has no fragment";
172
+ if (url.pathname !== "/")
173
+ return "an origin has no path: allow the whole origin";
174
+ const host = originHost(url);
175
+ if (parseCidr(host) || privateHostEntryProblem(host) !== null) {
176
+ return "an origin's host must be a hostname or an IP address";
177
+ }
178
+ return hostProblem(host);
179
+ }
180
+ /**
181
+ * Why an allowance entry is invalid (English, shown to the super admin), or null when it is valid
182
+ * (see the file header for the accepted forms). Reuses `privateHostEntryProblem` for hosts, IPs and
183
+ * CIDRs; refuses link-local, loopback and unspecified addresses (also as `localhost` names, numeric
184
+ * hosts and inside origins), IPv6 forms that embed IPv4, wildcards over a public suffix, and
185
+ * origins with a path, query, fragment or credentials.
186
+ */
187
+ export function allowanceEntryProblem(entry) {
188
+ const e = entry.trim();
189
+ if (e === "")
190
+ return "must not be empty";
191
+ if (e.length > ENTRY_MAX_LENGTH)
192
+ return `must be at most ${ENTRY_MAX_LENGTH} characters`;
193
+ if (isOrigin(e))
194
+ return originProblem(e);
195
+ if (e.startsWith("*"))
196
+ return wildcardProblem(e);
197
+ return hostEntryProblem(e);
198
+ }
199
+ /**
200
+ * The stored form of a valid entry: hosts lower case without brackets or trailing dots, IPv6
201
+ * addresses and CIDRs in canonical spelling, origins as scheme, host and port (default ports
202
+ * dropped), so one endpoint is stored once.
203
+ */
204
+ export function normalizeAllowanceEntry(entry) {
205
+ const e = entry.trim();
206
+ if (isOrigin(e)) {
207
+ const url = new URL(e);
208
+ const host = originHost(url);
209
+ url.hostname = isIP(host) === 6 ? `[${host}]` : host;
210
+ return url.origin;
211
+ }
212
+ if (e.startsWith("*."))
213
+ return `*.${normalizeHost(e.slice(2))}`;
214
+ const cidr = parseCidr(e);
215
+ if (cidr) {
216
+ const [addr, prefix, family] = cidr;
217
+ return `${family === "ipv6" ? canonicalV6(addr) : addr}/${prefix}`;
218
+ }
219
+ const host = normalizeHost(e);
220
+ return isIP(host) === 6 ? canonicalV6(host) : host;
221
+ }
222
+ let OrgNetworkAllowances = class OrgNetworkAllowances {
223
+ db;
224
+ txHost;
225
+ orgLock;
226
+ constructor(db, txHost, orgLock) {
227
+ this.db = db;
228
+ this.txHost = txHost;
229
+ this.orgLock = orgLock;
230
+ }
231
+ /** The org's entries, oldest first. */
232
+ async list(orgId) {
233
+ const rows = await this.db
234
+ .selectFrom("org_network_allowances")
235
+ .select(["id", "entry", "created_at", "created_by"])
236
+ .where("org_id", "=", orgId)
237
+ .orderBy("created_at")
238
+ .orderBy("id")
239
+ .execute();
240
+ return rows.map(toAllowance);
241
+ }
242
+ /**
243
+ * Adds an entry (super admin only; the route enforces it). Refuses an invalid entry with
244
+ * `org.network_allowance_invalid` and the reason; an entry already listed is returned as is,
245
+ * without a second audit event. `actor.tokenId` (a personal access token) and `auditDetail` (e.g.
246
+ * `viaAgent`) go into the audit event; the caller's detail cannot override `entry`.
247
+ */
248
+ async add(orgId, entry, actor, auditDetail = {}) {
249
+ const problem = allowanceEntryProblem(entry);
250
+ if (problem !== null) {
251
+ const shown = echoed(entry);
252
+ throw new ApiError("org.network_allowance_invalid", `${shown}: ${problem}`, [
253
+ { entry: shown, reason: problem },
254
+ ]);
255
+ }
256
+ const normalized = normalizeAllowanceEntry(entry);
257
+ // the org row lock (FOR NO KEY UPDATE; a missing or deleted org -> org.not_found): concurrent
258
+ // adds count against the cap one at a time
259
+ await this.orgLock.lock(orgId);
260
+ const existing = await this.db
261
+ .selectFrom("org_network_allowances")
262
+ .select(["id", "entry", "created_at", "created_by"])
263
+ .where("org_id", "=", orgId)
264
+ .where("entry", "=", normalized)
265
+ .executeTakeFirst();
266
+ if (existing)
267
+ return toAllowance(existing);
268
+ const { count } = await this.db
269
+ .selectFrom("org_network_allowances")
270
+ .select((eb) => eb.fn.countAll().as("count"))
271
+ .where("org_id", "=", orgId)
272
+ .executeTakeFirstOrThrow();
273
+ if (Number(count) >= ORG_NETWORK_ALLOWANCES_MAX) {
274
+ const reason = `an organization may list at most ${ORG_NETWORK_ALLOWANCES_MAX} internal endpoints`;
275
+ throw new ApiError("org.network_allowance_invalid", reason, [
276
+ { entry: echoed(entry), reason },
277
+ ]);
278
+ }
279
+ const row = await this.db
280
+ .insertInto("org_network_allowances")
281
+ .values({ id: randomUUID(), org_id: orgId, entry: normalized, created_by: actor.accountId })
282
+ .returning(["id", "entry", "created_at", "created_by"])
283
+ .executeTakeFirstOrThrow();
284
+ await this.audit("org.network_allowance_added", orgId, row.id, normalized, actor, auditDetail);
285
+ return toAllowance(row);
286
+ }
287
+ /**
288
+ * Removes the org's entry `id`; false (and no audit event) when the org has no such entry. The
289
+ * actor and `auditDetail` are recorded as {@link add}'s.
290
+ */
291
+ async remove(orgId, id, actor, auditDetail = {}) {
292
+ if (!UUID.test(id))
293
+ return false;
294
+ const row = await this.db
295
+ .deleteFrom("org_network_allowances")
296
+ .where("org_id", "=", orgId)
297
+ .where("id", "=", id)
298
+ .returning(["entry"])
299
+ .executeTakeFirst();
300
+ if (!row)
301
+ return false;
302
+ await this.audit("org.network_allowance_removed", orgId, id, row.entry, actor, auditDetail);
303
+ return true;
304
+ }
305
+ /** An allowance audit event in the org; the caller's detail first, so `entry` wins. */
306
+ audit(action, orgId, target, entry, actor, detail) {
307
+ return audit(this.db.db, {
308
+ actorAccountId: actor.accountId,
309
+ ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }),
310
+ orgId,
311
+ action,
312
+ target,
313
+ detail: { ...detail, entry },
314
+ });
315
+ }
316
+ /**
317
+ * The exemptions of an org-bound request: origins become `trustedOrigins`, hosts, wildcards, IPs
318
+ * and CIDRs `allowPrivateHosts`. A deleted (or unknown) org allows nothing.
319
+ */
320
+ async policyFor(orgId) {
321
+ const rows = await this.db
322
+ .selectFrom("org_network_allowances as a")
323
+ .innerJoin("orgs as o", "o.id", "a.org_id")
324
+ .select("a.entry")
325
+ .where("a.org_id", "=", orgId)
326
+ .where("o.deleted_at", "is", null)
327
+ .orderBy("a.created_at")
328
+ .execute();
329
+ const policy = { allowPrivateHosts: [], trustedOrigins: [] };
330
+ for (const { entry } of rows) {
331
+ (isOrigin(entry) ? policy.trustedOrigins : policy.allowPrivateHosts).push(entry);
332
+ }
333
+ return policy;
334
+ }
335
+ };
336
+ __decorate([
337
+ Transactional()
338
+ ], OrgNetworkAllowances.prototype, "add", null);
339
+ __decorate([
340
+ Transactional()
341
+ ], OrgNetworkAllowances.prototype, "remove", null);
342
+ OrgNetworkAllowances = __decorate([
343
+ Injectable(),
344
+ __param(0, Inject(KernelDb)),
345
+ __param(1, Inject(TransactionHost)),
346
+ __param(2, Inject(OrgLock))
347
+ ], OrgNetworkAllowances);
348
+ export { OrgNetworkAllowances };
349
+ /** The raw entry as echoed in an error, cut to {@link ECHO_MAX_LENGTH} characters. */
350
+ function echoed(entry) {
351
+ const e = entry.trim();
352
+ return e.length > ECHO_MAX_LENGTH ? `${e.slice(0, ECHO_MAX_LENGTH)}…` : e;
353
+ }
354
+ function toAllowance(row) {
355
+ return { id: row.id, entry: row.entry, createdAt: row.created_at, createdBy: row.created_by };
356
+ }
357
+ /**
358
+ * {@link OrgNetworkAllowances} alone (its only dependencies are the global database providers), so
359
+ * the extension host (`ctx.net`) can read the allowances without importing the orgs domain, which
360
+ * itself imports the extensions domain.
361
+ */
362
+ let OrgNetworkAllowancesModule = class OrgNetworkAllowancesModule {
363
+ };
364
+ OrgNetworkAllowancesModule = __decorate([
365
+ Module({
366
+ imports: [OrgLockModule],
367
+ providers: [OrgNetworkAllowances],
368
+ exports: [OrgNetworkAllowances],
369
+ })
370
+ ], OrgNetworkAllowancesModule);
371
+ export { OrgNetworkAllowancesModule };
@@ -9,6 +9,7 @@ import type { KernelLogger } from "../log.js";
9
9
  import { ApprovalsService } from "../tools/approvals.service.js";
10
10
  import { Credentials } from "../tools/credentials.js";
11
11
  import { QuestionsService } from "../tools/questions.service.js";
12
+ import { OrgLock } from "./org-lock.js";
12
13
  import type { OrgRole } from "./roles.js";
13
14
  /** 离职原因:管理员移出、本人离开、通讯录同步判定离职。 */
14
15
  export type OffboardReason = "removed" | "left" | "directory";
@@ -83,13 +84,14 @@ export declare class Offboarding {
83
84
  /** Owes `org.member_removed` to the subscribing plugins, in the offboard transaction. */
84
85
  private readonly lifecycle;
85
86
  readonly log: KernelLogger;
87
+ private readonly orgLock;
86
88
  constructor(db: KernelDb, txHost: TransactionHost, sessions: Pick<SessionService, "markRevoked">, registry: Pick<ExtensionRegistry, "list">, eventLog: Pick<EventLog, "notify" | "publishChanged">,
87
89
  /** Owes the run stops and device destroys in the offboard transaction. */
88
90
  outbox: Pick<OutboxService, "add">,
89
91
  /** Stops the departed member's runs (`by: null`, a system action) in the `run-stop` job. */
90
92
  runs: OffboardingRunControl, credentials: Pick<Credentials, "clearAccount">, approvals: Pick<ApprovalsService, "pendingConversationsFor" | "cancelPendingFor">, questions: Pick<QuestionsService, "pendingConversationsFor" | "cancelPendingFor">,
91
93
  /** Owes `org.member_removed` to the subscribing plugins, in the offboard transaction. */
92
- lifecycle: Pick<LifecycleHooks, "recordIn">, log: KernelLogger);
94
+ lifecycle: Pick<LifecycleHooks, "recordIn">, log: KernelLogger, orgLock: Pick<OrgLock, "lockForRemoval">);
93
95
  /**
94
96
  * In the caller's transaction (`mandatory`: the caller holds the org row lock, order org row →
95
97
  * membership, and did the "last owner" checks):
@@ -30,6 +30,7 @@ import { oweDeviceDestroy } from "../sandbox/jobs.js";
30
30
  import { ApprovalsService } from "../tools/approvals.service.js";
31
31
  import { Credentials } from "../tools/credentials.js";
32
32
  import { QuestionsService } from "../tools/questions.service.js";
33
+ import { OrgLock } from "./org-lock.js";
33
34
  /**
34
35
  * The stop of a departed member's run (transactional outbox spec §8.1), owed by the offboard
35
36
  * transaction on the maintenance queue under {@link runStopJobId}; `MaintenanceProcessor` runs
@@ -65,13 +66,14 @@ let Offboarding = class Offboarding {
65
66
  questions;
66
67
  lifecycle;
67
68
  log;
69
+ orgLock;
68
70
  constructor(db, txHost, sessions, registry, eventLog,
69
71
  /** Owes the run stops and device destroys in the offboard transaction. */
70
72
  outbox,
71
73
  /** Stops the departed member's runs (`by: null`, a system action) in the `run-stop` job. */
72
74
  runs, credentials, approvals, questions,
73
75
  /** Owes `org.member_removed` to the subscribing plugins, in the offboard transaction. */
74
- lifecycle, log) {
76
+ lifecycle, log, orgLock) {
75
77
  this.db = db;
76
78
  this.txHost = txHost;
77
79
  this.sessions = sessions;
@@ -84,6 +86,7 @@ let Offboarding = class Offboarding {
84
86
  this.questions = questions;
85
87
  this.lifecycle = lifecycle;
86
88
  this.log = log;
89
+ this.orgLock = orgLock;
87
90
  }
88
91
  /**
89
92
  * In the caller's transaction (`mandatory`: the caller holds the org row lock, order org row →
@@ -108,6 +111,9 @@ let Offboarding = class Offboarding {
108
111
  * plugin).
109
112
  */
110
113
  async offboard(orgId, accountId, reason, actor = {}) {
114
+ // the org admission lock exclusively (the callers take it first, before the org row; a no-op
115
+ // then): it waits for the run writes the fence admitted shared and keeps new ones out
116
+ await this.orgLock.lockForRemoval(orgId);
111
117
  const deleted = await this.db
112
118
  .deleteFrom("memberships")
113
119
  .where("org_id", "=", orgId)
@@ -463,6 +469,7 @@ Offboarding = __decorate([
463
469
  __param(8, Inject(ApprovalsService)),
464
470
  __param(9, Inject(QuestionsService)),
465
471
  __param(10, Inject(LifecycleHooks)),
466
- __param(11, Inject(KERNEL_LOGGER))
472
+ __param(11, Inject(KERNEL_LOGGER)),
473
+ __param(12, Inject(OrgLock))
467
474
  ], Offboarding);
468
475
  export { Offboarding };
@@ -1,5 +1,6 @@
1
1
  import { KernelDb } from "../infra/database/kernel-db.js";
2
2
  import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { XactLock } from "../infra/database/xact-lock.js";
3
4
  import { type OrgAction, type OrgRole } from "./roles.js";
4
5
  /** The locked org's metadata (audits record the values before a change). */
5
6
  export interface LockedOrg {
@@ -15,12 +16,37 @@ export interface LockedOrg {
15
16
  * foreign key check against the org row (`FOR KEY SHARE`, taken by every insert of a row that
16
17
  * references the org, and by an update of a row the same transaction already wrote) is not blocked.
17
18
  * With FOR UPDATE, offboarding (org row, then the member's conversations) deadlocked with an event
18
- * log append (a conversation row, then the org foreign key check).
19
+ * log append (a conversation row, then the org foreign key check). Nothing takes the org row
20
+ * `FOR UPDATE`: org deletion's `deleted_at` update is a no-key update too.
21
+ *
22
+ * The global lock order: the org admission lock ({@link lockForRemoval}; the run fence's shared
23
+ * admission, `RunExecution`) → this org row lock (also the run fence's exclusive admission) → the
24
+ * root conversation → the conversation. A writer that locks several conversation or run rows of
25
+ * one tree locks the tree's root conversation first. A transaction the run fence admitted shared
26
+ * takes none of these org-level locks (each method throws in one, `assertNotSharedAdmission`).
19
27
  */
20
28
  export declare class OrgLock {
21
29
  private readonly db;
30
+ private readonly xactLock;
22
31
  readonly txHost: TransactionHost;
23
- constructor(db: KernelDb, txHost: TransactionHost);
32
+ constructor(db: KernelDb, xactLock: XactLock, txHost: TransactionHost);
33
+ /**
34
+ * Org deletion's and offboarding's lock: the org admission lock exclusively
35
+ * (`XactLock.admitOrgExclusive`), taken first in the transaction, before the org row
36
+ * ({@link lockAndAuthorize}). It waits for every run write the fence admitted shared (event
37
+ * appends, checkpoints) and keeps new ones out until the transaction ends, so a later one sees
38
+ * the org deleted; it queues fairly, so a stream of run writes does not starve it. Never inside
39
+ * a run's fenced transaction: that one may hold a conversation row that an admitted run write
40
+ * waits for.
41
+ */
42
+ lockForRemoval(orgId: string): Promise<void>;
43
+ /**
44
+ * The role check of {@link lockAndAuthorize} without any lock, for the callers of
45
+ * {@link lockForRemoval}: an unauthorized call is refused (`org.not_found` / `forbidden`) before
46
+ * it waits for the org's run writes and holds them off. Advisory only; the caller still runs
47
+ * {@link lockAndAuthorize} after the locks, which decides.
48
+ */
49
+ precheck(orgId: string, actorAccountId: string, action: OrgAction): Promise<void>;
24
50
  /** Locks the org row; undefined when the org does not exist or is soft-deleted. */
25
51
  tryLock(orgId: string): Promise<LockedOrg | undefined>;
26
52
  /** Like {@link tryLock}; a missing or soft-deleted org → `org.not_found`. */
@@ -10,8 +10,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable, Module } from "@nestjs/common";
11
11
  import { ApiError } from "../errors.js";
12
12
  import { KernelDb } from "../infra/database/kernel-db.js";
13
- import { TransactionHost } from "../infra/database/transaction-host.js";
13
+ import { assertNotSharedAdmission, inFencedTransaction, TransactionHost, } from "../infra/database/transaction-host.js";
14
14
  import { Transactional } from "../infra/database/transactional.decorator.js";
15
+ import { XactLock } from "../infra/database/xact-lock.js";
15
16
  import { can } from "./roles.js";
16
17
  /**
17
18
  * The org row lock that serializes an organization's member / invitation / token / config writes.
@@ -22,17 +23,64 @@ import { can } from "./roles.js";
22
23
  * foreign key check against the org row (`FOR KEY SHARE`, taken by every insert of a row that
23
24
  * references the org, and by an update of a row the same transaction already wrote) is not blocked.
24
25
  * With FOR UPDATE, offboarding (org row, then the member's conversations) deadlocked with an event
25
- * log append (a conversation row, then the org foreign key check).
26
+ * log append (a conversation row, then the org foreign key check). Nothing takes the org row
27
+ * `FOR UPDATE`: org deletion's `deleted_at` update is a no-key update too.
28
+ *
29
+ * The global lock order: the org admission lock ({@link lockForRemoval}; the run fence's shared
30
+ * admission, `RunExecution`) → this org row lock (also the run fence's exclusive admission) → the
31
+ * root conversation → the conversation. A writer that locks several conversation or run rows of
32
+ * one tree locks the tree's root conversation first. A transaction the run fence admitted shared
33
+ * takes none of these org-level locks (each method throws in one, `assertNotSharedAdmission`).
26
34
  */
27
35
  let OrgLock = class OrgLock {
28
36
  db;
37
+ xactLock;
29
38
  txHost;
30
- constructor(db, txHost) {
39
+ constructor(db, xactLock, txHost) {
31
40
  this.db = db;
41
+ this.xactLock = xactLock;
32
42
  this.txHost = txHost;
33
43
  }
44
+ /**
45
+ * Org deletion's and offboarding's lock: the org admission lock exclusively
46
+ * (`XactLock.admitOrgExclusive`), taken first in the transaction, before the org row
47
+ * ({@link lockAndAuthorize}). It waits for every run write the fence admitted shared (event
48
+ * appends, checkpoints) and keeps new ones out until the transaction ends, so a later one sees
49
+ * the org deleted; it queues fairly, so a stream of run writes does not starve it. Never inside
50
+ * a run's fenced transaction: that one may hold a conversation row that an admitted run write
51
+ * waits for.
52
+ */
53
+ async lockForRemoval(orgId) {
54
+ if (inFencedTransaction()) {
55
+ throw new Error("org deletion and offboarding never run inside a run's fenced transaction");
56
+ }
57
+ await this.xactLock.admitOrgExclusive(orgId);
58
+ }
59
+ /**
60
+ * The role check of {@link lockAndAuthorize} without any lock, for the callers of
61
+ * {@link lockForRemoval}: an unauthorized call is refused (`org.not_found` / `forbidden`) before
62
+ * it waits for the org's run writes and holds them off. Advisory only; the caller still runs
63
+ * {@link lockAndAuthorize} after the locks, which decides.
64
+ */
65
+ async precheck(orgId, actorAccountId, action) {
66
+ const row = await this.db
67
+ .selectFrom("orgs")
68
+ .leftJoin("memberships", (j) => j
69
+ .onRef("memberships.org_id", "=", "orgs.id")
70
+ .on("memberships.account_id", "=", actorAccountId))
71
+ .select("memberships.role")
72
+ .where("orgs.id", "=", orgId)
73
+ .where("orgs.deleted_at", "is", null)
74
+ .executeTakeFirst();
75
+ if (!row)
76
+ throw new ApiError("org.not_found", "Organization not found");
77
+ if (!row.role || !can(row.role, action)) {
78
+ throw new ApiError("forbidden", "Insufficient organization role");
79
+ }
80
+ }
34
81
  /** Locks the org row; undefined when the org does not exist or is soft-deleted. */
35
82
  async tryLock(orgId) {
83
+ assertNotSharedAdmission("the org lock");
36
84
  return this.db
37
85
  .selectFrom("orgs")
38
86
  .select(["slug", "name"])
@@ -43,6 +91,7 @@ let OrgLock = class OrgLock {
43
91
  }
44
92
  /** Like {@link tryLock}; a missing or soft-deleted org → `org.not_found`. */
45
93
  async lock(orgId) {
94
+ assertNotSharedAdmission("the org lock");
46
95
  const org = await this.tryLock(orgId);
47
96
  if (!org)
48
97
  throw new ApiError("org.not_found", "Organization not found");
@@ -55,6 +104,7 @@ let OrgLock = class OrgLock {
55
104
  * actor's account id, never a role from the caller.
56
105
  */
57
106
  async lockAndAuthorize(orgId, actorAccountId, action) {
107
+ assertNotSharedAdmission("the org lock");
58
108
  const org = await this.lock(orgId);
59
109
  const m = await this.db
60
110
  .selectFrom("memberships")
@@ -72,12 +122,16 @@ let OrgLock = class OrgLock {
72
122
  * person, such as the plugin scope sync) only the lock, since no role applies.
73
123
  */
74
124
  async lockFor(orgId, actor, action) {
125
+ assertNotSharedAdmission("the org lock");
75
126
  if (actor === null)
76
127
  await this.lock(orgId);
77
128
  else
78
129
  await this.lockAndAuthorize(orgId, actor, action);
79
130
  }
80
131
  };
132
+ __decorate([
133
+ Transactional({ propagation: "mandatory" })
134
+ ], OrgLock.prototype, "lockForRemoval", null);
81
135
  __decorate([
82
136
  Transactional({ propagation: "mandatory" })
83
137
  ], OrgLock.prototype, "tryLock", null);
@@ -93,7 +147,8 @@ __decorate([
93
147
  OrgLock = __decorate([
94
148
  Injectable(),
95
149
  __param(0, Inject(KernelDb)),
96
- __param(1, Inject(TransactionHost))
150
+ __param(1, Inject(XactLock)),
151
+ __param(2, Inject(TransactionHost))
97
152
  ], OrgLock);
98
153
  export { OrgLock };
99
154
  /** The one {@link OrgLock}: identity (service tokens), orgs and the other domains import it. */
@@ -2,8 +2,9 @@ import { z } from "zod";
2
2
  import { type ApiTokenRecord, ApiTokenService } from "../identity/api-tokens.js";
3
3
  import { type Principal } from "../identity/principal.js";
4
4
  import { type Member, MembersService } from "./members.service.js";
5
+ import { OrgNetworkAllowances } from "./network-allowances.service.js";
5
6
  import { type OrgContext } from "./org.guard.js";
6
- import { OrgUpdateBody } from "./orgs.schemas.js";
7
+ import { type NetworkAllowanceView, OrgUpdateBody } from "./orgs.schemas.js";
7
8
  import { type Org, OrgsService } from "./orgs.service.js";
8
9
  import { type OrgRole } from "./roles.js";
9
10
  declare const CreateSchema: z.ZodObject<{
@@ -35,7 +36,8 @@ export declare class OrgsController {
35
36
  private readonly orgs;
36
37
  private readonly members;
37
38
  private readonly tokens;
38
- constructor(orgs: OrgsService, members: MembersService, tokens: ApiTokenService);
39
+ private readonly allowances;
40
+ constructor(orgs: OrgsService, members: MembersService, tokens: ApiTokenService, allowances: OrgNetworkAllowances);
39
41
  create(principal: Principal, body: z.infer<typeof CreateSchema>): Promise<{
40
42
  org: Org;
41
43
  role: "owner";
@@ -58,6 +60,13 @@ export declare class OrgsController {
58
60
  listMembers(org: OrgContext): Promise<{
59
61
  members: Member[];
60
62
  }>;
63
+ /**
64
+ * The internal endpoints a super admin lets this org's extension requests reach (plugin safe
65
+ * fetch spec), read-only for org admins so a refused request is explainable; members get 403.
66
+ */
67
+ listNetworkAllowances(org: OrgContext): Promise<{
68
+ allowances: NetworkAllowanceView[];
69
+ }>;
61
70
  changeRole(principal: Principal, org: OrgContext, accountId: string, body: z.infer<typeof RoleSchema>): Promise<{
62
71
  accountId: string;
63
72
  role: OrgRole;