@capybara-hq/kernel 0.1.0-rc.37 → 0.1.0-rc.39

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 (77) hide show
  1. package/dist/admin/admin.module.d.ts +2 -1
  2. package/dist/admin/admin.module.js +5 -1
  3. package/dist/admin/org-network.controller.d.ts +30 -0
  4. package/dist/admin/org-network.controller.js +77 -0
  5. package/dist/admin/org-network.schemas.d.ts +16 -0
  6. package/dist/admin/org-network.schemas.js +27 -0
  7. package/dist/admin/org-network.service.d.ts +41 -0
  8. package/dist/admin/org-network.service.js +101 -0
  9. package/dist/catalog/marketplaces.service.d.ts +1 -1
  10. package/dist/config/schema.d.ts +1 -0
  11. package/dist/config/schema.js +8 -2
  12. package/dist/conversations/attachments.service.d.ts +39 -0
  13. package/dist/conversations/attachments.service.js +59 -22
  14. package/dist/conversations/conversations.controller.d.ts +1 -1
  15. package/dist/conversations/conversations.controller.js +1 -1
  16. package/dist/conversations/conversations.service.d.ts +5 -1
  17. package/dist/conversations/conversations.service.js +9 -2
  18. package/dist/conversations/event-log.js +4 -1
  19. package/dist/conversations/files.d.ts +39 -12
  20. package/dist/conversations/files.js +134 -55
  21. package/dist/ctx/create-ctx.d.ts +8 -1
  22. package/dist/ctx/create-ctx.js +12 -1
  23. package/dist/ctx/net.d.ts +50 -0
  24. package/dist/ctx/net.js +67 -0
  25. package/dist/db/kernel-schema.d.ts +10 -0
  26. package/dist/devices/devices.service.js +2 -1
  27. package/dist/errors.d.ts +5 -0
  28. package/dist/errors.js +5 -0
  29. package/dist/extensions/extensions.module.js +3 -0
  30. package/dist/extensions/host.d.ts +7 -1
  31. package/dist/extensions/host.js +13 -3
  32. package/dist/files/previewers.js +6 -0
  33. package/dist/http/api.module.js +2 -0
  34. package/dist/infra/database/transaction-host.d.ts +32 -1
  35. package/dist/infra/database/transaction-host.js +30 -4
  36. package/dist/infra/database/xact-lock.d.ts +16 -0
  37. package/dist/infra/database/xact-lock.js +28 -1
  38. package/dist/net/public-address.d.ts +21 -1
  39. package/dist/net/public-address.js +56 -10
  40. package/dist/net/safe-fetch.d.ts +4 -1
  41. package/dist/net/safe-fetch.js +15 -4
  42. package/dist/orgs/directory-sync.js +2 -0
  43. package/dist/orgs/members.service.js +5 -0
  44. package/dist/orgs/network-allowances.service.d.ts +79 -0
  45. package/dist/orgs/network-allowances.service.js +371 -0
  46. package/dist/orgs/offboarding.d.ts +3 -1
  47. package/dist/orgs/offboarding.js +9 -2
  48. package/dist/orgs/org-lock.d.ts +28 -2
  49. package/dist/orgs/org-lock.js +59 -4
  50. package/dist/orgs/orgs.controller.d.ts +11 -2
  51. package/dist/orgs/orgs.controller.js +19 -3
  52. package/dist/orgs/orgs.module.d.ts +2 -1
  53. package/dist/orgs/orgs.module.js +5 -1
  54. package/dist/orgs/orgs.schemas.d.ts +12 -0
  55. package/dist/orgs/orgs.schemas.js +5 -0
  56. package/dist/orgs/orgs.service.js +6 -1
  57. package/dist/overrides.d.ts +4 -0
  58. package/dist/overrides.js +2 -0
  59. package/dist/platform/ops/conversations.ops.js +2 -1
  60. package/dist/platform/ops/orgs.ops.d.ts +7 -1
  61. package/dist/platform/ops/orgs.ops.js +122 -3
  62. package/dist/platform/route-schemas.js +3 -0
  63. package/dist/runtime/checkpointer.d.ts +3 -0
  64. package/dist/runtime/checkpointer.js +7 -4
  65. package/dist/runtime/langgraph-loop.js +8 -3
  66. package/dist/runtime/run-execution.d.ts +56 -3
  67. package/dist/runtime/run-execution.js +77 -8
  68. package/dist/runtime/step-log.d.ts +5 -0
  69. package/dist/runtime/step-log.js +9 -4
  70. package/dist/runtime/waits.js +3 -1
  71. package/dist/tools/connector-content.js +1 -0
  72. package/dist/tools/connectors.service.js +9 -6
  73. package/dist/tools/drift.d.ts +5 -1
  74. package/dist/tools/drift.js +9 -4
  75. package/dist/tools/pipeline.js +1 -0
  76. package/package.json +3 -3
  77. package/src/migrations/0145_org_network_allowances.sql +12 -0
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  import { Module } from "@nestjs/common";
8
8
  import { SuperAdminLockModule } from "../identity/super-admin.js";
9
9
  import { ModelsModule } from "../models/models.module.js";
