@capybara-hq/kernel 0.1.0-rc.131 → 0.1.0-rc.133

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 (155) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/admin.schemas.d.ts +4 -0
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/admin/setup.service.js +6 -1
  7. package/dist/agents/agents.controller.js +3 -2
  8. package/dist/agents/agents.service.d.ts +2 -0
  9. package/dist/agents/agents.service.js +7 -0
  10. package/dist/catalog/catalog.service.d.ts +2 -0
  11. package/dist/catalog/catalog.service.js +28 -5
  12. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  13. package/dist/catalog/marketplace-fetch.js +15 -0
  14. package/dist/catalog/marketplaces.service.d.ts +4 -4
  15. package/dist/catalog/marketplaces.service.js +3 -2
  16. package/dist/catalog/owned-items.d.ts +2 -0
  17. package/dist/catalog/owned-items.js +30 -31
  18. package/dist/catalog/ownership.js +40 -38
  19. package/dist/catalog/plugin-import.d.ts +6 -5
  20. package/dist/catalog/plugin-import.js +69 -16
  21. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  22. package/dist/catalog/plugin-upgrade.js +95 -7
  23. package/dist/catalog/publisher-policy.d.ts +9 -0
  24. package/dist/catalog/publisher-policy.js +12 -0
  25. package/dist/catalog/unshare.js +66 -58
  26. package/dist/client/client-access.service.js +5 -3
  27. package/dist/config/schema.d.ts +1 -0
  28. package/dist/config/schema.js +9 -1
  29. package/dist/conversations/conversations.controller.js +4 -14
  30. package/dist/conversations/conversations.service.d.ts +14 -0
  31. package/dist/conversations/conversations.service.js +20 -2
  32. package/dist/ctx/create-ctx.d.ts +14 -4
  33. package/dist/ctx/create-ctx.js +131 -59
  34. package/dist/ctx/queue.js +7 -4
  35. package/dist/db/extension-db.d.ts +30 -0
  36. package/dist/db/extension-db.js +91 -0
  37. package/dist/db/extension-rls-predicate.d.ts +1 -0
  38. package/dist/db/extension-rls-predicate.js +8 -0
  39. package/dist/db/extension-schema-transfer.d.ts +6 -0
  40. package/dist/db/extension-schema-transfer.js +141 -0
  41. package/dist/db/kernel-schema.d.ts +50 -4
  42. package/dist/db/migrator.d.ts +6 -0
  43. package/dist/db/migrator.js +35 -7
  44. package/dist/db/pool.d.ts +6 -2
  45. package/dist/db/pool.js +37 -2
  46. package/dist/db/sql-statements.d.ts +3 -0
  47. package/dist/db/sql-statements.js +15 -5
  48. package/dist/device-access/device-access.module.js +12 -2
  49. package/dist/device-access/device-access.service.d.ts +30 -2
  50. package/dist/device-access/device-access.service.js +38 -4
  51. package/dist/device-access/host-gate.d.ts +45 -0
  52. package/dist/device-access/host-gate.js +92 -0
  53. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  54. package/dist/device-access/host-service-stop-sweep.js +112 -0
  55. package/dist/device-access/host-service-stop.d.ts +78 -0
  56. package/dist/device-access/host-service-stop.js +144 -0
  57. package/dist/device-access/host-services.d.ts +211 -0
  58. package/dist/device-access/host-services.js +803 -0
  59. package/dist/device-access/person-handles.d.ts +10 -0
  60. package/dist/device-access/person-handles.js +25 -0
  61. package/dist/device-access/service-events.d.ts +199 -0
  62. package/dist/device-access/service-events.js +704 -0
  63. package/dist/device-access/token.d.ts +5 -0
  64. package/dist/device-access/token.js +5 -0
  65. package/dist/devices/devices.service.js +3 -0
  66. package/dist/dial-in/access.d.ts +5 -5
  67. package/dist/dial-in/access.js +19 -12
  68. package/dist/dial-in/gateway.js +6 -2
  69. package/dist/dial-in/machines.d.ts +9 -2
  70. package/dist/dial-in/machines.js +27 -4
  71. package/dist/erasure/device-cleanup.js +12 -0
  72. package/dist/erasure/org-catalog.js +2 -2
  73. package/dist/erasure/org-rules.js +9 -0
  74. package/dist/errors.d.ts +2 -0
  75. package/dist/errors.js +2 -0
  76. package/dist/extensions/admin-ops.d.ts +3 -1
  77. package/dist/extensions/admin-ops.js +19 -9
  78. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  79. package/dist/extensions/deployed-snapshots.js +7 -2
  80. package/dist/extensions/extensions.module.js +3 -0
  81. package/dist/extensions/host.d.ts +11 -3
  82. package/dist/extensions/host.js +40 -8
  83. package/dist/extensions/instance.d.ts +6 -0
  84. package/dist/extensions/instance.js +7 -1
  85. package/dist/extensions/ledger.d.ts +1 -1
  86. package/dist/extensions/lifecycle-hooks.js +3 -3
  87. package/dist/extensions/migrate-lock.d.ts +4 -1
  88. package/dist/extensions/migrate-lock.js +19 -2
  89. package/dist/extensions/org-config.js +6 -1
  90. package/dist/extensions/permission-set.d.ts +7 -0
  91. package/dist/extensions/permission-set.js +10 -0
  92. package/dist/extensions/permission-view.d.ts +1 -1
  93. package/dist/extensions/permission-view.js +10 -1
  94. package/dist/git/tickets.js +32 -27
  95. package/dist/http/app.js +5 -3
  96. package/dist/identity/accounts.d.ts +6 -1
  97. package/dist/identity/accounts.js +11 -2
  98. package/dist/identity/api-tokens.js +7 -6
  99. package/dist/identity/settings.d.ts +9 -1
  100. package/dist/identity/settings.js +16 -1
  101. package/dist/inbox/org-notices.js +3 -2
  102. package/dist/index.d.ts +1 -0
  103. package/dist/index.js +1 -0
  104. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  105. package/dist/infra/database/scoped-dialect.js +260 -72
  106. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  107. package/dist/infra/database/startup-activation-transaction.js +3 -2
  108. package/dist/infra/outbox/registry.d.ts +28 -14
  109. package/dist/infra/outbox/registry.js +30 -15
  110. package/dist/infra/queue/queue-names.d.ts +1 -1
  111. package/dist/infra/queue/queue-names.js +1 -0
  112. package/dist/infra/queue/run-job.d.ts +4 -1
  113. package/dist/infra/queue/run-job.js +10 -2
  114. package/dist/kernel.js +4 -0
  115. package/dist/kernel.module.js +3 -0
  116. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  117. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  118. package/dist/orgs/offboarding.js +18 -9
  119. package/dist/orgs/settings.service.js +3 -0
  120. package/dist/packages/npm-publish-keys.json +27 -0
  121. package/dist/packages/official-publisher.d.ts +19 -0
  122. package/dist/packages/official-publisher.js +152 -0
  123. package/dist/packages/provenance.d.ts +7 -0
  124. package/dist/packages/provenance.js +22 -19
  125. package/dist/packages/sigstore-trusted-root.json +126 -0
  126. package/dist/platform/ops/admin.ops.js +2 -1
  127. package/dist/platform/ops/orgs.ops.js +1 -0
  128. package/dist/roles/worker-role.d.ts +6 -3
  129. package/dist/roles/worker-role.js +12 -4
  130. package/dist/roles/worker.module.js +7 -6
  131. package/dist/runtime/maintenance.d.ts +5 -4
  132. package/dist/runtime/maintenance.js +16 -13
  133. package/dist/sandbox/device-reports.d.ts +4 -4
  134. package/dist/sandbox/device-reports.js +40 -30
  135. package/dist/sandbox/device-services.d.ts +2 -1
  136. package/dist/sandbox/device-services.js +5 -1
  137. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  138. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  139. package/dist/sandbox/permission-config-publication.js +5 -1
  140. package/dist/themes/theme-state.js +24 -13
  141. package/dist/tools/call-scope.d.ts +6 -0
  142. package/dist/tools/call-scope.js +22 -0
  143. package/dist/tools/registry.js +20 -2
  144. package/dist/ui/views.js +36 -8
  145. package/package.json +9 -4
  146. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  147. package/src/migrations/0220_require_event_org.sql +18 -0
  148. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  149. package/src/migrations/0222_device_host_services.sql +27 -0
  150. package/src/migrations/0223_device_service_events.sql +54 -0
  151. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
  152. package/dist/conversations/event-org-backfill.d.ts +0 -111
  153. package/dist/conversations/event-org-backfill.js +0 -264
  154. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
  155. package/dist/conversations/event-org-backfill.module.js +0 -18
@@ -27,6 +27,7 @@ export const FutureIsoDate = z.iso
27
27
  .refine((s) => new Date(s).getTime() > Date.now(), "must be in the future")
28
28
  .transform((s) => new Date(s));
29
29
  const PREFIX = { personal: "cap_pat_", service: "cap_svc_" };
30
+ const tokenTouchDue = sql `(last_used_at is null or last_used_at < now() - interval '5 minutes')`;
30
31
  function toRecord(r) {
31
32
  return {
32
33
  id: r.id,
@@ -141,6 +142,7 @@ let ApiTokenService = class ApiTokenService {
141
142
  const row = await this.db
142
143
  .selectFrom("api_tokens")
143
144
  .selectAll()
145
+ .select(tokenTouchDue.as("touch_due"))
144
146
  .where("token_hash", "=", sha256Hex(token))
145
147
  .where("kind", "=", kind)
146
148
  .where("revoked_at", "is", null)
@@ -148,19 +150,18 @@ let ApiTokenService = class ApiTokenService {
148
150
  .executeTakeFirst();
149
151
  if (!row)
150
152
  return null;
151
- // Touch the token at most once every five minutes.
153
+ const record = toRecord(row);
154
+ // Skip the usual no-op write. The write also checks the deadline for concurrent callers.
155
+ if (!row.touch_due)
156
+ return record;
152
157
  // org-filter: deployment-wide update by primary key of the token authenticated above.
153
158
  const touched = await this.db
154
159
  .updateTable("api_tokens")
155
160
  .set({ last_used_at: sql `now()` })
156
161
  .where("id", "=", row.id)
157
- .where((eb) => eb.or([
158
- eb("last_used_at", "is", null),
159
- eb("last_used_at", "<", sql `now() - interval '5 minutes'`),
160
- ]))
162
+ .where(tokenTouchDue)
161
163
  .returning("last_used_at")
162
164
  .executeTakeFirst();
163
- const record = toRecord(row);
164
165
  if (touched)
165
166
  record.lastUsedAt = touched.last_used_at;
166
167
  return record;
@@ -203,6 +203,10 @@ export declare const DEPLOYMENT_SETTINGS: z.ZodObject<{
203
203
  }, z.core.$strict>>;
204
204
  }, z.core.$strict>>;
205
205
  }, z.core.$strict>>;
206
+ officialPublisherProof: z.ZodDefault<z.ZodEnum<{
207
+ "pin-only": "pin-only";
208
+ require: "require";
209
+ }>>;
206
210
  priceCurrency: z.ZodDefault<z.ZodString>;
207
211
  sandboxLimitOverrides: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
208
212
  cpu: z.ZodOptional<z.ZodNumber>;
@@ -329,6 +333,10 @@ export declare const DEPLOYMENT_SETTINGS_PATCH: z.ZodObject<{
329
333
  }, z.core.$strict>>;
330
334
  }, z.core.$strict>>;
331
335
  }, z.core.$strict>>>;