10
+ import { OrgNetworkAllowancesModule } from "../orgs/network-allowances.service.js";
10
11
  import { OrgLockModule } from "../orgs/org-lock.js";
11
12
  import { StorageModule } from "../storage/storage.module.js";
12
13
  import { EmbedTokensModule } from "../ui/embed-token.js";
@@ -51,6 +52,8 @@ ExtensionsModule = __decorate([
51
52
  ModelsModule,
52
53
  // the lifecycle clears the `usage.report` subscriber cache on PLUGINS_CHANGED
53
54
  UsageSubscribersModule,
55
+ // ctx.net reads each org's allowed internal endpoints per call
56
+ OrgNetworkAllowancesModule,
54
57
  ],
55
58
  providers: [
56
59
  PluginInstallLock,
@@ -4,6 +4,7 @@ import type { core } from "zod";
4
4
  import type { KernelAppOptions } from "../app.js";
5
5
  import type { BusSubscriber } from "../ctx/bus.js";
6
6
  import { type Route } from "../ctx/create-ctx.js";
7
+ import { type ExtensionNetSeams } from "../ctx/net.js";
7
8
  import type { Keyring } from "../ctx/secrets.js";
8
9
  import type { PluginRouteTable } from "../http/plugin-dispatch.js";
9
10
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -11,6 +12,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
11
12
  import { LockService } from "../infra/lock/lock.service.js";
12
13
  import type { KernelLogger } from "../log.js";
13
14
  import { ModelEmbeddings } from "../models/embeddings.js";
15
+ import { OrgNetworkAllowances } from "../orgs/network-allowances.service.js";
14
16
  import { EmbedTokens } from "../ui/embed-token.js";
15
17
  import type { UiActionHandler, UiRender } from "../ui/registry.js";
16
18
  import { ExtensionApprovals, type PendingExtension } from "./approvals.js";
@@ -264,7 +266,11 @@ export declare class ExtensionHost {
264
266
  */
265
267
  effective: Pick<EffectiveConfigs, "get">,
266
268
  /** `ctx.models`: the embeddings broker (spec B §5.4). */
267
- models: Pick<ModelEmbeddings, "embed" | "describe">);
269
+ models: Pick<ModelEmbeddings, "embed" | "describe">,
270
+ /** `ctx.net`: the internal endpoints each org's extension requests may reach (read per call). */
271
+ allowances: OrgNetworkAllowances,
272
+ /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
273
+ netSeams?: ExtensionNetSeams);
268
274
  /** The startup config's `extensionConfig` (file / Nacos merged with env). */
269
275
  private get extensionConfig();
270
276
  /** `extensionPermissions.autoApprove` (development and trials only; see `planApprovals`). */
@@ -12,9 +12,10 @@ import { createRequire } from "node:module";
12
12
  import { dirname, isAbsolute, join, resolve as resolvePath } from "node:path";
13
13
  import { fileURLToPath, pathToFileURL } from "node:url";
14
14
  import { EXTENSION_POINT_CARDINALITY, parseExtensionPoint, SDK_VERSION, } from "@capybara-hq/plugin-sdk";
15
- import { Inject, Injectable } from "@nestjs/common";
15
+ import { Inject, Injectable, Optional } from "@nestjs/common";
16
16
  import { changedPaths, configFields, secretValues, unreachableSecrets } from "../config/fields.js";
17
17
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
18
+ import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
18
19
  import { kernelDb } from "../db/kernel-schema.js";
19
20
  import { migrate } from "../db/migrator.js";
20
21
  import { createDb } from "../db/pool.js";
@@ -25,6 +26,7 @@ import { LockService } from "../infra/lock/lock.service.js";
25
26
  import { KERNEL_LOGGER, KEYRING, REDIS, REDIS_SUBSCRIBER } from "../infra/tokens.js";
26
27
  import { KERNEL_APP_OPTIONS } from "../lifecycle/tokens.js";
27
28
  import { ModelEmbeddings } from "../models/embeddings.js";
29
+ import { OrgNetworkAllowances } from "../orgs/network-allowances.service.js";
28
30
  import { packagePath } from "../packages/tgz.js";
29
31
  import { EmbedTokens } from "../ui/embed-token.js";
30
32
  import { ExtensionApprovals, planApprovals, readSnapshots, withPreApproved, } from "./approvals.js";
@@ -411,7 +413,11 @@ let ExtensionHost = class ExtensionHost {
411
413
  */
412
414
  effective,
413
415
  /** `ctx.models`: the embeddings broker (spec B §5.4). */
414
- models) {
416
+ models,
417
+ /** `ctx.net`: the internal endpoints each org's extension requests may reach (read per call). */
418
+ allowances,
419
+ /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
420
+ netSeams) {
415
421
  this.registry = registry;
416
422
  this.installs = installs;
417
423
  this.approvals = approvals;
@@ -442,6 +448,7 @@ let ExtensionHost = class ExtensionHost {
442
448
  models,
443
449
  // ctx.models.embed fires model.request through the same registry (spec B §5.4)
444
450
  hooks: this.hooks,
451
+ net: { config, allowances, ...(netSeams !== undefined && { seams: netSeams }) },
445
452
  locks,
446
453
  runWorkers: c.roles.includes("worker"),
447
454
  log,
@@ -2386,6 +2393,9 @@ ExtensionHost = __decorate([
2386
2393
  __param(11, Inject(KERNEL_LOGGER)),
2387
2394
  __param(12, Inject(KERNEL_APP_OPTIONS)),
2388
2395
  __param(13, Inject(EffectiveConfigs)),
2389
- __param(14, Inject(ModelEmbeddings))
2396
+ __param(14, Inject(ModelEmbeddings)),
2397
+ __param(15, Inject(OrgNetworkAllowances)),
2398
+ __param(16, Optional()),
2399
+ __param(16, Inject(EXTENSION_NET_SEAMS))
2390
2400
  ], ExtensionHost);
2391
2401
  export { ExtensionHost };
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { FILE_PREVIEW_EXTENSION_POINT, previewerAccepts, validateUiView, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
+ import { attachmentContentMatches } from "../conversations/attachments.service.js";
13
14
  import { ConversationFiles } from "../conversations/files.js";
14
15
  import { ApiError } from "../errors.js";
15
16
  import { EffectiveConfigs } from "../extensions/effective-config.js";
@@ -268,6 +269,11 @@ let PreviewerRegistry = class PreviewerRegistry {
268
269
  const got = await store.get(file.objectKey, { signal: s });
269
270
  if (!got)
270
271
  throw new Error("the file is no longer available");
272
+ // an attachment replaced since it was checked is not the file any more
273
+ if (file.recorded && !attachmentContentMatches(file.recorded, got.head)) {
274
+ await got.body.cancel().catch(() => { });
275
+ throw new Error("the file is no longer available");
276
+ }
271
277
  if (!open || s.aborted) {
272
278
  await got.body.cancel().catch(() => { });
273
279
  throw expired();
@@ -12,6 +12,7 @@ import { AdminAgentsController } from "../admin/admin-agents.controller.js";
12
12
  import { AdminConnectorsController } from "../admin/admin-connectors.controller.js";
13
13
  import { AdminAuditController, OrgAuditController } from "../admin/audit.controller.js";
14
14
  import { AdminExtensionsController } from "../admin/extensions.controller.js";
15
+ import { AdminOrgNetworkController } from "../admin/org-network.controller.js";
15
16
  import { OutboxDeadController } from "../admin/outbox-dead.controller.js";
16
17
  import { AdminOverviewController } from "../admin/overview.controller.js";
17
18
  import { SetupController } from "../admin/setup.controller.js";
@@ -111,6 +112,7 @@ const CONTROLLERS = [
111
112
  OrgAuditController,
112
113
  AdminOverviewController,
113
114
  OutboxDeadController,
115
+ AdminOrgNetworkController,
114
116
  AdminExtensionsController,
115
117
  AdminCatalogController,
116
118
  AdminComponentsController,
@@ -8,8 +8,22 @@ interface TransactionStore {
8
8
  hooks: AfterCommitHook[];
9
9
  /** Set once the transaction settled: continuations that outlive it must not use it. */
10
10
  done: boolean;
11
+ /**
12
+ * How a fence admitted it (`withTransactionFence`), once the fence ran; undefined when no fence
13
+ * admitted it (no fence in context, or read only).
14
+ */
15
+ admission?: AdmissionMode;
11
16
  }
12
- export declare function withTransactionFence<T>(fence: () => Promise<void>, fn: () => Promise<T>): Promise<T>;
17
+ /** How a fence admits the transaction it runs in ({@link TransactionOptions.admission}). */
18
+ export interface FenceAdmission {
19
+ /** The transaction asked for shared admission (`admission: "shared"`). */
20
+ shared: boolean;
21
+ }
22
+ /** The mode a fence admitted a transaction in (a fence returning nothing admits exclusively). */
23
+ export type AdmissionMode = "shared" | "exclusive";
24
+ /** A fence: checks the caller's authority, takes its admission locks and says in which mode. */
25
+ export type TransactionFence = (admission: FenceAdmission) => Promise<AdmissionMode | undefined | void>;
26
+ export declare function withTransactionFence<T>(fence: TransactionFence, fn: () => Promise<T>): Promise<T>;
13
27
  export type Propagation = "required" | "requires_new" | "mandatory";
14
28
  export interface TransactionOptions {
15
29
  /**
@@ -23,9 +37,26 @@ export interface TransactionOptions {
23
37
  isolationLevel?: IsolationLevel;
24
38
  /** Access mode of a transaction this call opens (ignored when it joins one). */
25
39
  accessMode?: AccessMode;
40
+ /**
41
+ * How the caller's fence (`withTransactionFence`) admits a transaction this call opens (ignored
42
+ * when it joins one, or with no fence in context). Default: the fence's exclusive admission.
43
+ * `shared`: the run loop's own hot-path writes (event appends, checkpoints, the suspend), which
44
+ * the run fence admits under a shared lock so the runs of one org write in parallel
45
+ * (`RunExecution`); a fence may still admit it exclusively (inside a tool step).
46
+ */
47
+ admission?: "shared";
26
48
  }
27
49
  /** Queues `fn` on the current live root transaction; with none open, runs it at once. */
28
50
  export declare function queueAfterCommit(fn: AfterCommitHook): void;
51
+ /** Whether the live transaction in context was admitted by a fence (a claimed run's write). */
52
+ export declare function inFencedTransaction(): boolean;
53
+ /**
54
+ * Throws when the live transaction in context was admitted shared by the run fence
55
+ * (`RunExecution`): such a transaction holds conversation rows without the org row, so taking an
56
+ * org-level lock (`what`: the org row, a membership, an advisory lock) would invert the global lock
57
+ * order org admission → org row → conversations. Called by every org-level lock.
58
+ */
59
+ export declare function assertNotSharedAdmission(what: string): void;
29
60
  /** The transaction store in the current async context (used by `afterCommit`). */
30
61
  export declare function currentStore(): TransactionStore | undefined;
31
62
  /**
@@ -46,6 +46,22 @@ function liveStore() {
46
46
  const store = storage.getStore();
47
47
  return store && !store.done ? store : undefined;
48
48
  }
49
+ /** Whether the live transaction in context was admitted by a fence (a claimed run's write). */
50
+ export function inFencedTransaction() {
51
+ return liveStore()?.admission !== undefined;
52
+ }
53
+ /**
54
+ * Throws when the live transaction in context was admitted shared by the run fence
55
+ * (`RunExecution`): such a transaction holds conversation rows without the org row, so taking an
56
+ * org-level lock (`what`: the org row, a membership, an advisory lock) would invert the global lock
57
+ * order org admission → org row → conversations. Called by every org-level lock.
58
+ */
59
+ export function assertNotSharedAdmission(what) {
60
+ if (liveStore()?.admission === "shared") {
61
+ throw new Error(`${what} inside a transaction the run fence admitted shared: hot-path writes take no ` +
62
+ 'org-level lock (open it without admission: "shared")');
63
+ }
64
+ }
49
65
  /** The transaction store in the current async context (used by `afterCommit`). */
50
66
  export function currentStore() {
51
67
  return liveStore();
@@ -91,6 +107,13 @@ let TransactionHost = class TransactionHost {
91
107
  }
92
108
  if (propagation === "required" && this.current())
93
109
  return fn();
110
+ if (opts.admission === "shared" &&
111
+ opts.isolationLevel !== undefined &&
112
+ opts.isolationLevel !== "read committed") {
113
+ // shared admission reads the org row unlocked after the advisory lock: only a fresh
114
+ // statement snapshot (READ COMMITTED) sees a deletion that committed while it waited
115
+ throw new Error('admission: "shared" needs READ COMMITTED isolation');
116
+ }
94
117
  const hooks = [];
95
118
  let store;
96
119
  let result;
@@ -101,12 +124,15 @@ let TransactionHost = class TransactionHost {
101
124
  if (opts.accessMode !== undefined)
102
125
  builder = builder.setAccessMode(opts.accessMode);
103
126
  result = await builder.execute((trx) => {
104
- store = { pool: this.pool, trx, hooks, done: false };
105
- return storage.run(store, async () => {
127
+ const fence = opts.accessMode === "read only" ? undefined : fences.getStore();
128
+ const own = { pool: this.pool, trx, hooks, done: false };
129
+ store = own;
130
+ return storage.run(own, async () => {
106
131
  // PostgreSQL forbids row locks in a read-only snapshot and enforces that it cannot
107
132
  // mutate. Every later mutation or external dispatch still enters a writable fence.
108
- if (opts.accessMode !== "read only")
109
- await fences.getStore()?.();
133
+ if (fence) {
134
+ own.admission = (await fence({ shared: opts.admission === "shared" })) || "exclusive";
135
+ }
110
136
  return fn();
111
137
  });
112
138
  });
@@ -14,4 +14,20 @@ export declare class XactLock {
14
14
  constructor(db: KernelDb, txHost: TransactionHost);
15
15
  /** Takes the lock named `key` until the caller's transaction ends (waits while another holds it). */
16
16
  lock(key: string): Promise<void>;
17
+ /**
18
+ * The org admission lock in its shared mode: the run fence admitting a run's hot-path write
19
+ * (`RunExecution`). Shared holders never wait for each other; they wait for an exclusive holder,
20
+ * and also queue behind an exclusive waiter (PostgreSQL grants heavyweight locks in order), so
21
+ * org deletion and offboarding are never starved by a stream of run writes. Two-key form
22
+ * ({@link ORG_ADMISSION_SPACE}, org id): a key space apart from {@link lock}'s one-key locks.
23
+ */
24
+ admitOrgShared(orgId: string): Promise<void>;
25
+ /**
26
+ * The org admission lock in its exclusive mode: org deletion and offboarding (`OrgLock`), taken
27
+ * first in their transaction. Waits for every admitted hot-path write of the org and keeps new
28
+ * ones out until the transaction ends.
29
+ */
30
+ admitOrgExclusive(orgId: string): Promise<void>;
17
31
  }
32
+ /** The first key of the org admission lock ({@link XactLock.admitOrgShared}). */
33
+ export declare const ORG_ADMISSION_SPACE = "capybara.org-admission";
@@ -10,7 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { KernelDb } from "./kernel-db.js";
13
- import { TransactionHost } from "./transaction-host.js";
13
+ import { assertNotSharedAdmission, TransactionHost } from "./transaction-host.js";
14
14
  import { Transactional } from "./transactional.decorator.js";
15
15
  /**
16
16
  * Transaction-scoped advisory locks (decision R9 of the Nest kernel spec): `pg_advisory_xact_lock`
@@ -29,15 +29,42 @@ let XactLock = class XactLock {
29
29
  }
30
30
  /** Takes the lock named `key` until the caller's transaction ends (waits while another holds it). */
31
31
  async lock(key) {
32
+ assertNotSharedAdmission(`the advisory lock ${key}`);
32
33
  await sql `SELECT pg_advisory_xact_lock(hashtext(${key}))`.execute(this.db.db);
33
34
  }
35
+ /**
36
+ * The org admission lock in its shared mode: the run fence admitting a run's hot-path write
37
+ * (`RunExecution`). Shared holders never wait for each other; they wait for an exclusive holder,
38
+ * and also queue behind an exclusive waiter (PostgreSQL grants heavyweight locks in order), so
39
+ * org deletion and offboarding are never starved by a stream of run writes. Two-key form
40
+ * ({@link ORG_ADMISSION_SPACE}, org id): a key space apart from {@link lock}'s one-key locks.
41
+ */
42
+ async admitOrgShared(orgId) {
43
+ await sql `SELECT pg_advisory_xact_lock_shared(hashtext(${ORG_ADMISSION_SPACE}), hashtext(${orgId}))`.execute(this.db.db);
44
+ }
45
+ /**
46
+ * The org admission lock in its exclusive mode: org deletion and offboarding (`OrgLock`), taken
47
+ * first in their transaction. Waits for every admitted hot-path write of the org and keeps new
48
+ * ones out until the transaction ends.
49
+ */
50
+ async admitOrgExclusive(orgId) {
51
+ await sql `SELECT pg_advisory_xact_lock(hashtext(${ORG_ADMISSION_SPACE}), hashtext(${orgId}))`.execute(this.db.db);
52
+ }
34
53
  };
35
54
  __decorate([
36
55
  Transactional({ propagation: "mandatory" })
37
56
  ], XactLock.prototype, "lock", null);
57
+ __decorate([
58
+ Transactional({ propagation: "mandatory" })
59
+ ], XactLock.prototype, "admitOrgShared", null);
60
+ __decorate([
61
+ Transactional({ propagation: "mandatory" })
62
+ ], XactLock.prototype, "admitOrgExclusive", null);
38
63
  XactLock = __decorate([
39
64
  Injectable(),
40
65
  __param(0, Inject(KernelDb)),
41
66
  __param(1, Inject(TransactionHost))
42
67
  ], XactLock);
43
68
  export { XactLock };
69
+ /** The first key of the org admission lock ({@link XactLock.admitOrgShared}). */
70
+ export const ORG_ADMISSION_SPACE = "capybara.org-admission";
@@ -1,7 +1,12 @@
1
1
  /** Whether connecting to this (resolved) IP is forbidden: private, loopback, reserved, or unparseable. */
2
2
  export declare function isForbiddenAddress(ip: string): boolean;
3
- /** Link-local (incl. cloud metadata 169.254.169.254) or unparseable: forbidden whatever the exemptions. */
3
+ /**
4
+ * Link-local (incl. cloud metadata 169.254.169.254), another cloud metadata endpoint
5
+ * (`100.100.100.200`, `fd00:ec2::254`) or unparseable: forbidden whatever the exemptions.
6
+ */
4
7
  export declare function isLinkLocalAddress(ip: string): boolean;
8
+ /** Loopback (`127.0.0.0/8`, `::1`) or unspecified (`0.0.0.0/8`, `::`), embedded forms included. */
9
+ export declare function isLoopbackOrUnspecifiedAddress(ip: string): boolean;
5
10
  /** A hostname normalized for comparison: lower case, no IPv6 brackets, no trailing dots. */
6
11
  export declare function normalizeHost(host: string): string;
7
12
  /** `localhost`, `127.0.0.0/8` or `::1` (as written in a URL). */
@@ -30,6 +35,15 @@ export type NetPolicy = {
30
35
  url: string;
31
36
  noProxy: string[];
32
37
  };
38
+ /**
39
+ * Set for an extension's request (`ctx.net.fetch`): loopback and unspecified addresses are
40
+ * refused whatever the exemptions (unless `allowInsecureLoopback`), `*.domain` entries in
41
+ * `allowPrivateHosts` match subdomains (never the apex), and a refused private address says
42
+ * `privateHint` (where such an endpoint is allowed) instead of the marketplace hint.
43
+ */
44
+ extension?: {
45
+ privateHint: string;
46
+ };
33
47
  };
34
48
  export type LookupFn = (host: string) => Promise<{
35
49
  address: string;
@@ -60,6 +74,12 @@ export declare function parseCidr(s: string): [string, number, "ipv4" | "ipv6"]
60
74
  export declare function privateHostEntryProblem(entry: string): string | null;
61
75
  /** A valid `marketplaces.allowPrivateHosts` entry (see {@link privateHostEntryProblem}). */
62
76
  export declare function isPrivateHostEntry(entry: string): boolean;
77
+ /**
78
+ * Whether a host entry of `policy.allowPrivateHosts` (a hostname, a `*.domain` wildcard, an IP or a
79
+ * CIDR) names `host`, ignoring trusted origins: such entries exempt https requests only, so a
80
+ * refused plain-http request to that host can point at an `http://host:port` origin entry.
81
+ */
82
+ export declare function hostEntryExempts(host: string, policy: NetPolicy): boolean;
63
83
  /**
64
84
  * Resolves `host` (an IP literal is taken as is) and returns every address, in resolution order,
65
85
  * after checking that each is public or exempt by `policy`. `origin` is the request URL's origin:
@@ -15,8 +15,12 @@ import { BlockList, isIP } from "node:net";
15
15
  * the embedded IPv4 address (proxy.mjs falls through to the IPv6 table, where they are not blocked);
16
16
  * a host behind a SIIT translator could otherwise reach a private IPv4 address.
17
17
  *
18
- * Link-local addresses (`169.254.0.0/16`, including cloud metadata, and `fe80::/10`) stay forbidden
19
- * whatever the exemptions: no internal mirror lives there.
18
+ * Link-local addresses (`169.254.0.0/16`, including cloud metadata, and `fe80::/10`) and the cloud
19
+ * metadata endpoints outside link-local (AWS IPv6 `fd00:ec2::254`, Alibaba Cloud `100.100.100.200`)
20
+ * stay forbidden whatever the exemptions: no internal mirror lives there.
21
+ *
22
+ * Extension requests (`ctx.net`, {@link NetPolicy.extension}) also refuse loopback and unspecified
23
+ * addresses whatever the exemptions (the kernel's own host), unless `allowInsecureLoopback` (tests).
20
24
  */
21
25
  const BLOCKED_V4 = [
22
26
  ["0.0.0.0", 8], // unspecified / this network
@@ -51,9 +55,18 @@ for (const [a, p] of BLOCKED_V4)
51
55
  blocked.addSubnet(a, p, "ipv4");
52
56
  for (const [a, p] of BLOCKED_V6)
53
57
  blocked.addSubnet(a, p, "ipv6");
54
- const linkLocal = new BlockList();
55
- linkLocal.addSubnet("169.254.0.0", 16, "ipv4");
56
- linkLocal.addSubnet("fe80::", 10, "ipv6");
58
+ /** Never allowed, whatever the exemptions: link-local and the cloud metadata endpoints. */
59
+ const neverAllowed = new BlockList();
60
+ neverAllowed.addSubnet("169.254.0.0", 16, "ipv4");
61
+ neverAllowed.addSubnet("fe80::", 10, "ipv6");
62
+ neverAllowed.addAddress("100.100.100.200", "ipv4"); // Alibaba Cloud metadata (inside CGNAT)
63
+ neverAllowed.addAddress("fd00:ec2::254", "ipv6"); // AWS IMDS over IPv6 (inside ULA)
64
+ /** Loopback and unspecified: never allowed for extension requests (see the file header). */
65
+ const loopbackOrUnspecified = new BlockList();
66
+ loopbackOrUnspecified.addSubnet("127.0.0.0", 8, "ipv4");
67
+ loopbackOrUnspecified.addSubnet("0.0.0.0", 8, "ipv4");
68
+ loopbackOrUnspecified.addAddress("::1", "ipv6");
69
+ loopbackOrUnspecified.addAddress("::", "ipv6");
57
70
  /** An IPv6 address as its 8 16-bit groups; null when it cannot be parsed. */
58
71
  function v6Groups(ip) {
59
72
  let s = ip.toLowerCase();
@@ -118,9 +131,16 @@ function inTable(ip, table) {
118
131
  export function isForbiddenAddress(ip) {
119
132
  return inTable(ip, blocked);
120
133
  }
121
- /** Link-local (incl. cloud metadata 169.254.169.254) or unparseable: forbidden whatever the exemptions. */
134
+ /**
135
+ * Link-local (incl. cloud metadata 169.254.169.254), another cloud metadata endpoint
136
+ * (`100.100.100.200`, `fd00:ec2::254`) or unparseable: forbidden whatever the exemptions.
137
+ */
122
138
  export function isLinkLocalAddress(ip) {
123
- return inTable(ip, linkLocal);
139
+ return inTable(ip, neverAllowed);
140
+ }
141
+ /** Loopback (`127.0.0.0/8`, `::1`) or unspecified (`0.0.0.0/8`, `::`), embedded forms included. */
142
+ export function isLoopbackOrUnspecifiedAddress(ip) {
143
+ return inTable(ip, loopbackOrUnspecified);
124
144
  }
125
145
  /** A hostname normalized for comparison: lower case, no IPv6 brackets, no trailing dots. */
126
146
  export function normalizeHost(host) {
@@ -201,6 +221,14 @@ function exemptions(host, policy, origin) {
201
221
  cidrs.addAddress("::1", "ipv6");
202
222
  }
203
223
  for (const entry of policy.allowPrivateHosts) {
224
+ // a `*.domain` wildcard (extension requests): a name under the domain, never the apex
225
+ if (entry.startsWith("*.")) {
226
+ const base = normalizeHost(entry.slice(2));
227
+ if (policy.extension && !literal && HOSTNAME.test(base) && host.endsWith(`.${base}`)) {
228
+ all = true;
229
+ }
230
+ continue;
231
+ }
204
232
  if (!isPrivateHostEntry(entry))
205
233
  continue;
206
234
  const cidr = parseCidr(entry);
@@ -248,6 +276,15 @@ function allowedBy(cidrs, ip) {
248
276
  }
249
277
  return false;
250
278
  }
279
+ /**
280
+ * Whether a host entry of `policy.allowPrivateHosts` (a hostname, a `*.domain` wildcard, an IP or a
281
+ * CIDR) names `host`, ignoring trusted origins: such entries exempt https requests only, so a
282
+ * refused plain-http request to that host can point at an `http://host:port` origin entry.
283
+ */
284
+ export function hostEntryExempts(host, policy) {
285
+ const { all, cidrs } = exemptions(host, { ...policy, allowInsecureLoopback: false }, undefined);
286
+ return all || (isIP(host) !== 0 && allowedBy(cidrs, host));
287
+ }
251
288
  /**
252
289
  * Resolves `host` (an IP literal is taken as is) and returns every address, in resolution order,
253
290
  * after checking that each is public or exempt by `policy`. `origin` is the request URL's origin:
@@ -272,11 +309,20 @@ export async function resolvePublic(host, policy, lookup = defaultLookup, origin
272
309
  throw new NetDeniedError("net.dns_failed", h, `Cannot resolve ${h}.`);
273
310
  }
274
311
  const ex = exemptions(h, policy, origin);
275
- const refused = (a) => isForbiddenAddress(a) && (isLinkLocalAddress(a) || (!ex.all && !allowedBy(ex.cidrs, a)));
312
+ // extension requests never reach the kernel's own host, whatever the exemptions
313
+ const ownHost = (a) => policy.extension !== undefined &&
314
+ !policy.allowInsecureLoopback &&
315
+ isLoopbackOrUnspecifiedAddress(a);
316
+ const refused = (a) => isForbiddenAddress(a) &&
317
+ (isLinkLocalAddress(a) || ownHost(a) || (!ex.all && !allowedBy(ex.cidrs, a)));
276
318
  if (addrs.some(refused)) {
319
+ const hint = policy.extension?.privateHint ??
320
+ "add the hostname to marketplaces.allowPrivateHosts to allow an internal host";
277
321
  throw new NetDeniedError("net.private_address", h, addrs.some(isLinkLocalAddress)
278
- ? `Access to ${h} is refused: it resolves to a link-local address, which is never allowed.`
279
- : `Access to ${h} is refused: it resolves to a private or reserved address (add the hostname to marketplaces.allowPrivateHosts to allow an internal host).`);
322
+ ? `Access to ${h} is refused: it resolves to a link-local or cloud metadata address, which is never allowed.`
323
+ : addrs.some(ownHost)
324
+ ? `Access to ${h} is refused: it resolves to a loopback address (the kernel's own host), which is never allowed.`
325
+ : `Access to ${h} is refused: it resolves to a private or reserved address (${hint}).`);
280
326
  }
281
327
  return addrs;
282
328
  }
@@ -12,7 +12,8 @@ import { type LookupFn, type NetPolicy } from "./public-address.js";
12
12
  * `noProxy` tunnels through the proxy (`proxy.ts`) instead: the host is not resolved locally
13
13
  * (the proxy resolves it and owns SSRF protection for the resolved address), but an IP-literal
14
14
  * host is still checked against the private ranges and `allowPrivateHosts`;
15
- * - redirects are never followed: a 3xx (other than 304) is {@link NetDeniedError} `net.redirect`;
15
+ * - redirects are never followed: a 3xx (other than 304) is {@link NetDeniedError} `net.redirect`,
16
+ * or, with `redirects: "return"`, returned to the caller as is (its body unread);
16
17
  * - with `maxBytes`, a declared or streamed body over the limit is {@link NetBodyTooLargeError}.
17
18
  */
18
19
  /** The response body is larger than `maxBytes`. */
@@ -32,6 +33,8 @@ export declare function safeFetch(url: string, init: RequestInit & {
32
33
  }, policy: NetPolicy, opts?: {
33
34
  lookup?: LookupFn;
34
35
  maxBytes?: number;
36
+ /** A 3xx response (other than 304): `refuse` (default) rejects with `net.redirect`, `return` returns it. */
37
+ redirects?: "refuse" | "return";
35
38
  /** Tests only: wraps the pinned dispatcher (defaults to {@link pinnedAgent}). */
36
39
  dispatcherFor?: (ips: string[]) => Agent;
37
40
  /** Tests only: builds the proxy dispatcher (defaults to {@link proxyAgent}). */
@@ -1,7 +1,7 @@
1
1
  import { isIP } from "node:net";
2
2
  import { Agent, fetch as undiciFetch } from "undici";
3
3
  import { bypassesProxy, proxyAgent } from "./proxy.js";
4
- import { isLoopbackHost, NetDeniedError, normalizeHost, resolvePublic, } from "./public-address.js";
4
+ import { hostEntryExempts, isLoopbackHost, NetDeniedError, normalizeHost, resolvePublic, } from "./public-address.js";
5
5
  /**
6
6
  * `fetch` for URLs that come from a marketplace or an admin (spec §5.1):
7
7
  * - https only; plain http only for a loopback host under `allowInsecureLoopback` (testing), or
@@ -14,7 +14,8 @@ import { isLoopbackHost, NetDeniedError, normalizeHost, resolvePublic, } from ".
14
14
  * `noProxy` tunnels through the proxy (`proxy.ts`) instead: the host is not resolved locally
15
15
  * (the proxy resolves it and owns SSRF protection for the resolved address), but an IP-literal
16
16
  * host is still checked against the private ranges and `allowPrivateHosts`;
17
- * - redirects are never followed: a 3xx (other than 304) is {@link NetDeniedError} `net.redirect`;
17
+ * - redirects are never followed: a 3xx (other than 304) is {@link NetDeniedError} `net.redirect`,
18
+ * or, with `redirects: "return"`, returned to the caller as is (its body unread);
18
19
  * - with `maxBytes`, a declared or streamed body over the limit is {@link NetBodyTooLargeError}.
19
20
  */
20
21
  /** The response body is larger than `maxBytes`. */
@@ -83,7 +84,14 @@ export async function safeFetch(url, init, policy, opts = {}) {
83
84
  ((policy.allowInsecureLoopback && isLoopbackHost(host)) ||
84
85
  policy.trustedOrigins.some((o) => originOf(o) === target.origin));
85
86
  if (target.protocol !== "https:" && !insecureOk) {
86
- throw new NetDeniedError("net.insecure_url", host, `The URL must use https (${host}).`);
87
+ // an extension request to a host the org allows only as a host entry (https only): name the
88
+ // origin entry that would allow plain http
89
+ const hint = policy.extension !== undefined &&
90
+ target.protocol === "http:" &&
91
+ hostEntryExempts(host, policy)
92
+ ? ` ${host} is allowed for the organization over https only; to allow plain http, ask a super admin to allow the origin ${target.origin}.`
93
+ : "";
94
+ throw new NetDeniedError("net.insecure_url", host, `The URL must use https (${host}).${hint}`);
87
95
  }
88
96
  const proxy = policy.proxy;
89
97
  const proxied = proxy !== undefined &&
@@ -126,7 +134,10 @@ export async function safeFetch(url, init, policy, opts = {}) {
126
134
  }
127
135
  // close() waits for the in-flight request (the body still being read) before it closes
128
136
  void agent.close().catch(() => { });
129
- if (res.status >= 300 && res.status < 400 && res.status !== 304) {
137
+ if (res.status >= 300 &&
138
+ res.status < 400 &&
139
+ res.status !== 304 &&
140
+ (opts.redirects ?? "refuse") === "refuse") {
130
141
  await res.body?.cancel().catch(() => { });
131
142
  throw new NetDeniedError("net.redirect", host, `${host} responded with a redirect (${res.status}); redirects are not followed.`, res.status);
132
143
  }
@@ -599,6 +599,8 @@ let DirectorySync = class DirectorySync {
599
599
  }
600
600
  }
601
601
  async offboardIn(orgId, source, accountId) {
602
+ // offboarding: the org admission lock first (`Offboarding.offboard`)
603
+ await this.orgLock.lockForRemoval(orgId);
602
604
  if (!(await this.orgLock.tryLock(orgId)))
603
605
  return undefined;
604
606
  const row = await this.db
@@ -143,6 +143,10 @@ let MembersService = class MembersService {
143
143
  await this.removeIn(orgId, targetId, actorAccountId, actorTokenId);
144
144
  }
145
145
  async removeIn(orgId, targetId, actorAccountId, actorTokenId) {
146
+ // an unauthorized call is refused before it holds off the org's run writes
147
+ await this.orgLock.precheck(orgId, actorAccountId, "org.members.manage");
148
+ // offboarding: the org admission lock first (`Offboarding.offboard`)
149
+ await this.orgLock.lockForRemoval(orgId);
146
150
  const { role: actorRole } = await this.orgLock.lockAndAuthorize(orgId, actorAccountId, "org.members.manage");
147
151
  const before = await this.requireMember(orgId, targetId);
148
152
  await rejectAnonymousGuest(this.db.db, targetId);
@@ -167,6 +171,7 @@ let MembersService = class MembersService {
167
171
  await this.leaveIn(orgId, accountId, actorTokenId);
168
172
  }
169
173
  async leaveIn(orgId, accountId, actorTokenId) {
174
+ await this.orgLock.lockForRemoval(orgId);
170
175
  await this.orgLock.lock(orgId);
171
176
  const before = await this.requireMember(orgId, accountId);
172
177
  const actor = {