336
+ officialPublisherProof: z.ZodOptional<z.ZodEnum<{
337
+ "pin-only": "pin-only";
338
+ require: "require";
339
+ }>>;
332
340
  priceCurrency: z.ZodOptional<z.ZodString>;
333
341
  sandboxLimitOverrides: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodObject<{
334
342
  cpu: z.ZodOptional<z.ZodNumber>;
@@ -542,7 +550,7 @@ export declare class SettingsService {
542
550
  * `onlyNarrows` (an API token, the Platform tool): `devicesOutsideSandbox` may only turn it off,
543
551
  * `devicesNetwork` may only narrow to the allowlist,
544
552
  * `externalSharing` may only turn external sharing off, `shareMaxExpiryDays` may only decrease and
545
- * `htmlRenderCdnAllowlist` may only shrink.
553
+ * `htmlRenderCdnAllowlist` may only shrink. Only a web session may choose pin-only publisher proof.
546
554
  */
547
555
  update(patch: DeploymentSettingsPatch, actorAccountId: string, actorTokenId?: string,
548
556
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */
@@ -11,6 +11,7 @@ import { EXTENSION_NAME_RE, narrowerProjectReach } from "@capybara-hq/plugin-sdk
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { z } from "zod";
13
13
  import { applyPlatformAttributionPatch, PLATFORM_ATTRIBUTION_FIELDS, PLATFORM_ATTRIBUTION_PATCH, PLATFORM_ATTRIBUTION_SETTING, readStoredPlatformAttribution, resolvePlatformAttribution, } from "../attribution/platform-attribution.js";
14
+ import { OfficialPublisherProofMode, officialPublisherProofMode, } from "../catalog/publisher-policy.js";
14
15
  import { productName } from "../config/product-name.js";
15
16
  import { DEVICES_DEFAULT_PROVIDER_PATCH, DEVICES_DEFAULT_PROVIDER_SETTING, readPlatformDefaultProvider, } from "../devices/default-provider-setting.js";
16
17
  import { ApiError } from "../errors.js";
@@ -208,6 +209,7 @@ export const DEPLOYMENT_SETTINGS = z.object({
208
209
  runConcurrencyOverrides: z.record(z.string().min(1), z.number().int().positive()).default({}),
209
210
  retention: StoredPlatformRetentionSchema.default(OFF_RETENTION),
210
211
  modelBudgets: PlatformModelBudgetsSchema.default({}),
212
+ officialPublisherProof: OfficialPublisherProofMode.default("require"),
211
213
  /** The currency of model prices used for cost estimates, without conversion. */
212
214
  priceCurrency: PriceCurrency.default(DEFAULT_PRICE_CURRENCY),
213
215
  /** 按组织覆盖沙箱 cpu / 内存(orgId → 覆盖,C19);只对之后新建的沙箱生效。组织管理员只读。 */
@@ -297,6 +299,7 @@ export const DEPLOYMENT_SETTINGS_PATCH = z
297
299
  retention: PlatformRetentionSchema.partial().optional(),
298
300
  confirmRetentionShortening: z.literal(true).optional(),
299
301
  modelBudgets: PlatformModelBudgetsSchema.nullable().optional(),
302
+ officialPublisherProof: OfficialPublisherProofMode.optional(),
300
303
  priceCurrency: PriceCurrency.optional(),
301
304
  sandboxLimitOverrides: z
302
305
  .record(z.string().min(1), SANDBOX_LIMIT_OVERRIDE.nullable())
@@ -793,7 +796,7 @@ let SettingsService = class SettingsService {
793
796
  * `onlyNarrows` (an API token, the Platform tool): `devicesOutsideSandbox` may only turn it off,
794
797
  * `devicesNetwork` may only narrow to the allowlist,
795
798
  * `externalSharing` may only turn external sharing off, `shareMaxExpiryDays` may only decrease and
796
- * `htmlRenderCdnAllowlist` may only shrink.
799
+ * `htmlRenderCdnAllowlist` may only shrink. Only a web session may choose pin-only publisher proof.
797
800
  */
798
801
  async update(patch, actorAccountId, actorTokenId,
799
802
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */
@@ -881,6 +884,14 @@ let SettingsService = class SettingsService {
881
884
  }
882
885
  if (patch.orgCreation !== undefined)
883
886
  next.orgCreation = patch.orgCreation;
887
+ let officialPublisherProofPrevious;
888
+ if (patch.officialPublisherProof !== undefined) {
889
+ if (opts.onlyNarrows && patch.officialPublisherProof === "pin-only") {
890
+ throw new ApiError("deployment.publisher_policy_requires_session", "Switch to pin-only from the admin console in a super admin session");
891
+ }
892
+ officialPublisherProofPrevious = await officialPublisherProofMode(this.db.db);
893
+ next.officialPublisherProof = patch.officialPublisherProof;
894
+ }
884
895
  if (patch.priceCurrency !== undefined)
885
896
  next.priceCurrency = patch.priceCurrency;
886
897
  if (patch.customConnectors !== undefined)
@@ -1006,6 +1017,9 @@ let SettingsService = class SettingsService {
1006
1017
  (r.before.outsideSandbox.permission === "off" &&
1007
1018
  r.after.outsideSandbox.permission === "allowed") ||
1008
1019
  widened(r.before.network, r.after.network), reachTightened, r.after.allowedProfiles.value);
1020
+ // running outside the sandbox switched off closes the host gate on every device
1021
+ if (outsideOff)
1022
+ await this.ceilings.oweHostServiceStopsLocked({}, "platform");
1009
1023
  if (reachChanged && !reachTightened)
1010
1024
  await this.ceilings.invalidateProjectReachWideningLocked(r.before.projectReach.ceiling, r.after.projectReach.ceiling, r.after.allowedProfiles.value);
1011
1025
  }
@@ -1071,6 +1085,7 @@ let SettingsService = class SettingsService {
1071
1085
  detail: {
1072
1086
  ...patch,
1073
1087
  ...retentionAudit,
1088
+ ...(officialPublisherProofPrevious !== undefined && { officialPublisherProofPrevious }),
1074
1089
  ...(deviceSandboxChange !== undefined && { deviceSandboxEffective: deviceSandboxChange }),
1075
1090
  ...auditDetail,
1076
1091
  },
@@ -3,6 +3,7 @@
3
3
  // caller's transaction, so a notice exists exactly when its change does.
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { orgsUsing, ownerOf, ownersOf } from "../catalog/ownership.js";
6
+ import { withOrgScope } from "../infra/database/org-scope.js";
6
7
  /** An owned ref's display name: a plugin's (skills and agent templates have none). */
7
8
  const refDisplayName = (db, ref) => ref.kind === "plugin" ? itemDisplayName(db, ref.id) : Promise.resolve(null);
8
9
  /** A catalog item's display name for an upload notice (null without one, or for an unknown id). */
@@ -78,14 +79,14 @@ export async function notifySharedUpdate(db, ref, change) {
78
79
  const using = await orgsUsing(db, ref, { except: row.owner_org_id });
79
80
  const displayName = await refDisplayName(db, ref);
80
81
  for (const o of using) {
81
- await addOrgNotice(db, o.id, "shared_item_updated", {
82
+ await withOrgScope(o.id, () => addOrgNotice(db, o.id, "shared_item_updated", {
82
83
  ref,
83
84
  name: change.name,
84
85
  displayName,
85
86
  from: change.from,
86
87
  to: change.to,
87
88
  owner,
88
- });
89
+ }));
89
90
  }
90
91
  return using.length;
91
92
  }
package/dist/index.d.ts CHANGED
@@ -71,6 +71,7 @@ export { type ContextJob, type JobWrapper, type LogContext, logContext, setJobWr
71
71
  export { type Org, OrgsService } from "./orgs/orgs.service.js";
72
72
  export type { KernelOverride } from "./overrides.js";
73
73
  export { fetchNpmPackage, IntegrityMismatchError, type NpmFetchConfig, NpmFetchError, PackageTooLargeError, } from "./packages/npm.js";
74
+ export { fetchOfficialPublisher } from "./packages/official-publisher.js";
74
75
  export { packPackageTgz } from "./packages/tgz.js";
75
76
  export { checkInputParity, inputParity, type ParityFinding, type ParityOperation, } from "./platform/parity.js";
76
77
  export { PLATFORM_OPERATION_PROVIDERS } from "./platform/platform-ops.module.js";
package/dist/index.js CHANGED
@@ -67,6 +67,7 @@ export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js
67
67
  export { logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
68
68
  export { OrgsService } from "./orgs/orgs.service.js";
69
69
  export { fetchNpmPackage, IntegrityMismatchError, NpmFetchError, PackageTooLargeError, } from "./packages/npm.js";
70
+ export { fetchOfficialPublisher } from "./packages/official-publisher.js";
70
71
  // The canonical tgz of a package tree; `capybara-plugin bootstrap` pins git entries with it.
71
72
  export { packPackageTgz } from "./packages/tgz.js";
72
73
  // Test seam: the Platform input-parity test in tools/checks (no runtime caller).
@@ -2,7 +2,7 @@ import { type Driver, type KyselyPlugin, PostgresDialect, type PostgresDialectCo
2
2
  /**
3
3
  * `db.rls`: how the kernel pool carries the org scope to Postgres (RLS spec §5.2, §7).
4
4
  * - `off`: nothing is sent; the pool is a plain Kysely pool (no extra round trip).
5
- * - `scoped`: every connection carries the scope, with `capybara.rls = off`, so the policies admit
5
+ * - `scoped`: every transaction carries the scope, with `capybara.rls = off`, so the policies admit
6
6
  * every row; for measuring the round-trip cost (§8) and for the unscoped-query check.
7
7
  * - `enforce`: the same with `capybara.rls = enforce`: the policies filter by the scope.
8
8
  */
@@ -15,6 +15,7 @@ export declare const captureUnscopedQueryOrigins: KyselyPlugin;
15
15
  */
16
16
  export declare class ScopedPostgresDialect extends PostgresDialect {
17
17
  private readonly rls;
18
- constructor(config: PostgresDialectConfig, rls: RlsMode);
18
+ private readonly standaloneScope;
19
+ constructor(config: PostgresDialectConfig, rls: RlsMode, extendedProtocol?: boolean);
19
20
  createDriver(): Driver;
20
21
  }
@@ -1,12 +1,164 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import { CompiledQuery, PostgresDialect, } from "kysely";
3
+ import pg from "pg";
2
4
  import { currentScope, scopeKey, unscopedQueryCheck } from "./org-scope.js";
3
- const SET_SCOPE = "select set_config('capybara.org_id', $1, $4), set_config('capybara.scope', $2, $4), " +
4
- "set_config('capybara.rls', $3, $4)";
5
- /** The three settings for `scope`; an unscoped context sends empty values (fail closed). */
6
- function setScopeQuery(scope, rls, local) {
7
- const orgId = scope?.kind === "org" ? scope.orgId : "";
8
- const kind = scope?.kind ?? "";
9
- return CompiledQuery.raw(SET_SCOPE, [orgId, kind, rls, local]);
5
+ const SET_SCOPE = "select pg_catalog.set_config('capybara.org_id', $1, true), " +
6
+ "pg_catalog.set_config('capybara.scope', $2, true), " +
7
+ "pg_catalog.set_config('capybara.rls', $3, true)";
8
+ function scopeValues(scope, mode) {
9
+ return [scope?.kind === "org" ? scope.orgId : "", scope?.kind ?? "", mode];
10
+ }
11
+ const PREPARED_SCOPE = "capybara_set_local_scope";
12
+ /** Set the idle defaults. Each transaction reasserts its settings even after a session reset. */
13
+ function initializeScope(mode, prepare) {
14
+ const initialize = "select pg_catalog.set_config('capybara.org_id', '', false), " +
15
+ "pg_catalog.set_config('capybara.scope', '', false), " +
16
+ `pg_catalog.set_config('capybara.rls', '${mode}', false)`;
17
+ return prepare
18
+ ? `${initialize}; prepare ${PREPARED_SCOPE}(text, text, text) as ${SET_SCOPE}`
19
+ : initialize;
20
+ }
21
+ function beginSql(scope, mode, settings) {
22
+ let sql = "begin";
23
+ if (settings.isolationLevel)
24
+ sql += ` isolation level ${settings.isolationLevel}`;
25
+ if (settings.accessMode)
26
+ sql += ` ${settings.accessMode}`;
27
+ const [orgId, kind] = scopeValues(scope, mode);
28
+ if (orgId.includes("\0"))
29
+ throw new Error("An org scope cannot contain a NUL byte");
30
+ return (`${sql}; set local capybara.rls = '${mode}'; set local capybara.scope = '${kind}'; ` +
31
+ `set local capybara.org_id = ${pg.escapeLiteral(orgId)}`);
32
+ }
33
+ const STANDALONE = "/* scope transaction */ ";
34
+ const COMMIT_STANDALONE = CompiledQuery.raw(`${STANDALONE}commit`);
35
+ const ROLLBACK = CompiledQuery.raw("rollback");
36
+ /**
37
+ * Reuse plans for recurring scoped reads. A connection prepares at most 64 statements and
38
+ * remembers at most 128 first sightings; query shapes seen only once never use a prepared slot.
39
+ * PostgreSQL still chooses between custom and generic plans for the bound parameters.
40
+ */
41
+ class ReadPlans {
42
+ seen = new Set();
43
+ prepared = new Map();
44
+ nameFor(sql, parameters) {
45
+ // Avoid expanding wildcards in persistent prepared result types during rolling migrations.
46
+ if (!parameters.length ||
47
+ sql.length > 4096 ||
48
+ !sql.startsWith("select ") ||
49
+ sql.includes("*") ||
50
+ sql === SET_SCOPE)
51
+ return undefined;
52
+ const name = this.prepared.get(sql);
53
+ if (name || this.prepared.size >= 64)
54
+ return name;
55
+ if (this.seen.delete(sql)) {
56
+ const prepared = `capybara_read_${this.prepared.size}`;
57
+ this.prepared.set(sql, prepared);
58
+ return prepared;
59
+ }
60
+ if (this.seen.size === 128) {
61
+ const oldest = this.seen.values().next().value;
62
+ if (oldest !== undefined)
63
+ this.seen.delete(oldest);
64
+ }
65
+ this.seen.add(sql);
66
+ return undefined;
67
+ }
68
+ }
69
+ /**
70
+ * PostgreSQL executes the scope prelude and the statement in one implicit transaction when
71
+ * both executions precede the same Sync. The server discards the local settings at Sync,
72
+ * and skips the statement entirely if the prelude fails.
73
+ */
74
+ function scopedStatement(client, scope, mode, sql, parameters, name) {
75
+ return new Promise((resolve, reject) => {
76
+ const config = { text: sql, values: [...parameters], queryMode: "extended", name };
77
+ const query = new pg.Query(config, (error, results) => {
78
+ if (error) {
79
+ reject(error);
80
+ return;
81
+ }
82
+ // The first result is the scope prelude. An empty user statement has no result.
83
+ const result = Array.isArray(results) ? results[1] : undefined;
84
+ resolve((result ?? { rows: [], command: "", rowCount: 0 }));
85
+ });
86
+ const submit = query.submit.bind(query);
87
+ query.submit = (connection) => {
88
+ connection.stream.cork();
89
+ try {
90
+ connection.bind({
91
+ statement: PREPARED_SCOPE,
92
+ values: scopeValues(scope, mode),
93
+ }, true);
94
+ connection.describe({ type: "P" }, true);
95
+ connection.execute(null, true);
96
+ return submit(connection);
97
+ }
98
+ finally {
99
+ connection.stream.uncork();
100
+ }
101
+ };
102
+ // The scoped kernel pool uses node-postgres. Other Kysely-compatible pools use explicit
103
+ // transactions through the driver without passing a node-postgres Query object.
104
+ client.query(query);
105
+ });
106
+ }
107
+ /** Initialize each physical session once, before Kysely can reserve it. */
108
+ function withScopedConnections(pool, mode, scopeStore) {
109
+ const wrapped = new WeakMap();
110
+ const initialize = initializeScope(mode, !!scopeStore);
111
+ return {
112
+ ...(pool.Client ? { Client: pool.Client } : {}),
113
+ options: pool.options,
114
+ end: () => pool.end(),
115
+ async connect() {
116
+ const client = await pool.connect();
117
+ const existing = wrapped.get(client);
118
+ if (existing)
119
+ return existing;
120
+ try {
121
+ await client.query(initialize, []);
122
+ }
123
+ catch (error) {
124
+ // Discard this session so a failed bootstrap cannot leave it checked out or usable.
125
+ client.release(true);
126
+ throw error;
127
+ }
128
+ const plans = scopeStore ? new ReadPlans() : undefined;
129
+ let discard = false;
130
+ const connection = new Proxy(client, {
131
+ get(target, prop) {
132
+ if (prop === "release")
133
+ return () => target.release(discard);
134
+ if (prop === "query") {
135
+ return (query, parameters = []) => {
136
+ const pgClient = target;
137
+ // Kysely passes a cursor object to this method when streaming.
138
+ if (typeof query !== "string")
139
+ return pgClient.query(query);
140
+ const binding = scopeStore?.getStore();
141
+ const name = plans?.nameFor(query, parameters);
142
+ const result = binding
143
+ ? scopedStatement(target, binding.scope, mode, query, parameters, name)
144
+ : name
145
+ ? pgClient.query({ text: query, values: [...parameters], name })
146
+ : target.query(query, parameters);
147
+ return result.catch((error) => {
148
+ if (error instanceof pg.DatabaseError && error.code === "26000")
149
+ discard = true;
150
+ throw error;
151
+ });
152
+ };
153
+ }
154
+ const value = Reflect.get(target, prop);
155
+ return typeof value === "function" ? value.bind(target) : value;
156
+ },
157
+ });
158
+ wrapped.set(client, connection);
159
+ return connection;
160
+ },
161
+ };
10
162
  }
11
163
  /** Tables of the `capybara` schema with an `org_id` column (for the unscoped-query check). */
12
164
  const ORG_TABLES_SQL = "select table_name from information_schema.columns " +
@@ -25,26 +177,23 @@ export const captureUnscopedQueryOrigins = {
25
177
  };
26
178
  const TABLE_REF = /"capybara"\."([a-z0-9_]+)"|\bcapybara\.([a-z0-9_]+)/g;
27
179
  /**
28
- * One checkout of a pool connection. Before a query runs, the scope of the caller's async context
29
- * is put on the connection unless it is already there: session-level (`set_config(…, false)`)
30
- * outside a transaction, transaction-local (`true`) inside one, the first right after `BEGIN`.
31
- * A fresh checkout knows nothing about the session's values, so its first query always sets all
32
- * three: whatever an earlier holder left on the connection is overwritten before it can be read,
33
- * and a returned connection carries no scope into its next user. Queries on one checkout run one
34
- * after another (as pg runs them anyway), so a scope change and the query it precedes are never
35
- * split by another query of the same transaction.
180
+ * A checkout's tenant and platform values are transaction-local. Explicit transactions start
181
+ * with the caller's scope and reset it only on a scope transition. A standalone scoped query
182
+ * owns a short transaction. Queries on one checkout are serialized, keeping each transition
183
+ * together with the query it applies to.
36
184
  */
37
185
  class ScopedConnection {
38
186
  inner;
39
- rls;
187
+ mode;
188
+ standaloneScope;
40
189
  orgTables;
41
- /** The scope key now on the connection; undefined when unknown (fresh, or after a commit). */
42
190
  applied;
43
191
  inTransaction = false;
44
192
  tail = Promise.resolve();
45
- constructor(inner, rls, orgTables) {
193
+ constructor(inner, mode, standaloneScope, orgTables) {
46
194
  this.inner = inner;
47
- this.rls = rls;
195
+ this.mode = mode;
196
+ this.standaloneScope = standaloneScope;
48
197
  this.orgTables = orgTables;
49
198
  }
50
199
  // cancellation (an aborted query) goes to the inner connection, which knows the backend; the
@@ -66,7 +215,7 @@ class ScopedConnection {
66
215
  if (this.applied === key)
67
216
  return;
68
217
  this.applied = undefined;
69
- await this.inner.executeQuery(setScopeQuery(scope, this.rls, this.inTransaction));
218
+ await this.inner.executeQuery(CompiledQuery.raw(SET_SCOPE, scopeValues(scope, this.mode)));
70
219
  this.applied = key;
71
220
  }
72
221
  async check(scope, query) {
@@ -84,75 +233,98 @@ class ScopedConnection {
84
233
  const scope = currentScope();
85
234
  return this.serial(async () => {
86
235
  await this.check(scope, query);
87
- await this.ensure(scope);
88
- return this.inner.executeQuery(query);
236
+ if (this.inTransaction) {
237
+ await this.ensure(scope);
238
+ return this.inner.executeQuery(query);
239
+ }
240
+ // Extended protocol parses one statement. A raw SQL batch uses an explicit transaction.
241
+ if (this.standaloneScope && (query.parameters.length || !query.sql.includes(";"))) {
242
+ return this.standaloneScope.run({ scope }, () => this.inner.executeQuery(query));
243
+ }
244
+ await this.beginScoped(scope, {}, STANDALONE);
245
+ try {
246
+ const result = await this.inner.executeQuery(query);
247
+ await this.finish(() => this.inner.executeQuery(COMMIT_STANDALONE));
248
+ return result;
249
+ }
250
+ catch (error) {
251
+ await this.finish(() => this.inner.executeQuery(ROLLBACK)).catch(() => { });
252
+ throw error;
253
+ }
89
254
  });
90
255
  }
91
- /**
92
- * A cursor holds this checkout until it is closed: the scope is set and the stream read inside
93
- * one serial step, so no query of another scope runs in between.
94
- */
256
+ /** Keep the serial lane and the local scope until the cursor is closed. */
95
257
  async *streamQuery(query, chunkSize) {
96
258
  const scope = currentScope();
97
- let release = () => { };
259
+ let release = (_completed) => { };
98
260
  const held = new Promise((resolve) => {
99
261
  release = resolve;
100
262
  });
101
- let ready = () => { };
102
- const started = new Promise((resolve, reject) => {
103
- ready = (error) => (error === undefined ? resolve() : reject(error));
263
+ let entered = () => { };
264
+ let rejected = (_error) => { };
265
+ const ready = new Promise((resolve, reject) => {
266
+ entered = resolve;
267
+ rejected = reject;
104
268
  });
105
- void this.serial(async () => {
269
+ const step = this.serial(async () => {
270
+ const standalone = !this.inTransaction;
106
271
  try {
107
272
  await this.check(scope, query);
108
- await this.ensure(scope);
273
+ if (standalone)
274
+ await this.beginScoped(scope, {}, STANDALONE);
275
+ else if (this.inTransaction)
276
+ await this.ensure(scope);
109
277
  }
110
278
  catch (error) {
111
- ready(error ?? new Error("scope setup failed"));
279
+ rejected(error);
112
280
  return;
113
281
  }
114
- ready();
115
- await held;
282
+ entered();
283
+ const completed = await held;
284
+ if (standalone) {
285
+ await this.finish(() => this.inner.executeQuery(completed ? COMMIT_STANDALONE : ROLLBACK));
286
+ }
116
287
  });
288
+ let completed = false;
117
289
  try {
118
- await started;
290
+ await ready;
119
291
  yield* this.inner.streamQuery(query, chunkSize);
292
+ completed = true;
120
293
  }
121
294
  finally {
122
- release();
295
+ release(completed);
296
+ await step;
297
+ }
298
+ }
299
+ async beginScoped(scope, settings, prefix = "") {
300
+ const sql = prefix + beginSql(scope, this.mode, settings);
301
+ try {
302
+ await this.inner.executeQuery(CompiledQuery.raw(sql));
303
+ }
304
+ catch (error) {
305
+ // Kysely rolls back only a transaction whose begin resolved. A scope-setting error can
306
+ // leave this transaction aborted, so end it before releasing the connection.
307
+ await this.inner.executeQuery(ROLLBACK).catch(() => { });
308
+ throw error;
123
309
  }
310
+ this.inTransaction = true;
311
+ this.applied = scopeKey(scope);
124
312
  }
125
- /** `BEGIN`, then the scope of the caller transaction-local, as the transaction's first statement. */
126
- begin(driver, settings) {
313
+ begin(settings) {
127
314
  const scope = currentScope();
128
- return this.serial(async () => {
129
- await driver.beginTransaction(this.inner, settings);
130
- this.inTransaction = true;
315
+ return this.serial(() => this.beginScoped(scope, settings));
316
+ }
317
+ async finish(fn) {
318
+ try {
319
+ await fn();
320
+ }
321
+ finally {
322
+ this.inTransaction = false;
131
323
  this.applied = undefined;
132
- try {
133
- await this.ensure(scope);
134
- }
135
- catch (error) {
136
- // Kysely rolls back only a transaction whose begin resolved: end this one here, or the
137
- // connection would return to the pool inside it (best effort; the error is the caller's)
138
- await driver.rollbackTransaction(this.inner).catch(() => { });
139
- this.inTransaction = false;
140
- this.applied = undefined;
141
- throw error;
142
- }
143
- });
324
+ }
144
325
  }
145
- /** `COMMIT` / `ROLLBACK`: the local values end, the session's (unknown here) apply again. */
146
326
  end(fn) {
147
- return this.serial(async () => {
148
- try {
149
- await fn();
150
- }
151
- finally {
152
- this.inTransaction = false;
153
- this.applied = undefined;
154
- }
155
- });
327
+ return this.serial(() => this.finish(fn));
156
328
  }
157
329
  /**
158
330
  * A savepoint statement, in order with the queries. A rollback to a savepoint also undoes a
@@ -177,11 +349,13 @@ class ScopedConnection {
177
349
  */
178
350
  class ScopedDriver {
179
351
  inner;
180
- rls;
352
+ mode;
353
+ standaloneScope;
181
354
  tables;
182
- constructor(inner, rls) {
355
+ constructor(inner, mode, standaloneScope) {
183
356
  this.inner = inner;
184
- this.rls = rls;
357
+ this.mode = mode;
358
+ this.standaloneScope = standaloneScope;
185
359
  }
186
360
  init() {
187
361
  return this.inner.init();
@@ -201,10 +375,10 @@ class ScopedDriver {
201
375
  };
202
376
  async acquireConnection() {
203
377
  const inner = await this.inner.acquireConnection();
204
- return new ScopedConnection(inner, this.rls, this.orgTables);
378
+ return new ScopedConnection(inner, this.mode, this.standaloneScope, this.orgTables);
205
379
  }
206
380
  beginTransaction(conn, settings) {
207
- return scoped(conn).begin(this.inner, settings);
381
+ return scoped(conn).begin(settings);
208
382
  }
209
383
  commitTransaction(conn) {
210
384
  const c = scoped(conn);
@@ -244,14 +418,28 @@ function scoped(conn) {
244
418
  */
245
419
  export class ScopedPostgresDialect extends PostgresDialect {
246
420
  rls;
247
- constructor(config, rls) {
248
- super(config);
421
+ standaloneScope;
422
+ constructor(config, rls, extendedProtocol = false) {
423
+ const start = rls !== "off" && extendedProtocol
424
+ ? new AsyncLocalStorage()
425
+ : undefined;
426
+ const pool = config.pool;
427
+ const mode = rls === "enforce" ? "enforce" : "off";
428
+ super(rls === "off"
429
+ ? config
430
+ : {
431
+ ...config,
432
+ pool: typeof pool === "function"
433
+ ? async (options) => withScopedConnections(await pool(options), mode, start)
434
+ : withScopedConnections(pool, mode, start),
435
+ });
249
436
  this.rls = rls;
437
+ this.standaloneScope = start;
250
438
  }
251
439
  createDriver() {
252
440
  const inner = super.createDriver();
253
441
  if (this.rls === "off")
254
442
  return inner;
255
- return new ScopedDriver(inner, this.rls === "enforce" ? "enforce" : "off");
443
+ return new ScopedDriver(inner, this.rls === "enforce" ? "enforce" : "off", this.standaloneScope);
256
444
  }
257
445
  }
@@ -1,7 +1,9 @@
1
1
  import { type Transaction } from "kysely";
2
+ import { type RlsMode } from "./scoped-dialect.js";
2
3
  export interface StartupActivationOptions {
3
4
  connectionString: string;
4
5
  connectTimeoutMs?: number;
6
+ rls?: RlsMode;
5
7
  signal: AbortSignal;
6
8
  remainingMs: () => number;
7
9
  /**
@@ -1,7 +1,8 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { Kysely, PostgresDialect } from "kysely";
2
+ import { Kysely } from "kysely";
3
3
  import pg from "pg";
4
4
  import { pgConnectOptions } from "../../db/pool.js";
5
+ import { ScopedPostgresDialect } from "./scoped-dialect.js";
5
6
  /** Server-side bound on one statement of the owned startup session. */
6
7
  export const STARTUP_STATEMENT_TIMEOUT_MS = 500;
7
8
  /** Server-side bound on one lock wait of the owned startup session. */
@@ -169,7 +170,7 @@ fn, options) {
169
170
  if (closed)
170
171
  original.connection.stream.destroy();
171
172
  });
172
- const db = new Kysely({ dialect: new PostgresDialect({ pool }) });
173
+ const db = new Kysely({ dialect: new ScopedPostgresDialect({ pool }, options.rls ?? "off") });
173
174
  let rollbackConfirmed = false;
174
175
  try {
175
176
  guard.check();